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
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
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
//! Typed qualification bindings, bounded native/QEMU execution, and candidate evidence.

use crate::{
    builder::{
        run_qemu_process, run_qualification_process, CandidateArtifact, CommandSpec,
        ProcessEvidence,
    },
    file_digest, BuildAttempt, BuildBindingsV1, BuildCancellation, DigestError,
    FloorUnverifiedReason, FloorVerificationStatus, HostArch, HostOs, HostRequirement,
    LogicalOutputSelector, PlannedTarget, Qualification, ReleasePlan, SupportTier,
};
use eggpack_contract::DistributionContract;
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    fs::{self, File},
    io::{Read, Seek, SeekFrom},
    path::{Path, PathBuf},
    time::Duration,
};

const MAX_TARGETS: usize = 256;
const MAX_ARGS: usize = 128;
const MAX_ARG_LEN: usize = 4096;
const MAX_CAPTURE: usize = 256 * 1024;
const MAX_BINARY_HEADER: u64 = 4096;

/// Qualification binding validation or execution setup error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QualificationError(String);
impl std::fmt::Display for QualificationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::error::Error for QualificationError {}
fn qerr(message: &str) -> QualificationError {
    QualificationError(message.to_owned())
}

/// One fixed-argument smoke invocation for an exact logical candidate.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CandidateSmokeBinding {
    /// Exact contract logical output selector; never inferred as a primary output.
    pub selector: LogicalOutputSelector,
    /// Fixed arguments passed directly to the selected candidate, without a shell.
    #[serde(default)]
    pub argv: Vec<String>,
    /// Per-process deadline in milliseconds (1..=86,400,000).
    pub timeout_ms: u64,
    /// Retained stdout bound (1..=262,144 bytes).
    pub stdout_limit: usize,
    /// Retained stderr bound (1..=262,144 bytes).
    pub stderr_limit: usize,
}

/// Qualification settings for one canonical planned target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
pub struct TargetQualificationBinding {
    /// One candidate smoke check; required by Native, DeferredNative, and Emulated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub smoke: Option<CandidateSmokeBinding>,
}

/// Strict producer-side qualification bindings schema version 1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualificationBindingsV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Settings keyed by canonical target triple.
    pub targets: BTreeMap<String, TargetQualificationBinding>,
}

impl QualificationBindingsV1 {
    /// Strictly parse TOML qualification bindings.
    pub fn from_toml(text: &str) -> Result<Self, QualificationError> {
        let value: Self = toml::from_str(text).map_err(|_| qerr("invalid qualification TOML"))?;
        value.validate_shape()?;
        Ok(value)
    }

    /// Validate exact selected-target coverage and smoke selectors against build bindings.
    pub fn validate_for(
        &self,
        plan: &ReleasePlan,
        build_bindings: &BuildBindingsV1,
    ) -> Result<(), QualificationError> {
        self.validate_shape()?;
        if self.targets.len() != plan.targets.len()
            || self
                .targets
                .keys()
                .any(|target| !plan.targets.iter().any(|planned| &planned.target == target))
        {
            return Err(qerr(
                "qualification target inventory differs from ReleasePlan",
            ));
        }
        for target in &plan.targets {
            let settings = self
                .targets
                .get(&target.target)
                .ok_or_else(|| qerr("qualification target binding missing"))?;
            let must_smoke = matches!(
                target.policy.qualification,
                Qualification::Native | Qualification::DeferredNative | Qualification::Emulated
            );
            if settings.smoke.is_some() != must_smoke {
                return Err(qerr(
                    "smoke binding does not match qualification classification",
                ));
            }
            if let Some(smoke) = &settings.smoke {
                let candidates = build_bindings
                    .targets
                    .get(&target.target)
                    .ok_or_else(|| qerr("build target binding missing"))?;
                if !candidates
                    .iter()
                    .any(|candidate| candidate.selector == smoke.selector)
                {
                    return Err(qerr("smoke selector is absent from build bindings"));
                }
            }
            if target.policy.qualification == Qualification::DeferredNative
                && target.policy.qualification_host.is_none()
            {
                return Err(qerr("DeferredNative requires qualification_host"));
            }
        }
        Ok(())
    }

    fn validate_shape(&self) -> Result<(), QualificationError> {
        if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > MAX_TARGETS {
            return Err(qerr("unsupported version or invalid target count"));
        }
        for (target, binding) in &self.targets {
            if target.is_empty()
                || target.len() > 128
                || !target
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b))
            {
                return Err(qerr("invalid canonical target key"));
            }
            if let Some(smoke) = &binding.smoke {
                if smoke.timeout_ms == 0
                    || smoke.timeout_ms > 86_400_000
                    || smoke.stdout_limit == 0
                    || smoke.stdout_limit > MAX_CAPTURE
                    || smoke.stderr_limit == 0
                    || smoke.stderr_limit > MAX_CAPTURE
                    || smoke.argv.len() > MAX_ARGS
                    || smoke.argv.iter().any(|arg| {
                        arg.len() > MAX_ARG_LEN
                            || arg.contains('\0')
                            || arg.bytes().any(|b| b.is_ascii_control())
                    })
                {
                    return Err(qerr("smoke bounds or arguments are invalid"));
                }
            }
        }
        Ok(())
    }
}

/// Bounded QEMU runtime input. The executable and flags are fixed by the target mapping.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct QualificationRuntime {
    /// Optional absolute QEMU user-mode sysroot directory used with `-L`.
    pub qemu_sysroot: Option<PathBuf>,
}

/// Actual qualification method, distinct from requested policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualificationMethod {
    /// Candidate was directly run on the matching native qualification host.
    Native,
    /// DeferredNative was inspected on a different host and remains pending.
    Deferred,
    /// DeferredNative candidate ran on its matching later native host.
    DeferredNativeOnNativeHost,
    /// Candidate ran through a finite QEMU Linux user-mode mapping.
    QemuUser,
    /// Candidate structure was checked but no execution occurred.
    Structural,
}

/// Typed qualification outcome; a built candidate can never imply Passed by itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualificationStatus {
    /// Structural and any required execution checks passed.
    Passed,
    /// DeferredNative execution is pending on its required host.
    Deferred,
    /// Qualification failed for the bounded reason below.
    Failed(QualificationFailure),
}

/// Bounded reason for failed qualification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualificationFailure {
    /// Candidate format or architecture does not match the planned target.
    StructuralMismatch,
    /// Candidate bytes changed during qualification.
    CandidateChanged,
    /// The executing host does not match the required qualification host.
    HostMismatch,
    /// Candidate smoke exited unsuccessfully or could not be started.
    SmokeFailed,
    /// Candidate smoke exceeded its deadline.
    SmokeTimedOut,
    /// Candidate smoke exceeded its output bound.
    OutputLimitExceeded,
    /// Required finite QEMU executable was unavailable or failed preflight.
    EmulatorUnavailable,
    /// QEMU process failed or returned a non-zero exit status.
    EmulatorFailed,
    /// Candidate could not be safely read or its runtime preconditions failed.
    InvalidRuntimeEnvironment,
    /// The produced bytes require a newer runtime than the declared
    /// compatibility floor, so the declared floor is false.
    FloorNotSatisfied,
}

/// Supported executable file formats checked structurally.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateFormat {
    /// ELF executable.
    Elf,
    /// PE/COFF executable.
    PeCoff,
    /// Thin Mach-O executable.
    MachO,
}

/// Supported executable CPU architectures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateArchitecture {
    /// x86-64.
    X86_64,
    /// AArch64.
    Aarch64,
    /// 32-bit ARM.
    Armv7,
}

/// Exact candidate byte and structural identity observed for qualification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualifiedCandidateEvidence {
    /// Contract logical output selector.
    pub selector: LogicalOutputSelector,
    /// Explicit M002 source package.
    pub package: String,
    /// Explicit M002 binary target.
    pub binary: String,
    /// Number of bytes observed.
    pub size: u64,
    /// SHA-256 of exact pre-qualification bytes.
    pub sha256: String,
    /// Detected executable format.
    pub format: CandidateFormat,
    /// Detected machine architecture.
    pub architecture: CandidateArchitecture,
}

/// One bounded process result without output contents or environment values.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualificationProcessEvidence {
    /// `candidate_smoke` or `qemu_preflight`.
    pub purpose: String,
    /// Candidate selector associated with execution, absent for QEMU preflight.
    pub selector: Option<LogicalOutputSelector>,
    /// Exit/deadline/cancellation/output-limit classification.
    pub process: ProcessEvidence,
}

/// Complete bounded evidence for one release target qualification attempt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QualificationEvidence {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Release identity from ReleasePlan and BuildAttempt.
    pub release_id: String,
    /// Source revision from ReleasePlan and BuildAttempt.
    pub source_revision: String,
    /// Canonical target triple.
    pub target: String,
    /// Requested qualification classification.
    pub planned_classification: Qualification,
    /// Method actually applied.
    pub method: QualificationMethod,
    /// Actual host capability used for this attempt.
    pub actual_host: HostRequirement,
    /// Support tier, recorded without changing result semantics.
    pub support: SupportTier,
    /// Typed result.
    pub status: QualificationStatus,
    /// Verification status of the declared compatibility floor.
    ///
    /// The status is bound to the exact bytes this record describes: it is
    /// computed from the inspected candidate, never from a smoke run, because
    /// native execution is never floor proof (ADR-0005 §9). A document that
    /// omits the field is read as `NotDeclared`, which is refused for any
    /// target that declares a floor.
    #[serde(default)]
    pub floor: FloorVerificationStatus,
    /// Per-candidate evidence ordered by logical selector.
    pub candidates: Vec<QualifiedCandidateEvidence>,
    /// Configured smoke selector, if this mode has a smoke check.
    pub smoke_selector: Option<LogicalOutputSelector>,
    /// Bounded process outcome summaries.
    pub processes: Vec<QualificationProcessEvidence>,
}

impl QualificationEvidence {
    /// Validate evidence identity, candidate inventory, classification, and bounded fields.
    pub fn validate_for(
        &self,
        plan: &ReleasePlan,
        target: &PlannedTarget,
        attempt: &BuildAttempt,
    ) -> Result<(), QualificationError> {
        if self.schema_version != 1
            || !plan.targets.iter().any(|planned| planned == target)
            || self.release_id != plan.release_id
            || self.source_revision != plan.source_revision
            || attempt.release_id != plan.release_id
            || attempt.source_revision != plan.source_revision
            || self.target != target.target
            || self.planned_classification != target.policy.qualification
            || self.support != target.policy.support
            || (!matches!(self.status, QualificationStatus::Failed(_))
                && self.candidates.len() != attempt.candidates.len())
            || self.candidates.len() > 256
            || self.processes.len() > 1 + MAX_ARGS
            || target.floor_status != crate::planned_floor_status(&target.policy)
            || !crate::floor_status_admissible(
                &target.policy.floor,
                target.policy.strategy,
                self.floor,
            )
            || (self.floor == FloorVerificationStatus::NotSatisfied)
                != matches!(
                    self.status,
                    QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied)
                )
        {
            return Err(qerr(
                "qualification evidence identity or bounds are invalid",
            ));
        }
        let mut expected_candidates = BTreeMap::new();
        for candidate in &attempt.candidates {
            if expected_candidates
                .insert(candidate.selector.clone(), candidate)
                .is_some()
            {
                return Err(qerr("BuildAttempt candidate selector is duplicated"));
            }
        }
        for record in &self.candidates {
            let candidate = expected_candidates
                .get(&record.selector)
                .ok_or_else(|| qerr("qualification evidence contains an unknown candidate"))?;
            if record.selector != candidate.selector
                || record.package != candidate.package
                || record.binary != candidate.binary
                || record.size != candidate.size
                || crate::validate_sha256_hex(&record.sha256).is_err()
            {
                return Err(qerr("qualification evidence candidate identity is invalid"));
            }
        }
        if self
            .candidates
            .windows(2)
            .any(|pair| pair[0].selector >= pair[1].selector)
            || self.processes.iter().any(|process| {
                process.purpose.len() > 64
                    || process.process.stdout_bytes > MAX_CAPTURE
                    || process.process.stderr_bytes > MAX_CAPTURE
            })
        {
            return Err(qerr(
                "qualification evidence ordering or process bounds are invalid",
            ));
        }
        let method_matches = matches!(
            (target.policy.qualification, self.method),
            (Qualification::Native, QualificationMethod::Native)
                | (Qualification::DeferredNative, QualificationMethod::Deferred)
                | (
                    Qualification::DeferredNative,
                    QualificationMethod::DeferredNativeOnNativeHost
                )
                | (Qualification::Emulated, QualificationMethod::QemuUser)
                | (Qualification::Structural, QualificationMethod::Structural)
        );
        if !method_matches
            || (self.status == QualificationStatus::Deferred
                && (self.method != QualificationMethod::Deferred
                    || !self.processes.is_empty()
                    || target.policy.qualification_host.is_none()
                    || target.policy.qualification_host == Some(self.actual_host)))
            || (self.status == QualificationStatus::Passed
                && self.method == QualificationMethod::Deferred)
            || (self.method == QualificationMethod::Structural
                && (!self.processes.is_empty() || self.smoke_selector.is_some()))
            || (self.status == QualificationStatus::Passed
                && matches!(
                    target.policy.qualification,
                    Qualification::Native | Qualification::DeferredNative | Qualification::Emulated
                )
                && self.smoke_selector.is_none())
            || (self.status == QualificationStatus::Passed
                && matches!(
                    self.method,
                    QualificationMethod::Native | QualificationMethod::DeferredNativeOnNativeHost
                )
                && !target_matches_host(&target.target, self.actual_host))
            || (self.status == QualificationStatus::Passed
                && target.policy.qualification == Qualification::Native
                && target
                    .policy
                    .qualification_host
                    .is_some_and(|required| required != self.actual_host))
            || (self.status == QualificationStatus::Passed
                && target.policy.qualification == Qualification::DeferredNative
                && target
                    .policy
                    .qualification_host
                    .is_some_and(|required| required != self.actual_host))
            || (self.status == QualificationStatus::Passed
                && target.policy.qualification == Qualification::Emulated
                && target
                    .policy
                    .qualification_host
                    .is_some_and(|required| required != self.actual_host))
            || (self.status == QualificationStatus::Passed
                && self
                    .processes
                    .iter()
                    .any(|evidence| evidence.process.outcome != crate::CommandOutcome::Success))
            || (self.status == QualificationStatus::Passed
                && self.processes.iter().any(|evidence| {
                    match (
                        self.method,
                        evidence.purpose.as_str(),
                        evidence.selector.as_ref(),
                    ) {
                        (
                            QualificationMethod::Native
                            | QualificationMethod::DeferredNativeOnNativeHost,
                            "candidate_smoke",
                            Some(selector),
                        ) => self.smoke_selector.as_ref() != Some(selector),
                        (QualificationMethod::QemuUser, "qemu_preflight", None) => false,
                        (QualificationMethod::QemuUser, "candidate_smoke", Some(selector)) => {
                            self.smoke_selector.as_ref() != Some(selector)
                        }
                        _ => true,
                    }
                }))
            || (self.status == QualificationStatus::Passed
                && match self.method {
                    QualificationMethod::Native
                    | QualificationMethod::DeferredNativeOnNativeHost => self.processes.len() != 1,
                    QualificationMethod::QemuUser => self.processes.len() != 2,
                    QualificationMethod::Structural => !self.processes.is_empty(),
                    QualificationMethod::Deferred => true,
                })
        {
            return Err(qerr(
                "qualification evidence method or status is inconsistent",
            ));
        }
        Ok(())
    }
}

/// All explicit producer-side inputs required to qualify one planned target.
pub struct QualificationRequest<'a> {
    /// Portable distribution identity authority.
    pub contract: &'a DistributionContract,
    /// Invocation release plan.
    pub plan: &'a ReleasePlan,
    /// One exact selected plan target.
    pub target: &'a PlannedTarget,
    /// Successful M002 candidate build attempt.
    pub attempt: &'a BuildAttempt,
    /// Exact package/binary to logical-slot bindings used by M002.
    pub build_bindings: &'a BuildBindingsV1,
    /// Exact qualification smoke policy.
    pub qualification_bindings: &'a QualificationBindingsV1,
    /// Optional explicitly supplied runtime-specific path inputs.
    pub runtime: &'a QualificationRuntime,
    /// Caller cancellation flag.
    pub cancellation: &'a BuildCancellation,
}

/// Execute M003 qualification using actual local host facts.
pub fn qualify_target(
    request: QualificationRequest<'_>,
) -> Result<QualificationEvidence, QualificationError> {
    let QualificationRequest {
        contract,
        plan,
        target,
        attempt,
        build_bindings,
        qualification_bindings,
        runtime,
        cancellation,
    } = request;
    let host = actual_host()?;
    qualify_target_for_host(
        contract,
        plan,
        target,
        attempt,
        build_bindings,
        qualification_bindings,
        runtime,
        cancellation,
        host,
    )
}

#[allow(clippy::too_many_arguments)]
fn qualify_target_for_host(
    contract: &DistributionContract,
    plan: &ReleasePlan,
    target: &PlannedTarget,
    attempt: &BuildAttempt,
    build_bindings: &BuildBindingsV1,
    qualification_bindings: &QualificationBindingsV1,
    runtime: &QualificationRuntime,
    cancellation: &BuildCancellation,
    host: HostRequirement,
) -> Result<QualificationEvidence, QualificationError> {
    let runner = |spec: &CommandSpec, qemu: bool| {
        let result = if qemu {
            run_qemu_process(spec, cancellation)
        } else {
            run_qualification_process(spec, cancellation)
        };
        result.map_err(|_| ())
    };
    qualify_target_for_host_with_runner(
        contract,
        plan,
        target,
        attempt,
        build_bindings,
        qualification_bindings,
        runtime,
        cancellation,
        host,
        &runner,
    )
}

#[allow(clippy::too_many_arguments)]
fn qualify_target_for_host_with_runner<F>(
    contract: &DistributionContract,
    plan: &ReleasePlan,
    target: &PlannedTarget,
    attempt: &BuildAttempt,
    build_bindings: &BuildBindingsV1,
    qualification_bindings: &QualificationBindingsV1,
    runtime: &QualificationRuntime,
    cancellation: &BuildCancellation,
    host: HostRequirement,
    runner: &F,
) -> Result<QualificationEvidence, QualificationError>
where
    F: Fn(&CommandSpec, bool) -> Result<ProcessEvidence, ()>,
{
    if plan.schema_version != 1
        || plan.release_id.is_empty()
        || plan.source_revision.is_empty()
        || !plan.targets.iter().any(|planned| planned == target)
        || attempt.release_id != plan.release_id
        || attempt.source_revision != plan.source_revision
        || attempt.target != target.target
        || attempt.strategy != target.policy.strategy
        || attempt.process.outcome != crate::CommandOutcome::Success
        || attempt.candidates.is_empty()
        || attempt.candidates.len() > 256
    {
        return Err(qerr(
            "BuildAttempt identity or result does not match ReleasePlan",
        ));
    }
    build_bindings
        .validate_for(contract, plan)
        .map_err(|_| qerr("BuildBindings do not exactly cover ReleasePlan"))?;
    qualification_bindings.validate_for(plan, build_bindings)?;
    validate_runtime(runtime)?;
    if target.policy.qualification != Qualification::Emulated && runtime.qemu_sysroot.is_some() {
        return Err(qerr(
            "QEMU sysroot is only valid for Emulated qualification",
        ));
    }

    let target_builds = build_bindings
        .targets
        .get(&target.target)
        .ok_or_else(|| qerr("build target binding missing"))?;
    let mut expected = BTreeMap::new();
    for binding in target_builds {
        expected.insert(
            binding.selector.clone(),
            (binding.package.as_str(), binding.binary.as_str()),
        );
    }
    let mut actual = BTreeMap::new();
    for candidate in &attempt.candidates {
        if candidate.target != target.target
            || actual
                .insert(
                    candidate.selector.clone(),
                    (
                        candidate.package.as_str(),
                        candidate.binary.as_str(),
                        candidate,
                    ),
                )
                .is_some()
        {
            return Err(qerr("candidate target or selector is duplicated"));
        }
    }
    if expected.len() != actual.len()
        || expected.iter().any(|(selector, (package, binary))| {
            actual
                .get(selector)
                .is_none_or(|(actual_package, actual_binary, _)| {
                    package != actual_package || binary != actual_binary
                })
        })
    {
        return Err(qerr(
            "BuildAttempt candidate inventory differs from BuildBindings",
        ));
    }

    let mut evidence_candidates = Vec::new();
    let mut candidate_floors = Vec::new();
    for (selector, (_, _, candidate)) in &actual {
        match inspect_candidate(candidate, target) {
            Ok(inspected) => {
                candidate_floors.push(inspected.floor);
                evidence_candidates.push(inspected.evidence);
            }
            Err(failure) => {
                let method = match target.policy.qualification {
                    Qualification::Native => QualificationMethod::Native,
                    Qualification::DeferredNative => QualificationMethod::Deferred,
                    Qualification::Emulated => QualificationMethod::QemuUser,
                    Qualification::Structural => QualificationMethod::Structural,
                };
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    method,
                    QualificationStatus::Failed(failure),
                    Vec::new(),
                    None,
                    Vec::new(),
                    FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate),
                ));
            }
        }
        debug_assert_eq!(
            evidence_candidates.last().map(|c| &c.selector),
            Some(selector)
        );
    }
    let floor = crate::floor::aggregate_floor_status(&candidate_floors);
    let settings = qualification_bindings
        .targets
        .get(&target.target)
        .expect("validated target qualification binding");
    let smoke = settings.smoke.as_ref();
    let selected_smoke = smoke.and_then(|binding| actual.get(&binding.selector).map(|v| v.2));
    if smoke.is_some() && selected_smoke.is_none() {
        return Err(qerr("smoke selector is absent from candidate inventory"));
    }
    // A declared floor that the produced bytes contradict is false, so it
    // fails the qualification for this target before anything executes. It is
    // never reported as merely unverified.
    if floor == FloorVerificationStatus::NotSatisfied {
        let method = match target.policy.qualification {
            Qualification::Native => QualificationMethod::Native,
            Qualification::DeferredNative => QualificationMethod::Deferred,
            Qualification::Emulated => QualificationMethod::QemuUser,
            Qualification::Structural => QualificationMethod::Structural,
        };
        return Ok(make_evidence(
            plan,
            target,
            host,
            method,
            QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied),
            evidence_candidates,
            smoke.map(|s| s.selector.clone()),
            Vec::new(),
            floor,
        ));
    }

    let (method, should_execute) = match target.policy.qualification {
        Qualification::Structural => (QualificationMethod::Structural, false),
        Qualification::Native => {
            let required = target.policy.qualification_host.unwrap_or(HostRequirement {
                os: target.policy.host_os,
                arch: target.policy.host_arch,
            });
            if host != required || !target_matches_host(&target.target, host) {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    QualificationMethod::Native,
                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
                    evidence_candidates,
                    smoke.map(|s| s.selector.clone()),
                    Vec::new(),
                    floor,
                ));
            }
            (QualificationMethod::Native, true)
        }
        Qualification::DeferredNative => {
            let required = target
                .policy
                .qualification_host
                .ok_or_else(|| qerr("DeferredNative requires qualification_host"))?;
            if host != required {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    QualificationMethod::Deferred,
                    QualificationStatus::Deferred,
                    evidence_candidates,
                    smoke.map(|s| s.selector.clone()),
                    Vec::new(),
                    floor,
                ));
            }
            if !target_matches_host(&target.target, host) {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    QualificationMethod::DeferredNativeOnNativeHost,
                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
                    evidence_candidates,
                    smoke.map(|s| s.selector.clone()),
                    Vec::new(),
                    floor,
                ));
            }
            (QualificationMethod::DeferredNativeOnNativeHost, true)
        }
        Qualification::Emulated => {
            if !target.target.contains("-linux-")
                || evidence_candidates
                    .iter()
                    .any(|c| c.format != CandidateFormat::Elf)
            {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    QualificationMethod::QemuUser,
                    QualificationStatus::Failed(QualificationFailure::StructuralMismatch),
                    evidence_candidates,
                    smoke.map(|s| s.selector.clone()),
                    Vec::new(),
                    floor,
                ));
            }
            if target
                .policy
                .qualification_host
                .is_some_and(|required| required != host)
            {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    QualificationMethod::QemuUser,
                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
                    evidence_candidates,
                    smoke.map(|s| s.selector.clone()),
                    Vec::new(),
                    floor,
                ));
            }
            (QualificationMethod::QemuUser, true)
        }
    };
    if !should_execute {
        return Ok(make_evidence(
            plan,
            target,
            host,
            method,
            QualificationStatus::Passed,
            evidence_candidates,
            None,
            Vec::new(),
            floor,
        ));
    }
    let smoke = smoke.ok_or_else(|| qerr("execution qualification requires a smoke binding"))?;
    let candidate = selected_smoke.expect("smoke selector was validated");
    let mut processes = Vec::new();
    if method == QualificationMethod::QemuUser {
        let emulator =
            qemu_for_target(&target.target).ok_or_else(|| qerr("unsupported QEMU target"))?;
        let preflight = CommandSpec {
            executable: emulator.into(),
            args: vec!["--version".into()],
            cwd: qualification_cwd(candidate)?,
            env: BTreeMap::new(),
            timeout: Duration::from_secs(10),
            stdout_limit: 8192,
            stderr_limit: 8192,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        let result = match runner(&preflight, true) {
            Ok(result) => result,
            Err(_) => {
                return Ok(make_evidence(
                    plan,
                    target,
                    host,
                    method,
                    QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable),
                    evidence_candidates,
                    Some(smoke.selector.clone()),
                    processes,
                    floor,
                ))
            }
        };
        let preflight_ok = result.outcome == crate::CommandOutcome::Success;
        processes.push(QualificationProcessEvidence {
            purpose: "qemu_preflight".into(),
            selector: None,
            process: result,
        });
        if !preflight_ok {
            return Ok(make_evidence(
                plan,
                target,
                host,
                method,
                QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable),
                evidence_candidates,
                Some(smoke.selector.clone()),
                processes,
                floor,
            ));
        }
    }
    if cancellation.is_cancelled() {
        return Ok(make_evidence(
            plan,
            target,
            host,
            method,
            QualificationStatus::Failed(QualificationFailure::SmokeFailed),
            evidence_candidates,
            Some(smoke.selector.clone()),
            processes,
            floor,
        ));
    }
    let (command, is_qemu) = if method == QualificationMethod::QemuUser {
        let command = CommandSpec {
            executable: qemu_for_target(&target.target)
                .expect("validated QEMU target")
                .into(),
            args: qemu_args(runtime, candidate, smoke),
            cwd: qualification_cwd(candidate)?,
            env: BTreeMap::new(),
            timeout: Duration::from_millis(smoke.timeout_ms),
            stdout_limit: smoke.stdout_limit,
            stderr_limit: smoke.stderr_limit,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        (command, true)
    } else {
        let command = CommandSpec {
            executable: candidate.path.to_string_lossy().into_owned(),
            args: smoke.argv.clone(),
            cwd: qualification_cwd(candidate)?,
            env: BTreeMap::new(),
            timeout: Duration::from_millis(smoke.timeout_ms),
            stdout_limit: smoke.stdout_limit,
            stderr_limit: smoke.stderr_limit,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        (command, false)
    };
    let process = match runner(&command, is_qemu) {
        Ok(process) => process,
        Err(_) => {
            return Ok(make_evidence(
                plan,
                target,
                host,
                method,
                QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
                    QualificationFailure::EmulatorFailed
                } else {
                    QualificationFailure::SmokeFailed
                }),
                evidence_candidates,
                Some(smoke.selector.clone()),
                processes,
                floor,
            ))
        }
    };
    let status = status_from_process(process.outcome, method);
    processes.push(QualificationProcessEvidence {
        purpose: "candidate_smoke".into(),
        selector: Some(smoke.selector.clone()),
        process,
    });
    let mut status = status;
    if status == QualificationStatus::Passed {
        for (selector, (_, _, candidate)) in &actual {
            match inspect_candidate(candidate, target) {
                Ok(after) => {
                    let before = evidence_candidates
                        .iter()
                        .find(|evidence| &evidence.selector == selector)
                        .expect("preflight candidate evidence");
                    if after.evidence.size != before.size || after.evidence.sha256 != before.sha256
                    {
                        status =
                            QualificationStatus::Failed(QualificationFailure::CandidateChanged);
                        break;
                    }
                }
                Err(_) => {
                    status = QualificationStatus::Failed(QualificationFailure::CandidateChanged);
                    break;
                }
            }
        }
    }
    Ok(make_evidence(
        plan,
        target,
        host,
        method,
        status,
        evidence_candidates,
        Some(smoke.selector.clone()),
        processes,
        floor,
    ))
}

#[allow(clippy::too_many_arguments)]
fn make_evidence(
    plan: &ReleasePlan,
    target: &PlannedTarget,
    host: HostRequirement,
    method: QualificationMethod,
    status: QualificationStatus,
    candidates: Vec<QualifiedCandidateEvidence>,
    smoke_selector: Option<LogicalOutputSelector>,
    processes: Vec<QualificationProcessEvidence>,
    floor: FloorVerificationStatus,
) -> QualificationEvidence {
    QualificationEvidence {
        schema_version: 1,
        release_id: plan.release_id.clone(),
        source_revision: plan.source_revision.clone(),
        target: target.target.clone(),
        planned_classification: target.policy.qualification,
        method,
        actual_host: host,
        support: target.policy.support,
        status,
        floor,
        candidates,
        smoke_selector,
        processes,
    }
}

fn status_from_process(
    outcome: crate::CommandOutcome,
    method: QualificationMethod,
) -> QualificationStatus {
    match outcome {
        crate::CommandOutcome::Success => QualificationStatus::Passed,
        crate::CommandOutcome::TimedOut => {
            QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
                QualificationFailure::EmulatorFailed
            } else {
                QualificationFailure::SmokeTimedOut
            })
        }
        crate::CommandOutcome::OutputLimitExceeded => {
            QualificationStatus::Failed(QualificationFailure::OutputLimitExceeded)
        }
        crate::CommandOutcome::Failed(_) | crate::CommandOutcome::Cancelled => {
            QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
                QualificationFailure::EmulatorFailed
            } else {
                QualificationFailure::SmokeFailed
            })
        }
    }
}

fn validate_runtime(runtime: &QualificationRuntime) -> Result<(), QualificationError> {
    if let Some(sysroot) = &runtime.qemu_sysroot {
        if !sysroot.is_absolute() {
            return Err(qerr("QEMU sysroot must be absolute"));
        }
        let metadata =
            fs::symlink_metadata(sysroot).map_err(|_| qerr("QEMU sysroot unavailable"))?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            return Err(qerr("QEMU sysroot must be a regular directory"));
        }
    }
    Ok(())
}

fn qualification_cwd(candidate: &CandidateArtifact) -> Result<PathBuf, QualificationError> {
    let root = candidate
        .path
        .parent()
        .and_then(Path::parent)
        .ok_or_else(|| qerr("candidate qualification directory unavailable"))?;
    fs::canonicalize(root).map_err(|_| qerr("candidate qualification directory unavailable"))
}

fn actual_host() -> Result<HostRequirement, QualificationError> {
    let os = match std::env::consts::OS {
        "linux" => HostOs::Linux,
        "macos" => HostOs::Macos,
        "windows" => HostOs::Windows,
        _ => return Err(qerr("unsupported qualification host OS")),
    };
    let arch = match std::env::consts::ARCH {
        "x86_64" => HostArch::X86_64,
        "aarch64" => HostArch::Aarch64,
        #[cfg(all(target_arch = "arm", target_feature = "v7"))]
        "arm" => HostArch::Armv7,
        _ => return Err(qerr("unsupported qualification host architecture")),
    };
    Ok(HostRequirement { os, arch })
}

fn target_matches_host(target: &str, host: HostRequirement) -> bool {
    let os = match host.os {
        HostOs::Linux => target.contains("-linux-"),
        HostOs::Macos => target.ends_with("-apple-darwin"),
        HostOs::Windows => target.contains("-windows-"),
    };
    let arch = match host.arch {
        HostArch::X86_64 => target.starts_with("x86_64-"),
        HostArch::Aarch64 => target.starts_with("aarch64-"),
        HostArch::Armv7 => target.starts_with("armv7-"),
    };
    os && arch
}

fn qemu_for_target(target: &str) -> Option<&'static str> {
    if !target.contains("-linux-") {
        return None;
    }
    match target.split('-').next()? {
        "x86_64" => Some("qemu-x86_64"),
        "aarch64" => Some("qemu-aarch64"),
        "armv7" => Some("qemu-arm"),
        _ => None,
    }
}

fn qemu_args(
    runtime: &QualificationRuntime,
    candidate: &CandidateArtifact,
    smoke: &CandidateSmokeBinding,
) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(sysroot) = runtime.qemu_sysroot.as_ref() {
        args.extend(["-L".to_owned(), sysroot.to_string_lossy().into_owned()]);
    }
    args.push(candidate.path.to_string_lossy().into_owned());
    args.extend(smoke.argv.clone());
    args
}

fn target_identity(target: &str) -> Option<(CandidateFormat, CandidateArchitecture)> {
    let format = if target.contains("-linux-") {
        CandidateFormat::Elf
    } else if target.ends_with("-apple-darwin") {
        CandidateFormat::MachO
    } else if target.contains("-windows-") {
        CandidateFormat::PeCoff
    } else {
        return None;
    };
    let architecture = if target.starts_with("x86_64-") {
        CandidateArchitecture::X86_64
    } else if target.starts_with("aarch64-") {
        CandidateArchitecture::Aarch64
    } else if target.starts_with("armv7-") {
        CandidateArchitecture::Armv7
    } else {
        return None;
    };
    if architecture == CandidateArchitecture::Armv7 && format != CandidateFormat::Elf {
        return None;
    }
    Some((format, architecture))
}

/// One inspected candidate: its byte and structural identity, plus the floor
/// status computed from the same bytes.
#[derive(Debug, PartialEq, Eq)]
struct CandidateInspection {
    /// Byte and structural identity of the candidate.
    evidence: QualifiedCandidateEvidence,
    /// Verification status of the declared compatibility floor.
    floor: FloorVerificationStatus,
}

fn inspect_candidate(
    candidate: &CandidateArtifact,
    target: &PlannedTarget,
) -> Result<CandidateInspection, QualificationFailure> {
    let metadata = fs::symlink_metadata(&candidate.path)
        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
    if !candidate.path.is_absolute()
        || metadata.file_type().is_symlink()
        || !metadata.is_file()
        || metadata.len() == 0
    {
        return Err(QualificationFailure::InvalidRuntimeEnvironment);
    }
    if metadata.len() != candidate.size {
        return Err(QualificationFailure::CandidateChanged);
    }
    let canonical = fs::canonicalize(&candidate.path)
        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
    let target_dir = candidate
        .path
        .parent()
        .and_then(Path::parent)
        .ok_or(QualificationFailure::InvalidRuntimeEnvironment)?;
    let release_dir = candidate
        .path
        .parent()
        .ok_or(QualificationFailure::InvalidRuntimeEnvironment)?;
    for directory in [target_dir, release_dir] {
        let parent = fs::symlink_metadata(directory)
            .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
        if parent.file_type().is_symlink() || !parent.is_dir() {
            return Err(QualificationFailure::InvalidRuntimeEnvironment);
        }
    }
    let canonical_root = fs::canonicalize(target_dir)
        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
    if !canonical.starts_with(canonical_root) {
        return Err(QualificationFailure::InvalidRuntimeEnvironment);
    }
    let (expected_format, expected_arch) =
        target_identity(&target.target).ok_or(QualificationFailure::StructuralMismatch)?;
    let format_arch = parse_binary_header(&canonical, expected_format)
        .ok_or(QualificationFailure::StructuralMismatch)?;
    if format_arch != (expected_format, expected_arch) {
        return Err(QualificationFailure::StructuralMismatch);
    }
    // The declared floor is inspected against these exact bytes, never
    // against a smoke run: native execution is not floor proof (ADR-0005 §9).
    // The status therefore describes the same bytes the digest below records.
    let floor = crate::floor::inspect_candidate_floor(
        &canonical,
        &target.policy.floor,
        target.policy.strategy,
    );
    // The candidate bytes are digested by the crate's single file-digest
    // authority, so qualification evidence and the release manifest describe
    // the same bytes under the same rules.
    let (size, sha256) = file_digest(&canonical).map_err(|error| match error {
        DigestError::ChangedDuringRead => QualificationFailure::CandidateChanged,
        _ => QualificationFailure::InvalidRuntimeEnvironment,
    })?;
    let after = fs::symlink_metadata(&candidate.path)
        .map_err(|_| QualificationFailure::CandidateChanged)?;
    if size != metadata.len()
        || after.file_type().is_symlink()
        || !after.is_file()
        || after.len() != size
        || fs::canonicalize(&candidate.path).ok().as_ref() != Some(&canonical)
    {
        return Err(QualificationFailure::CandidateChanged);
    }
    Ok(CandidateInspection {
        evidence: QualifiedCandidateEvidence {
            selector: candidate.selector.clone(),
            package: candidate.package.clone(),
            binary: candidate.binary.clone(),
            size,
            sha256,
            format: expected_format,
            architecture: expected_arch,
        },
        floor,
    })
}

fn parse_binary_header(
    path: &Path,
    format: CandidateFormat,
) -> Option<(CandidateFormat, CandidateArchitecture)> {
    let mut file = File::open(path).ok()?;
    let length = file.metadata().ok()?.len();
    match format {
        CandidateFormat::Elf => {
            let mut header = [0u8; 20];
            file.read_exact(&mut header).ok()?;
            if &header[..4] != b"\x7fELF" || header[5] != 1 {
                return None;
            }
            let architecture = match u16::from_le_bytes([header[18], header[19]]) {
                62 if header[4] == 2 => CandidateArchitecture::X86_64,
                183 if header[4] == 2 => CandidateArchitecture::Aarch64,
                40 if header[4] == 1 => CandidateArchitecture::Armv7,
                _ => return None,
            };
            Some((CandidateFormat::Elf, architecture))
        }
        CandidateFormat::PeCoff => {
            let mut dos = [0u8; 64];
            file.read_exact(&mut dos).ok()?;
            if &dos[..2] != b"MZ" {
                return None;
            }
            let offset = u32::from_le_bytes(dos[60..64].try_into().ok()?) as u64;
            if !(64..=MAX_BINARY_HEADER).contains(&offset) || offset.checked_add(6)? > length {
                return None;
            }
            file.seek(SeekFrom::Start(offset)).ok()?;
            let mut header = [0u8; 6];
            file.read_exact(&mut header).ok()?;
            if &header[..4] != b"PE\0\0" {
                return None;
            }
            let architecture = match u16::from_le_bytes([header[4], header[5]]) {
                0x8664 => CandidateArchitecture::X86_64,
                0xAA64 => CandidateArchitecture::Aarch64,
                0x01c4 => CandidateArchitecture::Armv7,
                _ => return None,
            };
            Some((CandidateFormat::PeCoff, architecture))
        }
        CandidateFormat::MachO => {
            let mut header = [0u8; 8];
            file.read_exact(&mut header).ok()?;
            let endian = match &header[..4] {
                [0xfe, 0xed, 0xfa, 0xcf] => false,
                [0xcf, 0xfa, 0xed, 0xfe] => true,
                _ => return None,
            };
            let cpu = if endian {
                u32::from_le_bytes(header[4..8].try_into().ok()?)
            } else {
                u32::from_be_bytes(header[4..8].try_into().ok()?)
            };
            let architecture = match cpu {
                0x01000007 => CandidateArchitecture::X86_64,
                0x0100000c => CandidateArchitecture::Aarch64,
                _ => return None,
            };
            Some((CandidateFormat::MachO, architecture))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        BuildAttempt, BuildBindingsV1, BuildStrategy, CandidateArtifact, CommandOutcome,
        LogicalOutputSelector, PlannedAssetForm, PlannedTarget, ProcessEvidence, TargetPolicy,
        ToolchainRequirement,
    };
    use eggpack_contract::DistributionContract;

    fn local_host() -> HostRequirement {
        let os = match std::env::consts::OS {
            "linux" => HostOs::Linux,
            "macos" => HostOs::Macos,
            "windows" => HostOs::Windows,
            _ => panic!("unsupported test host"),
        };
        let arch = match std::env::consts::ARCH {
            "x86_64" => HostArch::X86_64,
            "aarch64" => HostArch::Aarch64,
            "arm" => HostArch::Armv7,
            _ => panic!("unsupported test architecture"),
        };
        HostRequirement { os, arch }
    }

    fn local_target() -> &'static str {
        match (std::env::consts::OS, std::env::consts::ARCH) {
            ("linux", "x86_64") => "x86_64-unknown-linux-gnu",
            ("linux", "aarch64") => "aarch64-unknown-linux-gnu",
            ("linux", "arm") => "armv7-unknown-linux-gnueabihf",
            ("macos", "x86_64") => "x86_64-apple-darwin",
            ("macos", "aarch64") => "aarch64-apple-darwin",
            ("windows", "x86_64") => "x86_64-pc-windows-msvc",
            ("windows", "aarch64") => "aarch64-pc-windows-msvc",
            _ => panic!("unsupported test target"),
        }
    }

    fn contract(target: &str) -> DistributionContract {
        DistributionContract::parse_toml_str(&format!(
            "schema_version = 1\n[product]\nid = \"fixture\"\ndisplay_name = \"fixture\"\n[[targets]]\ntriple = \"{target}\"\naliases = []\n[targets.asset]\nkind = \"direct\"\nasset = \"{{product}}-{{version}}-{{target}}\"\ninstall = \"fixture\"\n[targets.checksum]\nsidecar = \"{{asset}}.sha256\"\n"
        ))
        .unwrap()
    }

    fn candidate_path(root: &Path, target: &str) -> PathBuf {
        let mut path = root.join(target).join("release").join("fixture");
        if target.contains("windows") {
            path.set_extension("exe");
        }
        path
    }

    fn fixture(
        classification: Qualification,
        candidate_bytes: &[u8],
    ) -> (
        DistributionContract,
        ReleasePlan,
        PlannedTarget,
        BuildAttempt,
        BuildBindingsV1,
        QualificationBindingsV1,
        PathBuf,
    ) {
        let target_name = local_target();
        let root = crate::test_temp_dir("qualification");
        let path = candidate_path(&root, target_name);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, candidate_bytes).unwrap();
        let host = local_host();
        let target = PlannedTarget {
            target: target_name.into(),
            policy: TargetPolicy {
                target: target_name.into(),
                strategy: BuildStrategy::NativeCargo,
                host_os: host.os,
                host_arch: host.arch,
                qualification_host: Some(host),
                toolchain: ToolchainRequirement {
                    rust: "stable".into(),
                    cargo_zigbuild: None,
                    zig: None,
                },
                floor: crate::CompatibilityFloor::None,
                qualification: classification,
                support: SupportTier::Required,
            },
            artifact_form: PlannedAssetForm::Direct,
            floor_status: crate::FloorVerificationStatus::NotDeclared,
        };
        let plan = ReleasePlan {
            schema_version: 1,
            release_id: "v1".into(),
            source_revision: "abc123".into(),
            targets: vec![target.clone()],
        };
        let build_bindings = BuildBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                vec![crate::BuildBinding {
                    selector: LogicalOutputSelector::Direct,
                    package: "fixture".into(),
                    binary: "fixture".into(),
                }],
            )]
            .into_iter()
            .collect(),
        };
        let qualification_bindings = QualificationBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                TargetQualificationBinding {
                    smoke: matches!(
                        classification,
                        Qualification::Native
                            | Qualification::DeferredNative
                            | Qualification::Emulated
                    )
                    .then(|| CandidateSmokeBinding {
                        selector: LogicalOutputSelector::Direct,
                        argv: vec![],
                        timeout_ms: 5000,
                        stdout_limit: 4096,
                        stderr_limit: 4096,
                    }),
                },
            )]
            .into_iter()
            .collect(),
        };
        let attempt = BuildAttempt {
            release_id: plan.release_id.clone(),
            source_revision: plan.source_revision.clone(),
            target: target_name.into(),
            strategy: BuildStrategy::NativeCargo,
            tool_summary: "rust stable".into(),
            process: ProcessEvidence {
                outcome: CommandOutcome::Success,
                stdout_bytes: 0,
                stderr_bytes: 0,
            },
            candidates: vec![CandidateArtifact {
                target: target_name.into(),
                selector: LogicalOutputSelector::Direct,
                package: "fixture".into(),
                binary: "fixture".into(),
                path,
                size: candidate_bytes.len() as u64,
            }],
        };
        (
            contract(target_name),
            plan,
            target,
            attempt,
            build_bindings,
            qualification_bindings,
            root,
        )
    }

    fn elf(architecture: CandidateArchitecture) -> Vec<u8> {
        let mut bytes = vec![0u8; 64];
        bytes[..4].copy_from_slice(b"\x7fELF");
        bytes[5] = 1;
        let (class, machine) = match architecture {
            CandidateArchitecture::X86_64 => (2, 62u16),
            CandidateArchitecture::Aarch64 => (2, 183),
            CandidateArchitecture::Armv7 => (1, 40),
        };
        bytes[4] = class;
        bytes[18..20].copy_from_slice(&machine.to_le_bytes());
        bytes
    }

    fn pe(architecture: CandidateArchitecture) -> Vec<u8> {
        let mut bytes = vec![0u8; 128 + 6];
        bytes[..2].copy_from_slice(b"MZ");
        bytes[60..64].copy_from_slice(&128u32.to_le_bytes());
        bytes[128..132].copy_from_slice(b"PE\0\0");
        let machine = match architecture {
            CandidateArchitecture::X86_64 => 0x8664u16,
            CandidateArchitecture::Aarch64 => 0xAA64,
            CandidateArchitecture::Armv7 => 0x01c4,
        };
        bytes[132..134].copy_from_slice(&machine.to_le_bytes());
        bytes
    }

    fn macho(architecture: CandidateArchitecture) -> Vec<u8> {
        let mut bytes = vec![0u8; 32];
        bytes[..4].copy_from_slice(&[0xcf, 0xfa, 0xed, 0xfe]);
        let cpu = match architecture {
            CandidateArchitecture::X86_64 => 0x01000007u32,
            CandidateArchitecture::Aarch64 => 0x0100000c,
            CandidateArchitecture::Armv7 => 12,
        };
        bytes[4..8].copy_from_slice(&cpu.to_le_bytes());
        bytes
    }

    #[test]
    fn structural_headers_cover_elf_pe_and_thin_macho_targets() {
        for arch in [
            CandidateArchitecture::X86_64,
            CandidateArchitecture::Aarch64,
            CandidateArchitecture::Armv7,
        ] {
            assert_header(
                &elf(arch),
                CandidateFormat::Elf,
                Some((CandidateFormat::Elf, arch)),
            );
            assert_header(
                &pe(arch),
                CandidateFormat::PeCoff,
                Some((CandidateFormat::PeCoff, arch)),
            );
        }
        for arch in [
            CandidateArchitecture::X86_64,
            CandidateArchitecture::Aarch64,
        ] {
            assert_header(
                &macho(arch),
                CandidateFormat::MachO,
                Some((CandidateFormat::MachO, arch)),
            );
        }
        assert_header(b"bad", CandidateFormat::Elf, None);
        let mut fat = macho(CandidateArchitecture::X86_64);
        fat[..4].copy_from_slice(&[0xca, 0xfe, 0xba, 0xbe]);
        assert_header(&fat, CandidateFormat::MachO, None);
        let mut bad_pe = pe(CandidateArchitecture::X86_64);
        bad_pe[60..64].copy_from_slice(&u32::MAX.to_le_bytes());
        assert_header(&bad_pe, CandidateFormat::PeCoff, None);
        assert_eq!(
            qemu_for_target("x86_64-unknown-linux-gnu"),
            Some("qemu-x86_64")
        );
        assert_eq!(
            qemu_for_target("aarch64-unknown-linux-gnu"),
            Some("qemu-aarch64")
        );
        assert_eq!(
            qemu_for_target("armv7-unknown-linux-gnueabihf"),
            Some("qemu-arm")
        );
        assert_eq!(qemu_for_target("x86_64-pc-windows-msvc"), None);
    }

    fn assert_header(
        bytes: &[u8],
        format: CandidateFormat,
        expected: Option<(CandidateFormat, CandidateArchitecture)>,
    ) {
        let root = crate::test_temp_dir("header");
        let path = root.join("header");
        fs::write(&path, bytes).unwrap();
        assert_eq!(parse_binary_header(&path, format), expected);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn structural_classification_passes_without_execution() {
        let host = local_host();
        let target_name = local_target();
        let bytes = match target_identity(target_name).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (contract, plan, target, attempt, builds, quals, root) =
            fixture(Qualification::Structural, &bytes);
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert_eq!(evidence.method, QualificationMethod::Structural);
        assert!(evidence.processes.is_empty());
        assert_eq!(evidence.candidates[0].sha256.len(), 64);
        fs::remove_dir_all(root).unwrap();
    }

    impl From<HostArch> for CandidateArchitecture {
        fn from(value: HostArch) -> Self {
            match value {
                HostArch::X86_64 => Self::X86_64,
                HostArch::Aarch64 => Self::Aarch64,
                HostArch::Armv7 => Self::Armv7,
            }
        }
    }

    #[test]
    fn build_and_qualification_release_identity_mismatch_is_rejected() {
        let host = local_host();
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (contract, plan, target, mut attempt, builds, quals, root) =
            fixture(Qualification::Structural, &bytes);
        attempt.source_revision = "other".into();
        assert!(qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host
        )
        .is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn deferred_native_stays_pending_off_the_required_host() {
        let host = local_host();
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (contract, plan, mut target, attempt, builds, quals, root) =
            fixture(Qualification::DeferredNative, &bytes);
        let other = HostRequirement {
            os: if host.os == HostOs::Linux {
                HostOs::Macos
            } else {
                HostOs::Linux
            },
            arch: host.arch,
        };
        target.policy.qualification_host = Some(other);
        let plan = ReleasePlan {
            targets: vec![target.clone()],
            ..plan
        };
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(evidence.status, QualificationStatus::Deferred);
        assert!(evidence.processes.is_empty());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn qualification_bindings_are_strict_and_smoke_selector_is_exact() {
        let good = r#"schema_version = 1
[targets."x86_64-unknown-linux-gnu".smoke]
selector = { kind = "direct" }
argv = []
timeout_ms = 5000
stdout_limit = 1024
stderr_limit = 1024
"#;
        assert!(QualificationBindingsV1::from_toml(good).is_ok());
        assert!(QualificationBindingsV1::from_toml(
            &good.replace("schema_version = 1", "schema_version = 2")
        )
        .is_err());
        assert!(QualificationBindingsV1::from_toml(
            &good.replace("selector =", "extra = 1\nselector =")
        )
        .is_err());
    }

    #[test]
    fn classification_requires_the_exact_smoke_and_host_configuration() {
        let bytes = elf(CandidateArchitecture::X86_64);
        let (_contract, plan, target, _attempt, builds, mut quals, root) =
            fixture(Qualification::Native, &bytes);
        quals.targets.get_mut(&target.target).unwrap().smoke = None;
        assert!(quals.validate_for(&plan, &builds).is_err());
        fs::remove_dir_all(root).unwrap();

        let (contract, plan, target, attempt, builds, _quals, root) =
            fixture(Qualification::Structural, &bytes);
        let structural = QualificationBindingsV1 {
            schema_version: 1,
            targets: [(
                target.target.clone(),
                TargetQualificationBinding {
                    smoke: Some(CandidateSmokeBinding {
                        selector: LogicalOutputSelector::Direct,
                        argv: vec![],
                        timeout_ms: 1000,
                        stdout_limit: 1024,
                        stderr_limit: 1024,
                    }),
                },
            )]
            .into_iter()
            .collect(),
        };
        assert!(structural.validate_for(&plan, &builds).is_err());
        assert!(qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &structural,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            local_host(),
        )
        .is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn native_smoke_executes_the_exact_candidate_on_a_matching_host() {
        let host = local_host();
        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
        let (contract, plan, target, mut attempt, builds, mut quals, root) =
            fixture(Qualification::Native, &bytes);
        fs::copy(
            std::env::current_exe().unwrap(),
            &attempt.candidates[0].path,
        )
        .unwrap();
        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
        let smoke = quals
            .targets
            .get_mut(&target.target)
            .unwrap()
            .smoke
            .as_mut()
            .unwrap();
        smoke.argv = vec![
            "--exact".into(),
            "qualification::tests::qualification_child_target".into(),
            "--ignored".into(),
            "--nocapture".into(),
        ];
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert_eq!(evidence.method, QualificationMethod::Native);
        assert_eq!(
            evidence.processes[0].process.outcome,
            CommandOutcome::Success
        );
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        let json = serde_json::to_string(&evidence).unwrap();
        assert!(!json.contains(&attempt.candidates[0].path.to_string_lossy().to_string()));
        assert_eq!(json, serde_json::to_string(&evidence).unwrap());
        fs::remove_dir_all(root).unwrap();
    }

    /// Same executable candidate as `fixture`, but declared as the product of
    /// the cross-tool builder with an explicit compatibility floor. Cross tools
    /// change how bytes are produced, not which bytes are qualified.
    fn cross_tool_fixture(
        classification: Qualification,
        candidate_bytes: &[u8],
    ) -> (
        DistributionContract,
        ReleasePlan,
        PlannedTarget,
        BuildAttempt,
        BuildBindingsV1,
        QualificationBindingsV1,
        PathBuf,
    ) {
        let (contract, plan, mut target, mut attempt, builds, quals, root) =
            fixture(classification, candidate_bytes);
        target.policy.strategy = BuildStrategy::CargoZigbuild;
        target.policy.toolchain = ToolchainRequirement {
            rust: "1.89.0".into(),
            cargo_zigbuild: Some("0.23.3".into()),
            zig: Some("0.14.1".into()),
        };
        target.policy.floor = if target.target.contains("-linux-gnu") {
            crate::CompatibilityFloor::Glibc {
                major: 2,
                minor: 17,
            }
        } else {
            crate::CompatibilityFloor::None
        };
        // The plan states the status its declaration implies.
        target.floor_status = crate::planned_floor_status(&target.policy);
        attempt.strategy = BuildStrategy::CargoZigbuild;
        attempt.tool_summary = "rust 1.89.0 cargo-zigbuild 0.23.3 zig 0.14.1".into();
        let plan = ReleasePlan {
            targets: vec![target.clone()],
            ..plan
        };
        (contract, plan, target, attempt, builds, quals, root)
    }

    #[test]
    fn cross_tool_built_candidate_qualifies_natively_on_the_matching_host() {
        let host = local_host();
        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
        let (contract, plan, target, mut attempt, builds, mut quals, root) =
            cross_tool_fixture(Qualification::Native, &bytes);
        fs::copy(
            std::env::current_exe().unwrap(),
            &attempt.candidates[0].path,
        )
        .unwrap();
        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
        assert_eq!(target.policy.strategy, BuildStrategy::CargoZigbuild);
        let smoke = quals
            .targets
            .get_mut(&target.target)
            .unwrap()
            .smoke
            .as_mut()
            .unwrap();
        smoke.argv = vec![
            "--exact".into(),
            "qualification::tests::qualification_child_target".into(),
            "--ignored".into(),
            "--nocapture".into(),
        ];
        // The exact cross-tool-built candidate executes natively and is recorded
        // as native qualification with executed process evidence.
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert_eq!(evidence.method, QualificationMethod::Native);
        assert_eq!(evidence.processes.len(), 1);
        assert_eq!(evidence.processes[0].purpose, "candidate_smoke");
        assert_eq!(
            evidence.processes[0].process.outcome,
            CommandOutcome::Success
        );
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        // The public entry point, using the observed local host, reaches the
        // same native result for the same cross-tool-built candidate.
        let runtime = QualificationRuntime::default();
        let cancellation = BuildCancellation::new();
        let observed = qualify_target(QualificationRequest {
            contract: &contract,
            plan: &plan,
            target: &target,
            attempt: &attempt,
            build_bindings: &builds,
            qualification_bindings: &quals,
            runtime: &runtime,
            cancellation: &cancellation,
        })
        .unwrap();
        assert_eq!(observed.status, QualificationStatus::Passed);
        assert_eq!(observed.method, QualificationMethod::Native);
        assert_eq!(observed.processes.len(), 1);
        assert_eq!(
            observed.processes[0].process.outcome,
            CommandOutcome::Success
        );
        assert_eq!(observed.actual_host, host);
        // A non-matching host is still a failed HostMismatch record, never a
        // pass and never a skip, and never an executed smoke.
        let other_arch = HostRequirement {
            os: host.os,
            arch: match host.arch {
                HostArch::X86_64 => HostArch::Aarch64,
                _ => HostArch::X86_64,
            },
        };
        let mismatched = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            other_arch,
        )
        .unwrap();
        assert_eq!(
            mismatched.status,
            QualificationStatus::Failed(QualificationFailure::HostMismatch)
        );
        assert_eq!(mismatched.method, QualificationMethod::Native);
        assert!(mismatched.processes.is_empty());
        // The failed record is itself valid evidence: it describes exactly what
        // happened on the observed host.
        assert!(mismatched.validate_for(&plan, &target, &attempt).is_ok());
        // Native qualification still requires a bounded smoke binding.
        let mut without_smoke = quals.clone();
        without_smoke.targets.get_mut(&target.target).unwrap().smoke = None;
        assert!(without_smoke.validate_for(&plan, &builds).is_err());
        assert!(qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &without_smoke,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn candidate_inventory_and_structural_architecture_must_match() {
        let host = local_host();
        let wrong_arch = match host.arch {
            HostArch::X86_64 => CandidateArchitecture::Aarch64,
            _ => CandidateArchitecture::X86_64,
        };
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(wrong_arch),
            CandidateFormat::PeCoff => pe(wrong_arch),
            CandidateFormat::MachO => macho(wrong_arch),
        };
        let (contract, plan, target, mut attempt, builds, quals, root) =
            fixture(Qualification::Structural, &bytes);
        let result = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(
            result.status,
            QualificationStatus::Failed(QualificationFailure::StructuralMismatch)
        );
        attempt.candidates.clear();
        assert!(qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn native_host_mismatch_is_a_failure_and_never_runs_smoke() {
        let host = local_host();
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (contract, plan, mut target, attempt, builds, quals, root) =
            fixture(Qualification::Native, &bytes);
        let other = HostRequirement {
            os: if host.os == HostOs::Linux {
                HostOs::Macos
            } else {
                HostOs::Linux
            },
            arch: host.arch,
        };
        target.policy.qualification_host = Some(other);
        let plan = ReleasePlan {
            targets: vec![target.clone()],
            ..plan
        };
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(
            evidence.status,
            QualificationStatus::Failed(QualificationFailure::HostMismatch)
        );
        assert!(evidence.processes.is_empty());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn deferred_native_matching_host_executes_and_wrong_host_stays_deferred() {
        let host = local_host();
        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
        let (contract, plan, mut target, mut attempt, builds, mut quals, root) =
            fixture(Qualification::DeferredNative, &bytes);
        fs::copy(
            std::env::current_exe().unwrap(),
            &attempt.candidates[0].path,
        )
        .unwrap();
        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
        let smoke = quals
            .targets
            .get_mut(&target.target)
            .unwrap()
            .smoke
            .as_mut()
            .unwrap();
        smoke.argv = vec![
            "--exact".into(),
            "qualification::tests::qualification_child_target".into(),
            "--ignored".into(),
            "--nocapture".into(),
        ];
        let other = HostRequirement {
            os: if host.os == HostOs::Linux {
                HostOs::Macos
            } else {
                HostOs::Linux
            },
            arch: host.arch,
        };
        target.policy.qualification_host = Some(other);
        let deferred_plan = ReleasePlan {
            targets: vec![target.clone()],
            ..plan.clone()
        };
        let deferred = qualify_target_for_host(
            &contract,
            &deferred_plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(deferred.status, QualificationStatus::Deferred);
        assert!(deferred.processes.is_empty());

        target.policy.qualification_host = Some(host);
        let matching_plan = ReleasePlan {
            targets: vec![target.clone()],
            ..plan
        };
        let passed = qualify_target_for_host(
            &contract,
            &matching_plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert_eq!(passed.status, QualificationStatus::Passed);
        assert_eq!(
            passed.method,
            QualificationMethod::DeferredNativeOnNativeHost
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn qemu_command_mapping_is_fixed_and_uses_only_the_declared_sysroot() {
        let sysroot = PathBuf::from("/fixture/sysroot");
        let runtime = QualificationRuntime {
            qemu_sysroot: Some(sysroot),
        };
        let candidate = CandidateArtifact {
            target: "x86_64-unknown-linux-gnu".into(),
            selector: LogicalOutputSelector::Direct,
            package: "fixture".into(),
            binary: "fixture".into(),
            path: PathBuf::from("/private/candidate"),
            size: 1,
        };
        let smoke = CandidateSmokeBinding {
            selector: LogicalOutputSelector::Direct,
            argv: vec!["--smoke".into()],
            timeout_ms: 1000,
            stdout_limit: 1024,
            stderr_limit: 1024,
        };
        let args = qemu_args(&runtime, &candidate, &smoke);
        assert_eq!(
            qemu_for_target("x86_64-unknown-linux-gnu"),
            Some("qemu-x86_64")
        );
        assert_eq!(
            args,
            vec!["-L", "/fixture/sysroot", "/private/candidate", "--smoke"]
        );
        assert_eq!(qemu_for_target("aarch64-apple-darwin"), None);
    }

    #[test]
    fn emulated_linux_path_uses_injected_finite_qemu_runner() {
        let target_name = "x86_64-unknown-linux-gnu";
        let contract = contract(target_name);
        let host = local_host();
        let target = PlannedTarget {
            target: target_name.into(),
            policy: TargetPolicy {
                target: target_name.into(),
                strategy: BuildStrategy::CargoZigbuild,
                host_os: host.os,
                host_arch: host.arch,
                qualification_host: None,
                toolchain: ToolchainRequirement {
                    rust: "stable".into(),
                    cargo_zigbuild: Some("0.20.0".into()),
                    zig: Some("0.14.1".into()),
                },
                floor: crate::CompatibilityFloor::None,
                qualification: Qualification::Emulated,
                support: SupportTier::NonGating,
            },
            artifact_form: PlannedAssetForm::Direct,
            floor_status: crate::FloorVerificationStatus::NotDeclared,
        };
        let plan = ReleasePlan {
            schema_version: 1,
            release_id: "v2".into(),
            source_revision: "def456".into(),
            targets: vec![target.clone()],
        };
        let root = crate::test_temp_dir("qemu-fixture");
        let path = candidate_path(&root, target_name);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        let bytes = elf(CandidateArchitecture::X86_64);
        fs::write(&path, &bytes).unwrap();
        let builds = BuildBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                vec![crate::BuildBinding {
                    selector: LogicalOutputSelector::Direct,
                    package: "fixture".into(),
                    binary: "fixture".into(),
                }],
            )]
            .into_iter()
            .collect(),
        };
        let quals = QualificationBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                TargetQualificationBinding {
                    smoke: Some(CandidateSmokeBinding {
                        selector: LogicalOutputSelector::Direct,
                        argv: vec!["--smoke".into()],
                        timeout_ms: 2000,
                        stdout_limit: 1024,
                        stderr_limit: 1024,
                    }),
                },
            )]
            .into_iter()
            .collect(),
        };
        let attempt = BuildAttempt {
            release_id: plan.release_id.clone(),
            source_revision: plan.source_revision.clone(),
            target: target_name.into(),
            strategy: BuildStrategy::CargoZigbuild,
            tool_summary: "rust stable cargo-zigbuild 0.20.0".into(),
            process: ProcessEvidence {
                outcome: CommandOutcome::Success,
                stdout_bytes: 0,
                stderr_bytes: 0,
            },
            candidates: vec![CandidateArtifact {
                target: target_name.into(),
                selector: LogicalOutputSelector::Direct,
                package: "fixture".into(),
                binary: "fixture".into(),
                path: path.clone(),
                size: bytes.len() as u64,
            }],
        };
        let commands = std::sync::Mutex::new(Vec::new());
        let runner = |spec: &CommandSpec, qemu: bool| {
            assert!(qemu);
            commands.lock().unwrap().push(spec.clone());
            Ok(ProcessEvidence {
                outcome: CommandOutcome::Success,
                stdout_bytes: 10,
                stderr_bytes: 0,
            })
        };
        let evidence = qualify_target_for_host_with_runner(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
            &runner,
        )
        .unwrap();
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert_eq!(evidence.method, QualificationMethod::QemuUser);
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        let commands = commands.into_inner().unwrap();
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0].executable, "qemu-x86_64");
        assert_eq!(commands[0].args, ["--version"]);
        assert_eq!(commands[1].executable, "qemu-x86_64");
        assert_eq!(
            commands[1].args,
            vec![path.to_string_lossy().into_owned(), "--smoke".into()]
        );
        let unavailable_runner = |spec: &CommandSpec, qemu: bool| {
            assert!(qemu);
            assert_eq!(spec.args, ["--version"]);
            Ok(ProcessEvidence {
                outcome: CommandOutcome::Failed(127),
                stdout_bytes: 0,
                stderr_bytes: 0,
            })
        };
        let unavailable = qualify_target_for_host_with_runner(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
            &unavailable_runner,
        )
        .unwrap();
        assert_eq!(
            unavailable.status,
            QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable)
        );
        assert_eq!(unavailable.processes.len(), 1);
        assert_eq!(unavailable.processes[0].purpose, "qemu_preflight");
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn qualification_evidence_validation_reconciles_plan_and_candidates() {
        let host = local_host();
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (contract, plan, target, attempt, builds, quals, root) =
            fixture(Qualification::Structural, &bytes);
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            host,
        )
        .unwrap();
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        let json = serde_json::to_string(&evidence).unwrap();
        let roundtrip: QualificationEvidence = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtrip, evidence);
        assert!(roundtrip.validate_for(&plan, &target, &attempt).is_ok());
        let mut corrupted = roundtrip;
        corrupted.release_id = "other-release".into();
        assert!(corrupted.validate_for(&plan, &target, &attempt).is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn candidate_digest_changes_when_same_size_bytes_change() {
        let host = local_host();
        let bytes = match target_identity(local_target()).unwrap().0 {
            CandidateFormat::Elf => elf(host.arch.into()),
            CandidateFormat::PeCoff => pe(host.arch.into()),
            CandidateFormat::MachO => macho(host.arch.into()),
        };
        let (_contract, _plan, target, attempt, _builds, _quals, root) =
            fixture(Qualification::Structural, &bytes);
        let before = inspect_candidate(&attempt.candidates[0], &target).unwrap();
        let mut changed = bytes.clone();
        // Keep the structural header intact on all host formats. The final
        // byte in the minimal PE fixture is part of its COFF machine field.
        changed[20] ^= 1;
        fs::write(&attempt.candidates[0].path, &changed).unwrap();
        let after = inspect_candidate(&attempt.candidates[0], &target).unwrap();
        assert_eq!(before.evidence.size, after.evidence.size);
        assert_ne!(before.evidence.sha256, after.evidence.sha256);
        fs::remove_dir_all(root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn candidate_symlink_and_relative_paths_are_rejected() {
        use std::os::unix::fs::symlink;

        let host = local_host();
        let bytes = elf(host.arch.into());
        let (_contract, _plan, target, mut attempt, _builds, _quals, root) =
            fixture(Qualification::Structural, &bytes);
        let candidate = &mut attempt.candidates[0];
        let original = candidate.path.with_extension("original");
        fs::rename(&candidate.path, &original).unwrap();
        symlink(&original, &candidate.path).unwrap();
        assert_eq!(
            inspect_candidate(candidate, &target),
            Err(QualificationFailure::InvalidRuntimeEnvironment)
        );
        fs::remove_file(&candidate.path).unwrap();
        fs::rename(original, &candidate.path).unwrap();
        candidate.path = PathBuf::from("relative-candidate");
        assert_eq!(
            inspect_candidate(candidate, &target),
            Err(QualificationFailure::InvalidRuntimeEnvironment)
        );
        fs::remove_dir_all(root).unwrap();
    }

    // Not standalone coverage: these four are the child process fixtures that
    // `run_native_child` re-executes in this test binary to exercise the
    // bounded runner. `#[ignore]` keeps a normal `cargo test` run from hanging
    // for 30s, flooding output, or exiting the harness nonzero; each is
    // invoked deliberately, and only through that helper.
    #[test]
    #[ignore]
    fn qualification_child_target() {}

    /// Child fixture: outruns the caller's timeout to prove process-group kill.
    #[test]
    #[ignore]
    fn qualification_child_sleep() {
        std::thread::sleep(Duration::from_secs(30));
    }

    /// Child fixture: overruns the retained-output bound.
    #[test]
    #[ignore]
    fn qualification_child_output() {
        print!("{}", "x".repeat(16 * 1024));
    }

    /// Child fixture: exits nonzero to prove nonzero classification.
    #[test]
    #[ignore]
    fn qualification_child_nonzero() {
        std::process::exit(7);
    }

    fn run_native_child(
        child: &str,
        timeout_ms: u64,
        stdout_limit: usize,
        cancel_after: Option<Duration>,
    ) -> QualificationEvidence {
        let host = local_host();
        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
        let (contract, plan, target, mut attempt, builds, mut quals, root) =
            fixture(Qualification::Native, &bytes);
        fs::copy(
            std::env::current_exe().unwrap(),
            &attempt.candidates[0].path,
        )
        .unwrap();
        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
        let smoke = quals
            .targets
            .get_mut(&target.target)
            .unwrap()
            .smoke
            .as_mut()
            .unwrap();
        smoke.argv = vec![
            "--exact".into(),
            format!("qualification::tests::{child}"),
            "--ignored".into(),
            "--nocapture".into(),
        ];
        smoke.timeout_ms = timeout_ms;
        smoke.stdout_limit = stdout_limit;
        let cancellation = BuildCancellation::new();
        let cancel_thread = cancel_after.map(|delay| {
            let cancellation = cancellation.clone();
            std::thread::spawn(move || {
                std::thread::sleep(delay);
                cancellation.cancel();
            })
        });
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &cancellation,
            host,
        )
        .unwrap();
        if let Some(thread) = cancel_thread {
            thread.join().unwrap();
        }
        fs::remove_dir_all(root).unwrap();
        evidence
    }

    #[test]
    fn native_smoke_failure_timeout_cancellation_and_output_limit_are_typed() {
        let failed = run_native_child("qualification_child_nonzero", 5_000, 4096, None);
        assert_eq!(
            failed.status,
            QualificationStatus::Failed(QualificationFailure::SmokeFailed)
        );
        let timed_out = run_native_child("qualification_child_sleep", 100, 4096, None);
        assert_eq!(
            timed_out.status,
            QualificationStatus::Failed(QualificationFailure::SmokeTimedOut)
        );
        let cancelled = run_native_child(
            "qualification_child_sleep",
            5_000,
            4096,
            Some(Duration::from_millis(100)),
        );
        assert_eq!(
            cancelled.status,
            QualificationStatus::Failed(QualificationFailure::SmokeFailed)
        );
        let limited = run_native_child("qualification_child_output", 5_000, 1024, None);
        assert_eq!(
            limited.status,
            QualificationStatus::Failed(QualificationFailure::OutputLimitExceeded)
        );
    }

    #[test]
    fn structural_inspection_covers_pe_and_macho_targets_independent_of_host() {
        for (target_name, bytes, format, architecture) in [
            (
                "x86_64-pc-windows-msvc",
                pe(CandidateArchitecture::X86_64),
                CandidateFormat::PeCoff,
                CandidateArchitecture::X86_64,
            ),
            (
                "aarch64-pc-windows-msvc",
                pe(CandidateArchitecture::Aarch64),
                CandidateFormat::PeCoff,
                CandidateArchitecture::Aarch64,
            ),
            (
                "x86_64-apple-darwin",
                macho(CandidateArchitecture::X86_64),
                CandidateFormat::MachO,
                CandidateArchitecture::X86_64,
            ),
            (
                "aarch64-apple-darwin",
                macho(CandidateArchitecture::Aarch64),
                CandidateFormat::MachO,
                CandidateArchitecture::Aarch64,
            ),
        ] {
            let root = crate::test_temp_dir("cross-structure");
            let path = candidate_path(&root, target_name);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(&path, &bytes).unwrap();
            let candidate = CandidateArtifact {
                target: target_name.into(),
                selector: LogicalOutputSelector::Direct,
                package: "fixture".into(),
                binary: "fixture".into(),
                path,
                size: bytes.len() as u64,
            };
            let planned = PlannedTarget {
                target: target_name.into(),
                policy: TargetPolicy {
                    target: target_name.into(),
                    strategy: BuildStrategy::NativeCargo,
                    host_os: HostOs::Linux,
                    host_arch: HostArch::X86_64,
                    qualification_host: None,
                    toolchain: ToolchainRequirement {
                        rust: "stable".into(),
                        cargo_zigbuild: None,
                        zig: None,
                    },
                    floor: crate::CompatibilityFloor::None,
                    qualification: Qualification::Structural,
                    support: SupportTier::Required,
                },
                artifact_form: PlannedAssetForm::Direct,
                floor_status: crate::FloorVerificationStatus::NotDeclared,
            };
            let inspection = inspect_candidate(&candidate, &planned).unwrap();
            assert_eq!(inspection.evidence.format, format);
            assert_eq!(inspection.evidence.architecture, architecture);
            fs::remove_dir_all(root).unwrap();
        }
    }

    #[test]
    fn structural_candidate_inventory_supports_direct_bundle_and_archive() {
        let direct = DistributionContract::parse_toml_str(include_str!(
            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
        ))
        .unwrap();
        let bundle = DistributionContract::parse_toml_str(include_str!(
            "../../eggpack-contract/tests/fixtures/codegg-bundle.toml"
        ))
        .unwrap();
        let archive = DistributionContract::parse_toml_str(include_str!(
            "../../eggpack-contract/tests/fixtures/egress-archive.toml"
        ))
        .unwrap();
        let linux = "x86_64-unknown-linux-gnu";
        for (contract, selectors, form) in [
            (
                direct,
                vec![LogicalOutputSelector::Direct],
                PlannedAssetForm::Direct,
            ),
            (
                bundle,
                (0..3)
                    .map(|index| LogicalOutputSelector::BundleEntry { index })
                    .collect(),
                PlannedAssetForm::Bundle,
            ),
            (
                archive,
                vec![
                    LogicalOutputSelector::ArchiveMember {
                        source: "egress".into(),
                    },
                    LogicalOutputSelector::ArchiveMember {
                        source: "bin/egress-helper".into(),
                    },
                ],
                PlannedAssetForm::Archive,
            ),
        ] {
            let root = crate::test_temp_dir("layout-structure");
            let host = local_host();
            let planned = PlannedTarget {
                target: linux.into(),
                policy: TargetPolicy {
                    target: linux.into(),
                    strategy: BuildStrategy::NativeCargo,
                    host_os: host.os,
                    host_arch: host.arch,
                    qualification_host: None,
                    toolchain: ToolchainRequirement {
                        rust: "stable".into(),
                        cargo_zigbuild: None,
                        zig: None,
                    },
                    floor: crate::CompatibilityFloor::None,
                    qualification: Qualification::Structural,
                    support: SupportTier::Required,
                },
                artifact_form: form,
                floor_status: crate::FloorVerificationStatus::NotDeclared,
            };
            let plan = ReleasePlan {
                schema_version: 1,
                release_id: "v1".into(),
                source_revision: "abc".into(),
                targets: vec![planned.clone()],
            };
            let mut bindings = Vec::new();
            let mut candidates = Vec::new();
            for (index, selector) in selectors.into_iter().enumerate() {
                let binary = format!("fixture-{index}");
                bindings.push(crate::BuildBinding {
                    selector: selector.clone(),
                    package: "fixture".into(),
                    binary: binary.clone(),
                });
                let path = root.join(linux).join("release").join(&binary);
                fs::create_dir_all(path.parent().unwrap()).unwrap();
                fs::write(&path, elf(CandidateArchitecture::X86_64)).unwrap();
                candidates.push(CandidateArtifact {
                    target: linux.into(),
                    selector,
                    package: "fixture".into(),
                    binary,
                    path,
                    size: 64,
                });
            }
            let builds = BuildBindingsV1 {
                schema_version: 1,
                targets: [(linux.into(), bindings)].into_iter().collect(),
            };
            let quals = QualificationBindingsV1 {
                schema_version: 1,
                targets: [(linux.into(), TargetQualificationBinding::default())]
                    .into_iter()
                    .collect(),
            };
            let attempt = BuildAttempt {
                release_id: plan.release_id.clone(),
                source_revision: plan.source_revision.clone(),
                target: linux.into(),
                strategy: BuildStrategy::NativeCargo,
                tool_summary: "rust stable".into(),
                process: ProcessEvidence {
                    outcome: CommandOutcome::Success,
                    stdout_bytes: 0,
                    stderr_bytes: 0,
                },
                candidates,
            };
            let evidence = qualify_target_for_host(
                &contract,
                &plan,
                &planned,
                &attempt,
                &builds,
                &quals,
                &QualificationRuntime::default(),
                &BuildCancellation::new(),
                host,
            )
            .unwrap();
            assert_eq!(evidence.status, QualificationStatus::Passed);
            assert_eq!(evidence.candidates.len(), builds.targets[linux].len());
            assert!(evidence.validate_for(&plan, &planned, &attempt).is_ok());
            fs::remove_dir_all(root).unwrap();
        }
    }

    /// A GNU/Linux target that declares a compatibility floor, with a
    /// candidate that carries the given symbol version requirements.
    ///
    /// The target triple is pinned rather than host-adaptive: a glibc floor
    /// only applies to a GNU/Linux triple, so the fixture must name one on
    /// every host.
    fn floor_fixture(
        candidate_bytes: &[u8],
        floor: crate::CompatibilityFloor,
    ) -> (
        DistributionContract,
        ReleasePlan,
        PlannedTarget,
        BuildAttempt,
        BuildBindingsV1,
        QualificationBindingsV1,
        PathBuf,
    ) {
        let target_name = "x86_64-unknown-linux-gnu";
        let root = crate::test_temp_dir("floor-qualification");
        let path = candidate_path(&root, target_name);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, candidate_bytes).unwrap();
        let policy = TargetPolicy {
            target: target_name.into(),
            strategy: BuildStrategy::NativeCargo,
            host_os: HostOs::Linux,
            host_arch: HostArch::X86_64,
            qualification_host: None,
            toolchain: ToolchainRequirement {
                rust: "stable".into(),
                cargo_zigbuild: None,
                zig: None,
            },
            floor,
            qualification: Qualification::Structural,
            support: SupportTier::Required,
        };
        let floor_status = crate::planned_floor_status(&policy);
        let target = PlannedTarget {
            target: target_name.into(),
            policy,
            artifact_form: PlannedAssetForm::Direct,
            floor_status,
        };
        let plan = ReleasePlan {
            schema_version: 1,
            release_id: "v1".into(),
            source_revision: "abc123".into(),
            targets: vec![target.clone()],
        };
        let build_bindings = BuildBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                vec![crate::BuildBinding {
                    selector: LogicalOutputSelector::Direct,
                    package: "fixture".into(),
                    binary: "fixture".into(),
                }],
            )]
            .into_iter()
            .collect(),
        };
        let qualification_bindings = QualificationBindingsV1 {
            schema_version: 1,
            targets: [(
                target_name.into(),
                TargetQualificationBinding { smoke: None },
            )]
            .into_iter()
            .collect(),
        };
        let attempt = BuildAttempt {
            release_id: plan.release_id.clone(),
            source_revision: plan.source_revision.clone(),
            target: target_name.into(),
            strategy: BuildStrategy::NativeCargo,
            tool_summary: "rust stable".into(),
            process: ProcessEvidence {
                outcome: CommandOutcome::Success,
                stdout_bytes: 0,
                stderr_bytes: 0,
            },
            candidates: vec![CandidateArtifact {
                target: target_name.into(),
                selector: LogicalOutputSelector::Direct,
                package: "fixture".into(),
                binary: "fixture".into(),
                path,
                size: candidate_bytes.len() as u64,
            }],
        };
        (
            contract(target_name),
            plan,
            target,
            attempt,
            build_bindings,
            qualification_bindings,
            root,
        )
    }

    fn glibc_floor(major: u16, minor: u16) -> crate::CompatibilityFloor {
        crate::CompatibilityFloor::Glibc { major, minor }
    }

    fn floor_candidate(versions: &[&str]) -> Vec<u8> {
        crate::floor::test_support::ElfBuilder::new(true, true)
            .versions(versions)
            .build()
    }

    fn qualify_floor_fixture(
        bytes: &[u8],
        floor: crate::CompatibilityFloor,
    ) -> (
        QualificationEvidence,
        ReleasePlan,
        PlannedTarget,
        BuildAttempt,
        PathBuf,
    ) {
        let (contract, plan, target, attempt, builds, quals, root) = floor_fixture(bytes, floor);
        let evidence = qualify_target_for_host(
            &contract,
            &plan,
            &target,
            &attempt,
            &builds,
            &quals,
            &QualificationRuntime::default(),
            &BuildCancellation::new(),
            local_host(),
        )
        .unwrap();
        (evidence, plan, target, attempt, root)
    }

    #[test]
    fn a_native_glibc_floor_is_verified_against_the_inspected_bytes() {
        let bytes = floor_candidate(&["GLIBC_2.17"]);
        let (evidence, plan, target, attempt, root) =
            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
        assert_eq!(evidence.floor, FloorVerificationStatus::Verified);
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_glibc_floor_contradicted_by_the_bytes_fails_the_qualification() {
        let bytes = floor_candidate(&["GLIBC_2.34"]);
        let (evidence, plan, target, attempt, root) =
            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
        // The declared floor is false, so the qualification fails closed. It is
        // never reported as merely unverified.
        assert_eq!(
            evidence.status,
            QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied)
        );
        assert_eq!(evidence.floor, FloorVerificationStatus::NotSatisfied);
        assert!(!matches!(
            evidence.floor,
            FloorVerificationStatus::Unverified(_)
        ));
        assert!(evidence.processes.is_empty());
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_candidate_without_a_version_requirement_records_that_specifically() {
        let bytes = floor_candidate(&[]);
        let (evidence, plan, target, attempt, root) =
            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
        // Compatible with any floor, but not a confirmation of one: the
        // status says so specifically and is not a generic pass.
        assert_eq!(
            evidence.floor,
            FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement)
        );
        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
        // An unverifiable floor is a recorded status, not a failed release.
        assert_eq!(evidence.status, QualificationStatus::Passed);
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_malformed_candidate_is_never_floor_verified() {
        // A well-formed ELF header with a truncated dynamic table: the
        // structural inspection still passes, the floor inspection cannot.
        let mut bytes = floor_candidate(&["GLIBC_2.17"]);
        bytes.truncate(bytes.len() - 8);
        let (evidence, plan, target, attempt, root) =
            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
        assert_eq!(
            evidence.floor,
            FloorVerificationStatus::Unverified(FloorUnverifiedReason::MalformedCandidate)
        );
        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        fs::remove_dir_all(root).unwrap();

        // A candidate that is not an ELF image at all.
        let (evidence, plan, target, attempt, root) =
            qualify_floor_fixture(b"not an elf image", glibc_floor(2, 17));
        assert_eq!(
            evidence.floor,
            FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate)
        );
        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
        assert_eq!(
            evidence.status,
            QualificationStatus::Failed(QualificationFailure::StructuralMismatch)
        );
        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_plan_that_declares_a_floor_without_a_status_is_rejected() {
        let bytes = floor_candidate(&["GLIBC_2.17"]);
        let (_contract, plan, _target, _attempt, _builds, _quals, root) =
            floor_fixture(&bytes, glibc_floor(2, 17));
        assert_eq!(
            plan.targets[0].policy.floor,
            glibc_floor(2, 17),
            "the declared floor must survive into the plan"
        );
        assert!(plan.validate().is_ok());
        // A document that omits the status is read as `NotDeclared`, which is
        // refused for a target that declares a floor.
        let mut document =
            serde_json::from_str::<serde_json::Value>(&plan.to_json().unwrap()).unwrap();
        document["targets"][0]
            .as_object_mut()
            .unwrap()
            .remove("floor_status");
        let parsed: ReleasePlan = serde_json::from_value(document).unwrap();
        assert_eq!(
            parsed.targets[0].floor_status,
            FloorVerificationStatus::NotDeclared
        );
        assert!(parsed.validate().is_err());
        assert!(parsed.to_json().is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn evidence_that_contradicts_the_plan_floor_is_rejected() {
        let bytes = floor_candidate(&["GLIBC_2.17"]);
        let (mut evidence, plan, target, attempt, root) =
            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
        // The plan declares a floor, so the evidence cannot claim that no
        // floor was declared.
        evidence.floor = FloorVerificationStatus::NotDeclared;
        assert!(evidence.validate_for(&plan, &target, &attempt).is_err());
        // A contradiction is only admissible together with the matching
        // failure, so a contradiction claimed with a passing record is
        // refused too.
        evidence.floor = FloorVerificationStatus::NotSatisfied;
        assert!(evidence.validate_for(&plan, &target, &attempt).is_err());
        fs::remove_dir_all(root).unwrap();
    }
}