hermit-run 0.5.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::hash::Hash;
use std::hash::Hasher;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use std::num::NonZeroU64;
use std::os::fd::AsRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::LazyLock;
use std::time::Duration;
use std::time::SystemTime;

use clap::Parser;

#[cfg(test)]
mod preemption_tests;
use colored::Colorize;
use detcore_model::backend_engagement::BackendEngagement;
use detcore_model::backend_engagement::BackendEngagementReport;
use detcore_model::happens_before::HappensBeforeProgram;
use detcore_model::happens_before::Strength;
use detcore_model::network_trace::NetworkTraceConfig;
use detcore_model::network_trace::NetworkTraceMode;
use detcore_model::network_trace::NetworkTraceV2;
use detcore_model::summary::RunSummary;
use hermit::Backend;
use hermit::Context;
use hermit::DetConfig;
use hermit::Error;
use hermit::Shebang;
use hermit::SkidOvershootError;
use hermit::canonical_verdict::Verdict;
use hermit::happens_before::DebugInfoResolver;
use hermit::happens_before::HbLaunch;
use hermit::happens_before::describe_anchor;
use hermit::happens_before::load_program;
use hermit::happens_before::refuse_unenforceable_anchors;
use hermit::happens_before::resolve_program;
use hermit::host_input_change::HostInputs;
use hermit::host_input_change::PatternDifference;
use hermit::host_input_change::explains_divergence;
use hermit::host_input_change::find_pattern_difference;
use hermit::host_input_change::open_position;
use hermit::host_input_change::read_host_inputs;
use reverie::process::Bind;
use reverie::process::Command;
use reverie::process::Container;
use reverie::process::ExitStatus;
use reverie::process::Mount;
use reverie::process::MountFlags;
use reverie::process::Namespace;
use reverie::process::Output;

use super::container::IdentityGuard;
use super::container::PlannedMount;
use super::container::PolicyRefusal;
use super::container::apply_affinity;
use super::container::container_proc_mount;
use super::container::identity_hardening_mounts;
use super::container::image_container;
use super::container::namespace_container;
use super::global_opts::GlobalOpts;
use super::host_capabilities::cpu_identity;
use super::host_capabilities::exact_branch_counter_verdict;
use super::host_capabilities::host_inexact_branch_counter;
use super::record_envelope::RecordEnvelope;
use super::tracing::BoundedWriter;
use super::tracing::CappedWriter;
use super::tracing::init_sync_file_tracing;
use super::tracing::log_max_bytes;
use super::verify::ComparedRun;
use super::verify::ComparisonOptions;
use super::verify::LogCompareStrictness;
use super::verify::NoResultReason;
use super::verify::SecondRun;
use super::verify::SignalTerminationReports;
use super::verify::VerificationOutcome;
use super::verify::VerificationReport;
use super::verify::VerificationRun;
use super::verify::VerificationRuntime;
use super::verify::announce_verification_outcome;
use super::verify::compare_two_runs;
use super::verify::default_failed_verify_log_retention;
use super::verify::emit_compared_guest_output;
use super::verify::publish_run_failure;
use super::verify::retain_logs_after_verification_error;
use super::verify::retain_verification_error;
use super::verify::retain_verification_logs;
use super::verify::run_verification_execution;
use super::verify::temp_log_files_in;
use super::verify::validate_log_level;
use super::verify::verification_log_level;
use super::verify::verification_runtime_from_summaries;
use super::verify::write_host_input_change_verification_json;
use super::verify::write_pending_verification_json;
use super::verify::write_report_json;
use super::verify::write_skid_overshoot_verification_json;
use super::verify::write_skid_overshoot_without_comparison_json;
use super::verify::write_verification_json;
use super::verify_run;

const TMP_DIR: &str = "/tmp";

#[cfg(feature = "native-exec")]
type NativeContainerRun = super::native_exec_cli::PhysicalContainer;
#[cfg(not(feature = "native-exec"))]
type NativeContainerRun = ();

/// Descriptor-free forwarding selection retained by the common container owner.
/// Open the one physical stream only inside that container's child.
pub(super) enum ForwardedDetlogPlan {
    None,
    Socket { opened: bool },
}

impl ForwardedDetlogPlan {
    fn requires_socket(&self) -> bool {
        matches!(self, Self::Socket { .. })
    }

    #[cfg(all(test, feature = "dbt"))]
    pub(super) fn is_none(&self) -> bool {
        !self.requires_socket()
    }

    fn open_in_container(&mut self) -> Result<Option<(OwnedFd, OwnedFd)>, Error> {
        match self {
            Self::None => Ok(None),
            Self::Socket { opened } => {
                if std::mem::replace(opened, true) {
                    return Err(Error::msg("forwarded DETLOG plan already consumed"));
                }
                RunOpts::open_forwarded_detlog_channel()
            }
        }
    }
}

/// Why this host cannot arm Reverie's ptrace PMU timer.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TimerUnavailable {
    /// `perf_event_open` cannot open a hardware counter here.
    NoPerfEvents,
    /// The counters work, but Reverie has no profile (event and skid margin)
    /// for this CPU, so it gives no task a timer.
    NoPmuProfile(String),
}

/// Whether this host can arm Reverie's ptrace PMU timer.
fn reverie_timer_support() -> Result<(), TimerUnavailable> {
    if !reverie_ptrace::is_perf_supported() {
        return Err(TimerUnavailable::NoPerfEvents);
    }
    reverie_ptrace::host_pmu_profile()
        .map_err(|error| TimerUnavailable::NoPmuProfile(error.to_string()))
}

fn warn_bind_outside_tmp(bind: &Bind) {
    crate::tracing::diagnostic_eprintln!(
        "WARNING: --bind target {} is outside guest /tmp, so this option has no \
         effect; files outside /tmp are already visible unless another mount hides them",
        bind.target.to_string_lossy()
    );
}
const FAIL_CLOSED_ENV: &str = "HERMIT_FAIL_CLOSED";
const NORMALIZED_FORWARDED_DETLOG_TIMESTAMP: &str = "1970-01-01T00:00:00.000000Z";

fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

fn read_verify_summary(path: &Path) -> Option<RunSummary> {
    match fs::read(path)
        .with_context(|| format!("reading verification run summary {}", path.display()))
        .and_then(|bytes| {
            serde_json::from_slice(&bytes)
                .with_context(|| format!("parsing verification run summary {}", path.display()))
        }) {
        Ok(summary) => Some(summary),
        Err(error) => {
            // Also runs between the two --verify runs, before run 2 can
            // cross --max-log-bytes.
            crate::tracing::diagnostic_eprintln!(
                "WARNING: verification runtime statistics unavailable: {error:#}"
            );
            None
        }
    }
}

pub(super) fn first_run_rejected_report(
    output: &Output,
    runtime: Option<VerificationRuntime>,
) -> VerificationReport {
    let mut report = VerificationReport::no_result();
    report.no_result_reason = Some(NoResultReason::FirstRunRejected {
        exit_code: output.status.code(),
        signal: output.status.signal(),
        stdout_bytes: u64::try_from(output.stdout.len()).expect("guest stdout length fits u64"),
        stderr_bytes: u64::try_from(output.stderr.len()).expect("guest stderr length fits u64"),
    });
    report.guest_exit_code = output.status.code();
    report.guest_signal = output.status.signal();
    report.runtime = runtime;
    report
}

/// Where the private run summaries below are written.
///
/// Hermit's isolated /tmp is not the host /tmp, so these cannot go to the
/// default temporary directory: they must live on a path BOTH run containers
/// can see, which is why they were written into the checkout in the first
/// place. That part of the original reasoning is correct and is preserved.
///
/// ⚠️ WHAT WAS WRONG WITH THE CHECKOUT ROOT, measured on hermit main
/// ba3bfc97671666ae946841804624e7a2c355a0e4 in validate run 1819. Prepared
/// source identity enumerates untracked, non-ignored files:
///
///     git ls-files --others --exclude-standard -z
///
/// (`ci/manifest-plan/src/nextest_binaries.rs` source_identity, and the
/// byte-identical enumeration in `ci/prepare-rust-scripts.sh` write_state).
/// A summary here IS such a file, so creating one and dropping it on the same
/// run changes the identity, and dropping it between enumeration and hashing
/// makes it vanish mid-read. Both were observed: 13 nodes refused with
/// "prepared executables are stale: source identity changed", 6 with "cannot
/// inspect prepared input <path>: No such file or directory", and one with
/// "sha256sum: .hermit-verify-summary-...: No such file or directory". That is
/// 20 of the run's 26 failed nodes, none of which had run a single test.
///
/// ⚠️ THE FIX MOVES THE FILE; IT DOES NOT EXCUSE THE NAME. Adding
/// `.hermit-verify-summary-*` to .gitignore would also satisfy the enumeration,
/// and it is the wrong repair: `scripts/validate.rs` checkout_attribution_bracket
/// exists because run 1573 leaked these same files, and its stated property is
/// "No pathname is excused". Excusing the name would hide a genuine leak
/// anywhere in the tree -- and that bracket builds its own repository under a
/// temporary directory, so it would never have read this repo's .gitignore and
/// would not have caught the weakening.
///
/// `ignored/` is the existing directory for exactly this. Its .gitignore entry
/// reads "Everything under ignored/ is disposable and must not taint source
/// provenance or the version string." Using it adds no new ignore rule, and a
/// stray summary left anywhere else is still caught -- verified both ways.
fn private_summary_dir() -> Result<PathBuf, Error> {
    summary_dir_under(&std::env::current_dir()?)
}

/// Whether `<root>/ignored` is actually excluded from source accounting there.
///
/// ⚠️ THE WALK ABOVE CANNOT JUST TRUST A `.git`, and this is measured rather
/// than hypothetical: this host has a `/tmp/.git`. Without this check a run
/// whose working directory is any temporary directory resolves its "work tree"
/// to `/tmp` and writes the summary to `/tmp/ignored` -- which is not the
/// project, and worse, is not visible to both run containers, since Hermit's
/// isolated /tmp is not the host /tmp. That is the very property the original
/// comment was protecting.
///
/// So the candidate is accepted only where the disposable directory is really
/// disposable. That also removes an assumption the tests could not see: the
/// repair depends on `ignored/` being ignored in whichever repository the file
/// lands in, and nothing previously checked it.
fn disposable_dir_is_ignored(root: &Path) -> bool {
    let Ok(text) = std::fs::read_to_string(root.join(".gitignore")) else {
        return false;
    };
    text.lines()
        .map(|line| line.split('#').next().unwrap_or_default().trim())
        .any(|rule| matches!(rule, "ignored/" | "/ignored/" | "ignored" | "/ignored"))
}

/// Resolve the summary directory for a given starting directory.
///
/// Split out from [`private_summary_dir`] for one reason: it is the only part
/// that can be tested. The reviewer of PR 3026 found that the tests shipped
/// with the first version of this change lived in `hermit-manifest-plan` and
/// never named any of these functions -- a private `src/bin` item is not
/// importable from another crate, so that whole test surface could not reach
/// the code it was written for, even in principle. Taking the directory as an
/// argument lets the unit tests below drive every branch.
fn summary_dir_under(start: &Path) -> Result<PathBuf, Error> {
    // The enumeration is rooted at the work tree, not at the process cwd, so a
    // summary in ANY tracked subdirectory still trips it. Resolve the work-tree
    // root rather than assuming this runs from it.
    let mut root = start;
    loop {
        if root.join(".git").exists() && disposable_dir_is_ignored(root) {
            let disposable = root.join("ignored");
            // ⚠️ INSIDE A WORK TREE THIS REFUSES RATHER THAN FALLING BACK.
            //
            // The first version returned `cwd` when the directory could not be
            // created, justifying it as failing soft. It is the opposite: cwd
            // inside a work tree is exactly where prepared source identity
            // enumerates, so the fallback silently restored the defect. The
            // reviewer's case is concrete -- a regular FILE named `ignored`
            // makes create_dir_all fail -- and a measurement that only checked
            // writability and directory-ness of checkouts existing at the time
            // could not have ruled it out for checkouts made later.
            //
            // A loud failure here costs one run. The silent fallback costs a
            // whole validation, which is what it already cost once.
            std::fs::create_dir_all(&disposable).with_context(|| {
                format!(
                    "creating the disposable run-summary directory {}; refusing to fall back to \
                     the work tree, where this file would be counted as prepared source",
                    disposable.display()
                )
            })?;
            return Ok(disposable);
        }
        match root.parent() {
            Some(parent) => root = parent,
            None => break,
        }
    }
    // Outside a work tree only. Nothing enumerates source here, so the previous
    // location is still correct. It is NOT necessarily visible inside the run
    // container -- a working directory under the host /tmp is hidden behind
    // the guest's private /tmp -- which is why the container reaches these
    // files only through `private_summary_descriptor_path`, never by this name.
    Ok(start.to_path_buf())
}

/// The pathname through which the run container reaches a private summary.
///
/// ⚠️ NEVER HAND THE CONTAINER `file.path()`. That name is a HOST path, and
/// the container mounts a private directory over `/tmp`, so a summary created
/// under a host working directory below `/tmp` does not exist there. Detcore's
/// end-of-run summary write then failed with NotFound and panicked as PID 1 of
/// the container, so `hermit run --verify -- /bin/true` exited 125 before run 2
/// for every caller that starts tests from a temporary directory (Buck/TPX,
/// lit): https://github.com/rrnewton/hermit/issues/3260, 221 of the fbsource
/// import's Buck/TPX failures. A git work tree under `/tmp` fails the same way,
/// through `<work tree>/ignored/`.
///
/// The controller keeps `file` open across the container fork, and a fork
/// keeps descriptor numbers, so this one spelling names the same inode in the
/// controller and in the container whatever either mount namespace hides.
/// Captured runs already hand their staged summary to the container this way
/// (`staged_summary::writer_path`). The named file and its location are
/// unchanged, so what the guest can observe is unchanged too.
fn private_summary_descriptor_path(file: &tempfile::NamedTempFile) -> PathBuf {
    descriptor_path(file.as_file())
}

/// The `/proc/self/fd` spelling of `file`, which the run container reaches
/// whatever its mount namespace hides; see [`private_summary_descriptor_path`].
fn descriptor_path(file: &fs::File) -> PathBuf {
    use std::os::fd::AsRawFd;
    PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()))
}

/// The first host-input pattern difference between the runs and where its
/// open sits in each run's log (see `hermit::host_input_change`), or `None`
/// when the runs' records show none or cannot be read.
fn place_host_input_change(
    run1: std::io::Result<HostInputs>,
    run2: std::io::Result<HostInputs>,
    logs: [&Path; 2],
) -> Option<(PatternDifference, [Option<usize>; 2])> {
    let read = |result: std::io::Result<HostInputs>| {
        result
            .inspect_err(|error| {
                eprintln!(
                    "WARNING: the runs' host-input records cannot be read, so a host file \
                     change cannot be named: {error}"
                )
            })
            .ok()
    };
    let run1 = read(run1)?;
    let run2 = read(run2)?;
    let difference = find_pattern_difference(&run1, &run2)?;
    let place = |log: &Path, label: &str| {
        fs::read(log)
            .inspect_err(|error| {
                eprintln!(
                    "WARNING: the {label} log cannot be read, so a host file change cannot be \
                     placed: {error}"
                )
            })
            .ok()
            .and_then(|bytes| {
                open_position(
                    &String::from_utf8_lossy(&bytes),
                    difference.dtid,
                    difference.syscall,
                )
            })
    };
    let positions = [place(logs[0], "run 1"), place(logs[1], "run 2")];
    Some((difference, positions))
}

/// The `--strict` refusal on a `backend` whose virtual clock is the host's
/// retired-conditional-branch counter (see
/// `RunOpts::refuse_strict_with_inexact_branch_counter`): `Ok` when
/// `inexact_branch_counter` finds the counter exact, else a `PolicyRefusal`
/// that names the backend, Reverie's reason and the CPU. `hermit run`,
/// `hermit analyze`, `hermit bisect` and `hermit record start` share it, so
/// all four refuse with the same message.
pub(crate) fn refuse_an_inexact_branch_counter(
    backend: Backend,
    inexact_branch_counter: fn() -> Option<String>,
) -> Result<(), Error> {
    let Some(reason) = inexact_branch_counter() else {
        return Ok(());
    };
    Err(Error::new(PolicyRefusal).context(format!(
        "--strict refuses the `{}` backend on this host: its retired-conditional-branch \
         counter failed Reverie's performance-counter validation ({reason}; {}). That counter \
         is the virtual clock on this backend, so two runs of one program could diverge. Run \
         on a host whose counters pass the validation, or drop --strict to run without the \
         determinism guarantee (see https://github.com/rrnewton/hermit/issues/3794).",
        backend.as_str(),
        cpu_identity()
    )))
}

/// `hermit host-capabilities`'s own `exact_branch_counter` verdict, for a
/// verification report (`VerificationReport::exact_branch_counter`).
pub(crate) fn branch_counter_verdict() -> hermit::canonical_verdict::BranchCounterVerdict {
    let verdict = exact_branch_counter_verdict();
    hermit::canonical_verdict::BranchCounterVerdict {
        present: verdict.present,
        evidence: verdict.evidence,
    }
}

/// Why a run on `backend`, with `--passthru-opt` when `passthru_opt` is set,
/// can run guest code or syscalls that Hermit does not observe, or `None` when
/// Hermit sees every syscall of every guest process from its first
/// instruction after exec. In such a run a host file change found before the
/// first divergence is not evidence that the guest did not make the change
/// itself (see `hermit::host_input_change`).
fn unobserved_guest_execution(backend: Backend, passthru_opt: bool) -> Option<&'static str> {
    if passthru_opt {
        // Detcore subscribes only to its passthrough allow-list, so the
        // guest's own rename, link and unlink calls are never reported.
        return Some(
            "--passthru-opt lets every syscall outside Detcore's allow-list, rename and link \
             among them, run unobserved",
        );
    }
    match backend {
        // These observe every syscall Detcore subscribes to, from the first
        // instruction after exec. ptrace leaves one window open by design:
        // Reverie's seccomp filter lets a syscall through untraced when it is
        // issued from the untraced stub of Reverie's private page
        // (`cp::TRAMPOLINE_BASE`, reverie-ptrace `seccomp_filter`), which
        // Reverie needs to inject syscalls. Such a syscall is invisible to
        // Detcore. The instruction after that stub is `ud2`, so a guest that
        // uses it takes a SIGILL, and Detcore then records a change it could
        // not establish, so that no host input change is named in that run
        // (detcore `handle_signal_event`). The SIGILL does not stop a
        // deliberate guest: a handler can keep the result, or a forked child
        // can die of it and leave its effect behind, so determinism is lost
        // with no race needed (https://github.com/rrnewton/reverie/issues/1064).
        // A guest that rewrites or replaces the page to avoid the fault is
        // recorded the same way when it does so (`untraced_code_range`). See
        // docs/DIVERGENCE_CLASSES.md.
        Backend::Ptrace | Backend::E9patch | Backend::Kvm => None,
        Backend::Sabre => Some(
            "SaBRe's loader runs an exec'd program's .preinit_array before Detcore starts \
             and forwards those syscalls unobserved",
        ),
        Backend::Liteinst | Backend::InGuestTrap => {
            Some("in-guest LiteInst's preload starts after an exec'd program's .preinit_array runs")
        }
        Backend::Dbt => Some("DBT's launcher does not collect host inputs"),
    }
}

/// Reverie ptrace's private page, `[start, end)`, which Reverie maps in every
/// guest process (reverie-ptrace `cp::PRIVATE_PAGE_OFFSET` and
/// `cp::PRIVATE_PAGE_SIZE`, which that crate keeps private). It holds the
/// untraced stub described in [`unobserved_guest_execution`]. The cli test
/// `reverie_private_page_is_the_range_hermit_guards` pins it against a
/// guest's own memory map.
const REVERIE_PTRACE_PRIVATE_PAGE: (u64, u64) = (0x7100_0000, 0x7100_1000);

/// The guest code that makes syscalls `backend` lets through untraced
/// (`DetConfig::untraced_code_range`), which Detcore guards in a run that
/// records host inputs: Reverie's private page on the ptrace runtime, and
/// none elsewhere. KVM traps every syscall, and the other backends never
/// name a host input change ([`unobserved_guest_execution`]).
fn untraced_code_range(backend: Backend) -> Option<(u64, u64)> {
    match backend {
        Backend::Ptrace | Backend::E9patch => Some(REVERIE_PTRACE_PRIVATE_PAGE),
        Backend::Kvm | Backend::Sabre | Backend::Liteinst | Backend::InGuestTrap | Backend::Dbt => {
            None
        }
    }
}

fn private_verify_summary() -> Result<tempfile::NamedTempFile, Error> {
    tempfile::Builder::new()
        .prefix(".hermit-verify-summary-")
        // See private_summary_dir: visible to both run containers, and outside
        // prepared source identity. Removed on drop.
        .tempfile_in(private_summary_dir()?)
        .context("creating private verification run summary")
}

fn private_backend_engagement_summary() -> Result<tempfile::NamedTempFile, Error> {
    tempfile::Builder::new()
        .prefix(".hermit-backend-engagement-summary-")
        // See private_summary_dir: visible to the run container, and outside
        // prepared source identity. Removed on drop.
        .tempfile_in(private_summary_dir()?)
        .context("creating private backend-engagement run summary")
}

fn clear_machine_record(path: &Path, description: &str) -> Result<(), Error> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error)
            .with_context(|| format!("clearing stale {description} record {}", path.display())),
    }
}

fn write_backend_engagement(path: &Path, engagement: BackendEngagement) -> Result<(), Error> {
    let report = BackendEngagementReport::new(engagement);
    report.validate().map_err(Error::msg)?;
    let mut bytes = serde_json::to_vec(&report)?;
    bytes.push(b'\n');
    fs::write(path, bytes)
        .with_context(|| format!("writing backend engagement record {}", path.display()))
}

fn take_verify_summary_before_next_run(path: &Path) -> Result<Option<RunSummary>, Error> {
    let summary = read_verify_summary(path);
    fs::write(path, b"").with_context(|| {
        format!(
            "resetting private verification run summary {} before run 2",
            path.display()
        )
    })?;
    Ok(summary)
}

/// Moves the DETLOG records an in-guest Tool forwarded into the run's log at
/// `path`, under the log's size bound `limit` (`0`: unbounded), and returns how
/// many are syscall records. `stream` is what carried them: the guest's standard
/// error for SaBRe's plugin (`records_only` false), or, for in-guest LiteInst,
/// a socket that carries nothing but records (`records_only` true). On return
/// `stream` holds every line that was not a record.
///
/// A record is a line whose text, after leading whitespace, starts with
/// `INFO detcore` and contains ` DETLOG ` (`detcore::detlog::forwarded_line`).
/// From the guest's standard error every other line stays exactly as the guest
/// wrote it. A records-only stream must hold nothing else: a
/// `detcore::detlog::FORWARDING_LOSS_NOTICE` (a record the Tool could not send)
/// or any other line is an error, so verification reports no result instead of
/// comparing incomplete records.
///
/// The records are appended through the same bound as the log itself, counting
/// the bytes already in it, and never after an existing truncation marker: the
/// comparators recognize a truncated log only by that marker on the log's last
/// line, and a log whose observations were cut must compare as no result.
fn extract_forwarded_detlogs(
    path: &Path,
    stream: &mut Vec<u8>,
    limit: u64,
    records_only: bool,
) -> Result<usize, Error> {
    let mut kept = Vec::with_capacity(stream.len());
    let mut records = Vec::new();
    let mut syscall_records = 0;
    for line in stream.split_inclusive(|byte| *byte == b'\n') {
        let start = line
            .iter()
            .position(|byte| !byte.is_ascii_whitespace())
            .unwrap_or(line.len());
        let payload = line[start..].strip_suffix(b"\n").unwrap_or(&line[start..]);
        let payload = payload.strip_suffix(b"\r").unwrap_or(payload);
        if payload.starts_with(b"INFO detcore") && find_bytes(payload, b" DETLOG ").is_some() {
            records.extend_from_slice(NORMALIZED_FORWARDED_DETLOG_TIMESTAMP.as_bytes());
            records.push(b' ');
            records.extend_from_slice(payload);
            records.push(b'\n');
            syscall_records += usize::from(find_bytes(payload, b"DETLOG [syscall]").is_some());
        } else {
            kept.extend_from_slice(line);
        }
    }
    if records_only && !kept.is_empty() {
        let lost = kept
            .split(|byte| *byte == b'\n')
            .filter(|line| line.starts_with(detcore::detlog::FORWARDING_LOSS_NOTICE.as_bytes()))
            .count();
        if lost > 0 {
            anyhow::bail!(
                "the in-guest Tool could not forward {lost} DETLOG record(s) (it sent {} instead), \
                 so the compared records would be incomplete",
                detcore::detlog::FORWARDING_LOSS_NOTICE
            );
        }
        anyhow::bail!(
            "the in-guest DETLOG forwarding socket carried {} bytes outside any record",
            kept.len()
        );
    }
    *stream = kept;
    append_within_log_bound(path, &records, limit)?;
    Ok(syscall_records)
}

/// Appends `bytes` to the log at `path` within its size bound; see
/// [`extract_forwarded_detlogs`].
fn append_within_log_bound(path: &Path, bytes: &[u8], limit: u64) -> Result<(), Error> {
    let log = OpenOptions::new().read(true).append(true).open(path)?;
    if log_ends_truncated(&log)? {
        return Ok(());
    }
    let written = log.metadata()?.len();
    let mut log = BoundedWriter::resume(log, limit, written);
    log.write_all(bytes)?;
    log.flush()?;
    Ok(())
}

/// Whether `log` already ends with the bound's truncation marker.
fn log_ends_truncated(mut log: &fs::File) -> Result<bool, Error> {
    let written = log.metadata()?.len();
    // The truncation marker is a few hundred bytes; its whole last line fits.
    let tail_len = written.min(4096);
    log.seek(std::io::SeekFrom::Start(written - tail_len))?;
    let mut tail = Vec::new();
    log.read_to_end(&mut tail)?;
    Ok(detcore::logdiff::log_was_truncated(
        &String::from_utf8_lossy(&tail),
    ))
}

/// Starts a line the coordinator writes into a run's log for a message on the
/// forwarding socket that is not a record (a loss notice, or anything else), so
/// verification refuses the run instead of comparing incomplete records.
const FORWARDING_REFUSED_MARKER: &str = "HERMIT_DETLOG_FORWARDING_REFUSED";

/// A verification run's log writer, shared between the tracing subscriber and
/// the coordinator's forwarded records (`detcore::detlog::set_forwarded_source`).
/// Each write takes the one lock for the whole buffer, so a record and a
/// tracing event never interleave within a line, and both are counted against
/// `--max-log-bytes` and go through the log's byte bound.
///
/// Neither writer can act on a failed write: the forwarded-record sink has no
/// caller to return it to, and the tracing subscriber drops it. So the log
/// keeps the first write or flush error ([`SharedLog::failure`]), and
/// verification refuses the run ([`RunLatches`]) even when later writes
/// recover and the log reads complete.
#[derive(Clone)]
struct SharedLog {
    writer: std::sync::Arc<std::sync::Mutex<Box<dyn Write + Send>>>,
    failure: std::sync::Arc<std::sync::Mutex<Option<String>>>,
}

impl SharedLog {
    fn new(writer: impl Write + Send + 'static) -> Self {
        Self {
            writer: std::sync::Arc::new(std::sync::Mutex::new(Box::new(writer))),
            failure: Default::default(),
        }
    }

    /// Runs `op` on the writer under its lock, keeping its error if it is the
    /// first.
    fn with<R>(&self, op: impl FnOnce(&mut dyn Write) -> std::io::Result<R>) -> std::io::Result<R> {
        let result = op(&mut **self.writer.lock().unwrap());
        if let Err(error) = &result {
            self.failure
                .lock()
                .unwrap()
                .get_or_insert_with(|| error.to_string());
        }
        result
    }

    /// The log's first write or flush error, if any.
    fn failure(&self) -> Option<String> {
        self.failure.lock().unwrap().clone()
    }

    /// Writes each forwarded record as the line `extract_forwarded_detlogs`
    /// writes for one (the normalized timestamp, then the record), and any other
    /// message behind [`FORWARDING_REFUSED_MARKER`].
    fn record_sink(&self) -> detcore::detlog::ForwardedRecordSink {
        let log = self.clone();
        Box::new(move |message: &[u8]| {
            let payload = message.strip_suffix(b"\n").unwrap_or(message);
            let mut line = Vec::with_capacity(payload.len() + 40);
            if payload.starts_with(b"INFO detcore") && find_bytes(payload, b" DETLOG ").is_some() {
                line.extend_from_slice(NORMALIZED_FORWARDED_DETLOG_TIMESTAMP.as_bytes());
                line.push(b' ');
                line.extend_from_slice(payload);
            } else {
                line.extend_from_slice(FORWARDING_REFUSED_MARKER.as_bytes());
                line.push(b' ');
                line.extend_from_slice(&payload[..payload.len().min(200)]);
            }
            line.push(b'\n');
            // The sink cannot return an error; a failed write is kept in the
            // log's failure latch, which verification checks.
            let _ = log.with(|writer| writer.write_all(&line));
        })
    }
}

/// The writer of a verification run's log: [`BoundedWriter`] bounds the file
/// at `limit` bytes and [`CappedWriter`] charges every byte to `budget`, the
/// `--max-log-bytes` counter (`None` without the flag). The tracing subscriber
/// and the forwarded-record sink both write through the returned log.
fn verification_log(
    log_file: fs::File,
    limit: u64,
    budget: Option<super::tracing::LogBudget>,
) -> SharedLog {
    SharedLog::new(CappedWriter::new(
        BoundedWriter::new(log_file, limit),
        budget,
    ))
}

impl Write for SharedLog {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.with(|writer| writer.write(bytes))
    }

    fn write_all(&mut self, bytes: &[u8]) -> std::io::Result<()> {
        self.with(|writer| writer.write_all(bytes))
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.with(|writer| writer.flush())
    }
}

/// What one verification run recorded that makes its records untrustworthy,
/// carried out of the run's container process. Verification checks it before
/// any comparison, independently of what reached the log: a lost or failed
/// write can leave a log that reads complete.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub(super) struct RunLatches {
    /// Detcore's determinism-loss latch (`detcore::detlog::determinism_loss`):
    /// a record was lost, or an event happened at a moment the host chose.
    /// Under DBT it comes from the run's evidence instead
    /// (`backends::dbt_run_latches`), since the latch is in the guest.
    pub(super) determinism_loss: Option<String>,
    /// The first write or flush error of the run's log ([`SharedLog::failure`]).
    pub(super) log_sink_failure: Option<String>,
}

/// One completed physical verification run. DBT's typed statistics remain
/// deferred until the common owner has checked the run's latches and status.
pub(super) struct VerificationRunOutput {
    pub(super) output: Output,
    pub(super) skid_overshoots: u64,
    pub(super) latches: RunLatches,
    #[cfg(feature = "dbt")]
    pub(super) dbt: Option<super::backends::DbtRunCompletion>,
}

/// A verification run recorded a determinism loss ([`RunLatches`]), so it is
/// not compared. A type rather than a message so `run --verify` records the
/// run as failed by a determinism loss instead of leaving the `not_run` stamp.
#[derive(Debug)]
pub(super) struct DeterminismLossRecorded {
    run: String,
    reason: String,
}

impl DeterminismLossRecorded {
    #[cfg(test)]
    pub(super) fn new(run: &str, reason: &str) -> Self {
        Self {
            run: run.to_owned(),
            reason: reason.to_owned(),
        }
    }
}

impl std::fmt::Display for DeterminismLossRecorded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: determinism loss recorded: {}",
            self.run, self.reason
        )
    }
}

impl std::error::Error for DeterminismLossRecorded {}

impl RunLatches {
    /// Refuses to compare `run` when either latch is set.
    pub(super) fn refuse_comparison(&self, run: &str) -> Result<(), Error> {
        if let Some(reason) = &self.determinism_loss {
            return Err(Error::new(DeterminismLossRecorded {
                run: run.to_owned(),
                reason: reason.clone(),
            }));
        }
        if let Some(error) = &self.log_sink_failure {
            anyhow::bail!("{run}: log sink failure: {error}");
        }
        Ok(())
    }
}

/// How many forwarded syscall records the coordinator wrote into the log at
/// `path` during the run. A [`FORWARDING_REFUSED_MARKER`] line (the socket
/// carried a loss notice or anything else) is an error, so verification
/// reports no result instead of comparing incomplete records.
fn forwarded_records_in_log(path: &Path) -> Result<usize, Error> {
    let text = fs::read(path)?;
    let mut syscall_records = 0;
    for line in text.split(|byte| *byte == b'\n') {
        if let Some(refused) = line.strip_prefix(FORWARDING_REFUSED_MARKER.as_bytes()) {
            let refused = String::from_utf8_lossy(refused);
            if refused
                .trim_start()
                .starts_with(detcore::detlog::FORWARDING_LOSS_NOTICE)
            {
                anyhow::bail!(
                    "the in-guest Tool could not forward every DETLOG record (it sent{refused} \
                     instead), so the compared records would be incomplete"
                );
            }
            anyhow::bail!(
                "the in-guest DETLOG forwarding socket carried a message that is not a record:{refused}"
            );
        }
        if line.starts_with(NORMALIZED_FORWARDED_DETLOG_TIMESTAMP.as_bytes())
            && find_bytes(line, b"DETLOG [syscall]").is_some()
        {
            syscall_records += 1;
        }
    }
    Ok(syscall_records)
}

struct PreparedMounts {
    mounts: Vec<PlannedMount>,
    identity_sources: IdentityGuard,
}

#[derive(Debug, Clone)]
struct E9patchOverlay {
    source: PathBuf,
    target: PathBuf,
}

#[derive(Debug, Clone, Eq, PartialEq)]
enum GuestPathMapping {
    Mapped(PathBuf),
    Hidden,
    Unchanged,
}

// Just a place to put the clap(flatten) directive..
#[derive(Debug, Parser, Clone)]
pub(crate) struct DetOptions {
    /// detcore configuration
    #[clap(flatten)]
    pub det_config: DetConfig,
}

/// How long the tracer may spend writing one fatal core before it gives up
/// on it. The guest's clock does not move meanwhile; only the host waits.
const FATAL_CORE_TIME_LIMIT: Duration = Duration::from_secs(10);

/// A token that names one invocation's fatal cores and no other's: the
/// controller's process ID, for the reader, and 64 random bits, because a
/// later run on this host, or a run in another PID namespace sharing the
/// directory, can have the same process ID.
fn fatal_core_owner_token() -> String {
    let mut nonce = [0u8; 8];
    // SAFETY: getrandom writes at most `nonce.len()` bytes into `nonce`.
    let filled = unsafe { libc::getrandom(nonce.as_mut_ptr().cast(), nonce.len(), 0) };
    let nonce = if filled == nonce.len() as isize {
        u64::from_le_bytes(nonce)
    } else {
        // Host time only names a file; it never reaches the guest.
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |since| since.as_nanos() as u64)
    };
    format!("{}-{nonce:016x}", std::process::id())
}

/// Removes the files in `dir` that the invocation named by `owner` wrote:
/// its cores and any temporary file a capture left behind. Returns how many.
fn remove_fatal_core_files(dir: &Path, owner: &str) -> usize {
    let prefix = format!("hermit-{owner}-");
    let temp_prefix = format!(".{prefix}");
    let Ok(entries) = fs::read_dir(dir) else {
        return 0;
    };
    let mut removed = 0;
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if (name.starts_with(&prefix) || name.starts_with(&temp_prefix))
            && fs::remove_file(entry.path()).is_ok()
        {
            removed += 1;
        }
    }
    removed
}

/// Set, to `PID:TOKEN` (see [`dap_supervisor_socket_name`]), in the run that
/// `hermit run --dap-listen` starts and supervises, which is the same command
/// run as a plain `--gdbserver` run.
const DAP_LISTEN_INNER_ENV: &str = "HERMIT_DAP_LISTEN_INNER";

/// The abstract Unix socket a supervising `hermit run --dap-listen` holds
/// for as long as it supervises its run: `hermit-dap-listen/PID/TOKEN`, with
/// TOKEN random. The run is told PID and TOKEN through
/// [`DAP_LISTEN_INNER_ENV`]; the socket itself, unlike a passed descriptor,
/// survives the run's start (which closes every inherited descriptor above
/// 2), and nothing but its holder can make the kernel list it.
fn dap_supervisor_socket_name(pid: u32, token: &str) -> String {
    format!("hermit-dap-listen/{pid}/{token}")
}

/// Binds this process's supervisor socket (see
/// [`dap_supervisor_socket_name`]), returning it, to be held while the run is
/// supervised, and the value of [`DAP_LISTEN_INNER_ENV`] for the run,
/// `PID:TOKEN`.
fn bind_dap_supervisor_socket() -> Result<(std::os::unix::net::UnixListener, String), Error> {
    use std::os::linux::net::SocketAddrExt;
    let mut bytes = [0u8; 16];
    fs::File::open("/dev/urandom")
        .and_then(|mut random| random.read_exact(&mut bytes))
        .context("Failed to read a random token for the DAP supervisor")?;
    let token: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    let pid = std::process::id();
    let address = std::os::unix::net::SocketAddr::from_abstract_name(
        dap_supervisor_socket_name(pid, &token).as_bytes(),
    )
    .context("Failed to name the DAP supervisor's socket")?;
    let socket = std::os::unix::net::UnixListener::bind_addr(&address)
        .context("Failed to bind the DAP supervisor's socket")?;
    Ok((socket, format!("{pid}:{token}")))
}

/// Whether this process's parent is the `hermit run --dap-listen` that
/// `owner`, the value of [`DAP_LISTEN_INNER_ENV`], names as `PID:TOKEN`: its
/// process ID, running this same `hermit` executable (the same file), and
/// holding the supervisor socket named by PID and TOKEN (see
/// [`dap_supervisor_socket_name`]). This does not depend on how the parent
/// was given `--dap-listen` (on its command line or in a `--config` file).
/// Any other parent, a shell that set the variable to its own ID for one, is
/// not a supervisor.
fn started_by_a_dap_supervisor(owner: &OsStr) -> bool {
    let parent = std::os::unix::process::parent_id();
    let Some((pid, token)) = owner.to_str().and_then(|owner| owner.split_once(':')) else {
        return false;
    };
    if pid.parse() != Ok(parent)
        || token.len() != 32
        || !token.bytes().all(|byte| byte.is_ascii_hexdigit())
    {
        return false;
    }
    let identity = |path: String| {
        fs::metadata(path)
            .map(|metadata| {
                (
                    std::os::unix::fs::MetadataExt::dev(&metadata),
                    std::os::unix::fs::MetadataExt::ino(&metadata),
                )
            })
            .ok()
    };
    let same_executable = identity(format!("/proc/{parent}/exe"))
        .is_some_and(|parent| Some(parent) == identity("/proc/self/exe".to_owned()));
    // The socket's inode, from /proc/net/unix ("Num RefCount Protocol Flags
    // Type St Inode Path", an abstract path shown with a leading '@').
    let name = format!("@{}", dap_supervisor_socket_name(parent, token));
    let inodes: Vec<String> = fs::read_to_string("/proc/net/unix")
        .unwrap_or_default()
        .lines()
        .skip(1)
        .filter_map(|row| {
            let fields: Vec<&str> = row.split_whitespace().collect();
            (fields.len() >= 8 && fields[7] == name).then(|| format!("socket:[{}]", fields[6]))
        })
        .collect();
    let holds_the_socket = !inodes.is_empty()
        && fs::read_dir(format!("/proc/{parent}/fd")).is_ok_and(|entries| {
            entries.filter_map(Result::ok).any(|entry| {
                fs::read_link(entry.path()).is_ok_and(|target| {
                    inodes
                        .iter()
                        .any(|inode| target.as_os_str() == inode.as_str())
                })
            })
        });
    same_executable && holds_the_socket
}

/// Command-line options for the "run" subcommand.
#[derive(Debug, Parser, Clone)]
#[clap(group(clap::ArgGroup::new("verification").args(["verify", "verify_run"])))]
pub struct RunOpts {
    /// Request the first-image exec-stop launcher. Not ready for production:
    /// refuses before launch until the genuine Detcore runtime is integrated.
    #[clap(long)]
    in_guest_exec_stop: bool,

    /// Freeze explicitly declared dynamic files for the native trap exec domain.
    /// Static files, scripts, threads, fork and timers remain outside this domain.
    #[cfg(feature = "native-exec")]
    #[clap(long, value_name = "DECLARATION", requires = "verification")]
    native_exec_inputs: Option<PathBuf>,

    #[cfg(feature = "native-exec")]
    #[clap(skip)]
    native_exec_capture: Option<std::sync::Arc<super::native_exec_cli::Capture>>,

    /// The process instrumentation backend. It is selected only by the global
    /// option (`hermit --backend <BACKEND> run ...`); `run` does not accept
    /// `--backend` itself. [`RunOpts::main`] copies the global value here.
    #[clap(skip)]
    backend: Option<Backend>,

    /// Program to run. Bare names are resolved using the guest PATH. Paths under host `/tmp` are
    /// hidden by Hermit's isolated `/tmp` unless `--tmp=/tmp` or an explicit mount exposes them.
    #[clap(value_name = "PROGRAM")]
    program: PathBuf,

    /// Arguments for the program.
    #[clap(value_name = "ARGS")]
    args: Vec<String>,

    /// Serve this run to one Debug Adapter Protocol client, such as an
    /// editor, on the TCP address [HOST:]PORT (HOST defaults to 127.0.0.1).
    /// Implies --gdbserver: it starts `hermit-dap --listen` from beside this
    /// executable, and the client's attach request names the program and the
    /// GDB server, as printed. Not with --verify, which runs the program
    /// twice, --namespace-only, which has no GDB server, or --image, whose
    /// program lives in the image. See DEBUGGING.md.
    #[clap(
        long,
        value_name = "[HOST:]PORT",
        conflicts_with_all = ["verify", "namespace_only", "image"]
    )]
    dap_listen: Option<String>,

    /// The GDB, with its DAP interpreter, that `--dap-listen`'s adapter runs
    /// (default: /usr/bin/gdb, else gdb on PATH).
    #[clap(long, value_name = "PATH", requires = "dap_listen")]
    dap_gdb: Option<PathBuf>,

    /// Path to a happens-before specification (JSON; see RFC #1146) that places
    /// deterministic ordering edges between anchored events. Anchor code
    /// locations (`func`, `file:line`) are resolved against the guest program's
    /// debug info. The scheduler enforces anchors that name "the thread's Nth
    /// syscall" and anchors that name a syscall, optionally on one file
    /// descriptor ({"syscall": "writev", "fd": 9, "nth": 3}); a syscall anchor
    /// that never fires ends the run with HERMIT_HB_ANCHOR_NEVER_FIRED. A
    /// syscall anchor fires at the syscall's entry, or, with "phase":
    /// "posthook", when its result is final, so an edge from it to an entry
    /// anchor orders its completed effect; a posthook anchor on an interrupted
    /// call ends the run with HERMIT_HB_POSTHOOK_INTERRUPTED, and posthook
    /// anchors are refused with `--replay-schedule-from`.
    /// A version-2 spec ("version": 2) adds `futex_op` (one futex operation,
    /// {"syscall": "futex", "futex_op": 393}), `from` (count a syscall anchor
    /// strictly after another event on the same thread, so no calibration run
    /// is needed) and `max_hold_ns` (how long, in virtual time, a thread may be
    /// held, default 10 s; past it the run ends with
    /// HERMIT_HB_HOLD_BUDGET_EXCEEDED). A version-2 spec needs the preemption
    /// timer and is refused without it. Both
    /// kinds are enforced only when the guest runs under the ptrace runtime
    /// (the default, or `--backend=e9patch`): with `--namespace-only` or
    /// another backend, the run is refused before the guest starts (exit 122)
    /// rather than run with the ordering ignored. A spec the user must fix
    /// (missing, unreadable, not valid JSON, not a valid program) is refused the
    /// same way; any other failure to read it, such as EIO, is a Hermit failure
    /// (exit 125). Combine with `--hb-list-events` to preview how the spec
    /// resolves against the binary.
    #[clap(long, value_name = "filepath")]
    happens_before: Option<PathBuf>,

    /// Load the `--happens-before` specification, resolve its anchors against the
    /// guest program's debug info, print the resolved anchor/edge program, and
    /// exit without running the guest.
    #[clap(long, requires = "happens_before")]
    hb_list_events: bool,

    /// Runtime-only cache of the resolved happens-before program. Populated in
    /// `main()` after the guest binary's debug info is available (so anchor code
    /// locations resolve to addresses), then copied into `DetConfig` for the
    /// scheduler. It is never a CLI argument and never serialized; `#[clap(skip)]`
    /// defaults it to `None` when `RunOpts` is parsed or round-tripped.
    #[clap(skip)]
    resolved_happens_before: Option<HappensBeforeProgram>,

    /// Runtime-only: why argument validation turned `--max-timeslice` off,
    /// when the host cannot arm the preemption timer. Set by
    /// `validate_args_with_timer_support`; read by
    /// `refuse_happens_before_without_preemption`. Never a CLI argument.
    #[clap(skip)]
    timer_downgrade: Option<TimerUnavailable>,

    /// Runtime-only: where `--verify` has this run record the host files the
    /// guest opens (`DetConfig::host_input_log`). Never a CLI argument and
    /// never serialized, like `resolved_happens_before`.
    #[clap(skip)]
    host_input_log: Option<PathBuf>,

    /// Opt in to keeping a core file for each guest process that a
    /// core-dumping signal (SIGSEGV, SIGABRT, SIGBUS, ...) kills. The core is
    /// written zstd-compressed into DIR as
    /// `hermit-<HERMIT PID>-<RANDOM>-core.<PID>.<TID>.<SIGNAL>.zst`, where PID
    /// and TID are the guest's and RANDOM is unique to this invocation. Off by
    /// default: without this option no core is written. Only ptrace-backed
    /// backends write cores. A run that exits 0 (for `--verify`, whose two
    /// runs also matched) deletes the cores it wrote again. Writing a core
    /// stops the whole guest for up to 10 seconds of host time, which counts
    /// against `--timeout`.
    #[clap(long, value_name = "DIR")]
    fatal_core_dir: Option<PathBuf>,

    /// With `--fatal-core-dir`, the most bytes one compressed core may take. A
    /// core that does not fit is retried with only its stack, then with only
    /// its registers and memory layout.
    #[clap(long, value_name = "BYTES", default_value_t = 256 << 20, requires = "fatal_core_dir")]
    fatal_core_max_bytes: u64,

    /// With `--fatal-core-dir`, the most bytes the regular files directly in
    /// DIR may take together, counting files that were there before the run.
    #[clap(long, value_name = "BYTES", default_value_t = 1 << 30, requires = "fatal_core_dir")]
    fatal_core_total_max_bytes: u64,

    /// Runtime-only: `--fatal-core-dir`, held open by the controller so the
    /// run container reaches it through `/proc/self/fd` whatever its mount
    /// namespace hides (see [`descriptor_path`]). Opened by `main` just before
    /// the guest starts.
    #[clap(skip)]
    fatal_core_dir_handle: Option<std::sync::Arc<File>>,

    /// Runtime-only: which `--verify` run this is, so the two runs' cores do
    /// not share names.
    #[clap(skip)]
    fatal_core_run_label: Option<&'static str>,

    /// Runtime-only: the token naming this invocation's cores, made when
    /// `--fatal-core-dir` is opened (see [`fatal_core_owner_token`]). The
    /// tracer computes names inside the run's PID namespace, where its own
    /// process ID is not the controller's.
    #[clap(skip)]
    fatal_core_owner: String,

    /// Whether this invocation's epoch was captured from the host clock because
    /// neither `--epoch` nor `HERMIT_EPOCH` supplied an explicit input.
    ///
    /// This is CLI provenance only: the resolved timestamp itself is copied into
    /// `DetConfig` before any backend starts and is the sole value serialized or
    /// observed by the guest.
    #[clap(skip)]
    epoch_captured_from_host: bool,

    /// Whether neither `--epoch` nor `HERMIT_EPOCH` supplied the epoch, whether
    /// or not virtual time then sampled the host clock for it.
    #[clap(skip)]
    epoch_omitted: bool,

    /// Whether the epoch was taken from the preemption record being replayed,
    /// replacing an omitted one. See `adopt_replayed_schedule_epoch`.
    #[clap(skip)]
    epoch_from_recording: bool,

    /// Runtime-only: the options this invocation was given, captured from the
    /// parsed command line for `--save-config` (see [`crate::run_config::capture`]).
    #[clap(skip)]
    config_capture: Option<crate::run_config::RunConfig>,

    /// Clap provenance, captured before values are lowered to DetConfig.
    /// Programmatic callers have an effective configuration and must not have
    /// a positive maximum silently replaced merely because it equals a default.
    #[clap(skip = true)]
    max_timeslice_explicit: bool,

    /// Runtime-only: the seed `--seed-from` chose, which `--save-config`
    /// writes in its place.
    #[clap(skip)]
    seed_from_resolved: Option<u64>,

    #[clap(flatten)]
    pub(crate) det_opts: DetOptions,

    /// Require Hermit's deterministic defaults and reject incompatible opt-outs. Unsupported
    /// syscalls already fail closed in ordinary runs. `--no-virtualize-time` is still accepted:
    /// clock syscalls then return host time, so the run is not reproducible; record it with
    /// `hermit record` to reproduce it. `--verify --verify-strict` reports the difference; plain
    /// `--verify` reports it only when host time reaches the guest's output. On the ptrace and
    /// e9patch backends, `--strict` also refuses to run when the host's performance counters fail
    /// Reverie's validation, because the virtual clock counts retired branches and cannot be exact;
    /// with `--max-timeslice=disabled` Detcore uses no branch count, so that run is not refused
    /// (Reverie still sets up, calibrates and incidentally reads the counters, but none of
    /// those reads reaches the virtual clock, a preemption point or the guest). Every input must be
    /// on the command line: a strict run without `--epoch` (or `HERMIT_EPOCH`, or a replayed
    /// recording that supplies it), or with `--seed-from=SystemRandom`, is refused before the
    /// guest starts rather than drawing that input from the host.
    #[clap(
        long,
        conflicts_with_all = ["no_sequentialize_threads", "no_deterministic_io", "strace_only"]
    )]
    strict: bool,

    /// Permit unsupported syscalls to reach the host kernel. This weakens determinism and exists
    /// only as an explicit compatibility escape hatch; ordinary runs fail closed by default.
    #[clap(
        long,
        conflicts_with_all = ["strict", "panic_on_unsupported_syscalls"]
    )]
    allow_unsupported_syscalls: bool,

    /// Kill the run if the guest does not finish within this many seconds.
    ///
    /// Hermit created the container, so hermit unwinds it: on expiry the guest
    /// future is dropped, reverie reaps its tracees, detcore's state is torn
    /// down, and the container init returns normally. Exits 124, the same code
    /// GNU `timeout` and `hermit record --record-timeout` already use for a
    /// deadline. Wall-clock, so it never affects guest-visible determinism.
    #[clap(long, value_name = "SECONDS")]
    timeout: Option<NonZeroU64>,

    /// Disable deterministic sequential thread execution.
    #[clap(long)]
    pub(crate) no_sequentialize_threads: bool,

    /// Disable deterministic I/O behavior.
    #[clap(long)]
    no_deterministic_io: bool,

    /// Pin all guest threads to one or more cores, so that they do not migrate
    /// during execution. This is off by default, but it is implied by setting
    /// `max_timeslice` which requires stable RCB counters. RCB counters are
    /// not maintained consistently when Linux migrates a thread between cores.
    #[clap(long)]
    pin_threads: bool,

    /// Override the processor-specific PMU skid margin, in retired conditional branches. Larger
    /// values schedule the overflow interrupt earlier and can increase single-stepping overhead.
    // TODO-HUMAN-REVIEW(PR-991): Review the ptrace PMU skid-margin CLI override.
    #[clap(long, value_name = "RCBS")]
    skid_margin: Option<u64>,

    /// Mount a file or directory. This uses the same syntax as Docker's `--mount` option. The
    /// source must exist on the host. For simple bind mounts into guest `/tmp`, use `--bind`.
    #[clap(long, value_name = "path")]
    mount: Vec<Mount>,

    /// Bind-mount a host file or directory into guest `/tmp`. Use `SOURCE` to preserve its path or
    /// `SOURCE:TARGET` to choose a target under `/tmp`; the source must already exist.
    #[clap(long, value_name = "path")]
    pub(crate) bind: Vec<Bind>,

    /// Select guest networking. `local` creates an isolated loopback interface; `host` exposes the
    /// host network and compromises isolation and deterministic reproducibility.
    #[clap(
        long,
        alias = "net",
        value_name = "local|host",
        default_value = "local"
    )]
    network: NetworkingMode,

    /// Record outbound TCP traffic to a new trace at this path. The guest reaches the host
    /// network; every byte it receives is stamped with the deterministic time at which the
    /// guest observed it, so `--replay-networking` reproduces the run without the network.
    #[clap(
        long,
        value_name = "NEW_TRACE",
        conflicts_with_all = ["replay_networking", "network", "verify", "namespace_only"]
    )]
    record_networking: Option<PathBuf>,

    /// Replay outbound TCP traffic from a trace written by `--record-networking`, without
    /// contacting the network. Any difference in what the guest sends ends the run.
    #[clap(
        long,
        value_name = "TRACE",
        conflicts_with_all = ["record_networking", "network", "namespace_only"]
    )]
    replay_networking: Option<PathBuf>,

    /// Run with namespaces but without ptrace or determinization. This is a useful smoke test
    /// when diagnosing ptrace/seccomp policy failures; PID and `/tmp` isolation still apply. The
    /// guest carries one seccomp filter, which stops only `kill`: a `kill(0, sig)` from Hermit's
    /// own process group is refused with EPERM, unlike Linux, so it cannot reach Hermit and the
    /// processes that started it. The guest can see the filter (`Seccomp: 2` in
    /// /proc/self/status), its own seccomp listener fails with EBUSY, and a hermit run inside it
    /// refuses the inherited filter unless given --unsafe-ignore-host-seccomp.
    #[clap(
        long,
        alias = "lite",
        conflicts_with = "chaos",
        conflicts_with = "verify"
    )]
    namespace_only: bool,

    /// Run syscall interception directly on the host without creating Linux namespaces or
    /// mounting an isolated `/tmp`. This is not a sandbox and must only be used with trusted
    /// guests. Host process, filesystem, and network state are shared, reducing determinism.
    /// Schedule and preemption replay require stable namespace PIDs and are not supported.
    ///
    /// The guest's mount table (/proc/self/mountinfo, /proc/mounts) is not the host's: it
    /// lists the mounts holding the guest's working directory and the host /tmp, their
    /// ancestors, and the base mountpoints (/, /proc, /dev, /sys, /run and a few below them).
    /// Other host mounts are hidden; a file on one reports its nearest listed ancestor.
    ///
    /// Incompatible with `--image`, which chroots the guest into a materialized
    /// OCI rootfs and therefore requires namespaces; that conflict is reported
    /// at runtime with an explanatory message rather than as a generic clap
    /// argument conflict.
    #[clap(
        long,
        visible_alias = "core-only",
        conflicts_with_all = [
            "mount",
            "bind",
            "network",
            "tmp",
            "namespace_only",
            "analyze_networking",
            "replay_schedule_from",
            "replay_preemptions_from"
        ]
    )]
    no_namespace: bool,

    /// Run in a minimally invasive syscall-interception mode. Combine with `hermit --log=info` to
    /// print intercepted syscalls.
    ///
    /// This does not determinize execution. It is shorthand for `--tmp=/tmp --network=host
    /// --no-virtualize-cpuid --no-virtualize-time --no-virtualize-metadata
    /// --no-sequentialize-threads --no-deterministic-io --no-rcb-time`.
    #[clap(
        long,
        conflicts_with = "chaos",
        conflicts_with = "namespace_only",
        conflicts_with = "seed",
        conflicts_with = "seed_from",
        conflicts_with = "analyze_networking"
    )]
    strace_only: bool,

    /// Specifies the directory to use as `/tmp`. This path gets bind-mounted
    /// over `/tmp` and the guest program does not see the real `/tmp` directory.
    /// If this path does not exist, it is created.
    ///
    /// If this option is not specified, a temporary directory is created,
    /// mounted over `/tmp`, and deleted when the guest has exited.
    #[clap(long, value_name = "dirpath")]
    tmp: Option<PathBuf>,

    /// PROTOTYPE: run the guest against the root filesystem of a pinned OCI image
    /// instead of the host filesystem. The reference is materialized (pulled and
    /// unpacked, rootless) via `buildah` and the guest is `chroot`ed into a
    /// read-only cached root with an isolated writable `/tmp`, so its FILE INPUTS
    /// come deterministically from the image. Pin by digest for
    /// reproducibility, e.g.
    /// `--image docker.io/library/busybox@sha256:...`. The guest program path
    /// must resolve inside the image: give an absolute path (e.g. `/bin/sh`) or
    /// a relative path containing a `/` (e.g. `./bin/sh`), which is resolved
    /// against the image working directory; a bare command name (PATH search
    /// inside the image) is not yet supported. Requires namespaces (incompatible
    /// with `--no-namespace`). The prototype currently supports only the ptrace
    /// backend and does not yet compose with custom `--mount`/`--bind` options.
    #[clap(long, value_name = "OCI-REFERENCE")]
    image: Option<String>,

    /// Exactly like "seed" but we generate a seed for you. This is useful if multiple
    /// hermit runs execute in parallel and rand based collisions exist.  "Args" generates
    /// the seed from the other arguments passed to hermit, "SystemRandom" uses system
    /// randomness to generate a seed, and creates a log message recording it.
    #[clap(long, value_name = "'Args'|'SystemRandom'")]
    seed_from: Option<SeedFrom>,

    /// After running, immediately run a SECOND time, and compare the two
    /// executions. This will exit with an error if the guest process does OR if
    /// the executions do not match. In order to match, they must have the same
    /// observed output (e.g. stdout/stderr), and the same log of internal
    /// scheduler steps.
    ///
    /// It's on the user to ensure that the command run is idempotent, and thus
    /// that the first run will not have any side effects that affect the
    /// execution of the second run.
    #[clap(long)]
    verify: bool,

    /// Compare complete, unnormalized TRACE logs and show detailed differences.
    /// This detects internal timing and other trace-only divergence at the cost
    /// of substantially larger logs and stricter comparison. Implies the strict,
    /// bitwise comparison of --verify-strict, and additionally raises the diff
    /// verbosity (larger logs, more syscall history).
    #[clap(long, requires = "verification")]
    verify_verbose: bool,

    /// Compare the internal logs under the CANONICAL parity policy: strip only
    /// the real wall-clock timestamp prefix (genuinely irreproducible),
    /// canonicalize host memory addresses to first-appearance ordinals (so an
    /// ASLR shift is tolerated but allocation-order and aliasing changes still
    /// diverge), and compare every INFO message's remaining bytes — virtual-time
    /// timestamps, raw syscall argument/result values, counts, sizes, flags —
    /// exactly. An explicit `--log=debug` or `--log=trace` remains captured for
    /// `--print-verify-logs` diagnostics but does not change this INFO verdict; use
    /// `--verify-verbose` to request an all-level diagnostic comparison. Without
    /// this (and without --verify-verbose) the default `--verify` normalizes away
    /// numbers, addresses, tmp paths, and timestamps before comparing, so a
    /// "verified" result asserts only stripped parity, not bitwise identity.
    /// Unlike --verify-verbose this stays quiet: it changes only the comparison,
    /// not the diff output volume, so a determinism ratchet can require parity
    /// without drowning in trace logs.
    #[clap(long, requires = "verification")]
    verify_strict: bool,

    /// If --verify is specified, indicates what guest exit status is required for
    /// hermit to consider the verification successful.  Both runs must satisfy this criteria,
    /// and hermit does not perform the second run if the first does not.
    #[clap(long, value_name = "success|failure|both", default_value = "success")]
    verify_allow: VerifyAllow,

    /// If --verify is specified, echo the FIRST run's `--log` output to stderr,
    /// the same way a normal (non-verify) run does. During --verify the log is
    /// otherwise diverted to a temporary file for comparison, so the user never
    /// sees it. This restores observability of `--log` output while still
    /// performing the two-run determinism check.
    #[clap(long = "print-verify-logs", alias = "verify-logs", requires = "verify")]
    print_verify_logs: bool,

    /// Retain the captured verification logs after the comparison. After a
    /// match, only the first run's log is kept, as the golden log; the second
    /// run's log, which compared equal to it under the selected comparison
    /// policy, is deleted. After a divergence, a no-result, or an error, both
    /// logs are kept, or only the first run's when verification stopped before
    /// a second run.
    /// Logs are written under --verify-log-dir when provided; otherwise under
    /// $XDG_STATE_HOME/hermit/verify-logs (normally
    /// ~/.local/state/hermit/verify-logs). The final paths are printed.
    /// Without --keep-logs the logs are temporary files in $HERMIT_VERIFY_TMPDIR
    /// when it is set and not empty (also for `record start --verify`), otherwise
    /// in the system temporary directory; a verify that is killed leaves them
    /// there, and a HERMIT_VERIFY_TMPDIR that cannot hold them is an error that
    /// names it. Hermit does not pass HERMIT_VERIFY_TMPDIR on to the guest unless
    /// it is given with --env.
    #[clap(long, requires = "verify")]
    keep_logs: bool,

    /// Directory for logs retained by --keep-logs.
    #[clap(long, value_name = "DIRECTORY", requires = "keep_logs")]
    verify_log_dir: Option<PathBuf>,

    /// With --verify, write the verification verdict as a single JSON line to
    /// this path: `{"verified":bool,"bitwise_parity":bool,
    /// "verdict":"matched"|"diverged","comparison":{"strictness":
    /// "stripped"|"canonical","display_name":str,
    /// "compare_logs":bool,"compare_io_buffers":bool,
    /// "log_scope":
    /// "deterministic"|"info"|"full_trace","record_envelope":
    /// "all_records_v1","strip_lines":bool,
    /// "canonicalize_addresses":bool,"full_trace":bool,"exact_remainder":bool,
    /// "stripped_prefixes":[str],"canonicalizations":[str],"ignore_lines":bool,
    /// "skip_commit":bool,"skip_detlog":bool},"dbt_counted_branches":
    /// {"left":int,"right":int},"guest_exit_code":int|null,
    /// "guest_signal":int|null,"first_divergent_scheduler_turn":int|null,
    /// "first_divergent_virtual_nanoseconds":int|null,
    /// "first_divergent_record":int|null,"first_divergent_syscall":int|null}`.
    /// `dbt_counted_branches` is present only when DBT completed a typed
    /// whole-process comparison; it is omitted for other backends and no-result.
    /// If a sandbox exits before returning its guest Output, the report instead
    /// records `verdict: "no_result"` and `no_result_reason.kind:
    /// "container_failed"`, with `run: "run1"|"run2"` and the container's
    /// `exited` (code) or `signaled` (signal, core_dumped) disposition. Guest
    /// status, comparison, counts and divergence coordinates remain absent.
    /// An unchanged `not_run` reason means only that the initial stamp was not
    /// replaced; it does not prove that no execution was attempted.
    /// ALL FOUR divergence coordinates are emitted, and they are four
    /// DIFFERENT KEYSPACES that must never be compared across axes: one real
    /// divergence was record 7495, syscall 1074, scheduler turn 196 -- three
    /// numbers for one event. A consumer that reads a subset silently drops
    /// located evidence. This is the
    /// exit-code-independent verdict
    /// channel: `verified` reflects whether the two runs matched, regardless of
    /// what the guest exited with, so a caller need not (and must not) infer the
    /// verdict from the process exit code. A determinism / record-replay parity
    /// ratchet must key on `bitwise_parity`, NOT `verified`: `bitwise_parity` is
    /// true only under the `canonical` (`BitwiseInfoV1`) policy — a full-INFO
    /// comparison inside a named canonical record envelope that strips only the
    /// real wall-clock prefix, canonicalizes host addresses to first-appearance
    /// ordinals, includes syscall output-buffer hashes, and compares everything
    /// else exactly (see --verify-strict) — so it cannot be silently weakened to
    /// a stripped, content-blind, or opaque filtered compare.
    #[clap(long, requires = "verify", value_name = "PATH")]
    verify_json: Option<PathBuf>,

    /// Run the guest once, as one of the two executions of `--verify`, and
    /// write that execution's evidence to NEW_DIR, which must not exist: its
    /// verification log, the guest's standard output and error, its run
    /// summary, the host files its guest opened, and a verify-run.json record
    /// of how it ended. `hermit log-diff --verify-json REPORT DIR1 DIR2`
    /// compares two such directories and writes the report that `--verify
    /// --verify-json` writes, so a caller can start the two runs itself, in
    /// parallel if it likes, and keep both logs. `--verify-strict`,
    /// `--verify-verbose` and `--no-detlog-io-buffers` choose the comparison
    /// as they do for `--verify`, and both runs must choose the same one. Give
    /// both runs one `--epoch` (or HERMIT_EPOCH): the comparison refuses runs
    /// whose virtual clocks started at different epochs. On DBT the directory
    /// also holds DynamoRIO's typed statistics stream. The exit status is the
    /// guest's when the run completed.
    #[clap(
        long,
        value_name = "NEW_DIR",
        conflicts_with_all = ["verify", "namespace_only"]
    )]
    verify_run: Option<PathBuf>,

    /// INTERNAL, the native-exec pairing seam: adopt the sealed input set that
    /// `hermit verify-inputs` left at this descriptor, the same one in both
    /// runs of the pair (see `verify_inputs`). Hidden until a native-exec
    /// consumer lands.
    #[clap(long, value_name = "FD", requires = "verify_run", hide = true)]
    native_exec_shared_inputs: Option<std::os::fd::RawFd>,

    /// The inputs adopted from `--native-exec-shared-inputs`, held until the
    /// run ends.
    #[clap(skip)]
    shared_inputs: Option<std::sync::Arc<super::verify_inputs::AdoptedInputs>>,

    /// Print a summary of the process tree's execution to stderr before exiting.
    #[clap(long, short = 'u')]
    pub(crate) summary: bool,

    /// Print a machine readable version of --summary to a file.
    ///
    /// The summary is written from inside the run container, so an absolute
    /// path the container cannot see is refused before the guest starts: one
    /// under host /tmp (unless --tmp=/tmp or a --bind exposes it) or under a
    /// --mount without a source.
    #[clap(long)]
    pub(crate) summary_json: Option<PathBuf>,

    /// Write the selected backend's own engagement evidence as JSON.
    ///
    /// This is a single-run record. Verification has separate per-attempt
    /// records and therefore cannot use one path without losing an attempt.
    #[clap(
        long,
        conflicts_with_all = ["verify", "namespace_only"],
        value_name = "PATH"
    )]
    backend_engagement_json: Option<PathBuf>,

    /// Diagnose non-zero network binds. Implies an isolated network namespace and conflicts with
    /// `--network=host`.
    #[clap(long)]
    analyze_networking: bool,

    /// The base environment that is presented to the guest. "Empty" is completely empty, and "Host"
    /// allows through all the environment variables in hermit's own environment.
    /// "Minimal" provides a minimal deterministic environment, setting only PATH, HOSTNAME, and HOME.
    #[clap(long, default_value = "host", value_name = "str")]
    base_env: BaseEnv,

    /// Additionally append one or more environment variables to the container environment. If a
    /// name is provided without a value, pass that variable through from the host.
    #[clap(short = 'e', long, value_parser = parse_assignment, value_name="name[=val]")]
    env: Vec<(String, Option<String>)>,

    /// Set the guest working directory. The path is resolved after guest mounts are applied, so an
    /// isolated path such as `/tmp` refers to the guest view.
    #[clap(long, value_name = "path")]
    workdir: Option<String>,

    /// Load options from a run config file: YAML (or JSON) naming `hermit run` options by their
    /// long names, as `--save-config` writes it. The file's options count as given on the command
    /// line and are checked the same way. An option given on the command line replaces the
    /// file's value for that option (a repeatable option's whole list), a guest program given on
    /// the command line replaces the file's `program` and `args`, and the file's values replace
    /// the options' environment variables. For example, `{schema: hermit-run-config/v1, global:
    /// {log: info}, run: {seed: 7, env: [A=1, B=2], verify: true}, program: /bin/date}`; the
    /// format is described under "Run Configuration Files" in docs/USER_GUIDE.md. Unknown keys and any
    /// `schema` other than `hermit-run-config/v1` are refused.
    #[clap(long, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Write this run's options to FILE as a run config that `--config` loads to reproduce the
    /// run: the options given on the command line, in a `--config` file or through their
    /// environment variables, plus the implicit inputs hermit resolved (an epoch taken from the
    /// host clock or from a replayed recording, and the seed `--seed-from` chose). Defaults are
    /// not written, and neither is the host environment `--base-env=host` passes through. The
    /// file is written on the host before the guest starts, so a run that fails still leaves it.
    #[clap(long, value_name = "FILE")]
    pub save_config: Option<PathBuf>,

    /// Rerun the run a manifest records: load its options and guest command as `--config` loads a
    /// run config. RECORDING is `last` (the newest `hermit record` or `--record-networking`
    /// recording), `last-run` (the newest of any kind, a plain run's manifest included), a recording ID or a unique prefix of at least 6 hex digits, or the
    /// path of a `manifest.json` or of its directory; `hermit list` lists them. Options and a guest
    /// command given on this command line replace the manifest's, so `hermit run --from last-run
    /// --sched-seed=7` reruns the newest run under another schedule. A run that draws an
    /// input from the host (an epoch from the host clock, a seed from `--seed-from=SystemRandom`)
    /// writes such a manifest under the data directory (`HERMIT_DATA_DIR`, else
    /// `~/.cache/hermit`) and names it in a diagnostic
    /// (https://github.com/rrnewton/hermit/issues/4271). Like a run config, a manifest does not
    /// hold the host environment `--base-env=host` passes through, the files the guest reads, or
    /// the working directory (relative paths resolve against this one), and it leaves out output
    /// destinations such as `--log-file`.
    #[clap(long, value_name = "RECORDING", conflicts_with = "config")]
    from: Option<PathBuf>,

    /// When to write a run manifest, the small recording that reruns this execution with
    /// `--from`: `nonreproducible-only` (the default) writes one only when the run draws an input
    /// from the host; `always` also writes a `history` manifest for a reproducible run; `never`
    /// writes none. Without this option, the `manifest` key of `~/.config/hermit/config.yaml`
    /// decides, then the `HERMIT_MANIFEST` environment variable.
    #[clap(long, value_name = "POLICY", value_enum)]
    manifest: Option<crate::manifest::ManifestPolicy>,

    /// Runtime-only: where this run's manifest was written, once it is.
    #[clap(skip)]
    manifest_path: Option<PathBuf>,

    /// Runtime-only: a network recording's manifest, written only once the
    /// run has written its trace (`finish_manifest`).
    #[clap(skip)]
    pending_network_manifest: Option<crate::manifest::Manifest>,

    /// Read-only overlay that exposes the rewritten ELF at its original guest path.
    #[clap(skip)]
    e9patch_overlay: Option<E9patchOverlay>,

    /// Runtime-only: how many of the last `--mount`s and `--bind`s a backend
    /// adapter added to the caller's (`with_dbt_mounts`). They are installed
    /// as a backend's own mounts (`PlannedMount::backend`), which the guest's
    /// container mount table leaves out by that identity, so the table is
    /// the same on every backend.
    #[clap(skip)]
    backend_mounts: (usize, usize),

    /// Resolved guest executable path used after e9patch preprocessing.
    #[clap(skip)]
    e9patch_program: Option<PathBuf>,

    /// Complete root-image preparation result, retained so later consumers do
    /// not have to recover any count from the presentation banner.
    #[clap(skip)]
    e9patch_engagement: Option<BackendEngagement>,

    /// The root-image rewrite's sites in the dispatch record's terms; every
    /// count is unmeasured when the root executable was not an ELF image.
    #[clap(skip)]
    e9patch_sites: Option<reverie::SiteCounters>,

    /// Why this host's retired-branch counter is inexact, if it is. Only the
    /// `--strict` refusal consults it; tests replace it to reach that refusal
    /// on a host whose counters pass.
    #[clap(skip = host_inexact_branch_counter as fn() -> Option<String>)]
    inexact_branch_counter: fn() -> Option<String>,
}

pub(super) fn parse_assignment(src: &str) -> Result<(String, Option<String>), Error> {
    static ENV_RE: LazyLock<regex::Regex> = LazyLock::new(||
        // Here we are extremely permissive, allowing all charecters in the "Portable Character
        // Set", ISO/IEC 6429:1992 standard:
        regex::Regex::new("^([\x07-<>-~]+)=([\x07-~]*)$").unwrap());
    static VAR_RE: LazyLock<regex::Regex> =
        LazyLock::new(|| regex::Regex::new("^([\x07-<>-~]+)$").unwrap());

    if let Some(capture) = ENV_RE.captures(src) {
        if let (Some(name), Some(value)) = (capture.get(1), capture.get(2)) {
            Ok((name.as_str().to_owned(), Some(value.as_str().to_owned())))
        } else {
            anyhow::bail!("unable to parse name=value from '{}'", src)
        }
    } else if VAR_RE.is_match(src) {
        let var: String = src.to_owned();
        Ok((var, None))
    } else {
        anyhow::bail!("unable to parse env var name or name=value from '{}'", src)
    }
}

fn apply_base_and_explicit_environment(
    command: &mut Command,
    base_env: &BaseEnv,
    env: &[(String, Option<String>)],
) -> Result<(), Error> {
    match base_env {
        BaseEnv::Empty => {
            command.env_clear();
        }
        BaseEnv::Minimal => {
            command.env_clear();
            command.env("HOSTNAME", "hermetic-container.local");
            command.env(
                "PATH",
                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            );
            command.env("HOME", "/root");
        }
        BaseEnv::Host => {
            // Hermit's own settings, not the guest's: where its verify logs go,
            // its race probes, which must not change what the guest sees, and
            // the mark on the run that `--dap-listen` supervises, so the
            // guest's environment is that of the same run without it.
            command.env_remove(super::verify::VERIFY_TMPDIR_ENV);
            command.env_remove(detcore::race_probe::RACE_PROBE_ENV);
            command.env_remove(detcore::race_probe::RACE_PROBE_SEED_ENV);
            command.env_remove(detcore::race_probe::RACE_PROBE_HOLD_DIR_ENV);
            command.env_remove(DAP_LISTEN_INNER_ENV);
        }
    }
    for (name, value) in env {
        if let Some(value) = value {
            command.env(name, value);
        } else if let Ok(value) = std::env::var(name) {
            command.env(name, value);
        } else {
            anyhow::bail!(
                "Attempt to pass through env var {}, but it is not set in the host environment",
                name
            );
        }
    }

    Ok(())
}

fn disable_sanitizer_leak_detection(command: &mut Command) {
    command.env("ASAN_OPTIONS", "detect_leaks=0");
    command.env("LSAN_OPTIONS", "detect_leaks=0");
}

pub(super) fn apply_base_environment(
    command: &mut Command,
    base_env: &BaseEnv,
    env: &[(String, Option<String>)],
) -> Result<(), Error> {
    apply_base_and_explicit_environment(command, base_env, env)?;
    disable_sanitizer_leak_detection(command);
    Ok(())
}

#[derive(Debug, Default, Clone, Copy, Parser, Eq, PartialEq)]
pub enum NetworkingMode {
    /// Create a local loopback device and allow local, intra-container network communication only.
    // WARNING: written in two places, here and in the #[clap(default_value)] above.
    #[default]
    Local,
    /// Allow through all network access via the host's network interface.
    Host,
    // None, // TODO: no network interface at all
    // Record, // TODO: record network traffic only, not other syscalls.
}

impl NetworkingMode {
    /// Apply this networking mode to a container. `run` and `record start`
    /// both build their containers through this one function, so a recording
    /// sees the same network as the run it records. `analyze_networking`
    /// forces an isolated namespace even under `host`.
    pub(crate) fn configure(self, container: &mut Container, analyze_networking: bool) {
        if self.uses_local_namespace(analyze_networking) {
            container.local_networking_only();
        }
    }

    /// The dedicated DBT launcher must use the same resolved network policy.
    pub(super) fn uses_local_namespace(self, analyze_networking: bool) -> bool {
        self == Self::Local || analyze_networking
    }
}

// Upper case will work, but prefer lower case.
impl fmt::Display for NetworkingMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match &self {
            NetworkingMode::Local => "local",
            NetworkingMode::Host => "host",
        };
        write!(f, "{}", s)
    }
}

impl FromStr for NetworkingMode {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "local" => Ok(NetworkingMode::Local),
            "host" => Ok(NetworkingMode::Host),
            _ => Err(format!("Could not parse: {:?}", s)),
        }
    }
}

#[derive(Debug, Clone, Copy, Parser, Eq, PartialEq)]
pub enum VerifyAllow {
    Success,
    Failure,
    Both,
}

impl FromStr for VerifyAllow {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "success" => Ok(VerifyAllow::Success),
            "failure" => Ok(VerifyAllow::Failure),
            "both" => Ok(VerifyAllow::Both),
            _ => Err(format!("Could not parse: {:?}", s)),
        }
    }
}

impl VerifyAllow {
    pub(crate) fn satisfies(&self, status: ExitStatus) -> bool {
        match self {
            VerifyAllow::Success => status == ExitStatus::SUCCESS,
            VerifyAllow::Failure => status != ExitStatus::SUCCESS,
            VerifyAllow::Both => true,
        }
    }
}

fn describe_exit_status(status: ExitStatus) -> String {
    match status {
        ExitStatus::Exited(code) => format!("exited with code {code}"),
        ExitStatus::Signaled(signal, core_dumped) => {
            let core = if core_dumped { " (core dumped)" } else { "" };
            format!("terminated by signal {} ({signal:?}){core}", signal as i32)
        }
        ExitStatus::SignaledRaw(signal, core_dumped) => {
            let core = if core_dumped { " (core dumped)" } else { "" };
            format!("terminated by signal {signal} (SIG{signal}){core}")
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub(super) enum BaseEnv {
    Empty,
    Minimal,
    Host,
}

impl FromStr for BaseEnv {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "empty" => Ok(BaseEnv::Empty),
            "minimal" => Ok(BaseEnv::Minimal),
            "host" => Ok(BaseEnv::Host),
            _ => Err(format!(
                "Expected Empty | Minimal | Host, could not parse: {:?}",
                s
            )),
        }
    }
}

/// Where to generate the random seed from.
#[derive(Debug, Clone)]
pub enum SeedFrom {
    Args,
    SystemRandom,
}

// Error boilerplate.
#[derive(Debug, Clone)]
pub struct ParseSeedFromError {
    details: String,
}

impl fmt::Display for ParseSeedFromError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl std::error::Error for ParseSeedFromError {
    fn description(&self) -> &str {
        &self.details
    }
}

impl FromStr for SeedFrom {
    type Err = ParseSeedFromError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "args" => Ok(SeedFrom::Args),
            "systemrandom" => Ok(SeedFrom::SystemRandom),
            _ => Err(ParseSeedFromError {
                details: format!("Expected Args | SystemRandom, could not parse: {:?}", s),
            }),
        }
    }
}

/// Displays the `run` subcommand's own options, so that
/// `hermit{global_backend_arg()} run{self}` is a runnable command. The backend is a
/// global option and is therefore rendered by [`RunOpts::global_backend_arg`],
/// not here.
impl fmt::Display for RunOpts {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.in_guest_exec_stop {
            write!(f, " --in-guest-exec-stop")?;
        }
        let mut dop = self.det_opts.det_config.clone();
        // Fail-closed is the `run` default, so serialize only the compatibility
        // opt-out. `DetConfig` is also used outside `run` and retains a neutral
        // false default, so its Display would otherwise add the explicit opt-in.
        dop.panic_on_unsupported_syscalls = false;

        if let Some(skid_margin) = self.skid_margin {
            write!(f, " --skid-margin={skid_margin}")?;
        }
        if let Some(timeout) = self.timeout {
            write!(f, " --timeout={timeout}")?;
        }
        // `--strict` refuses runs a plain one accepts and makes a signal-delivery
        // contradiction fatal (`Config::signal_delivery_check_fatal`), so a
        // reproducer without it would not end the same way.
        if self.strict {
            write!(f, " --strict")?;
        }
        if self.no_sequentialize_threads {
            write!(f, " --no-sequentialize-threads")?;
        }
        if self.no_deterministic_io {
            write!(f, " --no-deterministic-io")?;
            assert!(!dop.deterministic_io)
        } else {
            assert!(dop.deterministic_io)
        }
        if self.allow_unsupported_syscalls {
            write!(f, " --allow-unsupported-syscalls")?;
        }
        // Recording switches to host networking; render the flag that asked for it.
        if let Some(path) = &self.record_networking {
            write!(
                f,
                " --record-networking={}",
                shell_words::quote(&path.to_string_lossy())
            )?;
        } else if self.network != Default::default() {
            write!(f, " --network={}", self.network)?;
        }
        if let Some(path) = &self.replay_networking {
            write!(
                f,
                " --replay-networking={}",
                shell_words::quote(&path.to_string_lossy())
            )?;
        }
        if self.namespace_only {
            write!(f, " --namespace-only")?;
        }
        if self.no_namespace {
            write!(f, " --no-namespace")?;
        }
        if self.summary {
            write!(f, " --summary")?;
        }
        if let Some(p) = &self.summary_json {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --summary-json={}", shell_words::quote(s))?;
        }
        if let Some(p) = &self.backend_engagement_json {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --backend-engagement-json={}", shell_words::quote(s))?;
        }
        if self.analyze_networking {
            write!(f, " --analyze-networking")?;
        }
        if self.verify {
            write!(f, " --verify")?;
        }
        if self.verify_verbose {
            write!(f, " --verify-verbose")?;
        }
        if self.verify_strict {
            write!(f, " --verify-strict")?;
        }
        if self.print_verify_logs {
            write!(f, " --print-verify-logs")?;
        }
        if self.keep_logs {
            write!(f, " --keep-logs")?;
        }
        if let Some(p) = &self.verify_log_dir {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --verify-log-dir={}", shell_words::quote(s))?;
        }
        if let Some(p) = &self.verify_json {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --verify-json={}", shell_words::quote(s))?;
        }
        if let Some(p) = &self.verify_run {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --verify-run={}", shell_words::quote(s))?;
        }
        if let Some(fd) = self.native_exec_shared_inputs {
            write!(f, " --native-exec-shared-inputs={fd}")?;
        }
        if let Some(p) = &self.tmp {
            let s = p.to_str().expect("valid unicode path");
            write!(f, " --tmp={}", shell_words::quote(s))?;
        }
        if let Some(image) = &self.image {
            write!(f, " --image={}", shell_words::quote(image))?;
        }
        match &self.verify_allow {
            VerifyAllow::Success => {} // default
            VerifyAllow::Failure => {
                write!(f, " --verify-allow=failure")?;
            }
            VerifyAllow::Both => {
                write!(f, " --verify-allow=both")?;
            }
        }
        match &self.base_env {
            BaseEnv::Empty => {
                write!(f, " --base-env=empty")?;
            }
            BaseEnv::Minimal => {
                write!(f, " --base-env=minimal")?;
            }
            BaseEnv::Host => {} // default
        }
        for (key, m_val) in &self.env {
            if let Some(val) = m_val {
                write!(f, " --env={}={}", key, shell_words::quote(val))?;
            } else {
                write!(f, " --env={}", key)?;
            }
        }
        if let Some(p) = &self.workdir {
            write!(f, " --workdir={}", shell_words::quote(p))?;
        }
        if let Some(p) = &self.save_config {
            let s = p.to_str().expect("valid string provided to --save-config");
            write!(f, " --save-config={}", shell_words::quote(s))?;
        }
        if let Some(p) = &self.happens_before {
            let s = p
                .to_str()
                .expect("valid string provided to --happens-before");
            write!(f, " --happens-before={}", shell_words::quote(s))?;
        }
        if self.hb_list_events {
            write!(f, " --hb-list-events")?;
        }

        for mount in &self.mount {
            let mut acc = Vec::new();
            if let Some(s) = &mount.get_source() {
                acc.push(format!("source={}", s.display()));
            }
            acc.push(format!("target={}", mount.get_target().display()));
            write!(f, "--mount={}", shell_words::quote(&acc.join(",")),)?;
        }
        for bind in &self.bind {
            let src = bind.source.to_str().expect("valid unicode bind source");
            let tar = bind.target.to_str().expect("valid unicode target");
            if bind.source == bind.target {
                write!(f, " --bind={}", shell_words::quote(src))?;
            } else {
                write!(
                    f,
                    " --bind={}:{}",
                    shell_words::quote(src),
                    shell_words::quote(tar)
                )?;
            }
        }

        // A reproducer must retain the actual epoch, including the stable
        // library default: an omitted CLI epoch now captures a new host time.
        // Config already emits nondefault epochs, so add only its omitted case.
        write!(f, "{}", dop)?;
        if dop.has_default_epoch() {
            write!(f, " --epoch={}", dop.epoch.to_rfc3339())?;
        }

        write!(
            f,
            " -- {}",
            shell_words::quote(self.program.to_str().expect("valid unicode path"))
        )?;
        if !self.args.is_empty() {
            write!(f, " {}", shell_words::join(&self.args))?;
        }
        Ok(())
    }
}

/// Returns true if `program` names a hardware emulator / virtual machine
/// monitor whose emulated guest runs its own clock calibration. Such programs
/// (notably the `qemu-system-*` family) are sensitive to Hermit's host-time
/// virtualization. This is a filename heuristic used only to surface an advisory
/// warning; it never changes Hermit's behavior.
fn is_vmm_program(program: &Path) -> bool {
    program
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with("qemu-system-"))
}

/// Whether the emulator's own command line already asks for QEMU's
/// instruction-derived clock.
///
/// `-icount` is the remedy this advisory recommends, so a run that already
/// passes it has nothing left to act on and the advisory only adds noise.
/// Accepts both spellings QEMU takes: `-icount shift=0,sleep=off` as two
/// arguments, and `-icount=shift=0,sleep=off` as one.
fn emulator_uses_instruction_count_clock(args: &[String]) -> bool {
    args.iter()
        .any(|arg| arg == "-icount" || arg.starts_with("-icount="))
}

/// Advisory warning for running a VMM under Hermit's host-time virtualization.
///
/// QEMU and similar emulators derive the emulated PIT, PM timer, APIC timer,
/// RTC, and TSC from several different host clocks. Hermit virtualizes RDTSC and
/// `clock_gettime` from separate logical-time bases that are not mutually
/// coherent (especially under `--no-sequentialize-threads`), so the nested guest
/// observes inconsistent clock domains and its calibration breaks. See issue #6
/// and `docs/QEMU_BOOT.md`. Returns the message to print, or `None` when no
/// warning applies.
///
/// WHAT THIS USED TO SAY, AND WHY IT NO LONGER SAYS IT. Until 2026-08-21 the
/// message offered `--no-virtualize-time --no-virtualize-metadata` as one of two
/// remedies. Measured on 2026-08-21 with hermit `f05bf04e4f`, a busybox guest at
/// one vCPU and no `-icount`, that option changes nothing about this failure:
/// the run with it and the run without it both panic in guest timer setup and
/// both produce a 9,233-byte console. At the time, combined with `--strict` it
/// was worse than useless — strict mode rejected the unvirtualized
/// `gettimeofday` and Hermit exited 1 before the guest started (clock syscalls
/// now pass through to the host clock instead; see
/// https://github.com/rrnewton/hermit/issues/1176). Recommending it sent readers down a dead end
/// at the moment they were most likely to follow the advice, so the message now
/// names only remedies that were measured to reach a booted guest.
fn vmm_time_virtualization_warning(
    program: &Path,
    args: &[String],
    virtualize_time: bool,
) -> Option<String> {
    if virtualize_time && is_vmm_program(program) && !emulator_uses_instruction_count_clock(args) {
        Some(format!(
            "WARNING: {} looks like a hardware emulator (VMM). Hermit's host-time \
             virtualization exposes mutually inconsistent clock sources (a synthetic RDTSC \
             versus a virtualized clock_gettime) to the emulated guest, which can corrupt its \
             clock calibration (for example \"Unable to calibrate against PIT\", TSC marked \
             unstable, or \"No current clocksource\") and stall boot. Two routes were measured \
             to reach a booted guest: give the emulator a single instruction-derived clock \
             (for QEMU: -icount shift=0,sleep=off), or pass no_timer_check on the nested \
             guest's kernel command line. Note that -icount forecloses multi-threaded TCG, \
             which QEMU refuses to combine with it. See docs/QEMU_BOOT.md.",
            program.display()
        ))
    } else {
        None
    }
}

#[test]
fn vmm_time_warning_fires_for_qemu_with_virtual_time() {
    // A qemu-system-* emulator under virtual time gets the advisory.
    for program in [
        "qemu-system-x86_64",
        "/usr/bin/qemu-system-x86_64",
        "qemu-system-aarch64",
    ] {
        let warning = vmm_time_virtualization_warning(Path::new(program), &[], true);
        let message = warning
            .unwrap_or_else(|| panic!("expected a warning for {program} under virtual time"));
        assert!(message.contains("-icount"));
        assert!(message.contains("no_timer_check"));
    }
}

/// The advisory must not send a reader to a route that does not work.
///
/// This assertion replaces one that required the message to CONTAIN
/// `--no-virtualize-time`. That earlier assertion was not wrong when it was
/// written — it pinned the wording deliberately — but it outlived the
/// measurement, so a passing test stood between the reader and a correction.
/// The pin is kept and inverted rather than deleted: the wording is still
/// asserted, now against what the measurement supports.
#[test]
fn vmm_time_warning_does_not_recommend_disabling_virtual_time() {
    let message = vmm_time_virtualization_warning(Path::new("qemu-system-x86_64"), &[], true)
        .expect("expected a warning under virtual time");
    assert!(
        !message.contains("--no-virtualize-time"),
        "the advisory must not recommend --no-virtualize-time: measured 2026-08-21, it leaves \
         the guest panicking in timer setup with a byte-identical console, and combined with \
         --strict it aborts the run before the guest starts. Message was: {message}"
    );
    assert!(
        !message.contains("--no-virtualize-metadata"),
        "same: --no-virtualize-metadata is half of a route that does not work. Message was: \
         {message}"
    );
}

/// The second half of the defect: the advisory fired whenever virtual time was
/// on, including for runs that had already applied its own recommendation.
/// Measured before the fix: `hermit run --no-sequentialize-threads -- \
/// qemu-system-x86_64 -icount shift=0,sleep=off ...` printed the warning.
#[test]
fn vmm_time_warning_silent_when_the_emulator_already_uses_icount() {
    for args in [
        vec!["-icount".to_string(), "shift=0,sleep=off".to_string()],
        vec!["-icount=shift=0,sleep=off".to_string()],
        vec![
            "-nographic".to_string(),
            "-icount".to_string(),
            "shift=auto".to_string(),
        ],
    ] {
        assert!(
            vmm_time_virtualization_warning(Path::new("qemu-system-x86_64"), &args, true).is_none(),
            "the emulator already uses the instruction-derived clock this advisory \
             recommends, so there is nothing left to act on: {args:?}"
        );
    }
}

/// The guard on the guard: a command line that merely mentions icount in some
/// other position must still warn, or the silence above would swallow real
/// cases.
#[test]
fn vmm_time_warning_still_fires_for_arguments_that_only_resemble_icount() {
    for args in [
        vec!["-no-icount".to_string()],
        vec!["--icount".to_string()],
        vec!["-append".to_string(), "icount=1".to_string()],
        vec!["-drive".to_string(), "file=icount.qcow2".to_string()],
    ] {
        assert!(
            vmm_time_virtualization_warning(Path::new("qemu-system-x86_64"), &args, true).is_some(),
            "these do not enable QEMU's instruction-derived clock, so the advisory still \
             applies: {args:?}"
        );
    }
}

#[test]
fn vmm_time_warning_silent_without_virtual_time() {
    // Hermit's virtual clock is off, so there is no clock-domain mismatch to
    // warn about. (This is not an endorsement of --no-virtualize-time as a
    // remedy for a stalled boot; see the note on the warning function.)
    assert!(
        vmm_time_virtualization_warning(Path::new("qemu-system-x86_64"), &[], false).is_none(),
        "no warning is expected once virtual time is disabled"
    );
}

#[test]
fn vmm_time_warning_silent_for_non_vmm_programs() {
    for program in ["ls", "/bin/echo", "qemu-img", "my-qemu-wrapper"] {
        assert!(
            vmm_time_virtualization_warning(Path::new(program), &[], true).is_none(),
            "unexpected VMM warning for {program}"
        );
    }
}

/// Parse `hermit [GLOBAL...] run [RUN...]` through the real top-level parser and
/// apply the global `--backend` the way [`RunOpts::main`] does. `run` itself does
/// not accept `--backend`; see `cli.rs::run_rejects_subcommand_level_backend`.
#[cfg(test)]
fn run_opts_for(argv: &[&str]) -> RunOpts {
    use clap::CommandFactory;
    use clap::FromArgMatches;
    let matches = crate::Args::command()
        .try_get_matches_from(argv)
        .unwrap_or_else(|error| panic!("{argv:?} should parse: {error}"));
    let args = crate::Args::from_arg_matches(&matches).unwrap();
    let crate::Subcommand::Run(mut run) = args.command else {
        panic!("{argv:?} is not a `run` command");
    };
    run.capture_max_timeslice_source(matches.subcommand_matches("run").unwrap());
    run.backend = args.global.backend;
    *run
}

#[cfg(test)]
fn assert_exec_stop_not_ready(error: &Error) {
    assert!(error.downcast_ref::<PolicyRefusal>().is_some(), "{error:#}");
    assert!(
        error.to_string().contains("exec-stop-runtime-not-ready"),
        "{error:#}"
    );
}

#[test]
fn exec_stop_opt_in_is_uniform_and_retained_in_reproducers() {
    let mut ordinary = run_opts_for(&["hermit", "run", "--", "/nonexistent/guest"]);
    assert!(!ordinary.in_guest_exec_stop);
    ordinary.refuse_unready_exec_stop().unwrap();
    ordinary.validate_args_with_perf_support(true).unwrap();
    assert!(!ordinary.to_string().contains("--in-guest-exec-stop"));

    for backend in <Backend as clap::ValueEnum>::value_variants() {
        let backend_arg = format!("--backend={}", backend.as_str());
        let options = run_opts_for(&[
            "hermit",
            &backend_arg,
            "run",
            "--in-guest-exec-stop",
            "--",
            "/nonexistent/guest",
        ]);
        assert!(options.in_guest_exec_stop);
        assert_exec_stop_not_ready(&options.refuse_unready_exec_stop().unwrap_err());
        // Display consumes a normalized configuration. A pending launch is
        // deliberately refused before normalization; test its serialization
        // separately, without bypassing the admission exercised above.
        let mut rendered =
            run_opts_for(&["hermit", &backend_arg, "run", "--", "/nonexistent/guest"]);
        rendered.validate_args_with_perf_support(true).unwrap();
        rendered.in_guest_exec_stop = true;
        assert!(rendered.to_string().contains("--in-guest-exec-stop"));
    }
}

#[test]
fn exec_stop_direct_entries_refuse_before_launch_work() {
    let args = crate::Args::try_parse_from([
        "hermit",
        "run",
        "--in-guest-exec-stop",
        "--dap-listen=127.0.0.1:0",
        "--",
        "/nonexistent/guest",
    ])
    .unwrap();
    let crate::Subcommand::Run(mut options) = args.command else {
        unreachable!()
    };
    // main must refuse before it can spawn the DAP supervisor; validation
    // must refuse before it probes timers, and run before it creates a container.
    assert_exec_stop_not_ready(&options.main(&args.global).unwrap_err());
    assert_exec_stop_not_ready(&options.validate_args().unwrap_err());
    for timer_available in [false, true] {
        assert_exec_stop_not_ready(
            &options
                .validate_args_with_perf_support(timer_available)
                .unwrap_err(),
        );
    }
    assert_exec_stop_not_ready(&options.run(&args.global, false).unwrap_err());
    let container_result = options.launch_in_container(
        (),
        "exec-stop refusal test",
        None,
        |_, _, _| -> Result<(), Error> { panic!("flagged request reached container work") },
    );
    assert_exec_stop_not_ready(&container_result.unwrap_err());
    let verification_result = options.verify_with_execution(|_, _, _, _, _| {
        panic!("flagged request reached verification execution")
    });
    assert_exec_stop_not_ready(&verification_result.unwrap_err());
}

/// A version-2 happens-before spec needs an effective preemption timer.
/// Validation can turn a requested timer off when the host cannot arm it; the
/// check right after validation must then refuse the run, naming the spec and
/// the reason, while a supported timer and a version-1 spec are not refused.
#[test]
fn a_version_2_spec_is_refused_when_validation_turns_the_timer_off() {
    let dir = tempfile::tempdir().unwrap();
    let v2 = dir.path().join("v2.json");
    let v1 = dir.path().join("v1.json");
    std::fs::write(
        &v2,
        r#"{"version": 2, "events": {"w": {"thread": "3", "syscall": "write", "fd": 1}}}"#,
    )
    .unwrap();
    std::fs::write(
        &v1,
        r#"{"version": 1, "events": {"w": {"thread": "3", "syscall": "write", "fd": 1}}}"#,
    )
    .unwrap();
    let after_validation = |spec: &Path, timer: Result<(), TimerUnavailable>| {
        let mut ro = run_opts_for(&[
            "hermit",
            "run",
            "--happens-before",
            spec.to_str().unwrap(),
            "fakeprog",
        ]);
        assert!(
            ro.det_opts.det_config.max_timeslice.is_some(),
            "the default requests a timer"
        );
        ro.validate_args_with_timer_support(timer).unwrap();
        let refusal = ro.refuse_happens_before_without_preemption();
        (ro.det_opts.det_config.max_timeslice.is_some(), refusal)
    };

    let (timer, refusal) = after_validation(&v2, Err(TimerUnavailable::NoPerfEvents));
    assert!(!timer);
    let error = refusal.expect_err("no perf counters");
    assert!(
        error
            .downcast_ref::<super::container::PolicyRefusal>()
            .is_some(),
        "{error:#}"
    );
    let message = format!("{error:#}");
    assert!(
        message.contains("HERMIT_HB_HOLD_WITHOUT_PREEMPTION: happens-before spec ")
            && message.contains(v2.to_str().unwrap())
            && message.contains("is version 2")
            && message.contains("this host cannot arm it: perf_event_open is unavailable"),
        "{message}"
    );

    let profile = "Unsupported CPU family 0x6, model 0x1: Reverie has no performance-counter \
                   profile for it";
    let (timer, refusal) =
        after_validation(&v2, Err(TimerUnavailable::NoPmuProfile(profile.to_owned())));
    assert!(!timer);
    let message = format!("{:#}", refusal.expect_err("no PMU profile"));
    assert!(
        message.contains(&format!("this host cannot arm it: {profile}")),
        "{message}"
    );

    let (timer, refusal) = after_validation(&v2, Ok(()));
    assert!(timer);
    refusal.expect("a supported timer is not refused");

    let (timer, refusal) = after_validation(&v1, Err(TimerUnavailable::NoPerfEvents));
    assert!(!timer);
    refusal.expect("a version-1 spec has no budget and runs without the timer");
}

/// The launch-time happens-before refusal keys on the runtime backend:
/// `--backend=e9patch` rewrites the program and runs it under ptrace, which
/// enforces count and syscall-occurrence anchors, so neither is refused there.
/// An in-guest backend never receives the program, so both are refused.
#[test]
fn happens_before_refusal_accepts_e9patch_and_refuses_in_guest_backends() {
    let dir = tempfile::tempdir().unwrap();
    let spec = dir.path().join("spec.json");
    let spec_arg = spec.to_str().unwrap();
    for (name, json) in [
        (
            "count",
            r#"{"version": 1, "events": {"c": {"thread": "3", "syscalls": 5}}}"#,
        ),
        (
            "occurrence",
            r#"{"version": 1, "events": {"w": {"thread": "3", "syscall": "write", "fd": 1}}}"#,
        ),
    ] {
        std::fs::write(&spec, json).unwrap();
        let check = |backend: Option<&str>| {
            let mut argv = vec!["hermit"];
            if let Some(backend) = backend {
                argv.extend(["--backend", backend]);
            }
            argv.extend(["run", "--happens-before", spec_arg, "fakeprog"]);
            run_opts_for(&argv).refuse_unenforceable_happens_before()
        };
        for backend in [None, Some("ptrace"), Some("e9patch")] {
            if let Err(error) = check(backend) {
                panic!("{name} anchor refused under {backend:?}: {error:#}");
            }
        }
        for backend in ["sabre", "kvm", "dbt", "liteinst", "in-guest-trap"] {
            let error = check(Some(backend)).expect_err(backend);
            assert!(
                error
                    .downcast_ref::<super::container::PolicyRefusal>()
                    .is_some()
                    && format!("{error:#}").contains("enforced only on the ptrace backend"),
                "{name} anchor under {backend}: {error:#}"
            );
        }
    }
}

/// A spec the user must fix is a policy refusal; a failure to read it that is
/// not the user's (here `EIO`, from reading `/proc/self/mem` at address 0) is
/// not.
#[test]
fn happens_before_spec_load_errors_are_refusals_except_host_read_failures() {
    let dir = tempfile::tempdir().unwrap();
    let nth_zero = dir.path().join("nth0.json");
    std::fs::write(
        &nth_zero,
        r#"{"version": 1, "events": {"z": {"thread": "3", "syscall": "write", "nth": 0}}}"#,
    )
    .unwrap();
    let not_json = dir.path().join("bad.json");
    std::fs::write(&not_json, "{").unwrap();
    let not_utf8 = dir.path().join("latin1.json");
    std::fs::write(&not_utf8, b"\xff").unwrap();
    for path in [
        nth_zero,
        not_json,
        not_utf8,
        dir.path().join("missing.json"),
        dir.path().to_path_buf(),
        // ENOTDIR: a path through a regular file.
        dir.path().join("bad.json").join("spec.json"),
    ] {
        let error = RunOpts::load_happens_before_spec(&path).expect_err("must not load");
        assert!(
            error
                .downcast_ref::<super::container::PolicyRefusal>()
                .is_some(),
            "{}: {error:#}",
            path.display()
        );
    }
    let error = RunOpts::load_happens_before_spec(Path::new("/proc/self/mem"))
        .expect_err("reading /proc/self/mem at address 0 fails");
    assert_eq!(
        error
            .downcast_ref::<std::io::Error>()
            .and_then(std::io::Error::raw_os_error),
        Some(libc::EIO),
        "{error:#}"
    );
    assert!(
        error
            .downcast_ref::<super::container::PolicyRefusal>()
            .is_none(),
        "{error:#}"
    );
}

#[cfg(test)]
impl RunOpts {
    /// These options as a run config must reproduce them: every field
    /// except the runtime-only provenance that a reload legitimately changes.
    /// An epoch the first parse took from the clock is explicit after a
    /// reload, and `--save-config` is never written into the file.
    pub(crate) fn config_equivalence_key(&self) -> String {
        let mut options = self.clone();
        options.epoch_omitted = false;
        options.epoch_captured_from_host = false;
        options.epoch_from_recording = false;
        options.config_capture = None;
        options.save_config = None;
        options.manifest = None;
        options.manifest_path = None;
        options.pending_network_manifest = None;
        format!("{options:#?}")
    }
}

/// `--save-config` writes the seed `--seed-from` chose in its place, so the
/// saved run does not choose again.
#[test]
fn saved_config_records_the_seed_seed_from_chose() {
    let argv = [
        "hermit",
        "run",
        "--seed-from=SystemRandom",
        "--seed=3",
        "--save-config=unused.yaml",
        "/bin/true",
    ];
    let matches = <crate::Args as clap::CommandFactory>::command()
        .try_get_matches_from(argv)
        .unwrap();
    let args = crate::args_from_matches_with_clock(&matches, SystemTime::now).unwrap();
    let crate::Subcommand::Run(mut ro) = args.command else {
        panic!("{argv:?} is not a `run` command");
    };
    let before = ro.saved_run_config().unwrap();
    assert_eq!(before.run["seed-from"], "SystemRandom");
    assert_eq!(before.run["seed"], 3);
    ro.validate_args_with_perf_support(true).unwrap();
    let chosen = ro.det_opts.det_config.seed;
    let saved = ro.saved_run_config().unwrap();
    assert_eq!(saved.run.get("seed-from"), None, "{saved:?}");
    assert_eq!(saved.run["seed"], chosen, "{saved:?}");
}

/// An epoch adopted from a replayed recording is an implicit input too.
#[test]
fn saved_config_records_an_epoch_adopted_from_a_recording() {
    let argv = ["hermit", "run", "--save-config=unused.yaml", "/bin/true"];
    let matches = <crate::Args as clap::CommandFactory>::command()
        .try_get_matches_from(argv)
        .unwrap();
    let mut args = crate::args_from_matches_with_clock(&matches, SystemTime::now).unwrap();
    let crate::Subcommand::Run(ro) = &mut args.command else {
        panic!("{argv:?} is not a `run` command");
    };
    // What `adopt_replayed_schedule_epoch` leaves behind.
    ro.det_opts.det_config.epoch = "2001-02-03T04:05:06.5Z".parse().unwrap();
    ro.epoch_captured_from_host = false;
    ro.epoch_from_recording = true;
    let saved = ro.saved_run_config().unwrap();
    assert_eq!(saved.run["epoch"], "2001-02-03T04:05:06.500+00:00");
}

/// Without `--save-config` there is nothing to capture, and asking for the
/// config says why instead of writing an empty one.
#[test]
fn saved_config_requires_the_parsers_capture() {
    let ro = RunOpts::parse_from(["fakehermit", "--save-config=x.yaml", "fakeprog"]);
    let error = ro.saved_run_config().unwrap_err().to_string();
    assert!(
        error.contains("only by a `hermit run` invocation"),
        "{error}"
    );
}

#[test]
fn display_runopts1() {
    let vec: Vec<&str> = vec!["fakehermit", "fakeprog", "arg1", "arg2"];
    let mut ro = RunOpts::parse_from(vec.iter());
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        format!("{}", ro),
        " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog arg1 arg2"
    );
}

#[test]
fn backend_defaults_to_ptrace() {
    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(ro.backend, None);
    assert_eq!(ro.selected_backend(), Backend::Ptrace);
    assert_eq!(
        format!("{}", ro),
        " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn backend_values_parse_and_round_trip() {
    for (value, expected) in [
        ("ptrace", Backend::Ptrace),
        ("dbt", Backend::Dbt),
        ("liteinst", Backend::Liteinst),
        ("in-guest-trap", Backend::InGuestTrap),
        ("sabre", Backend::Sabre),
        ("kvm", Backend::Kvm),
        ("e9patch", Backend::E9patch),
    ] {
        let mut ro = run_opts_for(&["hermit", "--backend", value, "run", "fakeprog"]);
        ro.validate_args_with_perf_support(true).unwrap();
        assert_eq!(ro.backend, Some(expected));
        assert_eq!(ro.selected_backend(), expected);
        // The backend is global, so it renders before the subcommand and is not
        // part of the `run` options' own rendering.
        assert_eq!(ro.global_backend_arg(), format!(" --backend={value}"));
        assert_eq!(
            format!("{}", ro),
            " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
        );
    }
}

/// A PLAIN `--verify` CANNOT REACH THE CANONICAL COMPARATOR, AND `--verify-strict`
/// ALWAYS CAN — ON EVERY BACKEND, INCLUDING KVM.
///
/// Ported from the superseded hermit#2217, which fixed
/// `let kvm_output_only = self.selected_backend() == Backend::Kvm` by making the
/// bypass conditional. Current main fixed it more strongly, by DELETING the
/// backend term outright, so that pull request's own test could not be ported as
/// written: it asserted on a `compare_verification_logs(backend, ..)` helper that
/// main has no equivalent of, and re-creating one to test would have pinned the
/// new helper rather than the shipped call sites.
///
/// ⚠️ THE HAZARD THIS ANSWERS: a removed branch leaves nothing behind to notice
/// its return. `bitwise_parity_contract_accepts_only_named_canonical_envelopes`
/// already pins that only a canonical envelope may claim parity, but nothing
/// pinned WHICH REQUESTS REACH canonical — so re-introducing a backend term in
/// `verification_strictness` would have restored the original defect silently.
/// Iterating every `Backend` variant is what makes that impossible: a KVM-shaped
/// special case fails here by name.
#[test]
fn comparator_choice_does_not_depend_on_the_backend() {
    for (value, backend) in [
        ("ptrace", Backend::Ptrace),
        ("dbt", Backend::Dbt),
        ("liteinst", Backend::Liteinst),
        ("in-guest-trap", Backend::InGuestTrap),
        ("sabre", Backend::Sabre),
        ("kvm", Backend::Kvm),
        ("e9patch", Backend::E9patch),
    ] {
        let plain = run_opts_for(&["hermit", "--backend", value, "run", "--verify", "fakeprog"]);
        assert_eq!(plain.selected_backend(), backend);
        assert_eq!(
            plain.verification_strictness(),
            LogCompareStrictness::Stripped,
            "plain --verify on {value} must stay on the lossy comparator, so it \
             cannot claim canonical bitwise parity"
        );

        for flag in ["--verify-strict", "--verify-verbose"] {
            let canonical = run_opts_for(&[
                "hermit",
                "--backend",
                value,
                "run",
                "--verify",
                flag,
                "fakeprog",
            ]);
            assert_eq!(
                canonical.verification_strictness(),
                LogCompareStrictness::Canonical,
                "{flag} on {value} must reach the canonical comparator; KVM \
                 bypassing it unconditionally was the hermit#2217 defect"
            );
        }
    }
}

#[test]
fn verification_always_compares_retained_logs() {
    for backend in [
        "ptrace",
        "dbt",
        "liteinst",
        "in-guest-trap",
        "sabre",
        "kvm",
        "e9patch",
    ] {
        let run = run_opts_for(&[
            "hermit",
            "--backend",
            backend,
            "run",
            "--verify",
            "fakeprog",
        ]);
        assert!(
            run.verification_comparison_options().compare_logs,
            "--verify on {backend} must compare both retained logs"
        );
    }
}

#[test]
fn every_backend_keeps_io_buffer_checking_on_by_default() {
    for backend in [
        "ptrace",
        "dbt",
        "liteinst",
        "in-guest-trap",
        "sabre",
        "kvm",
        "e9patch",
    ] {
        let run = run_opts_for(&[
            "hermit",
            "--backend",
            backend,
            "run",
            "--verify",
            "--verify-strict",
            "fakeprog",
        ]);
        let prepared =
            hermit::prepare_backend_config(run.effective_det_config(), run.runtime_backend());
        assert!(
            prepared.detlog_io_buffers,
            "{backend} disabled syscall output-buffer checking while the ordinary strict-verify \
             request left it enabled"
        );
        {
            assert_eq!(
                run.verification_comparison_options().compare_io_buffers,
                prepared.detlog_io_buffers,
                "{backend} reported an io-buffer comparison state different from the \
                 configuration that backend actually receives"
            );
        }

        let opted_out = run_opts_for(&[
            "hermit",
            "--backend",
            backend,
            "run",
            "--verify",
            "--verify-strict",
            "--no-detlog-io-buffers",
            "fakeprog",
        ]);
        let prepared_opt_out = hermit::prepare_backend_config(
            opted_out.effective_det_config(),
            opted_out.runtime_backend(),
        );
        assert!(
            !prepared_opt_out.detlog_io_buffers,
            "{backend} ignored the explicit --no-detlog-io-buffers relaxation"
        );
        {
            assert_eq!(
                opted_out
                    .verification_comparison_options()
                    .compare_io_buffers,
                prepared_opt_out.detlog_io_buffers,
                "{backend} reported an io-buffer comparison state different from its explicit \
                 opt-out"
            );
        }
    }
}

#[test]
fn e9patch_preserves_executable_identity_and_uses_ptrace_runtime() {
    let mut ro = run_opts_for(&[
        "hermit",
        "--backend",
        "e9patch",
        "run",
        "/bin/echo",
        "hello",
    ]);
    ro.e9patch_overlay = Some(E9patchOverlay {
        source: PathBuf::from("/cache/patched-echo"),
        target: PathBuf::from("/bin/echo"),
    });
    let command = ro.guest_command().unwrap();
    assert_eq!(command.get_program(), "/bin/echo");
    assert_eq!(command.get_arg0(), "/bin/echo");
    assert_eq!(ro.runtime_backend(), Backend::Ptrace);

    let tmpfs = tempfile::tempdir().unwrap();
    let mounts = ro.mounts(tmpfs.path()).unwrap();
    let overlay = mounts
        .mounts
        .iter()
        .find(|planned| planned.mount.get_source() == Some(Path::new("/cache/patched-echo")))
        .unwrap();
    assert_eq!(overlay.mount.get_target(), Path::new("/bin/echo"));
    // The overlay is e9patch's own mount, which the guest's mount table
    // leaves out by this identity.
    assert!(overlay.backend);
}

#[test]
fn mapped_guest_path_is_resolved_before_host_validation() {
    let tmp = tempfile::tempdir().unwrap();
    let tool = tmp.path().join("tool");
    fs::write(&tool, b"fixture").unwrap();
    let mut permissions = fs::metadata(&tool).unwrap().permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&tool, permissions).unwrap();

    let tmp_arg = format!("--tmp={}", tmp.path().display());
    let mut ro = run_opts_for(&[
        "hermit",
        "--backend",
        "e9patch",
        "run",
        &tmp_arg,
        "-e",
        "PATH=/tmp",
        "tool",
    ]);
    assert_eq!(ro.tmp.as_deref(), Some(tmp.path()));
    assert_eq!(
        ro.guest_command()
            .unwrap()
            .get_captured_envs()
            .get(OsStr::new("PATH")),
        Some(&OsStr::new("/tmp").to_os_string())
    );
    assert_eq!(
        ro.mapped_host_program(Path::new("/tmp/tool")),
        GuestPathMapping::Mapped(tool.clone())
    );
    let (guest, host) = ro.resolve_guest_and_host_program().unwrap();
    assert_eq!(guest, Path::new("/tmp/tool"));
    assert_eq!(host, tool);
    ro.e9patch_program = Some(guest);
    let command = ro.guest_command().unwrap();
    assert_eq!(command.get_program(), "/tmp/tool");
    assert_eq!(command.get_arg0(), "tool");
}

#[test]
fn non_e9patch_validation_preserves_parent_component_paths() {
    let ro = run_opts_for(&["hermit", "--backend", "ptrace", "run", "/bin/../bin/echo"]);
    ro.validate_program().unwrap();
}

/// The guest environment must be identical across backends. Sanitizer leak
/// detection is disabled in `guest_command()` (the single backend-independent
/// place) rather than only in the ptrace tracer, so the out-of-process KVM
/// backend presents the guest the same environment as ptrace/e9patch/sabre.
/// Regression test for the KVM-vs-ptrace env divergence, where the guest saw
/// two fewer variables under KVM.
#[test]
fn guest_env_disables_sanitizer_leak_detection_on_every_backend() {
    let asan = OsStr::new("ASAN_OPTIONS");
    let lsan = OsStr::new("LSAN_OPTIONS");
    let expected = OsStr::new("detect_leaks=0").to_os_string();

    // The two variables are present with identical values regardless of the
    // selected backend, so no backend-specific spawn hook is required for parity.
    for backend in ["ptrace", "kvm", "sabre", "dbt"] {
        let ro = run_opts_for(&["hermit", "--backend", backend, "run", "/bin/echo", "hi"]);
        let envs = ro.guest_command().unwrap().get_captured_envs();
        assert_eq!(
            envs.get(asan),
            Some(&expected),
            "ASAN_OPTIONS not set for backend {backend}"
        );
        assert_eq!(
            envs.get(lsan),
            Some(&expected),
            "LSAN_OPTIONS not set for backend {backend}"
        );
    }
}

#[test]
fn namespace_only_guest_command_applies_process_options_once() {
    let ro = RunOpts::parse_from([
        "fakehermit",
        "--namespace-only",
        "--base-env=minimal",
        "--env=NAMESPACE_ONLY_EXPLICIT=present",
        "--workdir=/test",
        "/bin/echo",
        "first",
        "second",
    ]);
    let command = ro.namespace_only_guest_command().unwrap();

    assert_eq!(command.get_program(), OsStr::new("/bin/echo"));
    assert_eq!(
        command.get_args().collect::<Vec<_>>(),
        &[OsStr::new("first"), OsStr::new("second")]
    );
    assert_eq!(command.get_current_dir(), Some(Path::new("/test")));

    let envs = command.get_captured_envs();
    assert_eq!(
        envs.len(),
        4,
        "unexpected namespace-only environment: {envs:?}"
    );
    assert_eq!(
        envs.get(OsStr::new("HOME")).map(|value| value.as_os_str()),
        Some(OsStr::new("/root"))
    );
    assert_eq!(
        envs.get(OsStr::new("HOSTNAME"))
            .map(|value| value.as_os_str()),
        Some(OsStr::new("hermetic-container.local"))
    );
    assert_eq!(
        envs.get(OsStr::new("PATH")).map(|value| value.as_os_str()),
        Some(OsStr::new(
            "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ))
    );
    assert_eq!(
        envs.get(OsStr::new("NAMESPACE_ONLY_EXPLICIT"))
            .map(|value| value.as_os_str()),
        Some(OsStr::new("present"))
    );
}

#[test]
fn namespace_only_guest_command_preserves_sanitizer_environment() {
    let ro = RunOpts::parse_from(["fakehermit", "--namespace-only", "/bin/true"]);
    let command = ro.namespace_only_guest_command().unwrap();
    let sanitizer_overrides: Vec<_> = command
        .get_envs()
        .filter(|(name, _)| {
            *name == OsStr::new("ASAN_OPTIONS") || *name == OsStr::new("LSAN_OPTIONS")
        })
        .map(|(name, value)| (name.to_owned(), value.map(OsStr::to_owned)))
        .collect();

    assert!(
        sanitizer_overrides.is_empty(),
        "namespace-only added explicit sanitizer overrides: {sanitizer_overrides:?}"
    );

    let missing = format!("HERMIT_NAMESPACE_ONLY_MISSING_ENV_{}", std::process::id());
    assert!(std::env::var_os(&missing).is_none());
    let option = format!("--env={missing}");
    let ro = RunOpts::parse_from(["fakehermit", "--namespace-only", &option, "/bin/true"]);
    let error = match ro.namespace_only_guest_command() {
        Ok(_) => panic!("namespace-only accepted a missing pass-through environment variable"),
        Err(error) => error.to_string(),
    };
    assert!(error.contains(&missing), "unexpected error: {error}");
    assert!(error.contains("not set in the host environment"), "{error}");
}

#[cfg(feature = "dbt")]
#[test]
fn dbt_runtime_binds_do_not_change_original_options_or_guest_inputs() {
    let options = run_opts_for(&[
        "hermit",
        "--backend=dbt",
        "run",
        "--strict",
        "--",
        "/bin/echo",
        "guest argument",
    ]);
    let original = format!("{options:?}");
    let guest = options.guest_command().unwrap();
    let config = hermit::dbt_detconfig_json(&options.effective_det_config()).unwrap();
    let binding = Bind::new("/host/private/stats", "/tmp/.hermit-dbt-stats-0");
    let launch = options.with_dbt_mounts(std::slice::from_ref(&binding), Vec::new());
    assert_eq!(launch.bind.last(), Some(&binding));
    assert_eq!(format!("{options:?}"), original);
    assert!(options.dbt_binds().is_empty());
    assert_eq!(
        hermit::dbt_detconfig_json(&launch.effective_det_config()).unwrap(),
        config
    );
    let launched_guest = launch.guest_command().unwrap();
    assert_eq!(guest.get_program(), launched_guest.get_program());
    assert_eq!(
        guest.get_args().collect::<Vec<_>>(),
        launched_guest.get_args().collect::<Vec<_>>()
    );
    assert_eq!(
        guest.get_envs().collect::<Vec<_>>(),
        launched_guest.get_envs().collect::<Vec<_>>()
    );
}

#[cfg(feature = "dbt")]
#[test]
fn dbt_rejects_mount_but_accepts_bind_and_workdir() {
    let mut with_mount = run_opts_for(&[
        "hermit",
        "--backend",
        "dbt",
        "run",
        "--mount=type=tmpfs,target=/test",
        "/bin/true",
    ]);
    let error = with_mount
        .validate_args_with_perf_support(true)
        .unwrap_err()
        .to_string();
    assert!(error.contains("dbt backend cannot apply --mount"));

    // The adapter applies a bind under /tmp; one outside it has no effect, as
    // for the other backends.
    let mut with_bind = run_opts_for(&[
        "hermit",
        "--backend",
        "dbt",
        "run",
        "--bind=/tmp:/tmp/test",
        "--bind=/tmp:/test",
        "--workdir",
        "/tmp/test",
        "/bin/true",
    ]);
    with_bind.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        with_bind.dbt_binds(),
        vec![(PathBuf::from("/tmp"), PathBuf::from("/tmp/test"))]
    );

    let mut with_workdir = run_opts_for(&[
        "hermit",
        "--backend",
        "dbt",
        "run",
        "--workdir",
        "/test",
        "/bin/true",
    ]);
    with_workdir.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        with_workdir.guest_command().unwrap().get_current_dir(),
        Some(Path::new("/test"))
    );
}

#[test]
fn guest_path_normalization_rejects_parent_components() {
    let error = normalize_guest_path(Path::new("/mnt/../tool")).unwrap_err();
    assert!(error.to_string().contains("parent components"));
}

#[test]
fn e9patch_mount_target_rejects_parent_components() {
    let ro = run_opts_for(&[
        "hermit",
        "--backend",
        "e9patch",
        "run",
        "--mount=type=tmpfs,target=/tmp/../bin",
        "/bin/echo",
    ]);
    let error = ro.validate_e9patch_mount_targets().unwrap_err().to_string();
    assert!(error.contains("mount target cannot contain parent components"));
}

#[test]
fn e9patch_mount_target_rejects_symlink_components() {
    let directory = tempfile::tempdir().unwrap();
    let link = directory.path().join("link");
    std::os::unix::fs::symlink("/tmp", &link).unwrap();
    let mount = format!(
        "--mount=type=tmpfs,target={}",
        link.join("target").display()
    );
    let ro = run_opts_for(&["hermit", "--backend", "e9patch", "run", &mount, "/bin/echo"]);
    let error = ro.validate_e9patch_mount_targets().unwrap_err();
    assert!(error.to_string().contains("mount target traverses symlink"));
}

#[test]
fn source_less_mount_hides_program_from_resolution() {
    let ro = RunOpts::parse_from(["fakehermit", "--mount=type=tmpfs,target=/bin", "/bin/echo"]);
    assert_eq!(
        ro.mapped_host_program(Path::new("/bin/echo")),
        GuestPathMapping::Hidden
    );
    let error = ro.resolve_guest_and_host_program().unwrap_err().to_string();
    assert!(error.contains("not visible through the configured guest mounts"));
}

#[test]
fn non_elf_entrypoints_skip_e9patch_preprocessing() {
    let directory = tempfile::tempdir().unwrap();
    let script = directory.path().join("script");
    fs::write(&script, b"#!/bin/sh\nexit 0\n").unwrap();
    let mut permissions = fs::metadata(&script).unwrap().permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&script, permissions).unwrap();
    assert!(!is_elf_file(&script).unwrap());
    assert!(is_elf_file(Path::new("/bin/sh")).unwrap());

    let mount_link = directory.path().join("mount-link");
    std::os::unix::fs::symlink("/var/run", &mount_link).unwrap();
    let unrelated_mount = format!(
        "--mount=type=tmpfs,target={}",
        mount_link.join("target").display()
    );
    let tmp = format!("--tmp={}", directory.path().display());
    let mut ro = run_opts_for(&[
        "hermit",
        "--backend",
        "e9patch",
        "run",
        &unrelated_mount,
        &tmp,
        "/tmp/script",
    ]);
    ro.prepare_e9patch_program().unwrap();
    assert!(ro.e9patch_overlay.is_none());
}

#[test]
fn e9patch_overlay_uses_canonical_target_without_custom_mounts() {
    let ro = run_opts_for(&["hermit", "--backend", "e9patch", "run", "/bin/echo"]);
    assert_eq!(
        ro.resolve_e9patch_overlay_target(Path::new("/bin/echo"), Path::new("/bin/echo"))
            .unwrap(),
        fs::canonicalize("/bin/echo").unwrap()
    );
}

#[test]
fn e9patch_rejects_symlinked_executables_through_custom_mounts() {
    let directory = tempfile::tempdir().unwrap();
    let executable = directory.path().join("executable");
    let link = directory.path().join("link");
    fs::write(&executable, b"fixture").unwrap();
    std::os::unix::fs::symlink(&executable, &link).unwrap();
    let mount = format!(
        "--mount=type=bind,source={},target=/e9patch-test",
        directory.path().display()
    );
    let ro = run_opts_for(&[
        "hermit",
        "--backend",
        "e9patch",
        "run",
        &mount,
        "/e9patch-test/link",
    ]);
    let error = ro
        .resolve_e9patch_overlay_target(Path::new("/e9patch-test/link"), &link)
        .unwrap_err();
    assert!(error.to_string().contains("symlinked executable"));
}

#[test]
fn e9patch_rejects_mounts_that_change_a_symlink_target() {
    let directory = tempfile::tempdir().unwrap();
    let mount = format!(
        "--mount=type=bind,source={},target=/usr",
        directory.path().display()
    );
    let ro = run_opts_for(&["hermit", "--backend", "e9patch", "run", &mount, "/bin/echo"]);
    let error = ro
        .resolve_e9patch_overlay_target(Path::new("/bin/echo"), Path::new("/bin/echo"))
        .unwrap_err();
    assert!(error.to_string().contains("symlinked executable"));
}

#[test]
fn detects_symlink_resolution_through_implicit_mounts() {
    use std::os::fd::AsRawFd;

    // ⚠️ THE PREFIX MUST BE THE TEMP DIRECTORY IN USE, NOT THE LITERAL `/tmp`.
    // `NamedTempFile` honours `TMPDIR`, and validate runs this suite with
    // `TMPDIR` pointed inside its own runtime directory. Hardcoding `/tmp`
    // therefore asserted a property of the developer's default environment
    // rather than of `path_resolution_visits_prefix`, and the test passed
    // locally while failing in every validate run.
    let temp_root = std::env::temp_dir();
    let file = tempfile::NamedTempFile::new().unwrap();
    let proc_fd = PathBuf::from(format!("/proc/self/fd/{}", file.as_raw_fd()));
    assert!(path_resolution_visits_prefix(&proc_fd, &temp_root).unwrap());
    assert!(path_resolution_visits_prefix(&proc_fd, Path::new("/proc")).unwrap());
    assert!(!path_resolution_visits_prefix(Path::new("/bin/echo"), &temp_root).unwrap());
}

#[test]
fn display_runopts2() {
    let vec: Vec<&str> = vec![
        "fakehermit",
        "--sequentialize-threads",
        "fakeprog",
        "arg1",
        "arg2",
    ];
    let mut ro = RunOpts::parse_from(vec.iter());
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        format!("{}", ro),
        " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog arg1 arg2"
    );
}

#[test]
fn display_runopts3() {
    let vec: Vec<&str> = vec![
        "fakehermit",
        "--no-sequentialize-threads",
        "--no-virtualize-metadata",
        "--epoch=2000-12-31T23:59:59+00:00",
        "fakeprog",
        "arg1",
        "arg2",
    ];
    let mut ro = RunOpts::parse_from(vec.iter());
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        format!("{}", ro),
        " --no-sequentialize-threads --no-virtualize-metadata --epoch=2000-12-31T23:59:59+00:00 -- fakeprog arg1 arg2"
    );
}

#[test]
fn display_runopts4() {
    let vec: Vec<&str> = vec!["fakehermit", "--sequentialize-threads", "fakeprog", "arg1"];
    let mut ro = RunOpts::parse_from(vec.iter());
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        format!("{}", ro),
        " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog arg1"
    );
}

#[test]
fn unsupported_syscalls_fail_closed_by_default_with_explicit_opt_out() {
    let mut normal = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    normal.validate_args_with_perf_support(true).unwrap();
    assert!(normal.det_opts.det_config.panic_on_unsupported_syscalls);
    assert!(!normal.det_opts.det_config.passthru_opt);
    assert_eq!(
        format!("{}", normal),
        " --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );

    let mut strict = RunOpts::parse_from(["fakehermit", "--strict", "fakeprog"]);
    strict.validate_args_with_perf_support(true).unwrap();

    assert!(strict.det_opts.det_config.sequentialize_threads);
    assert!(strict.det_opts.det_config.deterministic_io);
    assert!(!strict.det_opts.det_config.passthru_opt);
    assert!(strict.det_opts.det_config.panic_on_unsupported_syscalls);
    assert_eq!(
        format!("{}", strict),
        " --strict --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );

    let mut compatibility =
        RunOpts::parse_from(["fakehermit", "--allow-unsupported-syscalls", "fakeprog"]);
    compatibility.validate_args_with_perf_support(true).unwrap();
    assert!(
        !compatibility
            .det_opts
            .det_config
            .panic_on_unsupported_syscalls
    );
    assert_eq!(
        format!("{}", compatibility),
        " --allow-unsupported-syscalls --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn panic_on_rbc_overshoot_flag_wires_to_detcore_config() {
    let default = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    assert!(!default.det_opts.det_config.panic_on_rcb_overshoot);

    let mut opts = RunOpts::parse_from(["fakehermit", "--panic-on-rbc-overshoot", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert!(opts.det_opts.det_config.panic_on_rcb_overshoot);
    assert_eq!(
        format!("{}", opts),
        " --panic-on-rbc-overshoot --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn passthru_opt_leaves_guest_syscalls_unobserved_on_every_backend() {
    for backend in [
        Backend::Ptrace,
        Backend::E9patch,
        Backend::Kvm,
        Backend::Sabre,
        Backend::Liteinst,
        Backend::InGuestTrap,
        Backend::Dbt,
    ] {
        let reason = unobserved_guest_execution(backend, true)
            .unwrap_or_else(|| panic!("{backend:?} under --passthru-opt observes everything"));
        assert!(reason.contains("--passthru-opt"), "{backend:?}: {reason}");
    }
    for backend in [Backend::Ptrace, Backend::E9patch, Backend::Kvm] {
        assert_eq!(
            unobserved_guest_execution(backend, false),
            None,
            "{backend:?}"
        );
    }
    for backend in [
        Backend::Sabre,
        Backend::Liteinst,
        Backend::InGuestTrap,
        Backend::Dbt,
    ] {
        assert!(
            unobserved_guest_execution(backend, false).is_some(),
            "{backend:?}"
        );
    }
}

/// Detcore guards Reverie's private page on the ptrace runtime, the one
/// backend that names host input changes and lets the guest's syscalls past
/// its tracer from code it maps; nowhere else is any range guarded.
#[test]
fn the_ptrace_runtime_guards_reverie_private_page() {
    for backend in [Backend::Ptrace, Backend::E9patch] {
        assert_eq!(
            untraced_code_range(backend),
            Some(REVERIE_PTRACE_PRIVATE_PAGE),
            "{backend:?}"
        );
    }
    for backend in [
        Backend::Kvm,
        Backend::Sabre,
        Backend::Liteinst,
        Backend::InGuestTrap,
        Backend::Dbt,
    ] {
        assert_eq!(untraced_code_range(backend), None, "{backend:?}");
    }
    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    assert_eq!(
        ro.effective_det_config().untraced_code_range,
        Some((0x7100_0000, 0x7100_1000))
    );
    ro.set_backend(Some(Backend::Kvm));
    assert_eq!(ro.effective_det_config().untraced_code_range, None);
}

#[test]
fn passthru_optimization_requires_explicit_compatibility_opt_out() {
    let mut ro = RunOpts::parse_from([
        "fakehermit",
        "--allow-unsupported-syscalls",
        "--passthru-opt",
        "fakeprog",
    ]);
    ro.validate_args_with_perf_support(true).unwrap();

    assert!(ro.det_opts.det_config.passthru_opt);
    assert_eq!(
        format!("{}", ro),
        " --allow-unsupported-syscalls --passthru-opt --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-644): Review rejecting optimization that bypasses fail-closed policy.
#[test]
fn passthru_optimization_rejects_fail_closed_modes() {
    for arguments in [
        vec!["fakehermit", "--passthru-opt", "fakeprog"],
        vec!["fakehermit", "--passthru-opt", "--strict", "fakeprog"],
        vec![
            "fakehermit",
            "--passthru-opt",
            "--panic-on-unsupported-syscalls",
            "fakeprog",
        ],
    ] {
        let mut opts = RunOpts::parse_from(arguments);
        let error = opts.validate_args_with_perf_support(true).unwrap_err();
        let message = error.to_string();
        assert!(
            message.contains("--passthru-opt"),
            "unexpected error: {message}"
        );
        assert!(
            message.contains("fail-closed"),
            "unexpected error: {message}"
        );
        assert!(
            message.contains("--allow-unsupported-syscalls"),
            "unexpected error: {message}"
        );
    }
}

#[test]
fn network_trace_is_off_without_a_networking_flag() {
    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        ro.det_opts.det_config.network_trace,
        NetworkTraceConfig::default()
    );
    assert_eq!(ro.network, NetworkingMode::Local);
}

#[test]
fn record_networking_selects_record_mode_and_host_networking() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("net.trace");
    let flag = format!("--record-networking={}", trace.display());
    let mut ro = RunOpts::parse_from(["fakehermit", "--strict", &flag, "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    let config = &ro.det_opts.det_config.network_trace;
    assert_eq!(config.mode, NetworkTraceMode::Record);
    assert_eq!(config.path.as_deref(), Some(trace.as_path()));
    assert_eq!(ro.network, NetworkingMode::Host);

    let rendered = format!("{}", ro);
    assert!(rendered.contains(&flag), "{rendered}");
    assert!(!rendered.contains("--network="), "{rendered}");
    let mut reparsed_args = vec!["fakehermit".to_owned()];
    reparsed_args.extend(shell_words::split(&rendered).unwrap());
    let mut reparsed = RunOpts::parse_from(reparsed_args);
    reparsed.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        reparsed.det_opts.det_config.network_trace,
        ro.det_opts.det_config.network_trace
    );
}

#[test]
fn record_networking_refuses_a_missing_directory_and_conflicting_flags() {
    let mut ro = RunOpts::parse_from([
        "fakehermit",
        "--record-networking=/nonexistent-hermit-dir/net.trace",
        "fakeprog",
    ]);
    let error = ro.validate_args_with_perf_support(true).unwrap_err();
    assert!(
        error
            .to_string()
            .contains("create it or choose a trace path"),
        "{error:#}"
    );
    for conflicting in ["--verify", "--network=host", "--replay-networking=t"] {
        assert!(
            RunOpts::try_parse_from([
                "fakehermit",
                "--record-networking=t",
                conflicting,
                "fakeprog"
            ])
            .is_err(),
            "{conflicting} must conflict with --record-networking"
        );
    }
}

#[test]
fn replay_networking_reads_the_trace_before_the_guest_starts() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("net.trace");
    let epoch = "2026-01-01T00:00:00Z".parse().unwrap();
    detcore_model::network_engine::NetworkEngine::new_record(epoch)
        .finish()
        .unwrap()
        .write_framed(File::create(&trace).unwrap())
        .unwrap();
    let flag = format!("--replay-networking={}", trace.display());
    let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    let config = &ro.det_opts.det_config.network_trace;
    assert_eq!(config.mode, NetworkTraceMode::Replay);
    assert_eq!(config.path.as_deref(), Some(trace.as_path()));
    assert_eq!(ro.network, NetworkingMode::Local);
    assert!(format!("{}", ro).contains(&flag));

    let missing = dir.path().join("missing.trace");
    let flag = format!("--replay-networking={}", missing.display());
    let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
    let error = ro.validate_args_with_perf_support(true).unwrap_err();
    assert!(
        format!("{error:#}").contains("pass a trace written by --record-networking"),
        "{error:#}"
    );

    fs::write(&missing, b"not a trace").unwrap();
    let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
    let error = ro.validate_args_with_perf_support(true).unwrap_err();
    assert!(
        format!("{error:#}").contains("is not a valid network trace"),
        "{error:#}"
    );
}

#[test]
fn replay_networking_adopts_the_trace_epoch_and_refuses_another() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("net.trace");
    let recorded = "2026-01-01T00:00:00Z".parse().unwrap();
    detcore_model::network_engine::NetworkEngine::new_record(recorded)
        .finish()
        .unwrap()
        .write_framed(File::create(&trace).unwrap())
        .unwrap();
    let flag = format!("--replay-networking={}", trace.display());
    let parse = |arguments: &[&str]| {
        let mut ro = RunOpts::parse_from(arguments);
        if !arguments
            .iter()
            .any(|argument| argument.starts_with("--epoch"))
        {
            ro.capture_default_epoch(SystemTime::now);
        }
        ro.validate_args_with_perf_support(true).unwrap();
        ro
    };

    let mut ro = parse(&["fakehermit", &flag, "fakeprog"]);
    ro.adopt_replayed_schedule_epoch().unwrap();
    assert_eq!(ro.det_opts.det_config.epoch, recorded);
    assert!(ro.epoch_from_recording && !ro.epoch_captured_from_host);

    let mut ro = parse(&[
        "fakehermit",
        "--epoch=2026-01-01T00:00:00Z",
        &flag,
        "fakeprog",
    ]);
    ro.adopt_replayed_schedule_epoch().unwrap();
    assert_eq!(ro.det_opts.det_config.epoch, recorded);

    let mut ro = parse(&[
        "fakehermit",
        "--epoch=2027-01-01T00:00:00Z",
        &flag,
        "fakeprog",
    ]);
    let error = format!("{:#}", ro.adopt_replayed_schedule_epoch().unwrap_err());
    assert!(
        error.contains("the explicit virtual-time epoch 2027-01-01T00:00:00+00:00")
            && error.contains("pass --epoch=2026-01-01T00:00:00+00:00"),
        "{error}"
    );

    // As if a preemption record from another run had fixed the epoch first:
    // the trace must then agree with it.
    let mut ro = parse(&["fakehermit", &flag, "fakeprog"]);
    ro.epoch_from_recording = true;
    ro.det_opts.det_config.epoch = "2027-01-01T00:00:00Z".parse().unwrap();
    let error = format!("{:#}", ro.adopt_replayed_schedule_epoch().unwrap_err());
    assert!(
        error.contains("adopted from another recording replayed in this run")
            && error.contains("replay them separately"),
        "{error}"
    );
}

/// The environment variable that turned the signal-state copy on while it
/// was opt-in (before A5 step 2d). It is no longer read.
const SIGNAL_STATE_CHECK_ENV: &str = "HERMIT_SIGNAL_STATE_CHECK";

/// Refuses a run whose environment sets [`SIGNAL_STATE_CHECK_ENV`], with any
/// value. The copy is a run option now (`--no-signal-state-copy`), which a
/// saved run configuration, a rendered command line and a recorded schedule
/// all carry; a variable read beside it would be a hidden input, and one
/// silently ignored would leave a run that asked for the copy off with it
/// on.
fn refuse_signal_state_check_env(value: Option<&std::ffi::OsStr>) -> Result<(), String> {
    match value {
        None => Ok(()),
        Some(value) => Err(format!(
            "{SIGNAL_STATE_CHECK_ENV}={value:?} is no longer read: the signal-state copy is on \
             by default, and --no-signal-state-copy turns it off. Unset the variable."
        )),
    }
}

/// `HERMIT_SIGNAL_STATE_CHECK` is refused whatever its value, so that no run
/// depends on it.
#[test]
fn the_retired_signal_state_check_variable_is_refused() {
    use std::ffi::OsStr;
    assert_eq!(refuse_signal_state_check_env(None), Ok(()));
    for value in ["0", "1", "", "false"] {
        let error = refuse_signal_state_check_env(Some(OsStr::new(value))).unwrap_err();
        assert!(error.contains("--no-signal-state-copy"), "{error}");
    }
}

/// A replay of a record made under another `--pipe-wake-latency` is refused,
/// in both directions and for a different latency, under both replay flags;
/// `0` is not off; a record without the field is off
/// (https://github.com/rrnewton/hermit/issues/4380).
#[test]
fn replay_refuses_another_pipe_wake_latency() {
    let dir = tempfile::tempdir().unwrap();
    let record = |name: &str, latency: Option<u64>| {
        let path = dir.path().join(name);
        let record = detcore::preemptions::PreemptionRecord::from_sched_events(Vec::new())
            .with_pipe_wake_latency(latency);
        std::fs::write(&path, serde_json::to_string(&record).unwrap()).unwrap();
        path
    };
    let off = record("off.json", None);
    let zero = record("zero.json", Some(0));
    let three = record("three.json", Some(3_000_000));
    assert!(
        !std::fs::read_to_string(&off)
            .unwrap()
            .contains("pipe_wake_latency")
    );
    for flag in ["--replay-schedule-from", "--replay-preemptions-from"] {
        for (path, latency, refused) in [
            (&off, None, false),
            (&off, Some("0"), true),
            (&zero, None, true),
            (&zero, Some("0"), false),
            (&zero, Some("3000000"), true),
            (&three, Some("0"), true),
            (&three, Some("3000000"), false),
        ] {
            let replay = format!("{flag}={}", path.display());
            let mut argv = vec!["fakehermit".to_owned(), replay];
            if let Some(latency) = latency {
                argv.push(format!("--pipe-wake-latency={latency}"));
            }
            argv.push("fakeprog".to_owned());
            let ro = RunOpts::parse_from(&argv);
            let result = ro.refuse_replay_under_another_pipe_wake_latency();
            assert_eq!(result.is_err(), refused, "{argv:?}: {result:?}");
            if let Err(error) = result {
                let error = format!("{error:#}");
                assert!(
                    error.contains(flag) && error.contains("cannot reproduce the run"),
                    "{error}"
                );
            }
        }
    }
}

#[test]
fn network_trace_is_reached_through_a_descriptor_opened_before_the_container() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("net.trace");
    fs::write(&trace, b"stale trace").unwrap();
    let flag = format!("--record-networking={}", trace.display());
    let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    let file = ro.open_network_trace().unwrap().unwrap();
    let inner = ro.det_opts.det_config.network_trace.path.clone().unwrap();
    assert!(inner.starts_with("/proc/self/fd/"), "{}", inner.display());
    assert_eq!(
        fs::read(&trace).unwrap(),
        b"",
        "a record truncates up front"
    );
    let epoch = "2026-01-01T00:00:00Z".parse().unwrap();
    detcore_model::network_engine::NetworkEngine::new_record(epoch)
        .finish()
        .unwrap()
        .write_framed(File::create(&inner).unwrap())
        .unwrap();
    drop(file);
    NetworkTraceV2::read_framed(File::open(&trace).unwrap()).unwrap();

    let flag = format!("--replay-networking={}", trace.display());
    let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    let _file = ro.open_network_trace().unwrap().unwrap();
    let inner = ro.det_opts.det_config.network_trace.path.clone().unwrap();
    assert!(inner.starts_with("/proc/self/fd/"), "{}", inner.display());
    NetworkTraceV2::read_framed(File::open(&inner).unwrap()).unwrap();

    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    assert!(ro.open_network_trace().unwrap().is_none());
    assert_eq!(ro.det_opts.det_config.network_trace.path, None);

    for networking in [
        "--record-networking=t".to_owned(),
        format!("--replay-networking={}", trace.display()),
    ] {
        assert!(
            RunOpts::try_parse_from(["fakehermit", &networking, "--namespace-only", "fakeprog"])
                .is_err(),
            "{networking} must conflict with --namespace-only, which bypasses detcore"
        );
    }
}

#[test]
fn timeslice_flags_parse_and_round_trip() {
    let mut ro = RunOpts::parse_from([
        "fakehermit",
        "--max-timeslice=100000",
        "--target-timeslice=20000",
        "fakeprog",
    ]);
    ro.validate_args_with_perf_support(true).unwrap();

    assert_eq!(
        ro.det_opts.det_config.max_timeslice,
        std::num::NonZeroU64::new(100_000)
    );
    assert_eq!(
        ro.det_opts.det_config.target_timeslice,
        std::num::NonZeroU64::new(20_000)
    );
    let rendered = format!("{}", ro);
    assert_eq!(
        rendered,
        " --max-timeslice=100000 --target-timeslice=20000 --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );

    let mut reparsed_args = vec!["fakehermit".to_owned()];
    reparsed_args.extend(shell_words::split(&rendered).unwrap());
    let mut reparsed = RunOpts::parse_from(reparsed_args);
    reparsed.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        reparsed.det_opts.det_config.max_timeslice,
        ro.det_opts.det_config.max_timeslice
    );
    assert_eq!(
        reparsed.det_opts.det_config.target_timeslice,
        ro.det_opts.det_config.target_timeslice
    );
    assert!(!reparsed.det_opts.det_config.target_timeslice_syscalls_only);

    // --target-timeslice-syscalls-only parses, is rendered into the reproduce
    // command, round-trips, and is refused without --target-timeslice.
    let mut syscalls_only = RunOpts::parse_from([
        "fakehermit",
        "--target-timeslice=20000",
        "--target-timeslice-syscalls-only",
        "fakeprog",
    ]);
    syscalls_only.validate_args_with_perf_support(true).unwrap();
    assert!(
        syscalls_only
            .det_opts
            .det_config
            .target_timeslice_syscalls_only
    );
    let rendered = format!("{}", syscalls_only);
    assert!(
        rendered.contains(" --target-timeslice=20000 --target-timeslice-syscalls-only"),
        "{rendered}"
    );
    let mut reparsed_args = vec!["fakehermit".to_owned()];
    reparsed_args.extend(shell_words::split(&rendered).unwrap());
    let reparsed = RunOpts::parse_from(reparsed_args);
    assert!(reparsed.det_opts.det_config.target_timeslice_syscalls_only);
    assert!(
        RunOpts::try_parse_from(["fakehermit", "--target-timeslice-syscalls-only", "fakeprog"])
            .is_err(),
        "--target-timeslice-syscalls-only must require --target-timeslice"
    );
}

#[test]
fn skid_margin_override_parses_and_round_trips() {
    let mut opts = RunOpts::parse_from(["fakehermit", "--skid-margin=500", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();

    assert_eq!(opts.skid_margin, Some(500));
    assert_eq!(
        format!("{opts}"),
        " --skid-margin=500 --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn skid_margin_override_rejects_non_ptrace_backed_backends() {
    for backend in ["dbt", "kvm", "sabre"] {
        let mut opts = run_opts_for(&[
            "hermit",
            &format!("--backend={backend}"),
            "run",
            "--skid-margin=500",
            "fakeprog",
        ]);
        let error = opts.validate_args_with_perf_support(true).unwrap_err();
        let message = format!("{error:#}");
        assert!(
            message.contains(&format!(
                "unsupported_preemption: --backend={backend} refuses --skid-margin"
            )),
            "unexpected {backend} error: {message}"
        );
        assert!(
            message.contains("cannot deliver Detcore preemption timer events"),
            "{message}"
        );
    }
}

/// `--futex-wake-yields` parses, is rendered into the reproduce
/// command and round-trips. It is refused where it cannot apply: without
/// sequentialized threads, outside the precise futex mode, and with the DBT
/// backend, whose runtime reads a configuration form that cannot carry it.
#[test]
fn futex_wake_yields_parses_round_trips_and_is_refused_where_inert() {
    let mut opts = RunOpts::parse_from(["fakehermit", "--futex-wake-yields", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert!(opts.det_opts.det_config.futex_wake_yields);
    let rendered = format!("{opts}");
    assert!(rendered.contains(" --futex-wake-yields"), "{rendered}");
    let mut reparsed_args = vec!["fakehermit".to_owned()];
    reparsed_args.extend(shell_words::split(&rendered).unwrap());
    let mut reparsed = RunOpts::parse_from(reparsed_args);
    reparsed.validate_args_with_perf_support(true).unwrap();
    assert!(reparsed.det_opts.det_config.futex_wake_yields);

    let mut default = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    default.validate_args_with_perf_support(true).unwrap();
    assert!(!default.det_opts.det_config.futex_wake_yields);
    assert!(!format!("{default}").contains("futex-wake"));

    // e9patch is preprocessing on the ptrace backend, where Detcore and the
    // handoff run unchanged, so the gate accepts it.
    let e9patch = [
        "hermit",
        "--backend=e9patch",
        "run",
        "--futex-wake-yields",
        "fakeprog",
    ];
    if let Err(error) = run_opts_for(&e9patch).validate_args_with_perf_support(true) {
        assert!(
            !error.to_string().contains("futex-wake-yields"),
            "{e9patch:?}: {error}"
        );
    }

    for (argv, expected) in [
        (
            vec![
                "hermit",
                "run",
                "--no-sequentialize-threads",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "--no-sequentialize-threads",
        ),
        (
            vec![
                "hermit",
                "run",
                "--debug-futex-mode=polling",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "--debug-futex-mode=precise",
        ),
        (
            vec![
                "hermit",
                "--backend=dbt",
                "run",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "the dbt backend cannot apply --futex-wake-yields",
        ),
        (
            vec![
                "hermit",
                "--backend=kvm",
                "run",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "--futex-wake-yields has been tested only on the ptrace backend",
        ),
        (
            vec![
                "hermit",
                "run",
                "--namespace-only",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "--namespace-only (--lite) runs the guest natively",
        ),
        (
            vec!["hermit", "run", "--lite", "--futex-wake-yields", "fakeprog"],
            "--namespace-only (--lite) runs the guest natively",
        ),
        (
            vec![
                "hermit",
                "run",
                "--strace-only",
                "--futex-wake-yields",
                "fakeprog",
            ],
            "--strace-only turns sequentialization off",
        ),
    ] {
        let error = run_opts_for(&argv)
            .validate_args_with_perf_support(true)
            .unwrap_err();
        assert!(error.to_string().contains(expected), "{argv:?}: {error}");
    }
}

/// `--pipe-wake-latency` parses, is rendered into the reproduce command and
/// round-trips, keeping `0` distinct from unset. It is refused wherever it
/// would be ignored: without sequentialized threads, with `--namespace-only`
/// (`--lite`) or `--strace-only`, under every `--sched-heuristic` that does
/// not select by priority (the same predicate the scheduler uses), and with
/// the DBT backend (https://github.com/rrnewton/hermit/issues/4380).
#[test]
fn pipe_wake_latency_parses_round_trips_and_is_refused_where_inert() {
    for value in ["0", "3000000"] {
        let flag = format!("--pipe-wake-latency={value}");
        let mut opts = RunOpts::parse_from(["fakehermit", flag.as_str(), "fakeprog"]);
        opts.validate_args_with_perf_support(true).unwrap();
        let expected = Some(value.parse::<u64>().unwrap());
        assert_eq!(opts.det_opts.det_config.pipe_wake_latency, expected);
        let rendered = format!("{opts}");
        assert!(rendered.contains(&format!(" {flag}")), "{rendered}");
        let mut reparsed_args = vec!["fakehermit".to_owned()];
        reparsed_args.extend(shell_words::split(&rendered).unwrap());
        let mut reparsed = RunOpts::parse_from(reparsed_args);
        reparsed.validate_args_with_perf_support(true).unwrap();
        assert_eq!(reparsed.det_opts.det_config.pipe_wake_latency, expected);
    }
    let mut default = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    default.validate_args_with_perf_support(true).unwrap();
    assert_eq!(default.det_opts.det_config.pipe_wake_latency, None);
    assert!(!format!("{default}").contains("pipe-wake"));

    for heuristic in ["none", "connectbind", "random", "stickyrandom"] {
        let parsed: detcore::SchedHeuristic = heuristic.parse().unwrap();
        let flag = format!("--sched-heuristic={heuristic}");
        let argv = [
            "hermit",
            "run",
            flag.as_str(),
            "--pipe-wake-latency=0",
            "fakeprog",
        ];
        let result = run_opts_for(&argv).validate_args_with_perf_support(true);
        assert_eq!(
            result.is_ok(),
            parsed.is_priority_ordered(),
            "{argv:?}: {result:?}"
        );
    }

    for (argv, expected) in [
        (
            vec![
                "hermit",
                "run",
                "--no-sequentialize-threads",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "--no-sequentialize-threads",
        ),
        (
            vec![
                "hermit",
                "--backend=dbt",
                "run",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "the dbt backend cannot apply --pipe-wake-latency",
        ),
        (
            vec![
                "hermit",
                "run",
                "--debug-externalize-sockets",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "--debug-externalize-sockets makes them block in the kernel",
        ),
        (
            vec![
                "hermit",
                "run",
                "--namespace-only",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "--namespace-only (--lite) runs the guest natively",
        ),
        (
            vec![
                "hermit",
                "run",
                "--lite",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "--namespace-only (--lite) runs the guest natively",
        ),
        (
            vec![
                "hermit",
                "run",
                "--strace-only",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "--strace-only turns sequentialization off",
        ),
        (
            vec![
                "hermit",
                "run",
                "--sched-heuristic=random",
                "--pipe-wake-latency=0",
                "fakeprog",
            ],
            "does not select by priority",
        ),
    ] {
        let error = run_opts_for(&argv)
            .validate_args_with_perf_support(true)
            .unwrap_err();
        assert!(error.to_string().contains(expected), "{argv:?}: {error}");
    }
}

/// `--scheduler-turn-cost` parses, is rendered into the reproduce command and
/// round-trips; zero and the DBT backend are refused.
#[test]
fn scheduler_turn_cost_parses_round_trips_and_is_refused_for_dbt() {
    let mut opts = RunOpts::parse_from(["fakehermit", "--scheduler-turn-cost=10000", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        opts.det_opts.det_config.scheduler_turn_cost,
        std::num::NonZeroU64::new(10_000)
    );
    let rendered = format!("{opts}");
    assert!(
        rendered.contains(" --scheduler-turn-cost=10000"),
        "{rendered}"
    );
    let mut reparsed_args = vec!["fakehermit".to_owned()];
    reparsed_args.extend(shell_words::split(&rendered).unwrap());
    let reparsed = RunOpts::parse_from(reparsed_args);
    assert_eq!(
        reparsed.det_opts.det_config.scheduler_turn_cost,
        std::num::NonZeroU64::new(10_000)
    );
    let mut default = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    default.validate_args_with_perf_support(true).unwrap();
    assert!(!format!("{default}").contains("turn-cost"));
    assert!(
        RunOpts::try_parse_from(["fakehermit", "--scheduler-turn-cost=0", "fakeprog"]).is_err(),
        "a zero charge would freeze time across turns"
    );
    // A cost that the multiplier scales below one nanosecond would charge
    // nothing per turn; a cost above the bound is refused too.
    for args in [
        vec!["--scheduler-turn-cost=9", "--clock-multiplier=0.1"],
        vec!["--scheduler-turn-cost=1000000001", "--clock-multiplier=1"],
        // A permitted cost that the multiplier scales past the bound.
        vec![
            "--scheduler-turn-cost=1000000000",
            "--clock-multiplier=9000000000",
            "--max-timeslice=disabled",
        ],
    ] {
        let mut argv = vec!["fakehermit"];
        argv.extend(args.iter().copied());
        argv.push("fakeprog");
        let error = RunOpts::parse_from(argv)
            .validate_args_with_perf_support(true)
            .unwrap_err();
        assert!(
            error.to_string().contains("--scheduler-turn-cost"),
            "{args:?}: {error}"
        );
    }
    let mut smallest = RunOpts::parse_from([
        "fakehermit",
        "--scheduler-turn-cost=10",
        "--clock-multiplier=0.1",
        "fakeprog",
    ]);
    smallest.validate_args_with_perf_support(true).unwrap();
    let error = run_opts_for(&[
        "hermit",
        "--backend=dbt",
        "run",
        "--scheduler-turn-cost=10000",
        "fakeprog",
    ])
    .validate_args_with_perf_support(true)
    .unwrap_err();
    assert!(
        error
            .to_string()
            .contains("the dbt backend cannot apply --scheduler-turn-cost"),
        "{error}"
    );
}

#[cfg(test)]
fn liteinst_in_guest_refusal(options: &[&str]) -> Result<(), anyhow::Error> {
    in_guest_refusal("--backend=liteinst", options)
}

#[cfg(test)]
fn in_guest_refusal(backend_flag: &str, options: &[&str]) -> Result<(), anyhow::Error> {
    let mut argv = vec!["hermit", backend_flag, "run"];
    argv.extend_from_slice(options);
    argv.push("fakeprog");
    let run = run_opts_for(&argv);
    run.resolve_preemption_settings()?;
    run.refuse_unqualified_liteinst_in_guest_options()
}

/// in-guest-trap runs the in-guest LiteInst runtime, so it refuses exactly
/// the options liteinst refuses, and each refusal names the backend the
/// caller selected.
#[test]
fn in_guest_trap_refuses_the_options_liteinst_refuses() {
    #[cfg(feature = "liteinst")]
    {
        let error = in_guest_refusal("--backend=in-guest-trap", &[]).unwrap_err();
        assert!(error.downcast_ref::<PolicyRefusal>().is_some(), "{error:#}");
        assert!(
            error.to_string().contains("pass --max-timeslice=disabled"),
            "{error:#}"
        );
    }
    for option in ["--timeout=3", "--skid-margin=500", "--gdbserver"] {
        let options = ["--max-timeslice=disabled", option];
        let trap = in_guest_refusal("--backend=in-guest-trap", &options).unwrap_err();
        let liteinst = liteinst_in_guest_refusal(&options).unwrap_err();
        assert!(
            trap.downcast_ref::<PolicyRefusal>().is_some(),
            "{option}: {trap:#}"
        );
        assert_eq!(
            trap.to_string()
                .replace("--backend=in-guest-trap", "--backend=liteinst"),
            liteinst.to_string(),
            "{option}"
        );
        assert!(
            trap.to_string()
                .starts_with(if option.starts_with("--skid-margin") {
                    "unsupported_preemption: --backend=in-guest-trap refuses --skid-margin:"
                } else {
                    "--backend=in-guest-trap "
                }),
            "{option}: {trap:#}"
        );
    }
    in_guest_refusal(
        "--backend=in-guest-trap",
        &["--max-timeslice=disabled", "--verify"],
    )
    .unwrap();
    let run = run_opts_for(&[
        "hermit",
        "--backend=in-guest-trap",
        "run",
        "--max-timeslice=disabled",
        "fakeprog",
    ]);
    assert!(run.uses_in_guest_liteinst());
    assert!(run.forwards_in_guest_detlogs());
    assert!(!run.arms_reverie_ptrace_pmu_timer());
}

#[test]
fn liteinst_in_guest_refuses_options_it_cannot_honour() {
    // Preserve the existing inherited-maximum refusal for the in-guest
    // runtime. The explicit request has the shared named refusal as well.
    #[cfg(feature = "liteinst")]
    {
        let error = liteinst_in_guest_refusal(&[]).unwrap_err();
        assert!(error.downcast_ref::<PolicyRefusal>().is_some(), "{error:#}");
        assert!(
            error.to_string().contains("pass --max-timeslice=disabled"),
            "{error:#}"
        );
    }
    // The other refusals hold in every build.
    for (option, reason) in [
        ("--timeout=3", "--timeout has not been qualified"),
        ("--skid-margin=500", "refuses --skid-margin"),
        ("--gdbserver", "--gdbserver needs the ptrace tracer"),
    ] {
        let error = liteinst_in_guest_refusal(&["--max-timeslice=disabled", option]).unwrap_err();
        assert!(
            error.downcast_ref::<PolicyRefusal>().is_some(),
            "{option}: {error:#}"
        );
        assert!(error.to_string().contains(reason), "{option}: {error:#}");
    }
    liteinst_in_guest_refusal(&["--max-timeslice=disabled"]).unwrap();
    // The in-guest Tool forwards its DETLOG records, so `--verify` compares them.
    liteinst_in_guest_refusal(&["--max-timeslice=disabled", "--verify"]).unwrap();
    // A build with the feature never refuses for the feature.
    #[cfg(feature = "liteinst")]
    run_opts_for(&["hermit", "--backend=liteinst", "run", "fakeprog"])
        .refuse_liteinst_without_the_feature()
        .unwrap();
}

/// Without the `liteinst` feature there is no in-guest runtime to advise
/// about: a `--backend=liteinst` run that no other in-guest refusal stops,
/// including one with the default maximum timeslice, is refused for the
/// missing build feature instead.
#[test]
#[cfg(not(feature = "liteinst"))]
fn liteinst_without_the_feature_is_refused_for_the_feature() {
    for options in [
        &[][..],
        &["--max-timeslice=disabled"][..],
        &["--verify"][..],
        &["--max-timeslice=disabled", "--verify"][..],
    ] {
        liteinst_in_guest_refusal(options).unwrap_or_else(|error| panic!("{options:?}: {error:#}"));
        let mut argv = vec!["hermit", "--backend=liteinst", "run"];
        argv.extend_from_slice(options);
        argv.push("fakeprog");
        let error = run_opts_for(&argv)
            .refuse_liteinst_without_the_feature()
            .unwrap_err();
        let unavailable = error
            .downcast_ref::<hermit::BackendUnavailable>()
            .unwrap_or_else(|| panic!("{options:?}: {error:#}"));
        assert_eq!(unavailable.backend(), Backend::Liteinst, "{options:?}");
        assert!(
            error
                .to_string()
                .contains("compiled without the liteinst backend"),
            "{options:?}: {error:#}"
        );
    }
    // Other backends are not this refusal's business.
    run_opts_for(&["hermit", "run", "fakeprog"])
        .refuse_liteinst_without_the_feature()
        .unwrap();
}

/// `RunOpts::refuse_unsupervised_log_cap` for `hermit GLOBAL... run OPTIONS...
/// fakeprog`.
#[cfg(test)]
fn log_cap_refusal_for(global: &[&str], options: &[&str]) -> Result<(), Error> {
    let mut argv = vec!["hermit"];
    argv.extend_from_slice(global);
    argv.push("run");
    argv.extend_from_slice(options);
    argv.push("fakeprog");
    let args = crate::Args::try_parse_from(&argv)
        .unwrap_or_else(|error| panic!("{argv:?} should parse: {error}"));
    let crate::Subcommand::Run(mut run) = args.command else {
        panic!("{argv:?} is not a `run` command");
    };
    run.backend = args.global.backend;
    run.refuse_unsupervised_log_cap(args.global.max_log_bytes)
}

/// Round-2 review of https://github.com/rrnewton/hermit/pull/3686, finding 2:
/// the cap ends a run by exiting the hermit process that crossed it, which
/// ends nothing where the guest is not bound to that process.
#[test]
fn log_cap_is_refused_where_the_guest_could_outlive_hermit() {
    let refused: [(&[&str], &[&str], &str); 10] = [
        (
            &["--max-log-bytes=4K", "--backend=liteinst"],
            &["--no-namespace", "--max-timeslice=disabled"],
            "--backend=liteinst and --no-namespace",
        ),
        (
            &["--max-log-bytes=4K", "--backend=dbt"],
            &[],
            "--backend=dbt",
        ),
        (
            &["--max-log-bytes=4K", "--backend=dbt"],
            &["--no-namespace"],
            "--backend=dbt",
        ),
        (
            &["--max-log-bytes=4K", "--backend=kvm"],
            &["--no-namespace"],
            "--backend=kvm and --no-namespace",
        ),
        // Round-3 review, finding 2: the launcher hands the guest to the
        // SaBRe worker stopped and untraced, before PTRACE_O_EXITKILL binds it.
        (
            &["--max-log-bytes=4K", "--backend=sabre"],
            &["--no-namespace"],
            "--backend=sabre and --no-namespace",
        ),
        // Round-4c review, finding 1: the ptrace tracer sets PTRACE_O_EXITKILL
        // only after it has spawned the guest (and started any GDB server),
        // and a charged write can cross the cap in between. e9patch's guest
        // runs on the same ptrace runtime.
        (
            &["--max-log-bytes=4K", "--backend=ptrace"],
            &["--no-namespace"],
            "--no-namespace",
        ),
        (
            &["--max-log-bytes=4K", "--backend=e9patch"],
            &["--no-namespace"],
            "--no-namespace",
        ),
        (
            &["--max-log-bytes=4K"],
            &["--no-namespace"],
            "--no-namespace",
        ),
        (
            &["--max-log-bytes=4K", "--backend=ptrace"],
            &["--no-namespace", "--gdbserver"],
            "--no-namespace",
        ),
        (
            &["--max-log-bytes=4K"],
            &["--gdbserver", "--no-namespace"],
            "--no-namespace",
        ),
    ];
    for (global, options, named) in refused {
        let error = log_cap_refusal_for(global, options).unwrap_err();
        assert!(
            error.downcast_ref::<PolicyRefusal>().is_some(),
            "{global:?} {options:?}: {error:#}"
        );
        let message = error.to_string();
        assert!(
            message.starts_with(&format!(
                "--max-log-bytes cannot be enforced with {named}: "
            )),
            "{global:?} {options:?}: {message}"
        );
        assert!(!message.contains('\n'), "one line: {message}");
        assert!(!message.contains("  "), "no runs of spaces: {message}");
        // The same configuration without the flag is not this check's business.
        log_cap_refusal_for(&global[1..], options).unwrap();
    }
}

/// Inside hermit's PID namespace, whose death takes every guest process with
/// it, each backend but DBT is accepted. `--no-namespace` is refused on every
/// backend (the test above).
#[test]
fn log_cap_is_accepted_where_hermit_takes_the_guest_down_with_it() {
    for backend in [
        "--backend=ptrace",
        "--backend=sabre",
        "--backend=kvm",
        "--backend=e9patch",
        "--backend=liteinst",
    ] {
        log_cap_refusal_for(&["--max-log-bytes=4K", backend], &[])
            .unwrap_or_else(|error| panic!("{backend}: {error:#}"));
    }
    // LiteInst is accepted inside hermit's PID namespace, whose death takes the
    // untraced in-guest LiteInst guest with it.
    log_cap_refusal_for(
        &["--max-log-bytes=4K", "--backend=liteinst"],
        &["--max-timeslice=disabled"],
    )
    .unwrap();
    // The default backend, without --backend.
    log_cap_refusal_for(&["--max-log-bytes=4K"], &[]).unwrap();
    // --gdbserver inside hermit's PID namespace, whose death takes the guest
    // with it even before PTRACE_O_EXITKILL is set.
    log_cap_refusal_for(
        &["--max-log-bytes=4K", "--backend=ptrace"],
        &["--gdbserver"],
    )
    .unwrap();
}

/// Every backend and namespace mode, so a change to the decision is a change
/// to this table.
#[test]
fn log_cap_refusal_table_covers_every_backend() {
    let backends = [
        Backend::Ptrace,
        Backend::Dbt,
        Backend::Liteinst,
        Backend::InGuestTrap,
        Backend::Sabre,
        Backend::Kvm,
        Backend::E9patch,
    ];
    let mut refused = Vec::new();
    for backend in backends {
        for no_namespace in [false, true] {
            if RunOpts::log_cap_refusal(backend, no_namespace).is_some() {
                refused.push((backend, no_namespace));
            }
        }
    }
    assert_eq!(
        refused,
        [
            (Backend::Ptrace, true),
            (Backend::Dbt, false),
            (Backend::Dbt, true),
            (Backend::Liteinst, true),
            (Backend::InGuestTrap, true),
            (Backend::Sabre, true),
            (Backend::Kvm, true),
            (Backend::E9patch, true),
        ]
    );
}

#[test]
fn deprecated_preemption_timeout_alias_round_trips_canonically() {
    let mut ro = RunOpts::parse_from(["fakehermit", "--preemption-timeout=100000", "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();

    assert_eq!(
        ro.det_opts.det_config.max_timeslice,
        std::num::NonZeroU64::new(100_000)
    );
    assert_eq!(
        format!("{}", ro),
        " --max-timeslice=100000 --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn deprecated_preemption_timeout_disabled_values_round_trip_canonically() {
    for value in ["disabled", "0"] {
        let flag = format!("--preemption-timeout={value}");
        let mut ro = RunOpts::parse_from(["fakehermit", &flag, "fakeprog"]);
        ro.validate_args_with_perf_support(true).unwrap();

        assert_eq!(ro.det_opts.det_config.max_timeslice, None);
        assert_eq!(
            format!("{}", ro),
            " --max-timeslice=disabled --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
        );
    }
}

#[test]
fn max_timeslice_rejects_less_than_one_rcb() {
    let error =
        RunOpts::try_parse_from(["fakehermit", "--max-timeslice=9", "fakeprog"]).unwrap_err();

    assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
    assert!(error.to_string().contains("at least one RCB"));

    let mut ro = RunOpts::parse_from(["fakehermit", "--max-timeslice=10", "fakeprog"]);
    ro.validate_args_with_perf_support(true).unwrap();
    assert_eq!(
        ro.det_opts.det_config.max_timeslice,
        std::num::NonZeroU64::new(10)
    );

    let mut scaled = RunOpts::parse_from([
        "fakehermit",
        "--max-timeslice=10",
        "--clock-multiplier=2",
        "fakeprog",
    ]);
    let error = scaled.validate_args_with_perf_support(true).unwrap_err();
    assert!(error.to_string().contains("at least one RCB"));

    let mut zero = RunOpts::parse_from(["fakehermit", "--clock-multiplier=0", "fakeprog"]);
    assert!(
        zero.validate_args_with_perf_support(true)
            .unwrap_err()
            .to_string()
            .contains("finite and positive")
    );
}

#[test]
fn strict_flag_rejects_determinism_opt_outs() {
    for opt_out in ["--no-sequentialize-threads", "--no-deterministic-io"] {
        let error =
            RunOpts::try_parse_from(["fakehermit", "--strict", opt_out, "fakeprog"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
        let message = error.to_string();
        assert!(message.contains("--strict"));
        assert!(message.contains(opt_out));
    }
}

#[test]
fn strict_refuses_an_epoch_or_seed_drawn_from_the_host() {
    let parse = |arguments: &[&str]| {
        let mut ro = RunOpts::parse_from(arguments);
        if !arguments
            .iter()
            .any(|argument| argument.starts_with("--epoch"))
        {
            ro.capture_default_epoch(|| {
                SystemTime::UNIX_EPOCH + Duration::from_secs(1_790_000_000)
            });
        }
        ro.validate_args_with_perf_support(true).unwrap();
        ro.adopt_replayed_schedule_epoch().unwrap();
        ro
    };

    let error = parse(&["fakehermit", "--strict", "fakeprog"])
        .refuse_strict_with_host_drawn_inputs()
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("--strict requires every input")
            && error.contains("the virtual-time epoch, from the host clock")
            && error.contains("--epoch=2026-09-21T14:13:20Z")
            && error.contains("HERMIT_EPOCH"),
        "{error}"
    );

    let error = parse(&[
        "fakehermit",
        "--strict",
        "--epoch=2026-01-01T00:00:00Z",
        "--seed-from=SystemRandom",
        "fakeprog",
    ])
    .refuse_strict_with_host_drawn_inputs()
    .unwrap_err()
    .to_string();
    assert!(
        error.contains("the seed, from --seed-from=SystemRandom")
            && error.contains("--seed=N")
            && !error.contains("epoch"),
        "{error}"
    );

    for arguments in [
        &[
            "fakehermit",
            "--strict",
            "--epoch=2026-01-01T00:00:00Z",
            "fakeprog",
        ][..],
        &[
            "fakehermit",
            "--strict",
            "--epoch=2026-01-01T00:00:00Z",
            "--seed-from=Args",
            "fakeprog",
        ],
        // Without --strict the same draws are recorded instead.
        &["fakehermit", "fakeprog"],
        &["fakehermit", "--seed-from=SystemRandom", "fakeprog"],
    ] {
        parse(arguments)
            .refuse_strict_with_host_drawn_inputs()
            .unwrap_or_else(|error| panic!("{arguments:?}: {error:#}"));
    }

    // A replay supplies its recorded epoch, which is not drawn from the host.
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("net.trace");
    detcore_model::network_engine::NetworkEngine::new_record(
        "2026-01-01T00:00:00Z".parse().unwrap(),
    )
    .finish()
    .unwrap()
    .write_framed(File::create(&trace).unwrap())
    .unwrap();
    let flag = format!("--replay-networking={}", trace.display());
    parse(&["fakehermit", "--strict", &flag, "fakeprog"])
        .refuse_strict_with_host_drawn_inputs()
        .unwrap();
}

#[test]
fn strict_rejects_strace_only() {
    // `--strace-only`'s own doc comment says it is shorthand for, among other
    // things, `--no-sequentialize-threads --no-deterministic-io` -- the exact
    // two flags `--strict` already refuses by name. Accepting the shorthand
    // while refusing its parts is the inconsistency this closes.
    let error = RunOpts::try_parse_from(["fakehermit", "--strict", "--strace-only", "fakeprog"])
        .unwrap_err();
    assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
    let message = error.to_string();
    assert!(message.contains("--strict"));
    assert!(message.contains("--strace-only"));
}

#[test]
fn strict_rejects_every_route_to_host_networking() {
    // Explicit, and the two routes that reach host networking as a side effect
    // of a flag that is not about networking. All three were accepted silently
    // before: measured from inside the guest, each showed interfaces `eth0 lo`
    // where `--strict` alone shows `lo`.
    for (args, expected_cause) in [
        (vec!["--strict", "--network=host"], "--network=host"),
        (vec!["--strict", "--no-namespace"], "--no-namespace"),
        (vec!["--strict", "--gdbserver"], "--gdbserver"),
    ] {
        let mut argv = vec!["fakehermit"];
        argv.extend(args.iter().copied());
        argv.push("fakeprog");
        let mut opts = match RunOpts::try_parse_from(&argv) {
            Ok(opts) => opts,
            Err(error) => {
                // `--no-namespace` already carries a clap conflict with
                // `network`; a parse-time refusal is an acceptable refusal.
                assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
                continue;
            }
        };
        let error = opts
            .validate_args_with_perf_support(true)
            .expect_err(&format!("{argv:?} must be refused under --strict"));
        let message = error.to_string();
        assert!(
            message.contains("--strict"),
            "{argv:?}: message must name --strict: {message}"
        );
        assert!(
            message.contains(expected_cause),
            "{argv:?}: message must name the cause {expected_cause}: {message}"
        );
    }
}

/// `main`'s branch-counter check: a run without `--strict` on a host whose
/// counter failed validation goes on and writes one warning line, even when
/// Reverie's reason spans lines; with `--strict` it is refused and writes
/// nothing; a counter that passed, or a run without a timeslice, writes
/// nothing (https://github.com/rrnewton/hermit/issues/4515).
#[test]
fn a_run_on_an_inexact_branch_counter_warns_without_strict() {
    let check = |argv: &[&str], inexact_branch_counter: fn() -> Option<String>| {
        let mut options = run_opts_for(argv);
        options.inexact_branch_counter = inexact_branch_counter;
        let mut lines = Vec::new();
        let result = options.admit_branch_counter(&mut |line: &str| lines.push(line.to_owned()));
        (result, lines)
    };
    let multiline: fn() -> Option<String> = || {
        Some(
            "Hardware performance counters seem to not be working.\n  counted 0 branches\n  \
             expected 500"
                .to_string(),
        )
    };
    let (result, lines) = check(&["hermit", "run", "fakeprog"], multiline);
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(lines.len(), 1, "{lines:?}");
    let warning = &lines[0];
    assert!(warning.starts_with("WARNING: "), "{warning}");
    assert!(
        warning.contains("counted 0 branches expected 500"),
        "{warning}"
    );
    assert!(warning.contains("--strict"), "{warning}");
    assert_eq!(warning.matches('\n').count(), 1, "one line: {warning:?}");
    assert!(warning.ends_with('\n'), "{warning:?}");
    let (result, lines) = check(&["hermit", "run", "--strict", "fakeprog"], multiline);
    assert!(
        result.is_err_and(|error| error.downcast_ref::<PolicyRefusal>().is_some()),
        "--strict refuses"
    );
    assert!(lines.is_empty(), "{lines:?}");
    let (result, lines) = check(&["hermit", "run", "fakeprog"], || None);
    assert!(result.is_ok() && lines.is_empty(), "{lines:?}");
    let (result, lines) = check(
        &["hermit", "run", "--max-timeslice=disabled", "fakeprog"],
        multiline,
    );
    assert!(result.is_ok() && lines.is_empty(), "{lines:?}");
}

#[test]
fn strict_refuses_an_inexact_branch_counter_on_the_pmu_backends() {
    for backend in ["ptrace", "e9patch"] {
        let backend_flag = format!("--backend={backend}");
        let mut options = run_opts_for(&["hermit", &backend_flag, "run", "--strict", "fakeprog"]);
        options.inexact_branch_counter = || Some("SpecLockMap is enabled".to_string());
        let error = options
            .refuse_strict_with_inexact_branch_counter()
            .expect_err(backend);
        assert!(error.downcast_ref::<PolicyRefusal>().is_some(), "{error:#}");
        let message = error.to_string();
        for expected in [
            "--strict",
            &format!("`{backend}` backend"),
            "SpecLockMap is enabled",
            "CPU ",
            "issues/3794",
        ] {
            assert!(
                message.contains(expected),
                "{backend}: {expected:?}: {message}"
            );
        }
    }
}

#[test]
fn strict_refusal_needs_strict_a_pmu_backend_and_an_inexact_counter() {
    let check = |argv: &[&str], inexact_branch_counter: fn() -> Option<String>| {
        let mut options = run_opts_for(argv);
        options.inexact_branch_counter = inexact_branch_counter;
        options
            .refuse_strict_with_inexact_branch_counter()
            .unwrap_or_else(|error| panic!("{argv:?}: {error:#}"));
    };
    let unreachable = || -> Option<String> { panic!("the counter is not consulted") };
    check(
        &["hermit", "--backend=ptrace", "run", "fakeprog"],
        unreachable,
    );
    check(
        &["hermit", "--backend=ptrace", "run", "--strict", "fakeprog"],
        || None,
    );
    for backend in ["kvm", "dbt", "sabre"] {
        let backend_flag = format!("--backend={backend}");
        check(
            &["hermit", &backend_flag, "run", "--strict", "fakeprog"],
            unreachable,
        );
    }
    check(
        &["hermit", "run", "--strict", "--namespace-only", "fakeprog"],
        unreachable,
    );
    // Without a timeslice Detcore uses no branch count, so the relaxed
    // strictness level runs where the counter miscounts
    // (https://github.com/rrnewton/hermit/issues/4291).
    for backend in ["ptrace", "e9patch"] {
        let backend_flag = format!("--backend={backend}");
        check(
            &[
                "hermit",
                &backend_flag,
                "run",
                "--strict",
                "--no-virtualize-cpuid",
                "--max-timeslice=disabled",
                "fakeprog",
            ],
            unreachable,
        );
    }
}

#[test]
fn strict_run_refuses_an_inexact_branch_counter_before_it_looks_at_the_program() {
    // Through `main`: the refusal must be wired into the run's preflight, not
    // only callable. The program does not exist, so a run that passed the
    // refusal fails on the missing program instead.
    let global = GlobalOpts::parse_from(["hermit"]);
    let mut options = RunOpts::parse_from(["run", "--strict", "/nonexistent-strict-pmu-guest"]);
    assert!(!options.program.exists());
    options.inexact_branch_counter = || Some("SpecLockMap is enabled".to_string());
    let error = options.main(&global).unwrap_err();
    assert!(error.downcast_ref::<PolicyRefusal>().is_some(), "{error:#}");
    assert!(
        error.to_string().contains("SpecLockMap is enabled"),
        "{error:#}"
    );

    options.inexact_branch_counter = || None;
    let error = options.main(&global).unwrap_err();
    assert!(error.downcast_ref::<PolicyRefusal>().is_none(), "{error:#}");
}

#[test]
#[cfg(feature = "native-exec")]
fn native_inputs_refuse_wrong_backend_before_program_or_declaration_access() {
    for backend in ["dbt", "e9patch", "ptrace", "liteinst"] {
        let backend_flag = format!("--backend={backend}");
        let global = GlobalOpts::parse_from(["hermit", &backend_flag]);
        let mut options = RunOpts::parse_from([
            "run",
            "--verify",
            "--native-exec-inputs=/nonexistent-native-declaration",
            "/nonexistent-native-guest",
        ]);
        // Exercise the actual common entry, in builds with or without DBT.
        // Reaching program/declaration validation or a backend probe instead
        // produces a different error and must fail this control.
        let error = options.main(&global).unwrap_err();
        assert_eq!(
            error.to_string(),
            "native exec currently requires in-guest-trap",
            "{backend}: {error:#}"
        );
        assert!(options.native_exec_capture.is_none());
    }
}

#[test]
fn non_strict_runs_still_allow_host_networking() {
    // The refusal is about `--strict` claiming something it did not enforce,
    // not about forbidding host networking outright.
    let mut opts = RunOpts::parse_from(["fakehermit", "--network=host", "fakeprog"]);
    opts.validate_args_with_perf_support(true)
        .expect("host networking without --strict must remain allowed");
    assert_eq!(opts.network, NetworkingMode::Host);
}

#[test]
fn gdbserver_forces_host_networking() {
    // Without --gdbserver the default networking stays local.
    let mut plain = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    plain.validate_args_with_perf_support(true).unwrap();
    assert_eq!(plain.network, NetworkingMode::Local);

    // With --gdbserver the isolated network namespace would hide the gdbserver
    // port from a host gdb client, so networking is forced to host.
    let mut opts = RunOpts::parse_from(["fakehermit", "--gdbserver", "fakeprog"]);
    assert_eq!(opts.network, NetworkingMode::Local);
    opts.validate_args_with_perf_support(true).unwrap();
    assert!(opts.det_opts.det_config.gdbserver);
    assert_eq!(opts.network, NetworkingMode::Host);
}

#[test]
fn gdbserver_respects_explicit_host_networking() {
    let mut opts = RunOpts::parse_from(["fakehermit", "--gdbserver", "--network=host", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert_eq!(opts.network, NetworkingMode::Host);
}

#[test]
fn gdbserver_conflicts_with_analyze_networking() {
    let mut opts = RunOpts::parse_from([
        "fakehermit",
        "--gdbserver",
        "--analyze-networking",
        "fakeprog",
    ]);
    let error = opts.validate_args_with_perf_support(true).unwrap_err();
    let message = error.to_string();
    assert!(message.contains("--gdbserver"), "message: {message}");
    assert!(
        message.contains("--analyze-networking"),
        "message: {message}"
    );
}

#[test]
fn no_namespace_uses_host_resources_and_disables_uts_assumption() {
    let mut opts = RunOpts::parse_from(["fakehermit", "--core-only", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();

    assert!(opts.no_namespace);
    assert_eq!(opts.network, NetworkingMode::Host);
    assert_eq!(opts.tmp.as_deref(), Some(Path::new(TMP_DIR)));
    assert!(!opts.det_opts.det_config.has_uts_namespace);
    assert!(opts.pin_threads);
    assert_eq!(
        format!("{}", opts),
        " --network=host --no-namespace --tmp=/tmp --epoch=2026-01-01T00:00:00+00:00 -- fakeprog"
    );
}

#[test]
fn dbt_backend_keeps_uts_assumption_with_namespaces() {
    // The DBT backend launches each physical run through Reverie's
    // `Container`, as ptrace does, so its guest is in a UTS namespace with the
    // deterministic hostname (https://github.com/rrnewton/hermit/issues/4009).
    let mut opts = run_opts_for(&["hermit", "--backend=dbt", "run", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert_eq!(opts.selected_backend(), Backend::Dbt);
    assert!(!opts.no_namespace);
    assert!(opts.det_opts.det_config.has_uts_namespace);
}

#[test]
fn dbt_backend_disables_uts_assumption_without_namespaces() {
    // `--no-namespace` starts no container, so Detcore's `handle_uname` must
    // rewrite the nodename instead of leaking the host FQDN.
    let mut opts = run_opts_for(&[
        "hermit",
        "--backend=dbt",
        "run",
        "--no-namespace",
        "fakeprog",
    ]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert_eq!(opts.selected_backend(), Backend::Dbt);
    assert!(opts.no_namespace);
    assert!(!opts.det_opts.det_config.has_uts_namespace);
}

#[test]
fn ptrace_backend_keeps_uts_assumption_with_namespaces() {
    // The default (ptrace) backend does launch through Reverie's `Container`,
    // which unshares CLONE_NEWUTS and sets the deterministic hostname, so the
    // UTS assumption must stay enabled when namespaces are on. Pins the fix to
    // DBT so it does not regress the ptrace trust-the-namespace path.
    let mut opts = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    opts.validate_args_with_perf_support(true).unwrap();
    assert_eq!(opts.selected_backend(), Backend::Ptrace);
    assert!(!opts.no_namespace);
    assert!(opts.det_opts.det_config.has_uts_namespace);
}

#[test]
fn image_conflicts_with_no_namespace_with_explanatory_error() {
    // The clap layer no longer lists `image` in `--no-namespace`'s
    // conflicts_with set, so parsing succeeds; the conflict is reported at
    // validation time with a message that explains *why* they are incompatible.
    let mut opts = RunOpts::parse_from([
        "fakehermit",
        "--image=docker.io/library/busybox@sha256:deadbeef",
        "--no-namespace",
        "/bin/sh",
    ]);
    let message = opts
        .validate_args_with_perf_support(true)
        .unwrap_err()
        .to_string();
    assert!(message.contains("--image"), "message: {message}");
    assert!(message.contains("--no-namespace"), "message: {message}");
    assert!(message.contains("chroot"), "message: {message}");
}

#[test]
fn image_rejects_unqualified_backend_and_namespace_paths() {
    let mut backend = run_opts_for(&[
        "hermit",
        "--backend=dbt",
        "run",
        "--image=busybox@sha256:deadbeef",
        "/bin/sh",
    ]);
    let message = backend
        .validate_args_with_perf_support(true)
        .unwrap_err()
        .to_string();
    assert!(
        message.contains("only the ptrace backend"),
        "message: {message}"
    );

    let mut namespace_only = RunOpts::parse_from([
        "fakehermit",
        "--image=busybox@sha256:deadbeef",
        "--namespace-only",
        "/bin/sh",
    ]);
    let message = namespace_only
        .validate_args_with_perf_support(true)
        .unwrap_err()
        .to_string();
    assert!(message.contains("--namespace-only"), "message: {message}");
}

#[test]
fn image_script_validation_resolves_interpreter_inside_rootfs() {
    let tmp = tempfile::TempDir::new().unwrap();
    let rootfs = tmp.path();
    let script = rootfs.join("bin/image-script");
    let interpreter = rootfs.join("image-only-interpreter");
    std::fs::create_dir_all(script.parent().unwrap()).unwrap();
    std::fs::write(&script, b"#!/image-only-interpreter\nexit 0\n").unwrap();
    std::fs::write(&interpreter, b"image interpreter fixture\n").unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    std::fs::set_permissions(&interpreter, std::fs::Permissions::from_mode(0o755)).unwrap();

    validate_executable(&script, Path::new("/bin/image-script"), Some(rootfs)).unwrap();

    std::fs::write(&script, b"#!/missing-image-interpreter\nexit 0\n").unwrap();
    let error = validate_executable(&script, Path::new("/bin/image-script"), Some(rootfs))
        .expect_err("a missing guest interpreter must be rejected");
    assert!(
        error.to_string().contains("/missing-image-interpreter"),
        "unexpected error: {error:#}"
    );
}

/// End-to-end preflight regression: an executable whose complete contents are a
/// shebang with no interpreter must be *rejected* by `validate_executable`, and
/// must not panic on the way there.
///
/// This is the checked-in discrimination for the shared-parser change. Each of
/// the two pre-fix states fails it, for a different reason:
///
/// * With the old duplicated `shebang_interpreter` helper in this file — the one
///   that did `bytes[2..].iter().position(..)? + 2` — the `?` returns `None` for
///   these inputs, so `validate_executable` skips its shebang block entirely and
///   returns `Ok(())`. Preflight silently accepts the file. The `Ok(())` arm
///   below panics.
/// * With `let mut j = 1 + i;` restored in `Shebang::from_buf`, the shared
///   parser slices `&buf[i..i + 1]` where `i == buf.len()` and panics with
///   "range end index N out of range for slice of length N".
///
/// Scope: this pins one preflight rejection for one input class. It is not a
/// shebang-parser test — interpreter arguments, the 256-byte truncation
/// boundary, and non-UTF-8 interpreter paths are not covered here, and the
/// positive case (a resolvable interpreter) lives in
/// `image_script_validation_resolves_interpreter_inside_rootfs`.
///
/// `#!\n` is carried for completeness only: it already yielded an empty
/// interpreter under the old helper, so on its own it discriminates nothing. The
/// two inputs that carry the regression are `#!` and `#! \t`, the shapes whose
/// interpreter field runs to the end of the header buffer.
#[test]
fn validate_executable_rejects_empty_shebang_interpreter() {
    let tmp = tempfile::TempDir::new().unwrap();
    let script = tmp.path().join("empty-shebang");
    let requested = Path::new("/bin/empty-shebang");

    for contents in [b"#!".as_slice(), b"#! \t", b"#!\n"] {
        std::fs::write(&script, contents).unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

        // The empty-interpreter rejection precedes guest-root resolution, so the
        // host preflight path and the image path must both reach it.
        for guest_root in [None, Some(tmp.path())] {
            let error = match validate_executable(&script, requested, guest_root) {
                Ok(()) => panic!(
                    "preflight accepted an executable whose contents are {contents:?} \
                     (guest_root: {guest_root:?}); it must be rejected"
                ),
                Err(error) => error,
            };
            assert!(
                error.to_string().contains("empty shebang interpreter"),
                "contents {contents:?} (guest_root: {guest_root:?}): unexpected error: {error:#}"
            );
        }
    }
}

#[test]
fn image_guest_program_resolution_matches_execve_pathname_rules() {
    // Absolute paths pass through unchanged.
    assert_eq!(
        resolve_image_guest_program(Path::new("/bin/sh"), Path::new("/")).unwrap(),
        PathBuf::from("/bin/sh")
    );
    // A relative path containing a '/' resolves against the guest working
    // directory (the image WorkingDir) and is normalized.
    assert_eq!(
        resolve_image_guest_program(Path::new("bin/busybox"), Path::new("/opt/app")).unwrap(),
        PathBuf::from("/opt/app/bin/busybox")
    );
    assert_eq!(
        resolve_image_guest_program(Path::new("./run.sh"), Path::new("/srv")).unwrap(),
        PathBuf::from("/srv/run.sh")
    );
    // Default working directory of `/` resolves relative paths at the root.
    assert_eq!(
        resolve_image_guest_program(Path::new("./bin/sh"), Path::new("/")).unwrap(),
        PathBuf::from("/bin/sh")
    );
    // A bare command name (no '/') would need an unsupported in-image PATH
    // search and is rejected with an actionable message.
    let bare = resolve_image_guest_program(Path::new("sh"), Path::new("/"))
        .unwrap_err()
        .to_string();
    assert!(bare.contains("PATH search"), "message: {bare}");
    assert!(bare.contains("bin/sh"), "message: {bare}");
    // Parent components cannot escape the guest root during validation.
    assert!(resolve_image_guest_program(Path::new("../etc/x"), Path::new("/app")).is_err());
}

#[test]
fn strict_help_describes_compatibility_and_opt_outs() {
    use clap::CommandFactory;

    let help = RunOpts::command().render_long_help().to_string();
    for expected in [
        "--strict",
        "Require Hermit's deterministic defaults",
        "already fail closed in ordinary runs",
        "replayed recording that supplies it",
        "--no-sequentialize-threads",
        "Disable deterministic sequential thread execution",
        "--no-deterministic-io",
        "Disable deterministic I/O behavior",
        "--passthru-opt",
        "optimized partial syscall subscription set",
        "--allow-unsupported-syscalls",
        "This weakens determinism",
        "--panic-on-rbc-overshoot",
        "--max-timeslice",
        "Reverie's validation",
        "--preemption-timeout",
        "--target-timeslice",
        "syscall boundaries",
    ] {
        assert!(
            help.contains(expected),
            "missing {expected:?} in run help:\n{help}"
        );
    }
    // The backend is a global option (`hermit --backend <BACKEND> run`); `run`
    // must not offer a second, subcommand-level spelling. The backend selection
    // and its values are documented in the top-level help instead.
    assert!(
        !help.contains("--backend <BACKEND>"),
        "run help still offers a subcommand-level --backend:\n{help}"
    );
    let top_level = crate::Args::command().render_long_help().to_string();
    for expected in [
        "--backend <BACKEND>",
        "Select the process instrumentation backend",
        "This is a global option",
        "ptrace",
        "dbt",
        "kvm",
    ] {
        assert!(
            top_level.contains(expected),
            "missing {expected:?} in top-level help:\n{top_level}"
        );
    }
}

#[test]
fn only_instrumented_ptrace_family_runs_depend_on_host_perf() {
    let default = RunOpts::parse_from(["fakehermit", "fakeprog"]);
    assert!(default.arms_reverie_ptrace_pmu_timer());
    let namespace_only = RunOpts::parse_from(["fakehermit", "--namespace-only", "fakeprog"]);
    assert_eq!(namespace_only.selected_backend(), Backend::Ptrace);
    assert!(!namespace_only.arms_reverie_ptrace_pmu_timer());
    let kvm = run_opts_for(&["hermit", "--backend=kvm", "run", "fakeprog"]);
    assert!(!kvm.arms_reverie_ptrace_pmu_timer());
    let liteinst = run_opts_for(&["hermit", "--backend=liteinst", "run", "fakeprog"]);
    assert!(!liteinst.arms_reverie_ptrace_pmu_timer());
}

#[test]
fn display_runopts_without_perf_support() {
    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog", "arg1"]);
    ro.validate_args_with_perf_support(false).unwrap();
    assert_eq!(
        format!("{}", ro),
        " --max-timeslice=disabled --epoch=2026-01-01T00:00:00+00:00 -- fakeprog arg1"
    );
}

/// Working counters on a CPU Reverie has no PMU profile for (a GitHub-hosted
/// runner's Emerald Rapids before Reverie had one) leave the run without the
/// timer, as missing counters do, instead of failing at the first task.
#[test]
fn display_runopts_without_a_pmu_profile() {
    let mut ro = RunOpts::parse_from(["fakehermit", "fakeprog", "arg1"]);
    ro.validate_args_with_timer_support(Err(TimerUnavailable::NoPmuProfile(
        "Unsupported CPU family 0x6, model 0x1: Reverie has no performance-counter profile for it"
            .to_owned(),
    )))
    .unwrap();
    assert_eq!(
        format!("{}", ro),
        " --max-timeslice=disabled --epoch=2026-01-01T00:00:00+00:00 -- fakeprog arg1"
    );
}

fn shebang_interpreter(path: &Path) -> Option<PathBuf> {
    let mut file = File::open(path).ok()?;
    let mut bytes = [0_u8; 256];
    let count = file.read(&mut bytes).ok()?;
    Shebang::interpreter_from_buf(&bytes[..count])
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-696): Review sharing ELF entrypoint detection with record.
pub(super) fn is_elf_file(path: &Path) -> Result<bool, Error> {
    let mut file = File::open(path)
        .with_context(|| format!("failed to open executable {}", path.display()))?;
    let mut magic = [0_u8; 4];
    match file.read_exact(&mut magic) {
        Ok(()) => Ok(magic == *b"\x7fELF"),
        Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(false),
        Err(error) => Err(error)
            .with_context(|| format!("failed to inspect executable format for {}", path.display())),
    }
}

/// The guest program itself could not be started — a GUEST-SIDE fact.
///
/// ⚠️ THIS IS NOT A HERMIT FAILURE AND MUST NOT BE REPORTED AS ONE. Hermit worked
/// correctly; the path it was given does not name something it can execute. The
/// distinction matters because every gate and harness on this project decides
/// pass/fail from `$?`, and "hermit is broken" and "you gave me a typo" demand
/// completely different responses from a caller.
///
/// The conventional codes are not invented here: GNU `env`, `chroot` and
/// `timeout` — the same convention hermit's 125 came from — reserve 127 for
/// "command not found" and 126 for "found but not executable".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuestProgramFault {
    /// Nothing usable at that path: 127.
    NotFound,
    /// It exists but cannot be executed as given: 126.
    NotExecutable,
}

impl GuestProgramFault {
    pub fn exit_code(self) -> i32 {
        // Named rather than written out, so `tests/cli.rs` can assert the SAME
        // definition instead of a second copy of the number. Copying it here is
        // how the internal-failure code went stale in eight tests.
        match self {
            Self::NotFound => hermit::GUEST_PROGRAM_NOT_FOUND_EXIT,
            Self::NotExecutable => hermit::GUEST_PROGRAM_NOT_EXECUTABLE_EXIT,
        }
    }

    pub fn class(self) -> &'static str {
        match self {
            Self::NotFound => "guest-program-not-found",
            Self::NotExecutable => "guest-program-not-executable",
        }
    }
}

impl std::fmt::Display for GuestProgramFault {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::NotFound => "guest program not found",
            Self::NotExecutable => "guest program not executable",
        })
    }
}

impl std::error::Error for GuestProgramFault {}

fn validate_executable(
    path: &Path,
    requested: &Path,
    guest_root: Option<&Path>,
) -> Result<(), Error> {
    let metadata = fs::metadata(path)
        .with_context(|| {
            format!(
                "Program {} does not exist or is not accessible. Check the path and any --mount \
                 or --bind target.",
                requested.display()
            )
        })
        .map_err(|error| error.context(GuestProgramFault::NotFound))?;
    if metadata.is_dir() {
        return Err(anyhow::anyhow!(
            "Program {} is a directory; provide the path to an executable file",
            requested.display()
        )
        .context(GuestProgramFault::NotExecutable));
    }
    if !metadata.is_file() {
        return Err(anyhow::anyhow!(
            "Program {} is not a regular executable file",
            requested.display()
        )
        .context(GuestProgramFault::NotExecutable));
    }
    if metadata.permissions().mode() & 0o111 == 0 {
        return Err(anyhow::anyhow!(
            "Program {} is not executable. Add execute permission (for example, `chmod +x {}`) \
             or select another file.",
            requested.display(),
            requested.display()
        )
        .context(GuestProgramFault::NotExecutable));
    }

    if let Some(interpreter) = shebang_interpreter(path) {
        if interpreter.as_os_str().is_empty() {
            anyhow::bail!(
                "Program {} has an empty shebang interpreter",
                requested.display()
            );
        }
        let interpreter_host = guest_root
            .map(|root| crate::image::resolve_in_rootfs(root, &interpreter))
            .unwrap_or_else(|| interpreter.clone());
        let interpreter_metadata = fs::metadata(&interpreter_host).with_context(|| {
            format!(
                "Program {} uses shebang interpreter {}, but that interpreter does not exist in \
                 the selected guest filesystem. Install it or update the script's #! line.",
                requested.display(),
                interpreter.display()
            )
        })?;
        if !interpreter_metadata.is_file() || interpreter_metadata.permissions().mode() & 0o111 == 0
        {
            anyhow::bail!(
                "Program {} uses shebang interpreter {}, but it is not an executable file",
                requested.display(),
                interpreter.display()
            );
        }
    }

    Ok(())
}

fn mapped_path(path: &Path, source: &Path, target: &Path) -> Option<PathBuf> {
    path.strip_prefix(target)
        .ok()
        .map(|suffix| source.join(suffix))
}

fn normalize_guest_path(path: &Path) -> Result<PathBuf, Error> {
    if !path.is_absolute() {
        anyhow::bail!("guest path must be absolute: {}", path.display());
    }
    let mut normalized = PathBuf::from("/");
    for component in path.components() {
        match component {
            std::path::Component::RootDir | std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                anyhow::bail!(
                    "guest path cannot contain parent components: {}",
                    path.display()
                );
            }
            std::path::Component::Normal(part) => normalized.push(part),
            std::path::Component::Prefix(_) => unreachable!("Unix guest path has a prefix"),
        }
    }
    Ok(normalized)
}

/// Resolve a guest program path to an absolute path *inside the image rootfs*,
/// mirroring execve(2) pathname resolution for the `--image` prototype:
///
///   * an absolute path is used as-is;
///   * a relative path that contains a `/` (e.g. `./bin/sh`, `bin/busybox`) is
///     resolved against `guest_cwd` (the image WorkingDir, or `/`), so the path
///     validated here is the same one the chrooted guest will execve;
///   * a bare command name (no `/`) would require a PATH search inside the
///     image, which the prototype does not implement, so it is rejected.
fn resolve_image_guest_program(requested: &Path, guest_cwd: &Path) -> Result<PathBuf, Error> {
    if requested.is_absolute() {
        Ok(requested.to_path_buf())
    } else if requested.to_string_lossy().contains('/') {
        normalize_guest_path(&guest_cwd.join(requested))
    } else {
        anyhow::bail!(
            "With --image, a bare program name ({:?}) would require a PATH search inside the \
             image, which is not yet supported; use a path containing '/' (absolute like \
             `/bin/sh`, or relative to the working directory like `./bin/sh`).",
            requested
        )
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-696): Review sharing mount-boundary resolution with record.
pub(super) fn path_resolution_visits_prefix(path: &Path, prefix: &Path) -> Result<bool, Error> {
    let mut candidate = std::path::absolute(path)?;
    for _ in 0..40 {
        let components = candidate
            .components()
            .map(|component| component.as_os_str().to_os_string())
            .collect::<Vec<_>>();
        let mut current = PathBuf::from("/");
        let mut followed_symlink = false;
        for (index, component) in components.iter().enumerate() {
            if component == OsStr::new("/") || component == OsStr::new(".") {
                continue;
            }
            if component == OsStr::new("..") {
                current.pop();
            } else {
                current.push(component);
            }
            if current.starts_with(prefix) {
                return Ok(true);
            }
            let metadata = match fs::symlink_metadata(&current) {
                Ok(metadata) => metadata,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.into()),
            };
            if !metadata.file_type().is_symlink() {
                continue;
            }
            let target = fs::read_link(&current)?;
            let mut next = if target.is_absolute() {
                target
            } else {
                current
                    .parent()
                    .ok_or_else(|| Error::msg("symlink has no parent"))?
                    .join(target)
            };
            for remaining in &components[index + 1..] {
                next.push(remaining);
            }
            candidate = next;
            followed_symlink = true;
            break;
        }
        if !followed_symlink {
            return Ok(false);
        }
    }
    anyhow::bail!("executable path exceeded Linux's symlink traversal limit")
}

fn validate_e9patch_mount_target(path: &Path) -> Result<(), Error> {
    if !path.is_absolute() {
        anyhow::bail!("e9patch mount target must be absolute: {}", path.display());
    }
    if path
        .components()
        .any(|component| matches!(component, std::path::Component::ParentDir))
    {
        anyhow::bail!(
            "e9patch mount target cannot contain parent components: {}",
            path.display()
        );
    }
    let mut current = PathBuf::from("/");
    for component in path.components() {
        let std::path::Component::Normal(part) = component else {
            continue;
        };
        current.push(part);
        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                anyhow::bail!(
                    "e9patch mount target traverses symlink {}",
                    current.display()
                );
            }
            Ok(_) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
            Err(error) => return Err(error.into()),
        }
    }
    Ok(())
}

/// The descriptors a verification snapshots and restores between its two runs.
///
/// ⚠️ ALL THREE, AND THE FIRST VERSION OF THIS FIX RESTORED ONLY STDERR.
/// The leak is a property of an INHERITED OPEN FILE DESCRIPTION, not of stderr:
/// a guest that sets a status flag on any descriptor hermit passed it leaves
/// that flag set on the description itself, which run 2 then inherits already
/// mutated. Nothing about fd 2 is special, and scoping the fix to the descriptor
/// the reproducing guest happened to touch was the limit of that guest, not the
/// limit of the defect.
///
/// Measured at `aeda16ff7de3`, the head that restored fd 2 alone, with a stock
/// `/usr/bin/perl` guest that conditionally sets `O_APPEND`:
///
/// ```text
/// mutating STDOUT, --backend kvm --strict --verify   rc=125  nondeterministic
/// mutating STDOUT, ptrace (control)                  rc=0    deterministic
/// mutating STDERR, kvm  (the shipped fix works)      rc=0    deterministic
/// mutating STDIN,  kvm                               rc=0    deterministic
/// touching no flags, kvm (negative control)          rc=0    deterministic
/// run 1: fcntl(1, F_GETFL) = Ok(32769)   run 2: fcntl(1, F_GETFL) = Ok(33793)
/// ```
///
/// ⚠️ STDIN IS INCLUDED THOUGH IT DID NOT REPRODUCE, DELIBERATELY. Its probe
/// is green because KVM reserves its own stdin path, which is a property of
/// today's backend rather than of the descriptor. Snapshotting it costs one
/// `F_GETFL` and one comparison per verification, and leaving it out would
/// rebuild the exact gap this change exists to close -- a descriptor omitted
/// because no test currently reaches it.
const VERIFY_RESTORED_FDS: [libc::c_int; 3] =
    [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO];

/// The status flags on one descriptor, or `None` if they cannot be read.
///
/// `None` is not an error: an unreadable descriptor simply means there is
/// nothing to restore, and a verification must not fail over housekeeping.
fn fd_status_flags(fd: libc::c_int) -> Option<libc::c_int> {
    // SAFETY: `F_GETFL` reads flags from a descriptor number and writes no
    // memory. Validity is NOT a precondition here: a closed or never-opened
    // descriptor returns -1 with `EBADF`, which this reads as `None`. Saying
    // "fd 2 is valid for the life of the process" would have been an unfounded
    // guarantee -- stderr can be closed -- so the safety argument rests on the
    // call being memory-safe for any integer, which it is.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 { None } else { Some(flags) }
}

/// The status flags of every descriptor a verification restores, in
/// `VERIFY_RESTORED_FDS` order.
///
/// Read once before the first verification run so the second can be handed the
/// same starting state.
fn standard_fd_status_flags() -> [Option<libc::c_int>; VERIFY_RESTORED_FDS.len()] {
    VERIFY_RESTORED_FDS.map(fd_status_flags)
}

/// Put each descriptor's status flags back to what the first run was handed.
///
/// ⚠️ ONLY WHEN THEY ACTUALLY CHANGED. An unconditional `F_SETFL` would be a
/// write on a descriptor hermit does not own whenever nothing moved, and the
/// common case is that nothing moved. Comparing first keeps this inert on every
/// run except the one it exists for -- and it is compared PER DESCRIPTOR, so a
/// guest that moves one flag does not cause writes on the other two.
fn restore_standard_fd_status_flags(before: [Option<libc::c_int>; VERIFY_RESTORED_FDS.len()]) {
    for (fd, before) in VERIFY_RESTORED_FDS.iter().copied().zip(before) {
        let Some(before) = before else {
            continue;
        };
        let Some(now) = fd_status_flags(fd) else {
            continue;
        };
        if now == before {
            continue;
        }
        // SAFETY: `F_SETFL` sets flags on a descriptor number and writes no
        // memory. The value is one this same descriptor reported earlier, and a
        // descriptor that has become invalid meanwhile fails with `EBADF`
        // rather than doing anything.
        unsafe {
            libc::fcntl(fd, libc::F_SETFL, before);
        }
    }
}

/// `path` with the user's home directory written as `~`, as a user types it.
pub(super) fn home_relative(path: &Path) -> String {
    match std::env::var_os("HOME")
        .filter(|home| !home.is_empty())
        .and_then(|home| path.strip_prefix(home).ok())
    {
        Some(rest) if rest.as_os_str().is_empty() => "~".to_owned(),
        Some(rest) => format!("~/{}", rest.display()),
        None => path.display().to_string(),
    }
}

/// Create two logging destinations and two global configs. Returns non-zero exit
/// status if there was a difference in any component of the output.
impl RunOpts {
    /// Resolve the one intentionally nondeterministic input of an ordinary run.
    ///
    /// The top-level parser calls this exactly once, before evidence setup or
    /// guest launch. Both halves of `--verify` and every backend then receive the
    /// same concrete `DateTime`; Detcore never reads the host clock itself.
    pub(crate) fn capture_default_epoch(&mut self, capture_now: impl FnOnce() -> SystemTime) {
        self.epoch_omitted = true;
        // The pending exec-stop path is refused after the verdict stamp; it
        // must not resolve an implicit input for a guest that cannot start.
        if !self.in_guest_exec_stop && self.uses_virtual_time_determinization() {
            self.det_opts
                .det_config
                .capture_epoch_from_host_time(capture_now());
            self.epoch_captured_from_host = true;
        }
    }

    #[cfg(test)]
    pub(crate) fn epoch_capture_for_test(&self) -> (String, bool) {
        (
            self.det_opts.det_config.epoch.to_rfc3339(),
            self.epoch_captured_from_host,
        )
    }

    #[cfg(test)]
    pub(crate) fn reports_virtual_epoch_for_test(&self) -> bool {
        self.uses_virtual_time_determinization()
    }

    /// Whether this execution path actually feeds virtual time to a guest.
    /// Namespace-only bypasses Detcore, while strace-only deliberately turns
    /// all determinization off during validation; neither owns an epoch input.
    fn uses_virtual_time_determinization(&self) -> bool {
        self.det_opts.det_config.virtualize_time
            && !self.namespace_only
            && !self.strace_only
            && !self.hb_list_events
    }

    fn epoch_rfc3339(&self) -> String {
        self.det_opts.det_config.epoch.to_rfc3339()
    }

    /// Start a replay from the virtual-time epoch its recording was made under.
    ///
    /// A preemption record stores absolute logical times, i.e. offsets from the
    /// recording run's epoch
    /// (<https://github.com/rrnewton/hermit/issues/3411>). A replay whose clock
    /// starts anywhere else sees every recorded timeslice end shifted by the
    /// difference, and detcore used to panic on the first one already in the
    /// past (<https://github.com/rrnewton/hermit/issues/3413>).
    ///
    /// So when this invocation omitted the epoch, the recorded epoch replaces
    /// the default. An explicit epoch (`--epoch` or `HERMIT_EPOCH`) that
    /// disagrees is refused before any guest starts. A record written before
    /// epochs were stored carries none and is replayed against this run's epoch
    /// exactly as before.
    ///
    /// A network trace (`--replay-networking`) is reconciled the same way: it
    /// releases each recorded input at an absolute virtual time, so replaying
    /// it from a later epoch would hand the guest every input at once. Two
    /// recordings replayed together must share one epoch.
    ///
    /// This holds with `--no-virtualize-time` too: detcore's logical clock, and
    /// so every recorded timeslice end, still starts at the epoch. Only
    /// `--namespace-only`, which bypasses detcore, has nothing to reconcile.
    fn adopt_replayed_schedule_epoch(&mut self) -> Result<(), Error> {
        if self.namespace_only {
            return Ok(());
        }
        let config = &self.det_opts.det_config;
        let mut recordings = Vec::new();
        if let Some(path) = config
            .replay_preemptions_from
            .as_ref()
            .or(config.replay_schedule_from.as_ref())
            && let Some(recorded) =
                detcore::preemptions::read_recorded_epoch(path).map_err(Error::msg)?
        {
            recordings.push((recorded, path.clone()));
        }
        if let (NetworkTraceMode::Replay, Some(path)) =
            (config.network_trace.mode, &config.network_trace.path)
        {
            let file = File::open(path)
                .with_context(|| format!("cannot open network trace {}", path.display()))?;
            let trace = NetworkTraceV2::read_framed(std::io::BufReader::new(file))
                .with_context(|| format!("{} is not a valid network trace", path.display()))?;
            recordings.push((trace.epoch, path.clone()));
        }
        for (recorded, path) in recordings {
            if self.epoch_omitted && !self.epoch_from_recording {
                self.det_opts.det_config.epoch = recorded;
                self.epoch_captured_from_host = false;
                self.epoch_from_recording = true;
                continue;
            }
            let current = self.det_opts.det_config.epoch;
            if current == recorded {
                continue;
            }
            let recorded = recorded.to_rfc3339();
            let current = current.to_rfc3339();
            let (current, remedy) = if self.epoch_from_recording {
                (
                    format!(
                        "the virtual-time epoch {current}, adopted from another recording \
                         replayed in this run,"
                    ),
                    "Replay recordings made in the same run together, or replay them separately."
                        .to_owned(),
                )
            } else {
                (
                    format!(
                        "the explicit virtual-time epoch {current} (from --epoch or HERMIT_EPOCH)"
                    ),
                    format!(
                        "Omit --epoch to replay from the recorded epoch, or pass \
                         --epoch={recorded}."
                    ),
                )
            };
            return Err(Error::new(PolicyRefusal).context(format!(
                "{current} differs from the epoch {recorded} that {} was recorded under. A \
                 recording's times are absolute virtual times measured from its own epoch, so \
                 replaying them from another epoch cannot reproduce the run. {remedy}",
                path.display(),
            )));
        }
        Ok(())
    }

    /// Refuse to replay a preemption or schedule record made under another
    /// `--pipe-wake-latency` than this run's, including a different latency
    /// (https://github.com/rrnewton/hermit/issues/4380). A record without the
    /// field was made with the option off. As for the epoch, the record is
    /// read before anything is launched.
    fn refuse_replay_under_another_pipe_wake_latency(&self) -> Result<(), Error> {
        if self.namespace_only {
            return Ok(());
        }
        let config = &self.det_opts.det_config;
        for (option, path) in [
            ("--replay-preemptions-from", &config.replay_preemptions_from),
            ("--replay-schedule-from", &config.replay_schedule_from),
        ] {
            let Some(path) = path else {
                continue;
            };
            let recorded =
                detcore::preemptions::read_recorded_pipe_wake_latency(path).map_err(Error::msg)?;
            if let Some(refusal) = detcore::preemptions::pipe_wake_latency_mismatch(
                &format!("{option} {}", path.display()),
                recorded,
                config.pipe_wake_latency,
            ) {
                return Err(Error::new(PolicyRefusal).context(refusal));
            }
        }
        Ok(())
    }

    /// Refuses a replay of a recorded schedule under the other signal-state
    /// copy setting (`--no-signal-state-copy`), as
    /// `refuse_replay_under_another_pipe_wake_latency` refuses another
    /// latency. A record written before the setting was stored is replayed
    /// under either.
    fn refuse_replay_under_another_signal_state_copy(&self) -> Result<(), Error> {
        if self.namespace_only {
            return Ok(());
        }
        let config = &self.det_opts.det_config;
        for (option, path) in [
            ("--replay-preemptions-from", &config.replay_preemptions_from),
            ("--replay-schedule-from", &config.replay_schedule_from),
        ] {
            let Some(path) = path else {
                continue;
            };
            let recorded =
                detcore::preemptions::read_recorded_signal_state_copy(path).map_err(Error::msg)?;
            if let Some(refusal) = detcore::preemptions::signal_state_copy_mismatch(
                &format!("{option} {}", path.display()),
                recorded,
                config.signal_state_copy,
            ) {
                return Err(Error::new(PolicyRefusal).context(refusal));
            }
        }
        Ok(())
    }

    /// Point this run at an OCI image rootfs, as `--image` does.
    ///
    /// Used by `hermit oci run`, which resolves the user's reference to the
    /// store's canonical image id first. A tag is a mutable pointer, so passing
    /// the resolved id — not the reference — is what keeps the rootfs cache from
    /// aliasing two different images that shared a tag.
    pub(crate) fn set_image(&mut self, image: String) {
        self.image = Some(image);
    }

    /// The `--image` reference this run was given, if any.
    pub(crate) fn image(&self) -> Option<&str> {
        self.image.as_deref()
    }

    fn selected_backend(&self) -> Backend {
        self.backend.unwrap_or_default()
    }

    /// Apply the global backend selection for a `RunOpts` built outside
    /// [`RunOpts::main`], such as `hermit analyze`'s trial options, so that
    /// validation and reproducers see the backend the run will use.
    pub(crate) fn set_backend(&mut self, backend: Option<Backend>) {
        self.backend = backend;
    }

    /// The global `--backend` option that selected this run's backend, rendered
    /// for the position before the subcommand (`hermit{this} run ...`). Empty
    /// when no backend was requested explicitly.
    pub(crate) fn global_backend_arg(&self) -> String {
        self.backend
            .map(|backend| format!(" --backend={}", backend.as_str()))
            .unwrap_or_default()
    }

    fn runtime_backend(&self) -> Backend {
        if self.selected_backend() == Backend::E9patch {
            Backend::Ptrace
        } else {
            self.selected_backend()
        }
    }

    /// Whether this run's Tool writes its DETLOG records to the guest's standard
    /// error for `--verify` to move into the run's log: SaBRe's plugin and the
    /// in-guest LiteInst runtime (`liteinst` and `in-guest-trap`) both do.
    fn forwards_in_guest_detlogs(&self) -> bool {
        let backend = self.selected_backend();
        backend == Backend::Sabre || backend.is_in_guest_liteinst()
    }

    /// Select forwarding with the same backend predicate before common setup.
    fn forwarded_detlog_plan(&self) -> Result<ForwardedDetlogPlan, Error> {
        if !self.uses_in_guest_liteinst() && !self.uses_sabre() {
            return Ok(ForwardedDetlogPlan::None);
        }
        Ok(ForwardedDetlogPlan::Socket { opened: false })
    }

    /// A Unix `SOCK_SEQPACKET` pair for one verification run's forwarded
    /// DETLOG records, when the run hosts Detcore inside the guest (in-guest
    /// LiteInst or SaBRe): the guest's runtime sends each record as one message
    /// on the sending end, a descriptor Reverie protects from the guest, so the
    /// guest's own output never mixes with them
    /// (`hermit::forward_in_guest_detlogs_to`). Returns the sending end and the
    /// receiving end; inside the run's container, the coordinator writes what
    /// arrives on the receiving end into the run's log in order
    /// (`detcore::detlog::set_forwarded_source`).
    fn open_forwarded_detlog_channel()
    -> Result<Option<(std::os::fd::OwnedFd, std::os::fd::OwnedFd)>, Error> {
        let mut pair = [-1; 2];
        // SAFETY: socketpair writes two descriptors into `pair` on success.
        let created = unsafe {
            libc::socketpair(
                libc::AF_UNIX,
                libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC,
                0,
                pair.as_mut_ptr(),
            )
        };
        if created != 0 {
            return Err(Error::new(std::io::Error::last_os_error())
                .context("creating the in-guest DETLOG forwarding socket pair"));
        }
        // SAFETY: socketpair returned two new descriptors this function owns.
        let [sender, receiver] = pair
            .map(|fd| unsafe { <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd) });
        // Room for the largest record; the kernel caps the request at its limit.
        let size: libc::c_int = 4 << 20;
        for (fd, option) in [(&sender, libc::SO_SNDBUF), (&receiver, libc::SO_RCVBUF)] {
            // SAFETY: a valid socket and an int option value.
            unsafe {
                libc::setsockopt(
                    fd.as_raw_fd(),
                    libc::SOL_SOCKET,
                    option,
                    (&raw const size).cast(),
                    std::mem::size_of::<libc::c_int>() as libc::socklen_t,
                )
            };
        }
        Ok(Some((sender, receiver)))
    }

    /// Moves the DETLOG records this run's in-guest Tool forwarded into the
    /// run's log and returns how many are syscall records, or `None` when the
    /// backend forwards none. In-guest LiteInst and SaBRe send them on their
    /// own socket (`socket`), whose records the coordinator already wrote into
    /// the log in order during the run; they are only counted here, and a run
    /// whose socket carried anything but records is refused. Without the
    /// socket, SaBRe's plugin forwards them on the guest's standard error, from
    /// which they are cut out and appended.
    fn take_forwarded_detlogs(
        &self,
        log: &Path,
        stderr: &mut Vec<u8>,
        socket: bool,
    ) -> Result<Option<usize>, Error> {
        if !self.forwards_in_guest_detlogs() {
            return Ok(None);
        }
        if socket {
            return forwarded_records_in_log(log).map(Some);
        }
        let limit = log_max_bytes().map_err(Error::msg)?;
        extract_forwarded_detlogs(log, stderr, limit, false).map(Some)
    }

    /// Whether this run hosts Detcore inside the guest through LiteInst
    /// (`liteinst` or `in-guest-trap`). `--namespace-only` runs no backend, so
    /// it never does.
    fn uses_in_guest_liteinst(&self) -> bool {
        !self.namespace_only && self.selected_backend().is_in_guest_liteinst()
    }

    /// Native launches qualify their embedded artifact catalog in
    /// `Capture::prepare` before either physical verification run starts.
    fn uses_native_exec(&self) -> bool {
        #[cfg(feature = "native-exec")]
        {
            self.native_exec_inputs.is_some()
        }
        #[cfg(not(feature = "native-exec"))]
        {
            false
        }
    }

    /// Whether this run hosts Detcore inside the guest through SaBRe.
    /// `--namespace-only` runs no backend, so it never does.
    fn uses_sabre(&self) -> bool {
        !self.namespace_only && self.selected_backend() == Backend::Sabre
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-3635): Review the in-guest LiteInst option refusals.
    /// Refuses options that in-guest LiteInst cannot honour yet, so a run never
    /// silently drops one of them.
    ///
    /// These refusals are static facts about the backend, so they hold in
    /// every build and come before the availability check: a command gets the
    /// same verdict whether or not the build has the `liteinst` feature
    /// (https://github.com/rrnewton/hermit/issues/3418). The maximum-timeslice
    /// advice is the exception. The timeslice is on by default, so in a build
    /// without the feature that advice would answer every run, and following
    /// it would only reach the build-feature refusal one run later. Such a
    /// build skips it, and `refuse_liteinst_without_the_feature` names the
    /// missing feature instead.
    /// Admits `--cpu-profile x86-64-v3` on this host and binds the host facts
    /// the guest's leaf 0xD and xstate answers come from, or refuses the run
    /// by name (<https://github.com/rrnewton/hermit/issues/4243>). A v2 run is
    /// untouched.
    fn admit_cpu_profile(&mut self) -> Result<(), Error> {
        let config = &self.det_opts.det_config;
        if config.cpu_profile.is_default() {
            return Ok(());
        }
        let backend = self.selected_backend();
        let request = hermit::cpu_profile_admission::AdmissionRequest {
            backend: backend.as_str(),
            ptrace: backend == Backend::Ptrace,
            virtualize_cpuid: config.virtualize_cpuid,
            strace_only: self.strace_only,
            gdbserver: config.gdbserver,
            namespace_only: self.namespace_only,
        };
        match hermit::cpu_profile_admission::admit(&request) {
            Ok((probe, host)) => {
                tracing::info!(
                    "--cpu-profile x86-64-v3 admitted: XINUSE probe on CPU {}, XCR0 {:#x}, {} cases, \
                     {} certified pairs",
                    probe.cpu,
                    probe.xcr0,
                    probe.cases,
                    probe.certified_pairs
                );
                self.det_opts.det_config.cpu_profile_host = Some(host);
                super::verify::CPU_PROFILE_V3_RAN.store(true, std::sync::atomic::Ordering::SeqCst);
                Ok(())
            }
            Err(refusal) => Err(Error::new(PolicyRefusal)
                .context(format!("--cpu-profile x86-64-v3 refused: {refusal}"))),
        }
    }

    fn refuse_unqualified_liteinst_in_guest_options(&self) -> Result<(), Error> {
        if !self.uses_in_guest_liteinst() {
            return Ok(());
        }
        let config = &self.det_opts.det_config;
        let reason = if cfg!(feature = "liteinst") && config.max_timeslice.is_some() {
            "it cannot deliver Detcore's preemption timer yet (the in-guest Tool host refuses \
             set_timer with ENOSYS), so the run would fail at its first timeslice; pass \
             --max-timeslice=disabled"
        } else if self.timeout.is_some() {
            "--timeout has not been qualified for the in-guest runtime, whose run future does \
             not kill the guest when it is dropped"
        } else if self.skid_margin.is_some() {
            "--skid-margin configures the Reverie ptrace PMU timer, which the in-guest runtime \
             does not arm"
        } else if config.gdbserver {
            "--gdbserver needs the ptrace tracer, which the in-guest runtime does not attach"
        } else {
            return Ok(());
        };
        Err(Error::new(PolicyRefusal).context(format!(
            "--backend={} (in-guest LiteInst) refuses this run: {reason}",
            self.selected_backend().as_str()
        )))
    }

    /// In a build without the `liteinst` feature, refuses `--backend=liteinst`
    /// for the missing feature ("this build was compiled without the liteinst
    /// backend"), in place of the inherited in-guest maximum-timeslice advice.
    /// Explicit unsupported timer requests are refused before this check.
    ///
    /// `main` calls it after every refusal that holds in every build: the
    /// in-guest option refusals, the `--max-log-bytes` refusal, the `--verify`
    /// log-level check, argument validation and replay-epoch reconciliation.
    /// So an unqualified `--timeout`, an unenforceable `--max-log-bytes` or a
    /// conflicting `--epoch` gets the same verdict whatever the build. It is
    /// also before `--verify` reads stdin, so this refusal does not
    /// wait for input either. Builds with the feature are unchanged: they
    /// check whether the LiteInst runtime is installed later, with the other
    /// backends.
    fn refuse_liteinst_without_the_feature(&self) -> Result<(), Error> {
        if cfg!(feature = "liteinst") || !self.uses_in_guest_liteinst() {
            return Ok(());
        }
        self.selected_backend().ensure_available()
    }

    /// Why `--max-log-bytes` cannot end a run of this backend in this namespace
    /// mode, or `None` when the guest runs inside hermit's PID namespace, which
    /// dies with the hermit process that would end the run.
    ///
    /// The cap ends a run by `_exit(123)` in whichever hermit process crossed
    /// it: the outer process or a container init. That ends the RUN only if the
    /// guest tree cannot outlive that process. The one mechanism that makes sure
    /// of it from before the guest exists is a PID namespace whose init is
    /// hermit's container init: the namespace dies with its init, and the init
    /// dies with the outer process through `container::arm_parent_death_signal`,
    /// armed before the init starts the guest. A crossing that lands before that
    /// arming, when the death signal can no longer come, is caught right after
    /// it by `tracing::exit_if_log_cap_already_crossed`.
    /// A ptrace tracee with `PTRACE_O_EXITKILL` also dies with its tracer, but
    /// Reverie sets that option only after the guest exists (below), so it
    /// binds the guest for the rest of the run, not for all of it.
    ///
    /// So every `--no-namespace` configuration is refused, and DBT is refused in
    /// both modes:
    ///
    /// - DBT with `--no-namespace`: `backends::run_dbt` starts `drrun` as a
    ///   plain child of the outer process, and Reverie's DBT launcher sets only
    ///   a process group and the personality: no parent-death signal and no
    ///   ptrace attachment. With namespaces, the guest is inside hermit's PID
    ///   namespace, but the cap has not yet been tested ending such a run.
    /// - ptrace with `--no-namespace`, and `--backend=e9patch` with it (e9patch
    ///   preprocessing, whose rewritten guest runs on the ptrace backend,
    ///   `runtime_backend`): Reverie's
    ///   `TracerBuilder::spawn` clones the guest, starts the `--gdbserver`
    ///   server if one is asked for, and only then, in `postspawn`, sets
    ///   `PTRACE_O_EXITKILL`. Linux clears the inherited parent-death signal in
    ///   the clone, so in between the guest is bound to nothing, and a charged
    ///   write can cross the cap there: the outer process's asynchronous file
    ///   appender draining a queued record, or the GDB server's charged
    ///   accepted-client event (round-4c review of
    ///   https://github.com/rrnewton/hermit/pull/3686, finding 1).
    /// - LiteInst with `--no-namespace` (LiteInst runs only in-guest at this
    ///   base): Reverie spawns the guest directly and does not trace it, and
    ///   no PID namespace contains it.
    /// - SaBRe with `--no-namespace`: `sabre_ptrace` detaches the guest with
    ///   SIGSTOP to hand it to the supervisor worker, which re-attaches and
    ///   only then sets `PTRACE_O_EXITKILL`. In between the guest is stopped,
    ///   untraced and in no PID namespace, and the worker's charged trace event
    ///   can cross the cap there, which would leave a stopped guest behind.
    /// - KVM with `--no-namespace`: reverie-kvm creates host processes at
    ///   several sites, and only some of them are shown to arm a parent-death
    ///   signal. Unproven is refused until each site is audited; inside
    ///   hermit's PID namespace the question does not arise.
    ///
    /// The match has no wildcard arm, so a new backend must be classified here
    /// before it compiles. Not every subcommand that accepts the global flag
    /// passes through this check, and each one stands as follows (round-3
    /// review of https://github.com/rrnewton/hermit/pull/3686, finding 6):
    ///
    /// - `run` and `oci run` call it through `RunOpts::main`.
    /// - `analyze` and `bisect` send their trials straight to `RunOpts::run`
    ///   and call it through `AnalyzeOpts::refuse_unsupervised_log_cap` before
    ///   any trial. `Subcommand::validate_backend_scope` admits only KVM there
    ///   besides ptrace, so `--no-namespace` given through `--run-arg` or after
    ///   `--`, with either, is the case it catches. They add no
    ///   `--no-namespace` of their own.
    /// - `record` and `replay` start their containers through
    ///   `owned_container::run` and never call it. They have no
    ///   `--no-namespace` mode: every one of those containers asks for a
    ///   private PID namespace, and their GDB servers (`replay` and `record
    ///   start --verify-with-gdbex`) run inside it.
    /// - `hermit --backend=sabre strace` starts no container: `StraceOpts::main`
    ///   refuses the flag itself, and `strace` with any other backend fails
    ///   before it starts anything.
    /// - `instruction-map` and `record list`, `remove` and `clean` charge their
    ///   tracing but run no guest. `version`, `host-capabilities`, `log-diff`
    ///   and `oci ls`, `inspect` and `pull` initialize no tracing at all.
    fn log_cap_refusal(backend: Backend, no_namespace: bool) -> Option<&'static str> {
        match backend {
            // In its container the guest is inside hermit's PID namespace, but
            // no run has yet shown the cap ending a DBT run there
            // (https://github.com/rrnewton/hermit/issues/4009).
            Backend::Dbt => Some(
                "--backend=dbt: under --no-namespace the DynamoRIO guest is a plain child of this \
                 hermit process that no PID namespace, parent-death signal or ptrace attachment \
                 binds to hermit, so exiting 123 at the cap would leave the guest running, and \
                 the cap has not been tested ending a DBT run inside hermit's PID namespace",
            ),
            Backend::Liteinst if no_namespace => Some(
                "--backend=liteinst and --no-namespace: the in-guest LiteInst guest is neither \
                 a ptrace tracee nor inside a PID namespace hermit owns, so exiting 123 at the \
                 cap would leave the guest running; drop --no-namespace",
            ),
            Backend::InGuestTrap if no_namespace => Some(
                "--backend=in-guest-trap and --no-namespace: the in-guest LiteInst guest is \
                 neither a ptrace tracee nor inside a PID namespace hermit owns, so exiting 123 \
                 at the cap would leave the guest running; drop --no-namespace",
            ),
            Backend::Sabre if no_namespace => Some(
                "--backend=sabre and --no-namespace: the guest is handed to the SaBRe worker \
                 stopped and untraced, before PTRACE_O_EXITKILL binds it, and no PID namespace \
                 contains it, so exiting 123 at the cap in that window would leave a stopped \
                 guest behind; drop --no-namespace",
            ),
            Backend::Kvm if no_namespace => Some(
                "--backend=kvm and --no-namespace: no PID namespace contains the KVM backend's \
                 host processes, and they are not shown to die with hermit, so exiting 123 at \
                 the cap might leave the guest running; drop --no-namespace",
            ),
            Backend::Ptrace | Backend::E9patch if no_namespace => Some(
                "--no-namespace: the ptrace tracer installs PTRACE_O_EXITKILL only after the \
                 guest exists, and after it starts any --gdbserver server, so a log write can \
                 cross the cap before the guest is bound to hermit; no PID namespace contains \
                 the guest, so exiting 123 there would leave it running; drop --no-namespace",
            ),
            Backend::Ptrace
            | Backend::Liteinst
            | Backend::InGuestTrap
            | Backend::Sabre
            | Backend::Kvm
            | Backend::E9patch => None,
        }
    }

    /// Refuses `--max-log-bytes` (exit 122) where [`Self::log_cap_refusal`]
    /// says the cap could end hermit and leave the guest running: DBT, and
    /// `--no-namespace` with any backend (`--gdbserver` included, which used
    /// to be a separate rule here and is now a case of `--no-namespace`).
    /// Hermit does not supervise the guest tree itself, so the honest answer
    /// is to refuse the combination rather than report a run as stopped when
    /// it is not.
    pub(crate) fn refuse_unsupervised_log_cap(
        &self,
        max_log_bytes: Option<u64>,
    ) -> Result<(), Error> {
        if max_log_bytes.is_none() {
            return Ok(());
        }
        let refusal = Self::log_cap_refusal(self.selected_backend(), self.no_namespace);
        match refusal {
            None => Ok(()),
            Some(reason) => Err(Error::new(PolicyRefusal)
                .context(format!("--max-log-bytes cannot be enforced with {reason}"))),
        }
    }

    /// Which comparator a `--verify` run uses, as a function of the request
    /// ALONE.
    ///
    /// DELIBERATELY BACKEND-INDEPENDENT, AND THAT IS THE PROPERTY UNDER GUARD.
    /// This used to read `let kvm_output_only = self.selected_backend() ==
    /// Backend::Kvm`, so plain KVM verification bypassed internal-log comparison
    /// entirely and `--verify-strict` could not reach the canonical comparator on
    /// that backend at all. The special case was not narrowed, it was removed:
    /// every backend now compares both captured logs and picks its comparator
    /// here from `verify_verbose`/`verify_strict` only.
    ///
    /// Removing a branch leaves nothing behind to notice its return, so
    /// `comparator_choice_does_not_depend_on_the_backend` pins the absence
    /// across every `Backend` variant. Re-introducing a backend term here is the
    /// regression it exists to catch.
    ///
    /// `--verify-verbose` historically implied a bitwise compare (it flipped
    /// `strip_lines` off and `FullTrace` on); that is preserved, and
    /// `--verify-strict` selects the same comparison quietly.
    fn verification_strictness(&self) -> LogCompareStrictness {
        if self.verify_verbose || self.verify_strict {
            LogCompareStrictness::Canonical
        } else {
            LogCompareStrictness::Stripped
        }
    }

    fn verification_comparison_options(&self) -> ComparisonOptions {
        // Use the configuration the selected runtime backend actually receives.
        // `run_with_output_backend` applies this same normalization before
        // constructing Detcore. Reading the pre-normalization CLI value here
        // would let a backend disable an observation while the verdict still
        // reported that it participated.
        let config =
            hermit::prepare_backend_config(self.effective_det_config(), self.runtime_backend());
        ComparisonOptions {
            verbose: self.verify_verbose,
            strictness: self.verification_strictness(),
            // The original KVM defect made this false for one backend, reducing
            // verification to guest-output comparison. Keep the actual options
            // consumed by compare_two_runs behind the all-backend regression
            // bracket above.
            compare_logs: true,
            diagnostic_full_trace: self.verify_verbose,
            compare_io_buffers: config.detlog_io_buffers,
            keep_logs: self.keep_logs,
            // `verify` sets this when a skid overshoot overrides the match.
            match_overridden: false,
            failed_log_retention: (!self.keep_logs).then(default_failed_verify_log_retention),
            record_envelope: RecordEnvelope::all_records_v1(),
            // Read from the LIVE config, not a constant: `--no-virtualize-time`
            // makes this a genuine runtime choice on the run path, so a hard-coded
            // `true` would publish a time policy the run did not use. The
            // record/replay path is a fixed decision instead and names it once, as
            // `RECORD_REPLAY_VIRTUALIZES_TIME`.
            virtualize_time: config.virtualize_time,
            caller_owns_logs: false,
        }
    }

    /// The `--verify-json` path this invocation will publish a verdict to, if
    /// any. Exposed so the top-level dispatcher can stamp the invocation-bound
    /// NO-RESULT record before ANY fallible preflight runs — several of this
    /// function's own early exits, and the DBT / `--namespace-only` bypasses
    /// below, never reach `verify()` at all.
    pub(crate) fn verify_json_path(&self) -> Option<&Path> {
        self.verify.then_some(self.verify_json.as_deref()).flatten()
    }

    fn retained_verify_log_dir(&self) -> Result<Option<PathBuf>, Error> {
        if !self.keep_logs {
            return Ok(None);
        }
        let directory = match &self.verify_log_dir {
            Some(directory) => directory.clone(),
            None => dirs::state_dir()
                .ok_or_else(|| {
                    Error::msg(
                        "--keep-logs needs --verify-log-dir because no user state directory is available",
                    )
                })?
                .join("hermit")
                .join("verify-logs"),
        };
        fs::create_dir_all(&directory).with_context(|| {
            format!(
                "could not create verification log directory {}",
                directory.display()
            )
        })?;
        Ok(Some(fs::canonicalize(&directory).with_context(|| {
            format!(
                "could not resolve verification log directory {}",
                directory.display()
            )
        })?))
    }

    /// A mechanics fixture cannot supply production Detcore readiness. Keep
    /// this admission independent of host capabilities and backend selection.
    pub(crate) fn refuse_unready_exec_stop(&self) -> Result<(), Error> {
        if self.in_guest_exec_stop {
            return Err(Error::new(PolicyRefusal).context(
                "--in-guest-exec-stop: exec-stop-runtime-not-ready: genuine Detcore readiness \
                 and production ToolRegion image reservation/adoption are not integrated",
            ));
        }
        Ok(())
    }

    pub fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        self.refuse_unready_exec_stop()?;
        if self.dap_listen.is_some() {
            // Before validation, so every --gdbserver refusal applies.
            self.det_opts.det_config.gdbserver = true;
            match std::env::var_os(DAP_LISTEN_INNER_ENV) {
                None => return self.serve_dap(),
                // The run a supervising `hermit run --dap-listen` started.
                Some(owner) if started_by_a_dap_supervisor(&owner) => {}
                Some(owner) => anyhow::bail!(
                    "{DAP_LISTEN_INNER_ENV}={owner:?} is set, but its parent did not start this \
                     hermit run --dap-listen; unset {DAP_LISTEN_INNER_ENV}"
                ),
            }
        }
        let result = self.main_without_core_cleanup(global);
        if let Ok(status) = &result {
            self.finish_manifest(*status);
        }
        if matches!(result, Ok(ExitStatus::Exited(0))) {
            self.discard_fatal_cores_after_success();
        }
        result
    }

    /// `--dap-listen`: this process supervises two children, the run itself
    /// (this same command, as a plain `--gdbserver` run) and, once the run's
    /// gdbserver is listening, `hermit-dap` on a socket this process bound.
    /// A run that is refused, or whose program is not found, ends before any
    /// adapter starts, with its own message and status. Before the adapter
    /// starts, the host file named to the debugger is checked against the
    /// file the waiting guest process sees (see
    /// [`super::dap_adapter::identify_debuggee`]). If the adapter ends
    /// for any reason while the gdbserver still waits for its one connection,
    /// no debugger can ever attach, so this ends the run instead of leaving it
    /// waiting. Both children die with this process.
    fn serve_dap(&self) -> Result<ExitStatus, Error> {
        let argument = self.dap_listen.as_deref().unwrap_or_default();
        let gdbserver_port = self.det_opts.det_config.gdbserver_port;
        anyhow::ensure!(
            gdbserver_port != 0,
            "--dap-listen needs a fixed --gdbserver-port, so it can tell when the run's \
             gdbserver listens and give that port to the debugger; pass another port than 0"
        );
        let listener = super::dap_adapter::bind(argument)?;
        // Where the guest command finds its program (guest working
        // directory, PATH), searched later in the guest's own view. A program
        // that cannot be found is left to the run, which reports it with its
        // own status (127 if it is not found); hermit-dap is looked for only
        // once the run gets that far.
        let guest = self.guest_program().ok();
        // Held until this function returns, while the run is supervised.
        let (_supervisor_socket, marker) = bind_dap_supervisor_socket()?;
        let run = super::dap_adapter::spawn_owned(
            std::process::Command::new(std::env::current_exe().context("Failed to locate hermit")?)
                .args(std::env::args_os().skip(1))
                .env(DAP_LISTEN_INNER_ENV, marker),
        )
        .context("Failed to start the run")?;
        super::dap_adapter::supervise(
            run,
            listener,
            gdbserver_port,
            |guest_pid| {
                let guest = guest.as_ref().ok_or_else(|| {
                    anyhow::anyhow!(
                        "--dap-listen cannot tell which file the guest runs for {}",
                        self.program.display()
                    )
                })?;
                super::dap_adapter::identify_debuggee(guest_pid, guest, |path| {
                    // Rebuilt from its components: a file mounted at exactly
                    // `path` maps to its source with a trailing '/'.
                    self.mapped_or_visible_host_program(path)
                        .map(|host| host.components().collect())
                })
            },
            self.dap_gdb.as_deref(),
        )
    }

    fn main_without_core_cleanup(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        // Set up an early tracing option before we're ready to set the global default:

        // The backend is a global option (`hermit --backend X run ...`), the only
        // place it can be given.
        self.backend = global.backend;
        // Static native-option policy belongs before stdin reservation,
        // availability probes, or backend-specific preprocessing/dispatch.
        #[cfg(feature = "native-exec")]
        if self.native_exec_inputs.is_some() {
            anyhow::ensure!(
                self.selected_backend() == Backend::InGuestTrap,
                "native exec currently requires in-guest-trap"
            );
        }
        self.refuse_unapplied_config()?;
        self.resolve_preemption_settings()?;
        if let Some(path) = &self.backend_engagement_json {
            clear_machine_record(path, "backend engagement")?;
        }
        // Before `--verify` reads stdin to its end below: a run that in-guest
        // LiteInst refuses must not wait for its input. `validate_args` repeats
        // the check for its other callers.
        self.refuse_unqualified_liteinst_in_guest_options()?;
        // Beside the refusals above, and before stdin is read for the same
        // reason: a refused run must not consume its input. It is also above the
        // DBT arm below, which returns without reaching `RunOpts::run`.
        self.refuse_unsupervised_log_cap(global.max_log_bytes)?;
        // Also before stdin is read and before any backend is probed: a
        // happens-before spec this launch cannot enforce needs neither, so it
        // is refused at once rather than after input or availability checks.
        self.refuse_unenforceable_happens_before()?;
        // Before stdin or any backend: a pair whose shared inputs are missing,
        // unsealed or not the manifest's objects is refused before it starts.
        #[cfg(feature = "native-exec")]
        anyhow::ensure!(
            self.native_exec_inputs.is_none()
                || self.verify_run.is_none()
                || self.native_exec_shared_inputs.is_some(),
            "native --verify-run requires the holder's shared-input manifest"
        );
        if let Some(fd) = self.native_exec_shared_inputs {
            let adopted = super::verify_inputs::take_adopted(fd)?;
            #[cfg(feature = "native-exec")]
            if self.native_exec_inputs.is_some() {
                self.native_exec_capture = Some(std::sync::Arc::new(
                    adopted.into_inputs::<super::native_exec_cli::Capture>()?,
                ));
            } else {
                self.shared_inputs = Some(std::sync::Arc::new(adopted));
            }
            #[cfg(not(feature = "native-exec"))]
            {
                self.shared_inputs = Some(std::sync::Arc::new(adopted));
            }
        }
        // Also before stdin is read: a host or run the x86-64-v3 profile
        // cannot qualify is refused at once.
        self.admit_cpu_profile()?;
        if self.verify || self.verify_run.is_some() {
            validate_log_level(global)?;
        }

        // TODO(T124429978): temporarily disabling this because it inexplicably clobbers our
        // subsequent tracing_subscriber::fmt::init() call.
        // tracing::subscriber::with_default(super::tracing::stderr_subscriber(global.log), || {

        // Argument validation and epoch reconciliation also come before stdin
        // is read: neither needs the input, and a run they refuse must not wait
        // for it.
        self.validate_args()?;
        // Right after validation, which may have turned the preemption timer
        // off, and still before stdin is read or anything is launched.
        self.refuse_happens_before_without_preemption()?;
        self.adopt_replayed_schedule_epoch()?;
        // After the replayed epoch is adopted, which makes an omitted epoch
        // explicit, and still before stdin is read or anything is launched.
        self.refuse_strict_with_host_drawn_inputs()?;
        self.refuse_replay_under_another_pipe_wake_latency()?;
        self.refuse_replay_under_another_signal_state_copy()?;
        if !self.namespace_only
            && (self.verify_verbose
                || global
                    .log
                    .is_some_and(|level| level >= tracing::metadata::LevelFilter::DEBUG))
        {
            global.write_controller_diagnostic(format_args!(
                "hermit: {}",
                self.preemption_summary()
            ))?;
        }
        // Once every implicit input it records is resolved, and before the
        // guest starts, so a run that fails or hangs still leaves it.
        self.write_saved_config()?;
        // For the same reason, the run manifest too. It is a convenience
        // beside the warning that already prints the inputs, so a data
        // directory that cannot be written does not stop the run.
        let recording = self.begin_manifest(global).unwrap_or_else(|error| {
            crate::tracing::diagnostic_eprintln!(
                "hermit: WARNING: this run's manifest was not written: {error:#}"
            );
            None
        });
        self.warn_of_host_drawn_inputs(global, recording)?;
        // After every refusal above, which holds in every build, so a build
        // without the feature refuses those runs the way a feature build does;
        // and before stdin is read.
        self.refuse_liteinst_without_the_feature()?;
        let verification = self.verify || self.verify_run.is_some();
        let dbt_verification_stdin = if verification && self.selected_backend() == Backend::Dbt {
            // DBT streams this reservation during live or saved-run execution.
            // The common live owner replays it without pre-draining stdin;
            // library output-capturing backends reserve their input below.
            super::startup_stdin()?
        } else if verification {
            // `--verify` runs the guest twice through the output-capturing
            // backend, which otherwise feeds the guest an empty stdin. Snapshot
            // the real stdin now so both runs replay identical input; without
            // this, piped input (e.g. `echo prog | hermit run --verify -- gcc
            // -x c -`) is dropped and hermit reports a false deterministic pass.
            hermit::reserve_output_stdin_snapshot(super::startup_stdin()?)?;
            None
        } else if self.selected_backend() == Backend::Kvm {
            hermit::reserve_kvm_stdin(super::startup_stdin()?)?;
            None
        } else {
            None
        };

        if self.allow_unsupported_syscalls {
            crate::tracing::diagnostic_eprintln!(
                "WARNING: --allow-unsupported-syscalls permits unmodeled syscalls to reach the \
                 host; a successful exit does not establish complete deterministic execution."
            );
        }
        let backend = self.selected_backend();
        if backend == Backend::E9patch && self.no_namespace {
            anyhow::bail!(
                "--backend=e9patch requires mount namespaces to overlay the rewritten ELF at its \
                 original guest path"
            );
        }
        if self.namespace_only
            && let Some(explicit_backend) = self.backend
        {
            anyhow::bail!(
                "--backend={} cannot be used with --namespace-only because namespace-only mode \
                 bypasses instrumentation",
                explicit_backend.as_str()
            );
        }
        // ⚠️ HERE, NOT IN `run()`. The DBT single-run arm below returns through
        // its physical launcher, so a check placed in `run()` covers every
        // backend except the one measured furthest from working. Same shape as
        // the `--namespace-only` second launch path documented in `run()`: the
        // first placement worked and was not yet complete. Measured: with the
        // check in `run()`, `--backend dbt --timeout 3` still accepted the flag
        // and ran unbounded.
        //
        // AND BEFORE THE AVAILABILITY PROBE. Whether `--timeout` is qualified on
        // a backend is a static policy fact; whether the backend is compiled in
        // depends on the build's features. Probing availability first made a
        // build without `sabre` answer "backend unavailable" (125) where every
        // other build answers "refused" (122), so the same command got a
        // different verdict per build
        // (https://github.com/rrnewton/hermit/issues/3418).
        self.ensure_timeout_supported()?;
        if !self.namespace_only && backend != Backend::Kvm && !self.uses_native_exec() {
            // E9patch's own availability check covers both its ptrace runtime and
            // the `e9patch` cargo feature (it reports "not included in this build"
            // when the feature is disabled), so it no longer needs a special case.
            // A `--no-namespace` run creates no namespace, so it is not refused
            // where only unshare(CLONE_NEWUSER) is denied
            // (https://github.com/rrnewton/hermit/issues/4515).
            backend.ensure_available_for(if self.no_namespace {
                hermit::NamespaceUse::None
            } else {
                hermit::NamespaceUse::Creates
            })?;
        }
        // Native exec uses the embedded, producer-qualified catalog rather
        // than the ordinary preload. Its complete Capture::prepare below
        // remains mandatory after program/config validation and before either
        // physical run; an adjacent preload cannot establish its availability.
        self.install_pmu_config()?;
        // After the PMU configuration, which Reverie's validation reads, and
        // before every check below that can still refuse the run: the pending
        // report is rewritten with the verdict, so that a run refused here,
        // by the strict counter check or a later one, still says which
        // counter it would have read.
        if let Some(path) = self.verify_json.as_deref()
            && self.arms_reverie_ptrace_pmu_timer()
        {
            crate::verify::record_exact_branch_counter(branch_counter_verdict());
            crate::verify::write_pending_verification_json(path)?;
        }
        self.admit_branch_counter(&mut crate::tracing::write_stderr_diagnostic)?;
        // The KVM backend reaches real reverie-kvm code from its dispatch path
        // and reports an accurate, program-specific error there, so it is not
        // pre-empted by the generic availability probe above. E9patch is a CLI
        // preprocessor and probes its ptrace runtime and tool separately.
        self.validate_mount_sources()?;
        self.validate_program()?;
        if self.hb_list_events {
            return self.list_happens_before_events();
        }
        // After the event listing, which runs no guest and writes no summary.
        self.validate_summary_json_visibility()?;
        if self.happens_before.is_some() {
            // Resolve the spec against the guest binary's debug info now and cache
            // it so every subsequent `effective_det_config()` (including both
            // `--verify` runs) hands the scheduler the identical resolved program.
            let program = self.load_and_resolve_happens_before()?;
            self.resolved_happens_before = Some(program);
        }
        if backend == Backend::E9patch {
            self.prepare_e9patch_program()?;
        }
        let private_engagement_summary = if self.backend_engagement_json.is_some()
            && backend == Backend::Ptrace
            && self.summary_json.is_none()
        {
            let file = private_backend_engagement_summary()?;
            // The container is handed the descriptor: see
            // private_summary_descriptor_path.
            self.summary_json = Some(private_summary_descriptor_path(&file));
            Some(file)
        } else {
            None
        };
        // });

        // Last, so that a run refused above creates no directory.
        self.open_fatal_core_dir()?;

        // Ordinary DBT execution keeps its physical launcher. Verification
        // joins the common two-run owner through the same launcher's one-run seam.
        if backend == Backend::Dbt && !self.verify {
            self.warn_no_namespace();
            #[cfg(feature = "dbt")]
            {
                if super::backends::dbt_log_file_is_refused(
                    global.log_file.is_some(),
                    self.verify_run.is_some(),
                ) {
                    return Err(Error::msg(super::backends::DBT_LOG_FILE_REFUSAL));
                }
                let invocation = self.dbt_invocation()?;
                if let Some(directory) = &self.verify_run {
                    return invocation.verify_run(
                        directory,
                        global.log,
                        self.verify_verbose,
                        dbt_verification_stdin,
                        self,
                    );
                }
                // The coordinator runs in this process, so this is where its
                // warnings print, the in-guest ones it receives included
                // (detcore::guest_log). At WARN at most: DBT's own channel
                // already prints the run's INFO and DEBUG records from the
                // guest, and printing the coordinator's per-turn records too
                // would put a stderr write on every scheduler turn, which
                // slowed loaded runs past their bounds. `--log=error` still
                // lowers it. A verification run keeps its log in the run's
                // evidence instead.
                let mut warnings = global.clone();
                warnings.log = Some(
                    global
                        .log
                        .unwrap_or(tracing::level_filters::LevelFilter::WARN)
                        .min(tracing::level_filters::LevelFilter::WARN),
                );
                let _tracing = warnings.init_tracing_for_backend(backend);
                return invocation.run(
                    self.summary,
                    self.backend_engagement_json.as_deref(),
                    global.log,
                    global.log_file.as_deref(),
                );
            }
            #[cfg(not(feature = "dbt"))]
            return Err(Error::msg("DBT support was not included in this build"));
        }

        if backend == Backend::Liteinst && self.uses_in_guest_liteinst() {
            // Nothing has started the guest yet, so this names the
            // configuration, not an outcome.
            crate::tracing::diagnostic_eprintln!(
                "hermit: [liteinst in-guest] selected: the guest preload is to host the Detcore Tool"
            );
        }
        if backend == Backend::InGuestTrap && self.uses_in_guest_liteinst() {
            if self.uses_native_exec() {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: [in-guest-trap] selected: the embedded native runtime is to host \
                     the Detcore Tool, with syscall site patching off"
                );
            } else {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: [in-guest-trap] selected: the guest preload is to host the Detcore Tool, \
                     with syscall site patching off (REVERIE_LITEINST_SITE_PATCHING=0)"
                );
            }
        }

        #[cfg(feature = "native-exec")]
        if let Some(declaration) = &self.native_exec_inputs {
            anyhow::ensure!(
                !self.no_namespace && !self.namespace_only && self.image.is_none(),
                "native exec requires the common declared-input namespace"
            );
            anyhow::ensure!(
                self.timer_downgrade.is_none(),
                "native exec requires an explicit no-timer configuration"
            );
            detcore::native_exec::validate_native_exec_host_configuration(
                &self.effective_det_config(),
            )?;
            let command = self.guest_command()?;
            let capture = if let Some(adopted) = self.native_exec_capture.take() {
                adopted
            } else {
                anyhow::ensure!(
                    self.native_exec_shared_inputs.is_none() && self.verify_run.is_none(),
                    "native shared enrollment cannot fall back to fresh capture"
                );
                super::native_exec_cli::Capture::prepare(declaration, &command)?
            };
            capture.require_initial(&command)?;
            self.native_exec_capture = Some(capture);
        }
        self.warn_no_namespace();

        if self.namespace_only {
            self.run_with_namespace_only(global)
        } else if self.verify {
            self.verify(global, dbt_verification_stdin)
        } else if let Some(directory) = &self.verify_run {
            self.verify_run(directory, global)
        } else {
            let (status, _) = self.run(global, false)?;
            self.write_backend_engagement_after_run()?;
            drop(private_engagement_summary);
            Ok(status)
        }
    }

    /// Some arguments imply others. This is the place where that validation occurs.
    /// Also this performs side effects like accessing system randomness to implement --seed-from=SystemArgs
    pub fn validate_args(&mut self) -> Result<(), Error> {
        self.refuse_unready_exec_stop()?;
        refuse_signal_state_check_env(std::env::var_os(SIGNAL_STATE_CHECK_ENV).as_deref())
            .map_err(Error::msg)?;
        let timer = if self.arms_reverie_ptrace_pmu_timer() {
            reverie_timer_support()
        } else {
            Ok(())
        };
        self.validate_args_with_timer_support(timer)?;
        self.refuse_unqualified_liteinst_in_guest_options()
    }

    /// Whether this run would arm Reverie ptrace's PMU timer for
    /// `--max-timeslice`, and so depends on host `perf_event_open` support.
    ///
    /// `--namespace-only` execs the guest directly without any instrumentation
    /// backend (see `run_with_namespace_only`), so it never arms that timer even
    /// though `selected_backend()` still reports the ptrace default. Probing perf
    /// for it would print a `--max-timeslice` downgrade warning about a timer the
    /// run never uses.
    ///
    /// Runtimes without a timer refuse explicit timer requests before this
    /// host-counter probe. Their inherited scheduling configuration is retained.
    fn arms_reverie_ptrace_pmu_timer(&self) -> bool {
        !self.namespace_only && self.backend_arms_reverie_ptrace_pmu_timer()
    }

    /// Whether the selected backend's own runtime arms Reverie ptrace's PMU
    /// timer, before `--namespace-only` is considered. `RunOpts::run` launches
    /// that runtime even with `--namespace-only`: only `main` dispatches the
    /// flag to `run_with_namespace_only`.
    fn backend_arms_reverie_ptrace_pmu_timer(&self) -> bool {
        hermit::backend_delivers_preemption_timer(self.selected_backend())
    }

    /// [`Self::validate_args_with_timer_support`] for tests, with a missing
    /// timer reported as missing perf counters.
    #[cfg(test)]
    fn validate_args_with_perf_support(&mut self, perf_supported: bool) -> Result<(), Error> {
        self.validate_args_with_timer_support(if perf_supported {
            Ok(())
        } else {
            Err(TimerUnavailable::NoPerfEvents)
        })
    }

    fn validate_args_with_timer_support(
        &mut self,
        timer: Result<(), TimerUnavailable>,
    ) -> Result<(), Error> {
        self.refuse_unready_exec_stop()?;
        self.resolve_preemption_settings()?;
        let backend = self.selected_backend();
        // LiteInst passes here so that the in-guest refusal, which names why
        // it cannot honour `--skid-margin`, is the one that stops the run.
        if self.skid_margin.is_some()
            && (self.namespace_only
                || !matches!(
                    backend,
                    Backend::Ptrace | Backend::Liteinst | Backend::InGuestTrap | Backend::E9patch
                ))
        {
            anyhow::bail!(
                "--skid-margin configures the Reverie ptrace PMU timer and requires a ptrace-backed backend"
            );
        }
        if self.fatal_core_dir.is_some()
            && (self.namespace_only || !matches!(backend, Backend::Ptrace | Backend::E9patch))
        {
            anyhow::bail!(
                "--fatal-core-dir captures cores at the ptrace backend's exit stop, so it \
                 needs --backend=ptrace or --backend=e9patch, without --namespace-only"
            );
        }
        if self.image.is_some() && self.no_namespace {
            anyhow::bail!(
                "--image chroots the guest into a materialized OCI rootfs, which requires mount \
                 and PID namespaces; it is incompatible with --no-namespace"
            );
        }
        if self.image.is_some() && backend != Backend::Ptrace {
            anyhow::bail!(
                "--image currently supports only the ptrace backend; backend `{}` has separate \
                 launcher/runtime-file requirements that have not been qualified inside the OCI rootfs",
                backend.as_str()
            );
        }
        if backend == Backend::Dbt && !self.mount.is_empty() {
            anyhow::bail!(
                "the dbt backend cannot apply --mount yet: its container would apply it, but no \
                 DBT run has been tested with one; it applies --bind targets under /tmp"
            );
        }
        if self.backend_engagement_json.is_some()
            && !matches!(backend, Backend::Ptrace | Backend::E9patch | Backend::Dbt)
        {
            anyhow::bail!(
                "--backend-engagement-json is not available for backend `{}`; SaBRe publishes \
                 HERMIT_SABRE_PATH_EVIDENCE, and liteinst/KVM expose no engagement value",
                backend.as_str()
            );
        }
        if self.image.is_some() && self.namespace_only {
            anyhow::bail!("--image cannot be combined with --namespace-only");
        }
        if self.image.is_some() && (!self.mount.is_empty() || !self.bind.is_empty()) {
            anyhow::bail!(
                "--image does not yet compose with custom --mount/--bind targets inside the OCI rootfs"
            );
        }

        let config = &mut self.det_opts.det_config;

        // Every backend, DBT included, launches the guest through Reverie's
        // `Container` (see `container::default_container`) unless
        // `--no-namespace` is given. It unshares `CLONE_NEWUTS` and applies the
        // deterministic hostname `hermetic-container.local`; without it,
        // Detcore's `handle_uname` rewrites the nodename instead.
        config.has_uts_namespace = !self.no_namespace;

        if self.no_namespace {
            self.network = NetworkingMode::Host;
            self.tmp = Some(PathBuf::from(TMP_DIR));
        }

        if self.analyze_networking {
            config.warn_non_zero_binds = true;
        }

        config.sequentialize_threads = self.strict || !self.no_sequentialize_threads;
        // A signal delivery the kernel contradicts ends a strict run (A5 step
        // 3.2); elsewhere it is logged as a divergence.
        config.signal_delivery_check_fatal = self.strict;
        // `--futex-wake-yields` is accepted only where Detcore's precise futex
        // scheduler runs the guest with sequentialized threads, on the ptrace
        // backend (with or without e9patch preprocessing). Every other launch
        // would accept the flag and ignore it, so it is refused before launch.
        if config.futex_wake_yields {
            if self.namespace_only {
                anyhow::bail!(
                    "--futex-wake-yields needs Detcore's scheduler; --namespace-only (--lite) \
                     runs the guest natively, without it"
                );
            }
            if self.strace_only {
                anyhow::bail!(
                    "--futex-wake-yields reorders the turns of sequentialized threads; \
                     --strace-only turns sequentialization off"
                );
            }
            if !config.sequentialize_threads {
                anyhow::bail!(
                    "--futex-wake-yields reorders the turns of sequentialized threads; it \
                     cannot be combined with --no-sequentialize-threads"
                );
            }
            if config.debug_futex_mode != detcore::BlockingMode::Precise {
                anyhow::bail!(
                    "--futex-wake-yields needs --debug-futex-mode=precise, the only futex \
                     mode in which Detcore knows how many waiters a FUTEX_WAKE woke"
                );
            }
            if backend == Backend::Dbt {
                anyhow::bail!(
                    "the dbt backend cannot apply --futex-wake-yields: its runtime reads \
                     a frozen configuration form that predates the option"
                );
            }
            if !matches!(backend, Backend::Ptrace | Backend::E9patch) {
                anyhow::bail!(
                    "--futex-wake-yields has been tested only on the ptrace backend (and e9patch \
                     preprocessing, which runs on it); backend `{}` is refused until its \
                     handoff is tested",
                    backend.as_str()
                );
            }
        }
        // `--pipe-wake-latency` reorders the turns of sequentialized threads
        // by priority (https://github.com/rrnewton/hermit/issues/4380). As for
        // `--futex-wake-yields`, every launch that would accept it and ignore
        // it refuses it before launch.
        if let Some(latency) = config.pipe_wake_latency {
            if self.namespace_only {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} needs Detcore's scheduler; --namespace-only \
                     (--lite) runs the guest natively, without it"
                );
            }
            if self.strace_only {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} reorders the turns of sequentialized threads; \
                     --strace-only turns sequentialization off"
                );
            }
            if !config.sequentialize_threads {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} reorders the turns of sequentialized threads; \
                     it cannot be combined with --no-sequentialize-threads"
                );
            }
            if !config.sched_heuristic.is_priority_ordered() {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} hands the turn over by priority order; \
                     --sched-heuristic={:?} does not select by priority, so it would be ignored",
                    config.sched_heuristic
                );
            }
            if backend == Backend::Dbt {
                anyhow::bail!(
                    "the dbt backend cannot apply --pipe-wake-latency: its runtime reads a \
                     frozen configuration form that predates the option"
                );
            }
            if !matches!(backend, Backend::Ptrace | Backend::E9patch | Backend::Sabre) {
                anyhow::bail!(
                    "--pipe-wake-latency has been tested only on the ptrace backend (and e9patch \
                     preprocessing, which runs on it) and on sabre; backend `{}` is refused \
                     until its hand-off is tested",
                    backend.as_str()
                );
            }
            if config.debug_externalize_sockets {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} hands off between threads polling \
                     scheduler-managed pipes; --debug-externalize-sockets makes them block in the \
                     kernel instead, so it would be ignored"
                );
            }
            // Whatever else makes the option inert is refused too, rather than
            // accepted and ignored (Codex review of
            // https://github.com/rrnewton/hermit/pull/4424).
            if config.pipe_wake_latency_in_effect().is_none() {
                anyhow::bail!(
                    "--pipe-wake-latency={latency} would have no effect with these options"
                );
            }
        }
        if config.scheduler_turn_cost.is_some() && backend == Backend::Dbt {
            anyhow::bail!(
                "the dbt backend cannot apply --scheduler-turn-cost: its runtime reads a frozen \
                 configuration form that predates the option"
            );
        }
        config.deterministic_io = self.strict || !self.no_deterministic_io;
        // An unmodeled host syscall makes a successful result unqualified.
        // Ordinary execution therefore fails closed; compatibility passthrough
        // is available only through the explicit, noisy opt-out.
        config.panic_on_unsupported_syscalls = !self.allow_unsupported_syscalls;
        if config.passthru_opt && config.panic_on_unsupported_syscalls {
            anyhow::bail!(
                "--passthru-opt cannot be combined with fail-closed unsupported-syscall handling \
                 (the default; pass --allow-unsupported-syscalls to opt out)"
            );
        }
        config.shutdown_on_unsupported_syscall = config.panic_on_unsupported_syscalls;

        // virtualize_metadata implies virtualize_time
        if config.virtualize_metadata && !config.virtualize_time {
            anyhow::bail!(
                "--no-virtualize-time also requires --no-virtualize-metadata; metadata timestamps \
                 cannot be virtualized without virtual time"
            );
        }
        if !(0.0..=1.0).contains(&config.sched_sticky_random_param) {
            anyhow::bail!(
                "--sched-sticky-random-param must be between 0 and 1 inclusive (received {})",
                config.sched_sticky_random_param
            );
        }
        if let Some(multiplier) = config.clock_multiplier
            && (!multiplier.is_finite() || multiplier <= 0.0)
        {
            anyhow::bail!(
                "--clock-multiplier must be finite and positive (received {})",
                multiplier
            );
        }
        if let Err(error) = config.scheduler_turn_charge() {
            anyhow::bail!("{error}");
        }
        let minimum_max_timeslice = config.minimum_max_timeslice_nanos();
        if let Some(max_timeslice) = config.max_timeslice
            && u64::from(max_timeslice) < minimum_max_timeslice
        {
            anyhow::bail!(
                "--max-timeslice must be at least one RCB ({} virtual nanoseconds at this clock multiplier)",
                minimum_max_timeslice
            );
        }

        // Perform internal validation on the Config args, before taking into account the
        // hermit run args. User-controlled panic conditions are checked above.
        config.validate();

        // This is a Detcore Config-internal matter, but relies on reverie_ptrace, which detcore is
        // allowed to depend on:
        if config.max_timeslice.is_some()
            && let Err(unavailable) = &timer
        {
            // TODO(T124429978): this could change back to tracing::warn! when the bug is fixed.
            // With --max-log-bytes this must not wait on a stderr nobody reads: it runs before
            // the container starts, so a blocked write would keep the run from ever reaching
            // the cap.
            match unavailable {
                TimerUnavailable::NoPerfEvents => crate::tracing::write_stderr_diagnostic(
                    "WARNING: --max-timeslice requires user-space perf counters, but \
                     perf_event_open is unavailable; continuing with \
                     --max-timeslice=disabled. Check the host perf_event_paranoid value and \
                     container seccomp policy.\n",
                ),
                TimerUnavailable::NoPmuProfile(reason) => {
                    crate::tracing::write_stderr_diagnostic(&format!(
                        "WARNING: --max-timeslice requires a performance-counter profile for \
                         this CPU, but {reason}; continuing with --max-timeslice=disabled.\n"
                    ))
                }
            }
            config.max_timeslice = None;
            self.timer_downgrade = Some(unavailable.clone());
        }

        if let Some(sf) = &self.seed_from {
            let seed = match sf {
                SeedFrom::Args => {
                    let mut hasher = DefaultHasher::new();
                    self.args.hash(&mut hasher);
                    self.program.hash(&mut hasher);
                    hasher.finish()
                }
                SeedFrom::SystemRandom => rand::random::<u64>(),
            };
            // TODO(T124429978): this could change back to tracing::warn! when the bug is fixed:
            crate::tracing::diagnostic_eprintln!(
                "[hermit] auto setting --seed {0:?} --sched-seed {0:?}",
                seed
            );
            config.seed = seed;
            self.seed_from_resolved = Some(seed);
        }

        // Deterministic RCB counts requires thread pinning.  But this only matters if
        // we're expecting full determinstic execution (sequentialize_threads).
        if config.max_timeslice.is_some() && config.sequentialize_threads {
            self.pin_threads = true;
        }

        if self.strace_only {
            config.virtualize_cpuid = false;
            config.virtualize_metadata = false;
            config.virtualize_time = false;
            config.deterministic_io = false;
            self.network = NetworkingMode::Host;
            config.sequentialize_threads = false;
            config.no_rcb_time = true;
            if self.tmp.is_none() {
                self.tmp = Some(PathBuf::from("/tmp"));
            }
        }

        // Happens-before enforcement parks the "after" thread until its "before"
        // anchor fires. That deterministic parking is only meaningful when the
        // scheduler owns thread selection; with threads running in parallel there
        // is no single serial order to constrain. Fail closed rather than silently
        // ignore the spec.
        if self.happens_before.is_some() && !config.sequentialize_threads {
            anyhow::bail!(
                "--happens-before requires deterministic sequential thread execution; remove \
                 --no-sequentialize-threads (and --strace-only) so the scheduler can enforce \
                 ordering edges"
            );
        }

        // The gdbserver listens on a TCP port that is bound inside the guest's
        // network namespace. With the default isolated (`local`) networking, that
        // port lives in the guest's unshared netns and is unreachable from a host
        // gdb client, so `hermit run --gdbserver` silently hangs waiting for a
        // connection that can never arrive. Fall back to host networking so the
        // debugger can attach. This mirrors how replay-mode gdbserver already
        // works: a gdb-served replay never unshares the network namespace, which
        // is exactly why its gdbserver is reachable from the host.
        if self.det_opts.det_config.gdbserver && self.network == NetworkingMode::Local {
            if self.analyze_networking {
                anyhow::bail!(
                    "--gdbserver requires host networking so a host gdb client can reach the \
                     gdbserver port, but --analyze-networking forces an isolated network \
                     namespace. Run these two modes separately."
                );
            }
            // TODO(T124429978): this could change back to tracing::warn! when the bug is fixed:
            crate::tracing::diagnostic_eprintln!(
                "WARNING: --gdbserver requires host networking so a host gdb client can reach \
                 the gdbserver port; overriding --network=local with --network=host for this \
                 debug session. Network isolation and deterministic networking are disabled \
                 while the gdbserver is attached."
            );
            self.network = NetworkingMode::Host;
        }

        // `--strict` calls itself fail-closed strict deterministic mode, so it
        // must refuse the settings hermit itself documents as
        // determinism-compromising rather than accept them silently. Before
        // this, `--strict --network=host` exited 0 with no warning, even though
        // `--network`'s own help says `host` "compromises isolation and
        // deterministic reproducibility".
        //
        // Checked HERE, after every override above, because two of the three
        // routes to host networking are side effects of flags that are not
        // about networking at all: `--no-namespace` sets it above, and
        // `--gdbserver` sets it just above (that one at least prints a
        // warning; the others were silent). Measured from inside the guest,
        // `--strict` alone sees interfaces `lo`, while `--strict --network=host`,
        // `--strict --no-namespace` and `--strict --strace-only` all see
        // `eth0 lo`.
        //
        // This forbids rather than warns because the directive is that a hole
        // must be opened deliberately: drop `--strict`, or ask for the hole
        // explicitly without also claiming strictness.
        if self.strict && self.network == NetworkingMode::Host {
            let cause = if self.no_namespace {
                "--no-namespace, which forces host networking"
            } else if self.det_opts.det_config.gdbserver {
                "--gdbserver, which forces host networking"
            } else {
                "--network=host"
            };
            anyhow::bail!(
                "--strict is fail-closed deterministic mode and cannot be combined with {}: \
                 host networking exposes the guest to external traffic that hermit does not \
                 determinize. Re-run without --strict to allow it deliberately.",
                cause
            );
        }

        // Set after the strict check: a recording shares the host network
        // namespace, so the strict refusal of host networking does not apply.
        // An IPv4 or IPv6 operation either becomes an outbound TCP channel,
        // whose inputs are captured and released deterministically, or ends
        // the run with a refusal. So do the other routes into that namespace
        // that detcore's `syscalls::network_trace` knows: other socket
        // families, abstract AF_UNIX addresses, interface ioctls, and opens
        // of /proc/net, /proc/sys/net and /sys network interfaces. Its module
        // documentation lists the routes that remain open. Replay applies the
        // same refusals in its private namespace.
        self.det_opts.det_config.network_trace = self.network_trace_config()?;
        if self.record_networking.is_some() {
            self.network = NetworkingMode::Host;
        }

        // Advise when running a VMM (e.g. QEMU) under host-time virtualization,
        // whose emulated guest clock calibration this corrupts (issue #6).
        // Checked last so it reflects any overrides above that disable virtual
        // time (e.g. --strace-only).
        let virtualize_time = self.det_opts.det_config.virtualize_time;
        if let Some(warning) =
            vmm_time_virtualization_warning(&self.program, &self.args, virtualize_time)
        {
            // TODO(T124429978): this could change back to tracing::warn! when the bug is fixed:
            crate::tracing::diagnostic_eprintln!("{warning}");
        }

        Ok(())
    }

    /// The run options `hermit analyze` and `hermit bisect` cannot pass to
    /// their trials, each with the reason, as given. Every trial would either
    /// leave the deterministic, isolated setup the trials are compared in, or
    /// write the same output path as every other trial. Options a trial sets
    /// for itself afterwards (analyze's own preemption record and stack-trace
    /// events) are not seen here.
    pub(crate) fn options_trials_refuse(&self) -> Vec<(&'static str, &'static str)> {
        let config = &self.det_opts.det_config;
        const SHARED: &str = "every trial writes that same path, so only the last trial's output \
                              would remain";
        [
            (
                self.config.is_some(),
                "--config",
                "the trials parse their run arguments directly and would ignore the file; give \
                 its options as run arguments",
            ),
            (
                self.strace_only,
                "--strace-only",
                "it turns off thread sequentialization and the rest of determinization, and the \
                 trials' schedule search needs both",
            ),
            (
                self.no_sequentialize_threads,
                "--no-sequentialize-threads",
                "the trials' schedule search needs sequentialized threads",
            ),
            (
                self.network == NetworkingMode::Host,
                "--network=host",
                "it puts every trial on the host network, so the trials are no longer reproducible",
            ),
            (
                self.no_namespace,
                "--no-namespace",
                "every trial would share the host's processes, files and network, and schedule \
                 and preemption replay, which the trials are, need stable namespace PIDs",
            ),
            (
                config.gdbserver,
                "--gdbserver",
                "it moves every trial to the host network and makes each one wait for a debugger \
                 on the same port",
            ),
            (
                self.dap_listen.is_some(),
                "--dap-listen",
                "it makes every trial wait for a debugger, and only the first trial could take \
                 the adapter's port",
            ),
            (
                config.record_preemptions_to.is_some(),
                "--record-preemptions-to",
                SHARED,
            ),
            (
                config
                    .stacktrace_event
                    .iter()
                    .any(|(_, path)| path.is_some()),
                "--stacktrace-event with a path",
                SHARED,
            ),
            (
                config.preemption_stacktrace_log_file.is_some(),
                "--preemption-stacktrace-log-file",
                SHARED,
            ),
        ]
        .into_iter()
        .filter_map(|(given, option, reason)| given.then_some((option, reason)))
        .collect()
    }

    /// The trace `--record-networking` names, as given. `hermit analyze` and
    /// `hermit bisect` refuse it in their run arguments
    /// (`AnalyzeOpts::refuse_outputs_trials_overwrite`).
    pub(crate) fn record_networking_trace(&self) -> Option<&Path> {
        self.record_networking.as_deref()
    }

    /// The trace `--replay-networking` names, as given. `hermit analyze` and
    /// `hermit bisect` reconcile its epoch before their trials start
    /// (`AnalyzeOpts::adopt_recorded_epoch`).
    pub(crate) fn replay_networking_trace(&self) -> Option<&Path> {
        self.replay_networking.as_deref()
    }

    /// The network trace mode the record and replay flags select, `Off` with
    /// neither. A replay trace is read and checked here so a bad path fails
    /// before the guest starts.
    fn network_trace_config(&self) -> Result<NetworkTraceConfig, Error> {
        let (mode, path) = match (&self.record_networking, &self.replay_networking) {
            (None, None) => return Ok(NetworkTraceConfig::default()),
            (Some(path), _) => (NetworkTraceMode::Record, path),
            (None, Some(path)) => (NetworkTraceMode::Replay, path),
        };
        // The trace is written by the tracer when the run ends; resolve it
        // against the directory the user named it from.
        let path = std::path::absolute(path)
            .with_context(|| format!("cannot resolve network trace path {}", path.display()))?;
        if mode == NetworkTraceMode::Record {
            let parent = path.parent().unwrap_or(Path::new("/"));
            if !parent.is_dir() {
                anyhow::bail!(
                    "--record-networking: directory {} does not exist; create it or choose a \
                     trace path in an existing directory",
                    parent.display()
                );
            }
        } else {
            let file = File::open(&path).with_context(|| {
                format!(
                    "--replay-networking: cannot open network trace {}; pass a trace written by \
                     --record-networking",
                    path.display()
                )
            })?;
            NetworkTraceV2::read_framed(std::io::BufReader::new(file)).with_context(|| {
                format!(
                    "--replay-networking: {} is not a valid network trace; record a new one with \
                     --record-networking",
                    path.display()
                )
            })?;
        }
        Ok(NetworkTraceConfig {
            mode,
            path: Some(path),
            network_perturb_seed: None,
        })
    }

    /// Open the network trace before the container starts and point the
    /// config at the inherited descriptor. Detcore reads and writes the trace
    /// inside the container, where the private `/tmp` and any chroot hide the
    /// host path. A record truncates now, so a run that fails before writing
    /// leaves an empty file that `--replay-networking` refuses.
    fn open_network_trace(&mut self) -> Result<Option<File>, Error> {
        let config = &mut self.det_opts.det_config.network_trace;
        let file = match (config.mode, &config.path) {
            (NetworkTraceMode::Off, _) | (_, None) => return Ok(None),
            (NetworkTraceMode::Record, Some(path)) => OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(path)
                .with_context(|| {
                    format!(
                        "--record-networking: cannot create network trace {}; choose a writable \
                         path",
                        path.display()
                    )
                })?,
            (NetworkTraceMode::Replay, Some(path)) => File::open(path).with_context(|| {
                format!(
                    "--replay-networking: cannot open network trace {}; pass a trace written by \
                     --record-networking",
                    path.display()
                )
            })?,
        };
        config.path = Some(PathBuf::from(format!(
            "/proc/self/fd/{}",
            std::os::fd::AsRawFd::as_raw_fd(&file)
        )));
        Ok(Some(file))
    }

    /// Records `--skid-margin` for Reverie's PMU configuration. Recording reads
    /// nothing from the host's CPU, so it holds wherever the configuration is
    /// built later, and a CPU with no profile is handled where a timer is armed.
    pub(crate) fn install_pmu_config(&self) -> Result<(), Error> {
        let Some(skid_margin) = self.skid_margin else {
            return Ok(());
        };
        reverie_ptrace::set_skid_margin_override(skid_margin).map_err(|_| {
            anyhow::anyhow!(
                "Reverie PMU configuration was initialized before --skid-margin could be applied"
            )
        })
    }

    fn validate_mount_sources(&self) -> Result<(), Error> {
        for bind in &self.bind {
            let source = Path::new(OsStr::from_bytes(bind.source.to_bytes()));
            if !source.exists() {
                anyhow::bail!(
                    "--bind source {} does not exist. Create it or correct the source path before \
                     starting Hermit.",
                    source.display()
                );
            }
        }
        for mount in &self.mount {
            if let Some(source) = mount.get_source()
                && !source.exists()
            {
                anyhow::bail!(
                    "--mount source {} does not exist. Create it or correct the source path \
                     before starting Hermit.",
                    source.display()
                );
            }
        }
        Ok(())
    }

    fn validate_e9patch_mount_targets(&self) -> Result<(), Error> {
        for bind in &self.bind {
            let target = Path::new(OsStr::from_bytes(bind.target.to_bytes()));
            validate_e9patch_mount_target(target)?;
        }
        for mount in &self.mount {
            validate_e9patch_mount_target(mount.get_target())?;
        }
        Ok(())
    }

    fn resolve_e9patch_overlay_target(&self, guest: &Path, host: &Path) -> Result<PathBuf, Error> {
        let canonical = fs::canonicalize(host)
            .with_context(|| format!("failed to resolve executable {}", host.display()))?;
        match self.mapped_host_program(guest) {
            GuestPathMapping::Mapped(mapped) => {
                let mapped = std::path::absolute(mapped)?;
                if canonical != mapped {
                    anyhow::bail!(
                        "e9patch cannot safely overlay symlinked executable {} through a custom \
                         guest mount; use the resolved executable path or remove the mount",
                        guest.display()
                    );
                }
                Ok(guest.to_path_buf())
            }
            GuestPathMapping::Unchanged => {
                let host = std::path::absolute(host)?;
                let symlinked = canonical != host;
                let tmp_is_remapped =
                    self.tmp.as_deref() != Some(Path::new(TMP_DIR)) || !self.bind.is_empty();
                let crosses_implicit_mount = symlinked
                    && ((tmp_is_remapped
                        && path_resolution_visits_prefix(&host, Path::new(TMP_DIR))?)
                        || path_resolution_visits_prefix(&host, Path::new("/proc"))?);
                if symlinked && (!self.mount.is_empty() || crosses_implicit_mount) {
                    anyhow::bail!(
                        "e9patch cannot safely resolve symlinked executable {} across guest \
                         mounts; use its resolved guest path or remove the relevant mounts",
                        guest.display()
                    );
                }
                let canonical_guest = normalize_guest_path(&canonical)?;
                match self.mapped_host_program(&canonical_guest) {
                    GuestPathMapping::Mapped(mapped)
                        if std::path::absolute(&mapped)? != canonical =>
                    {
                        anyhow::bail!(
                            "e9patch cannot safely resolve executable {} because a custom guest \
                             mount changes its canonical target {}; use the resolved guest path",
                            guest.display(),
                            canonical_guest.display()
                        );
                    }
                    GuestPathMapping::Hidden => anyhow::bail!(
                        "Program {} is hidden by a mount after resolving symlinks",
                        guest.display()
                    ),
                    GuestPathMapping::Mapped(_) | GuestPathMapping::Unchanged => {}
                }
                Ok(canonical_guest)
            }
            GuestPathMapping::Hidden => anyhow::bail!(
                "Program {} is not visible through the configured guest mounts",
                guest.display()
            ),
        }
    }

    fn mapped_host_program(&self, program: &Path) -> GuestPathMapping {
        for bind in self.bind.iter().rev() {
            let source = Path::new(OsStr::from_bytes(bind.source.to_bytes()));
            let target = Path::new(OsStr::from_bytes(bind.target.to_bytes()));
            if !target.starts_with(TMP_DIR) {
                continue;
            }
            if let Some(path) = mapped_path(program, source, target) {
                return GuestPathMapping::Mapped(path);
            }
        }
        for mount in self.mount.iter().rev() {
            let target = mount.get_target();
            if let Ok(suffix) = program.strip_prefix(target) {
                return match mount.get_source() {
                    Some(source) => GuestPathMapping::Mapped(source.join(suffix)),
                    None => GuestPathMapping::Hidden,
                };
            }
        }
        if let Ok(suffix) = program.strip_prefix(TMP_DIR) {
            return self
                .tmp
                .as_ref()
                .map(|tmp| GuestPathMapping::Mapped(tmp.join(suffix)))
                .unwrap_or(GuestPathMapping::Hidden);
        }
        GuestPathMapping::Unchanged
    }

    fn guest_current_dir(&self, command: &Command) -> Result<PathBuf, Error> {
        let directory = command
            .get_current_dir()
            .map(Path::to_path_buf)
            .unwrap_or(std::env::current_dir()?);
        let absolute = if directory.is_absolute() {
            directory
        } else {
            std::path::absolute(directory)?
        };
        normalize_guest_path(&absolute)
    }

    fn mapped_or_visible_host_program(&self, guest: &Path) -> Option<PathBuf> {
        match self.mapped_host_program(guest) {
            GuestPathMapping::Mapped(host) => Some(host),
            GuestPathMapping::Hidden => None,
            GuestPathMapping::Unchanged => Some(guest.to_path_buf()),
        }
    }

    /// Load the `--happens-before` spec, resolve its anchors against the guest
    /// program's debug info, print the resolved anchor/edge program, and return
    /// success without running the guest. Scheduler enforcement of these edges is
    /// a separate, forthcoming change; this path is pure introspection.
    /// Load the `--happens-before` spec and resolve its anchor code locations
    /// against the guest binary's debug info, returning the resolved program the
    /// scheduler will enforce. Unresolved code locations are reported but do not
    /// fail the run: a count-based anchor (after N syscalls / M RCBs) needs no
    /// debug info, and a purely deferred RIP anchor that never resolves simply
    /// never fires. This shares the same load/resolve path as
    /// `list_happens_before_events` so the preview and the enforced program agree.
    fn load_and_resolve_happens_before(&self) -> Result<HappensBeforeProgram, Error> {
        let spec_path = self
            .happens_before
            .as_ref()
            .expect("load_and_resolve_happens_before requires --happens-before");
        let mut program = Self::load_happens_before_spec(spec_path)?;

        let (_, host) = self.resolve_guest_and_host_program()?;
        match DebugInfoResolver::open(&host) {
            Ok(resolver) if !resolver.is_empty() => {
                let unresolved = resolve_program(&mut program, &resolver);
                if !unresolved.is_empty() {
                    crate::tracing::diagnostic_eprintln!(
                        "hermit: {} happens-before anchor(s) with unresolved code locations \
                         (they will never fire): {}",
                        unresolved.len(),
                        unresolved.join(", ")
                    );
                }
            }
            Ok(_) => {
                let unresolved: Vec<String> = program
                    .unresolved_locations()
                    .map(|a| a.name.clone())
                    .collect();
                if !unresolved.is_empty() {
                    crate::tracing::diagnostic_eprintln!(
                        "hermit: {} has no usable symbol/debug info; {} code-location anchor(s) \
                         will never fire: {}",
                        host.display(),
                        unresolved.len(),
                        unresolved.join(", ")
                    );
                }
            }
            Err(err) => {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: could not read debug info from {}: {:#}; code-location anchors will \
                     never fire",
                    host.display(),
                    err
                );
            }
        }
        Ok(program)
    }

    /// Load a `--happens-before` spec for a run or for `--hb-list-events`.
    ///
    /// A spec that is missing (including a path through a non-directory),
    /// unreadable for permission, a directory, not UTF-8, not valid JSON or not
    /// a valid program (`nth: 0`, `fd` on the wrong syscall, ...) is the user's
    /// to fix: a policy refusal, exit 122
    /// (https://github.com/rrnewton/hermit/issues/3943). Any other failure to read
    /// it (`EIO`, ...) is not the user's, and stays a Hermit failure, exit 125.
    fn load_happens_before_spec(path: &Path) -> Result<HappensBeforeProgram, Error> {
        load_program(path).map_err(|error| {
            let host_read_failure = error.downcast_ref::<std::io::Error>().is_some_and(|io| {
                !matches!(
                    io.kind(),
                    std::io::ErrorKind::NotFound
                        | std::io::ErrorKind::PermissionDenied
                        | std::io::ErrorKind::IsADirectory
                        | std::io::ErrorKind::NotADirectory
                        | std::io::ErrorKind::InvalidData
                )
            });
            if host_read_failure {
                error
            } else {
                error.context(super::container::PolicyRefusal)
            }
        })
    }

    /// Refuse a `--happens-before` spec that does not load
    /// ([`Self::load_happens_before_spec`]) or that this launch cannot enforce
    /// (`refuse_unenforceable_anchors`): a phase other than the prehook, an
    /// unobservable syscall, or a count or syscall-occurrence anchor on a launch
    /// whose runtime is not ptrace (`--backend=e9patch` runs under ptrace and is
    /// enforced). Needs only the spec, not the guest program, so it runs before
    /// stdin is read or a backend is probed.
    fn refuse_unenforceable_happens_before(&self) -> Result<(), Error> {
        let Some(path) = self.happens_before.as_deref() else {
            return Ok(());
        };
        if self.hb_list_events {
            return Ok(());
        }
        let program = Self::load_happens_before_spec(path)?;
        let backend_name = format!("{:?}", self.selected_backend());
        refuse_unenforceable_anchors(
            &program,
            path,
            HbLaunch {
                backend: &backend_name,
                // e9patch rewrites the program and then runs it under the
                // ptrace runtime, which receives and enforces the program.
                ptrace: self.runtime_backend() == Backend::Ptrace,
                namespace_only: self.namespace_only,
                passthru_opt: self.det_opts.det_config.passthru_opt,
                // The requested timer, before validation; an implicit loss is
                // refused later (`refuse_happens_before_without_preemption`).
                preemption: self.det_opts.det_config.max_timeslice.is_some(),
                replay_schedule: self.det_opts.det_config.replay_schedule_from.is_some(),
            },
        )
        // A spec the launch cannot enforce is a policy refusal (exit 122), not
        // a Hermit failure.
        .map_err(|error| error.context(super::container::PolicyRefusal))
    }

    /// Refuse a version-2 `--happens-before` spec when argument validation
    /// left the run without a preemption timer
    /// (`hermit::happens_before::refuse_hold_without_preemption`). The early
    /// check (`refuse_unenforceable_happens_before`) sees only the requested
    /// timer; this one sees the effective timer, which validation turns off
    /// when the host cannot arm it (`TimerUnavailable`), and names that
    /// reason. Nothing assigns `max_timeslice` after validation on the run
    /// path.
    fn refuse_happens_before_without_preemption(&self) -> Result<(), Error> {
        let Some(path) = self.happens_before.as_deref() else {
            return Ok(());
        };
        if self.hb_list_events || self.det_opts.det_config.max_timeslice.is_some() {
            return Ok(());
        }
        let program = Self::load_happens_before_spec(path)?;
        let reason = match &self.timer_downgrade {
            Some(TimerUnavailable::NoPerfEvents) => {
                "this host cannot arm it: perf_event_open is unavailable".to_owned()
            }
            Some(TimerUnavailable::NoPmuProfile(reason)) => {
                format!("this host cannot arm it: {reason}")
            }
            None => "--max-timeslice disabled turns the preemption timer off".to_owned(),
        };
        hermit::happens_before::refuse_hold_without_preemption(&program, path, &reason)
            .map_err(|error| error.context(super::container::PolicyRefusal))
    }

    fn list_happens_before_events(&self) -> Result<ExitStatus, Error> {
        let spec_path = self
            .happens_before
            .as_ref()
            .expect("--hb-list-events requires --happens-before");
        let mut program = Self::load_happens_before_spec(spec_path)?;

        let (_, host) = self.resolve_guest_and_host_program()?;
        let resolver = match DebugInfoResolver::open(&host) {
            Ok(r) if !r.is_empty() => Some(r),
            Ok(_) => {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: {} has no usable symbol/debug info; code-location anchors will not \
                     resolve",
                    host.display()
                );
                None
            }
            Err(err) => {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: could not read debug info from {}: {:#}",
                    host.display(),
                    err
                );
                None
            }
        };

        let unresolved = match &resolver {
            Some(r) => resolve_program(&mut program, r),
            None => program
                .unresolved_locations()
                .map(|a| a.name.clone())
                .collect(),
        };

        println!(
            "happens-before program: {} anchor(s), {} edge(s)",
            program.anchors.len(),
            program.edges.len()
        );
        println!("anchors:");
        for (name, anchor) in &program.anchors {
            println!(
                "  {} = {}",
                name,
                describe_anchor(anchor, resolver.as_ref())
            );
        }
        println!("edges:");
        for edge in &program.edges {
            let op = match edge.strength {
                Strength::Hard => "<",
                Strength::Soft => "<~",
            };
            println!("  {} {} {}", edge.before, op, edge.after);
        }
        if !unresolved.is_empty() {
            crate::tracing::diagnostic_eprintln!(
                "hermit: {} anchor(s) with unresolved code locations: {}",
                unresolved.len(),
                unresolved.join(", ")
            );
        }
        Ok(ExitStatus::SUCCESS)
    }

    /// Where the guest command finds its program, as guest paths: the path
    /// it names, made absolute against its working directory, or, for a bare
    /// name, each `PATH` candidate in order, as
    /// [`Self::resolve_guest_and_host_program`] tries them.
    fn guest_program(&self) -> Result<super::dap_adapter::GuestProgram, Error> {
        use super::dap_adapter::GuestProgram;
        let command = self.guest_command()?;
        let requested = Path::new(command.get_program());
        if requested.is_absolute() {
            return Ok(GuestProgram::Named(normalize_guest_path(requested)?));
        }
        let current_dir = self.guest_current_dir(&command)?;
        if requested.components().count() > 1 {
            return Ok(GuestProgram::Named(normalize_guest_path(
                &current_dir.join(requested),
            )?));
        }
        let path = command
            .get_captured_envs()
            .get(OsStr::new("PATH"))
            .cloned()
            .unwrap_or_default();
        let candidates = path
            .as_bytes()
            .split(|byte| *byte == b':')
            .map(|bytes| Path::new(OsStr::from_bytes(bytes)))
            .map(|directory| {
                normalize_guest_path(&if directory.is_absolute() {
                    directory.join(requested)
                } else {
                    current_dir.join(directory).join(requested)
                })
            })
            .collect::<Result<_, _>>()?;
        Ok(GuestProgram::Search(candidates))
    }

    fn resolve_guest_and_host_program(&self) -> Result<(PathBuf, PathBuf), Error> {
        let command = self.guest_command()?;
        let requested = Path::new(command.get_program());

        if requested.is_absolute() {
            let requested = normalize_guest_path(requested)?;
            if let Some(host) = self.mapped_or_visible_host_program(&requested) {
                return Ok((requested, host));
            }
            if requested.starts_with(TMP_DIR) && requested.exists() {
                anyhow::bail!(
                    "Program {} is under host /tmp, but Hermit replaces guest /tmp with an \
                     isolated directory. Pass --tmp=/tmp to expose host /tmp or bind the program \
                     to a guest path under /tmp.",
                    requested.display()
                );
            }
            anyhow::bail!(
                "Program {} is not visible through the configured guest mounts",
                requested.display()
            );
        }

        let current_dir = self.guest_current_dir(&command)?;
        if requested.components().count() > 1 {
            let guest = normalize_guest_path(&current_dir.join(requested))?;
            let host = self.mapped_or_visible_host_program(&guest).ok_or_else(|| {
                Error::msg(format!(
                    "Program {} is not visible through the configured guest mounts",
                    requested.display()
                ))
            })?;
            return Ok((guest, host));
        }

        let environment = command.get_captured_envs();
        let path = environment
            .get(OsStr::new("PATH"))
            .cloned()
            .unwrap_or_default();
        for directory in path
            .as_bytes()
            .split(|byte| *byte == b':')
            .map(|bytes| Path::new(OsStr::from_bytes(bytes)))
        {
            let candidate = if directory.is_absolute() {
                directory.join(requested)
            } else {
                current_dir.join(directory).join(requested)
            };
            let guest = normalize_guest_path(&candidate)?;
            let Some(host) = self.mapped_or_visible_host_program(&guest) else {
                continue;
            };
            if fs::metadata(&host).is_ok_and(|metadata| {
                metadata.is_file() && metadata.permissions().mode() & 0o111 != 0
            }) {
                return Ok((guest, host));
            }
        }
        anyhow::bail!(
            "Could not resolve program {:?} in the guest PATH. Check PATH or use an absolute \
             executable path.",
            requested
        )
    }

    /// Refuse an absolute `--summary-json` that the run container cannot see.
    ///
    /// Detcore writes the summary from inside the container, at the end of the
    /// run, and the container mounts a private directory over `/tmp`. A host
    /// path under `/tmp` therefore names nothing there: the write failed with
    /// NotFound and panicked at teardown, after the whole guest had run, or --
    /// when its parent happened to exist in the private `/tmp`, as for
    /// `/tmp/summary.json` -- succeeded into a directory that is deleted with
    /// the container, losing the summary without a word. Hermit's own private
    /// summaries no longer take this route (private_summary_descriptor_path);
    /// this is the same fault for a path the caller chose, so it is refused
    /// before anything runs, like a program under host `/tmp`. See
    /// https://github.com/rrnewton/hermit/issues/3260.
    ///
    /// "Cannot see" is decided by the same guest-path mapping the program check
    /// uses, so `--tmp=/tmp`, a `--bind` into `/tmp` and a sourced `--mount`
    /// keep working, and a source-less `--mount` (a tmpfs, equally discarded)
    /// is refused for the same reason. `--tmp=<dir>` other than `/tmp` is
    /// refused for a `/tmp` path too: the guest's `/tmp` is then `<dir>`, so
    /// the write would go to `<dir>/...` -- not the requested host path, and a
    /// NotFound panic when that subdirectory is absent. A relative path is not
    /// refused: the container inherits the caller's working directory itself,
    /// not its name, so a relative summary reaches the host directory even
    /// when that directory is under `/tmp`. Modes that never write the summary
    /// are not refused: DBT, `--namespace-only` and `--hb-list-events` (checked
    /// earlier). `--no-namespace` has no private mounts, and `--image` (a
    /// prototype) replaces the whole root, which this mapping does not model.
    fn validate_summary_json_visibility(&self) -> Result<(), Error> {
        let Some(path) = self.summary_json.as_deref() else {
            return Ok(());
        };
        if self.no_namespace
            || self.namespace_only
            || self.image.is_some()
            || self.selected_backend() == Backend::Dbt
            || !path.is_absolute()
        {
            return Ok(());
        }
        let hidden = match self.mapped_host_program(path) {
            GuestPathMapping::Hidden => true,
            // Mapped through `--tmp=<dir>` rather than a bind or mount.
            GuestPathMapping::Mapped(host) => self.tmp.as_deref().is_some_and(|tmp| {
                tmp != Path::new(TMP_DIR)
                    && path
                        .strip_prefix(TMP_DIR)
                        .is_ok_and(|suffix| host == tmp.join(suffix))
            }),
            GuestPathMapping::Unchanged => false,
        };
        if hidden {
            let (cause, remedy) = if path.starts_with(TMP_DIR) {
                (
                    "it is under host /tmp, but Hermit replaces guest /tmp with an isolated \
                     directory (or the --tmp directory)",
                    "Write it outside /tmp, or pass --tmp=/tmp to expose host /tmp.",
                )
            } else {
                (
                    "a --mount without a source hides it",
                    "Write it outside that mount.",
                )
            };
            anyhow::bail!(
                "--summary-json {} is not visible inside the run container: {cause}. The summary \
                 is written from inside the container, so it would be lost. {remedy}",
                path.display()
            );
        }
        Ok(())
    }

    fn validate_program(&self) -> Result<(), Error> {
        // PROTOTYPE (--image): the guest program is interpreted inside the
        // materialized OCI rootfs, not on the host filesystem. Resolve and
        // validate it against the rootfs so that image-only binaries (e.g.
        // busybox's `/bin/busybox`, absent from the host) are accepted, and so
        // host binaries that merely happen to share a path are never used.
        // materialize_rootfs is idempotent/cached, so this does not re-pull the
        // image later in `container()`.
        if let Some(image) = &self.image {
            // Materialize before building the command: on a cold cache this is
            // what makes the image's Env/WorkingDir available for relative-path
            // resolution during first-run validation.
            let rootfs = crate::image::materialize_rootfs(image)?;
            let command = self.guest_command()?;
            let requested = Path::new(command.get_program());
            // `guest_command()` sets the image working directory (WorkingDir, or
            // `/`) as the guest cwd; resolve a relative program path against it.
            let guest_cwd = command
                .get_current_dir()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from("/"));
            let guest_abs = resolve_image_guest_program(requested, &guest_cwd)?;
            // Resolve chroot-aware: images (nixos/nix especially) expose
            // `/bin/sh` as a symlink to an absolute `/nix/store/...` target that
            // only resolves under the image root, so a naive host `stat` would
            // follow it against the host `/` and fail.
            let in_rootfs = crate::image::resolve_in_rootfs(&rootfs, &guest_abs);
            return validate_executable(&in_rootfs, &guest_abs, Some(&rootfs));
        }

        if self.selected_backend() == Backend::E9patch {
            let (_, host) = self.resolve_guest_and_host_program()?;
            return validate_executable(&host, &self.program, None);
        }

        let command = self.guest_command()?;
        let requested = Path::new(command.get_program());
        if requested.is_absolute() {
            if let GuestPathMapping::Mapped(host) = self.mapped_host_program(requested) {
                return validate_executable(&host, requested, None);
            }
            if requested.starts_with(TMP_DIR) && self.tmp.is_none() && requested.exists() {
                anyhow::bail!(
                    "Program {} is under host /tmp, but Hermit replaces guest /tmp with an \
                     isolated directory. Pass --tmp=/tmp to expose host /tmp or bind the program \
                     into guest /tmp.",
                    requested.display()
                );
            }
            return validate_executable(requested, requested, None);
        }

        // ⚠️ SAME FAULT AS THE ABSOLUTE-PATH BRANCH ABOVE, SO THE SAME CODE.
        // The guest program is not there. Whether the caller spelled it as an
        // absolute path or as a bare name is a property of the COMMAND LINE, not
        // of the failure, and it was deciding the exit code: `/nope/x` gave 127
        // with class=guest-program-not-found while `nope-x` gave 125 with
        // class=cli-error. A caller scripting on the code got either for the same
        // mistake with no way to predict which.
        //
        // ⚠️ AND 125 IS NOT FREE. `bin/safehermit` sets rc=125 when a run is
        // cgroup-killed at the log byte cap -- "A distinct code, because 255 tells
        // a caller nothing about WHY". Under that wrapper a mistyped program name
        // was indistinguishable from a run killed for producing too much output.
        // 127 is the GNU convention for command-not-found and is what the
        // absolute branch already returns, so this joins it rather than minting a
        // third code.
        let resolved = command
            .find_program()
            .with_context(|| {
                format!(
                    "Could not resolve program {:?} in the guest PATH. Check PATH or use an absolute \
                     executable path.",
                    requested
                )
            })
            .map_err(|error| error.context(GuestProgramFault::NotFound))?;
        validate_executable(&resolved, requested, None)
    }

    fn validate_e9patch_source_visibility(&self, source: &Path) -> Result<(), Error> {
        for mount in &self.mount {
            let target = mount.get_target();
            if !target.starts_with(TMP_DIR) && source.starts_with(target) {
                anyhow::bail!(
                    "--mount target {} would hide the cached e9patch artifact {}; choose a more \
                     specific mount target or a different instruction-map cache directory",
                    target.display(),
                    source.display()
                );
            }
        }
        Ok(())
    }

    fn prepare_e9patch_program(&mut self) -> Result<(), Error> {
        let (guest, host) = self.resolve_guest_and_host_program()?;
        self.e9patch_program = Some(guest.clone());
        let overlay_target = self.resolve_e9patch_overlay_target(&guest, &host)?;
        if !is_elf_file(&host)? {
            self.e9patch_engagement = Some(BackendEngagement::E9patch {
                candidate_sites: 0,
                mapped_sites: 0,
                b0_sites: 0,
            });
            self.e9patch_sites = Some(reverie::SiteCounters::default());
            crate::tracing::diagnostic_eprintln!(
                ":: Backend: e9patch preprocessing + ptrace runtime; mapped_sites=0; \
                 main_executable=non-ELF; preprocessing=not-applicable"
            );
            return Ok(());
        }
        if let Some(reason) = hermit::e9patch::unavailable_reason() {
            anyhow::bail!("backend `e9patch` is unavailable: {reason}");
        }
        let prepared = hermit::e9patch::prepare(&host)?;
        self.e9patch_engagement = Some(BackendEngagement::E9patch {
            candidate_sites: u64::try_from(prepared.candidate_sites)
                .map_err(|_| Error::msg("e9patch candidate-site count does not fit u64"))?,
            mapped_sites: u64::try_from(prepared.patched_sites)
                .map_err(|_| Error::msg("e9patch mapped-site count does not fit u64"))?,
            b0_sites: u64::try_from(prepared.b0_sites)
                .map_err(|_| Error::msg("e9patch B0-site count does not fit u64"))?,
        });
        self.e9patch_sites = Some(reverie::SiteCounters::from_rewrite(
            prepared.candidate_sites as u64,
            prepared.patched_sites as u64,
        ));
        if prepared.patched_sites != 0 {
            self.validate_e9patch_mount_targets()?;
            self.validate_e9patch_source_visibility(&prepared.binary)?;
            self.e9patch_overlay = Some(E9patchOverlay {
                source: prepared.binary,
                target: overlay_target,
            });
        }
        let rewrite_cache = if prepared.patched_sites == 0 {
            "not-applicable"
        } else if prepared.rewrite_cache_hit {
            "hit"
        } else {
            "miss"
        };
        crate::tracing::diagnostic_eprintln!(
            ":: Backend: e9patch preprocessing + ptrace runtime; candidate_sites={}; \
             mapped_sites={}; b0_sites={}; \
             instruction_map_cache={:?}; rewrite_cache={}; artifact_sha256={}; \
             preprocess_us={}",
            prepared.candidate_sites,
            prepared.patched_sites,
            prepared.b0_sites,
            prepared.instruction_map_cache_status,
            rewrite_cache,
            prepared.artifact_sha256.as_deref().unwrap_or("none"),
            prepared.preprocess_micros,
        );
        // Opt-in (HERMIT_E9PATCH_STATS) patch-shape stats. These describe the
        // ahead-of-time rewrite of the single root guest image; the selected
        // `e9patch` spelling runs on the ptrace runtime, so this measures the
        // preprocessing shape, not any runtime instrumentation cost.
        if let Some(shape) = &prepared.patch_shape {
            crate::tracing::diagnostic_eprintln!(
                ":: e9patch patch-shape stats (selected=e9patch, runtime=ptrace, \
                 scope=root-image): {shape}"
            );
        }
        Ok(())
    }

    fn write_backend_engagement_after_run(&self) -> Result<(), Error> {
        let Some(path) = &self.backend_engagement_json else {
            return Ok(());
        };
        let engagement = match self.selected_backend() {
            Backend::Ptrace => {
                let summary_path = self.summary_json.as_deref().ok_or_else(|| {
                    Error::msg("ptrace backend engagement requires a typed run summary")
                })?;
                let summary = fs::read(summary_path)
                    .with_context(|| {
                        format!(
                            "reading ptrace backend engagement from {}",
                            summary_path.display()
                        )
                    })
                    .and_then(|bytes| {
                        serde_json::from_slice::<RunSummary>(&bytes).with_context(|| {
                            format!(
                                "parsing ptrace backend engagement from {}",
                                summary_path.display()
                            )
                        })
                    })?;
                BackendEngagement::Ptrace {
                    scheduler_turns: summary.sched_turns,
                }
            }
            Backend::E9patch => self.e9patch_engagement.clone().ok_or_else(|| {
                Error::msg("e9patch backend engagement was not recorded during preparation")
            })?,
            Backend::Dbt => unreachable!("the DBT adapter writes its own engagement record"),
            Backend::Liteinst | Backend::InGuestTrap | Backend::Sabre | Backend::Kvm => {
                return Err(Error::msg(format!(
                    "backend `{}` does not expose an engagement value",
                    self.selected_backend().as_str()
                )));
            }
        };
        write_backend_engagement(path, engagement)
    }

    fn tmpfs(&self) -> Result<Tmpfs, Error> {
        match self.tmp.as_ref() {
            Some(path) => {
                let path = path.as_path();
                fs::create_dir_all(path)?;
                Ok(Tmpfs::Path(path.to_path_buf()))
            }
            None => Ok(Tmpfs::Temp(tempfile::TempDir::new()?)),
        }
    }

    pub fn run(
        &self,
        global: &GlobalOpts,
        capture_output: bool,
    ) -> Result<(ExitStatus, Option<Output>), Error> {
        self.refuse_unready_exec_stop()?;
        let mut options = self.clone();
        let network_trace = options.open_network_trace()?;
        let global = global.clone();
        let resources = if network_trace.is_some() {
            "network trace descriptor"
        } else {
            "no descriptors"
        };
        self.launch_in_container(
            network_trace,
            resources,
            self.run_timeout(),
            move |_, identity, native| {
                #[cfg(feature = "native-exec")]
                if let Some(native) = native {
                    let _ = native;
                    return Err(Error::msg(
                        "native exec currently requires the verification run path",
                    ));
                }
                #[cfg(not(feature = "native-exec"))]
                let _ = native;
                options.run_in_container(&global, capture_output, identity)
            },
        )
        .map(|(value, _guards)| value)
    }

    fn warn_no_namespace(&self) {
        if self.no_namespace {
            // Not `eprintln!`, which panics when stderr's reader has gone
            // (EPIPE): a warning must not end the run with 101.
            use std::io::Write as _;
            let _ = writeln!(
                std::io::stderr(),
                "WARNING: --no-namespace is not a sandbox; run trusted guests only. The guest \
                 inherits the caller UID/GID/capabilities and shares host /proc, filesystem, /tmp, \
                 localhost/network, ports, Unix sockets, and mutable state between runs. Unsupported \
                 syscalls can mutate host state; --verify may be less deterministic due to shared state."
            );
        }
    }

    /// Run `work` as the init of this run's container: the PID, UTS, mount and
    /// network namespaces, private /tmp and identity mounts that every backend
    /// shares, or a plain child under `--no-namespace`. `work` receives the
    /// parent-held `guards`, the container's identity mounts, and any explicitly
    /// enrolled native run. An adapter that cannot consume a native run must
    /// refuse it.
    pub(super) fn launch_in_container<G, F, T>(
        &self,
        guards: G,
        resources: &str,
        timeout: Option<Duration>,
        mut work: F,
    ) -> Result<(T, G), Error>
    where
        G: 'static,
        F: FnMut(&mut G, Option<&IdentityGuard>, Option<NativeContainerRun>) -> Result<T, Error>
            + 'static,
        T: serde::Serialize + serde::de::DeserializeOwned + 'static,
    {
        self.refuse_unready_exec_stop()?;
        let (mut container, tmpfs, identity, resources) = if self.no_namespace {
            let mut container = Container::new();
            apply_affinity(&mut container, self.pin_threads);
            (
                container,
                None,
                None,
                format!("held {resources}; no PID namespace"),
            )
        } else {
            let tmpfs = self.tmpfs()?;
            let (container, identity) = self.container(tmpfs.path())?;
            let resources = format!(
                "private tmp {}, identity mounts and {resources}",
                tmpfs.path().display()
            );
            (container, Some(tmpfs), Some(identity), resources)
        };
        #[cfg(feature = "native-exec")]
        let native_plan = self
            .native_exec_capture
            .as_ref()
            .map(|capture| capture.plan(&mut container))
            .transpose()?;
        #[cfg(not(feature = "native-exec"))]
        let native_plan: Option<()> = None;
        super::owned_container::run(
            &mut container,
            (tmpfs, identity, guards, native_plan),
            resources,
            !self.no_namespace,
            "with_container",
            timeout,
            move |(_, identity, guards, native_plan)| {
                // What the mount plan made, before anything else uses the
                // container's mounts (a no-op for a plan with no record).
                if let Some(identity) = identity.as_mut() {
                    identity.record_plan()?;
                }
                #[cfg(feature = "native-exec")]
                let native = native_plan
                    .take()
                    .map(|plan| unsafe { plan.materialize() })
                    .transpose()?;
                #[cfg(not(feature = "native-exec"))]
                let native = native_plan.take();
                work(guards, identity.as_ref(), native)
            },
        )
        .map(|(value, (_, _, guards, _))| (value, guards))
    }

    fn run_with_namespace_only(&self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        // TODO: Make this use detcore instead after detcore is capable of being
        // "lightweight".
        let _guard = global.init_tracing_for_backend(self.runtime_backend());

        let tmpfs = self.tmpfs()?;
        let PreparedMounts {
            mounts,
            identity_sources: _identity_sources,
        } = self.mounts(tmpfs.path())?;

        let mut command = self.namespace_only_guest_command()?;
        // `--namespace-only` does NOT go through `with_container`: it unshares
        // `Namespace::PID` and execs the guest directly, so the guest process
        // ITSELF becomes PID 1 of the new namespace and inherits the same
        // undeliverable-signal protection. An adversarial review found this
        // second launch path after the `with_container` guards were in place --
        // the fix worked and was not yet complete.
        //
        // There is no closure to arm here, so the guard goes in `pre_exec`,
        // which reverie runs in the forked child before the guest image is
        // loaded (`reverie-process/src/container.rs:738`). `PR_SET_PDEATHSIG`
        // is preserved across `execve`, so it is still armed once the guest is
        // running; reverie uses the same idiom for exec'd untraced members in
        // `safeptrace/src/notifier.rs`.
        //
        // Only the death signal is armed, deliberately. The SIGTERM/SIGINT/
        // SIGHUP handlers installed for the `with_container` path cannot help
        // here: `execve` resets caught signals to `SIG_DFL`, so any handler set
        // before exec is gone by the time the guest runs. Installing one would
        // also be wrong on its own terms -- in this mode PID 1 is the user's own
        // program, and hermit changing its signal dispositions would alter the
        // behaviour being observed.
        //
        // SAFETY: the arming (prctl, an atomic read-modify-write and `_exit`)
        // and the proc diagnostic use only Linux syscall wrappers and
        // signal-set operations, without allocation or stdio locks.
        unsafe {
            command.pre_exec(|| {
                super::container::arm_namespace_only_guest()?;
                hermit::proc_mount::warn_if_readonly_proc();
                Ok(())
            });
        }
        // Every guest `kill` stops for Hermit, which refuses a `kill(0)` that
        // would reach its own process group: nothing else intercepts the guest
        // in this mode (https://github.com/rrnewton/hermit/issues/4065). The
        // guest installs the filter last in its setup and sends the listener
        // back over this socket (`install_group_kill_filter`).
        let (listener_socket, guest_socket) = {
            use std::os::fd::FromRawFd;
            let mut pair = [-1; 2];
            // SAFETY: socketpair writes two descriptors into `pair`.
            if unsafe {
                libc::socketpair(
                    libc::AF_UNIX,
                    libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC,
                    0,
                    pair.as_mut_ptr(),
                )
            } < 0
            {
                return Err(std::io::Error::last_os_error().into());
            }
            // SAFETY: both descriptors were just opened and are owned here.
            unsafe { (OwnedFd::from_raw_fd(pair[0]), OwnedFd::from_raw_fd(pair[1])) }
        };
        let filter = super::container::group_kill_filter();
        let guest_end = guest_socket.as_raw_fd();
        // SAFETY: `install_group_kill_filter` is async-signal-safe; the
        // guest's end of the socket stays open in Hermit until `spawn` returns.
        unsafe {
            command
                .pre_exec(move || super::container::install_group_kill_filter(&filter, guest_end));
        }
        command
            .unshare(Namespace::PID)
            .map_root()
            .hostname("hermetic-container.local")
            .domainname("local")
            .mount(Mount::proc().allow_readonly_fallback())
            .mounts(mounts.into_iter().map(|planned| planned.mount));

        match &self.network {
            NetworkingMode::Local => {
                command.local_networking_only();
            }
            NetworkingMode::Host => {}
        }

        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) => {
                let Some(errno) = super::container::group_kill_filter_failure(&listener_socket)
                else {
                    return Err(error.into());
                };
                // Failing closed is deliberate: without the filter a guest's
                // kill(0) reaches Hermit's group again.
                return Err(Error::new(super::container::PolicyRefusal).context(format!(
                    "hermit could not install the --namespace-only kill filter in the guest: \
                     seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_NEW_LISTENER) failed \
                     with {:?}. The filter keeps a guest's kill(0) from reaching Hermit and the \
                     processes that started it \
                     (https://github.com/rrnewton/hermit/issues/4065), so hermit refuses to start \
                     the guest without it. A host or container policy that denies seccomp, a \
                     seccomp filter of the caller's that already has a listener (another \
                     --namespace-only run, a seccomp-notify sandbox), or a kernel without \
                     SECCOMP_FILTER_FLAG_NEW_LISTENER causes it. Run hermit where seccomp is \
                     allowed and no other listener is installed.",
                    reverie::Errno::new(errno)
                )));
            }
        };
        drop(guest_socket);
        let listener = match super::container::receive_group_kill_listener(&listener_socket) {
            Ok(listener) => listener,
            Err(error) => {
                // The guest runs, but unpoliced: stop it rather than let it.
                let _ = child.signal(nix::sys::signal::Signal::SIGKILL);
                let _ = child.wait_blocking();
                return Err(error.into());
            }
        };
        // The thread stops once the guest has exited: the listener does not
        // always report that its last task is gone.
        let (stopped, stop) = {
            use std::os::fd::FromRawFd;
            let mut pipe = [-1; 2];
            // SAFETY: pipe2 writes two descriptors into `pipe`.
            if unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) } < 0 {
                let _ = child.signal(nix::sys::signal::Signal::SIGKILL);
                let _ = child.wait_blocking();
                return Err(std::io::Error::last_os_error().into());
            }
            // SAFETY: both descriptors were just opened and are owned here.
            unsafe { (OwnedFd::from_raw_fd(pipe[0]), OwnedFd::from_raw_fd(pipe[1])) }
        };
        let police =
            std::thread::spawn(move || super::container::police_group_kills(listener, stopped));

        let exit_status = child.wait_blocking()?;
        drop(stop);
        let _ = police.join();

        Ok(exit_status)
    }

    // Execution mode corresponding to `run --verify-run DIR`: one of
    // `verify`'s two executions, run the way `verify` runs each (the same
    // `run_verify`, log level, private summary, host-input record, latches and
    // forwarded-record count), with what `verify` would hand its comparison
    // written to DIR instead of compared. `hermit log-diff --verify-json`
    // compares two such directories (`verify_run::compare`).
    fn verify_run(&self, directory: &Path, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        let writer = verify_run::VerifyRunWriter::create(directory)?;
        let log_path = writer.path(verify_run::LOG);
        let log_file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&log_path)
            .with_context(|| format!("creating the verification log {}", log_path.display()))?;
        let forwarded = self.forwarded_detlog_plan()?;
        let socket = forwarded.requires_socket();
        // Both reached through the controller's descriptors, as `verify`
        // reaches its own (see private_summary_descriptor_path).
        let summary_file = private_verify_summary()?;
        let summary_path = private_summary_descriptor_path(&summary_file);
        let host_inputs_file = tempfile::tempfile().context("creating the host-input record")?;
        let host_inputs_path = descriptor_path(&host_inputs_file);
        let mut options = self.clone();
        options.summary_json = Some(summary_path.clone());
        options.host_input_log = Some(host_inputs_path.clone());
        options.fatal_core_run_label = Some("run");
        let comparison =
            verify_run::RecordedComparison::from_options(&self.verification_comparison_options());
        let exact_branch_counter = self
            .arms_reverie_ptrace_pmu_timer()
            .then(branch_counter_verdict);

        let completed = options
            .run_verify(
                log_file,
                &log_path,
                forwarded,
                global,
                VerificationRun::Run1,
                #[cfg(feature = "dbt")]
                None,
            )
            .and_then(|completed| {
                let VerificationRunOutput {
                    mut output,
                    skid_overshoots,
                    latches,
                    #[cfg(feature = "dbt")]
                        dbt: _,
                } = completed;
                latches.refuse_comparison("run")?;
                let forwarded_syscalls =
                    self.take_forwarded_detlogs(&log_path, &mut output.stderr, socket)?;
                Ok((output, skid_overshoots, forwarded_syscalls))
            });
        let (outcome, result) = match completed {
            Ok((output, skid_overshoots, forwarded_syscalls)) => {
                writer.write(verify_run::STDOUT, &output.stdout)?;
                writer.write(verify_run::STDERR, &output.stderr)?;
                (
                    verify_run::VerifyRunOutcome::Completed {
                        status: verify_run::RecordedStatus::of(output.status),
                        skid_overshoots,
                        forwarded_syscalls: forwarded_syscalls.map(|count| count as u64),
                    },
                    Ok(output.status),
                )
            }
            Err(error) => (verify_run_outcome_of(&error), Err(error)),
        };
        let summary = fs::read(&summary_path).unwrap_or_default();
        if !summary.is_empty() {
            writer.write(verify_run::SUMMARY, &summary)?;
            if let Some(public) = &self.summary_json {
                fs::write(public, &summary)
                    .with_context(|| format!("writing the run summary {}", public.display()))?;
            }
        }
        let host_inputs = fs::read(&host_inputs_path).context("reading the host-input record")?;
        writer.write(verify_run::HOST_INPUTS, &host_inputs)?;
        writer.commit(&self.verify_run_record(comparison, exact_branch_counter, outcome, None))?;
        result
    }

    /// The record a `--verify-run` execution of these options commits.
    pub(super) fn verify_run_record(
        &self,
        comparison: verify_run::RecordedComparison,
        exact_branch_counter: Option<hermit::canonical_verdict::BranchCounterVerdict>,
        outcome: verify_run::VerifyRunOutcome,
        dbt: Option<verify_run::DbtRunRecord>,
    ) -> verify_run::VerifyRunRecord {
        verify_run::VerifyRunRecord {
            schema: verify_run::SCHEMA,
            backend: self.selected_backend().as_str().to_string(),
            comparison,
            passthru_opt: self.det_opts.det_config.passthru_opt,
            epoch: self.epoch_rfc3339(),
            exact_branch_counter,
            dbt,
            role: verify_run::RunRole::Run,
            outcome,
        }
    }

    // Execution mode corresponding to `run --verify`:
    fn verify(
        &self,
        global: &GlobalOpts,
        _dbt_stdin: Option<fs::File>,
    ) -> Result<ExitStatus, Error> {
        // Stamp an explicit no-result BEFORE any fallible work. Several exits
        // below (a run that fails to start, a rejected first-run status, a SaBRe
        // capture with zero DETLOG) return early without ever reaching
        // `write_verification_json`; without this, reusing a --verify-json path
        // would leave the PREVIOUS invocation's record -- possibly a green -- to
        // be read as this invocation's result.
        if let Some(path) = &self.verify_json {
            write_pending_verification_json(path)?;
        }
        #[cfg(feature = "dbt")]
        let mut dbt = if self.selected_backend() == Backend::Dbt {
            Some(self.dbt_invocation()?.verification(_dbt_stdin)?)
        } else {
            None
        };
        self.verify_with_execution(|options, log, path, forwarded, run| {
            options.run_verify(
                log,
                path,
                forwarded,
                global,
                run,
                #[cfg(feature = "dbt")]
                dbt.as_mut(),
            )
        })
    }

    /// The common two-run owner, after the invocation has been stamped and
    /// its physical adapter prepared. The callback returns a completed run;
    /// disposition, deferred facts, comparison and reporting stay here.
    pub(super) fn verify_with_execution(
        &self,
        mut execute: impl FnMut(
            &Self,
            fs::File,
            &Path,
            ForwardedDetlogPlan,
            VerificationRun,
        ) -> Result<VerificationRunOutput, Error>,
    ) -> Result<ExitStatus, Error> {
        self.refuse_unready_exec_stop()?;
        let retained_log_dir = self.retained_verify_log_dir()?;
        let (log1, log2) = temp_log_files_in("run1", "run2", retained_log_dir.as_deref())
            .context("Failed to create verification log files")?;

        let (log1_file, log1_path) = log1.into_parts();
        let (log2_file, log2_path) = log2.into_parts();
        let forwarded1_for_run = self.forwarded_detlog_plan()?;
        let forwarded2_for_run = self.forwarded_detlog_plan()?;
        let (forwarded1, forwarded2) = (
            forwarded1_for_run.requires_socket(),
            forwarded2_for_run.requires_socket(),
        );

        // Verification historically sent both executions to one --summary-json
        // path, so run 2 overwrote run 1. Keep the public path's run-2 meaning,
        // while capturing run 1 privately. When no public path was requested,
        // the same private file is emptied before run 2 and reused.
        //
        // The private file lives in the checkout because Hermit's isolated /tmp
        // is not the host /tmp. It is consequently guest-visible. Leaving run
        // 1's JSON in it while run 2 executes changes the guest's input: a guest
        // that reads the file sees zero bytes in run 1 and a completed summary
        // in run 2. Emptying it before run 2 preserves the initial contents.
        //
        // Both runs and every read below use the descriptor spelling, never
        // `summary1_file.path()`: that host name does not exist inside the
        // container when the working directory is under the host /tmp. See
        // private_summary_descriptor_path. `summary1_file` stays open, and so
        // the spelling stays valid, until this function returns.
        // The current physical DBT adapter produces typed native facts, not
        // RunSummary or host-input files. Do not read an old public summary or
        // create a new checkout-path dependency on that path's behalf.
        let records_run_metadata = self.selected_backend() != Backend::Dbt;
        let summary1_file = records_run_metadata
            .then(private_verify_summary)
            .transpose()?;
        let summary1_path = summary1_file.as_ref().map(private_summary_descriptor_path);
        let summary2_path = records_run_metadata
            .then(|| self.summary_json.as_deref().or(summary1_path.as_deref()))
            .flatten();
        let mut run1_options = self.clone();
        run1_options.summary_json = summary1_path.clone();
        let mut run2_options = self.clone();
        run2_options.summary_json = summary2_path.map(Path::to_owned);

        // Each run records the host files its guest opens, so that a
        // divergence caused by a host file changing during a run can be named
        // (see `hermit::host_input_change`). Both runs share one unlinked file,
        // reached through the controller's descriptor as the private summary
        // is. Detcore writes it only when a run ends, and it is read and
        // emptied before run 2, so it is empty while either guest runs: a
        // guest that finds it through /proc sees the same thing in both runs.
        let host_inputs_file = records_run_metadata
            .then(tempfile::tempfile)
            .transpose()
            .context("creating the host-input record")?;
        let host_inputs_path = host_inputs_file.as_ref().map(descriptor_path);
        run1_options.host_input_log = host_inputs_path.clone();
        run2_options.host_input_log = host_inputs_path.clone();
        run1_options.fatal_core_run_label = Some("run1");
        run2_options.fatal_core_run_label = Some("run2");

        // Captured BEFORE run 1 so the same values can be put back before run 2.
        // See the restore call below for the measurement this exists for.
        let fd_flags_before_run1 = standard_fd_status_flags();

        crate::tracing::diagnostic_eprintln!(":: {}", "Run1...".yellow().bold());

        let VerificationRunOutput {
            output: out1,
            skid_overshoots: skid_overshoots_run1,
            latches: latches1,
            #[cfg(feature = "dbt")]
                dbt: dbt1,
        } = match run_verification_execution(
            self.verify_json.as_deref(),
            VerificationRun::Run1,
            || {
                execute(
                    &run1_options,
                    log1_file,
                    &log1_path,
                    forwarded1_for_run,
                    VerificationRun::Run1,
                )
            },
        ) {
            Ok(result) => result,
            Err(mut error) => {
                if let Some(overshoot) = error.downcast_ref::<SkidOvershootError>()
                    && let Some(path) = &self.verify_json
                {
                    let summary1 = summary1_path.as_deref().and_then(read_verify_summary);
                    if let Err(report_error) = write_skid_overshoot_without_comparison_json(
                        path,
                        overshoot.count(),
                        verification_runtime_from_summaries(summary1.as_ref(), None),
                        // `run_verify` returned only an Error, so this site has
                        // no guest ExitStatus to record.
                        None,
                    ) {
                        error = retain_verification_error(
                            error,
                            "publishing skid overshoot",
                            report_error,
                        );
                    }
                }
                error =
                    publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run1, error);
                if self.keep_logs {
                    error = retain_logs_after_verification_error(error, [("run 1", log1_path)]);
                }
                return Err(error);
            }
        };
        let mut out1 = out1;
        let mut signal_reports = SignalTerminationReports::default();
        if self.selected_backend() == Backend::Dbt {
            signal_reports.prepare("run 1", out1.status, &log1_path);
        }
        // The latches first: a determinism loss is named as one, even when its
        // loss notice also reached the forwarded records.
        if let Err(error) = latches1.refuse_comparison("run 1") {
            let error =
                publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run1, error);
            if self.keep_logs {
                retain_verification_logs([("run 1", log1_path)])?;
            }
            return Err(error);
        }
        let forwarded_syscalls1 =
            match self.take_forwarded_detlogs(&log1_path, &mut out1.stderr, forwarded1) {
                Ok(count) => count,
                Err(error) => {
                    if self.keep_logs {
                        retain_verification_logs([("run 1", log1_path)])?;
                    }
                    return Err(error);
                }
            };
        // Prepared now, with the forwarded records in place: the comparison
        // consumes the log. Written if the verification ends unverified.
        if self.selected_backend() != Backend::Dbt {
            signal_reports.prepare("run 1", out1.status, &log1_path);
        }

        // With --verify the first run's `--log` output was diverted to a
        // temporary file for later comparison rather than shown to the user.
        // When --print-verify-logs is set, echo that first run's log to stderr so the
        // user still sees `--log` output, matching a normal (non-verify) run.
        // The log file is fully flushed here because run_verify runs each
        // execution in a child process that has already exited.
        //
        // Run 2 has not started yet, so under --max-log-bytes this echo must not
        // wait on stderr: the log goes through `DroppingStderr`, which waits for
        // a full pipe only within `RetryingStderr`'s bounded deadline and drops
        // what it then cannot deliver. Without the cap it is written exactly as
        // before, and a failed write is still an error.
        if self.print_verify_logs {
            match fs::read(&log1_path) {
                Ok(bytes) if hermit::nonwaiting_write::diagnostics_must_not_wait() => {
                    let _ = detcore::util::DroppingStderr.write_all(&bytes);
                }
                Ok(bytes) => std::io::stderr().write_all(&bytes)?,
                Err(err) => crate::tracing::diagnostic_eprintln!(
                    "WARNING: --print-verify-logs could not read first-run log {}: {}",
                    log1_path.display(),
                    err
                ),
            }
        }

        if let Some(error) = reject_first_run(
            self.verify_json.as_deref(),
            self.verify_allow,
            &out1,
            skid_overshoots_run1,
            summary1_path
                .as_deref()
                .and_then(read_verify_summary)
                .as_ref(),
        ) {
            // Queued here; `main` writes it after everything else.
            drop(signal_reports);
            if self.keep_logs {
                retain_verification_logs([("run 1", log1_path)])?;
            }
            return Err(error);
        }

        #[cfg(feature = "dbt")]
        let dbt1 = match dbt1
            .map(|facts| facts.finish(&out1, VerificationRun::Run1))
            .transpose()
        {
            Ok(facts) => facts,
            Err(error) => {
                let mut error =
                    publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run1, error);
                if self.keep_logs {
                    error = retain_logs_after_verification_error(error, [("run 1", log1_path)]);
                }
                return Err(error);
            }
        };

        let summary1 = summary1_path
            .as_deref()
            .map(take_verify_summary_before_next_run)
            .transpose()?
            .flatten();
        let host_inputs1 = host_inputs_path.as_deref().map(read_host_inputs);
        if let Some(file) = &host_inputs_file {
            file.set_len(0)
                .context("emptying the host-input record before run 2")?;
        }
        if skid_overshoots_run1 > 0
            && let Some(path) = &self.verify_json
        {
            write_skid_overshoot_without_comparison_json(
                path,
                skid_overshoots_run1,
                verification_runtime_from_summaries(summary1.as_ref(), None),
                Some(out1.status),
            )?;
        }

        // ⚠️ THE TWO RUNS MUST START FROM IDENTICAL fd STATE, AND WITHOUT THIS
        // THEY DO NOT. Both runs inherit hermit's OWN stderr, so a guest that
        // mutates its status flags leaves run 2 starting from state run 1
        // created -- and the comparison then reports the guest as
        // nondeterministic when the guest was identical both times.
        //
        // MEASURED 2026-08-26 on `hermit --backend kvm run --strict --verify --
        // /usr/bin/awk 'BEGIN { print 42 }'`: awk sets O_APPEND on fd 2 only
        // when it is not already set, so
        //     run 1  fcntl(2, F_GETFL) = 32769  -> fcntl(2, F_SETFL, 33793)
        //     run 2  fcntl(2, F_GETFL) = 33793  -> no SETFL at all
        // One extra syscall in run 1 (161 vs 160), which shifts every later
        // record by one and reported TWENTY mismatches for TWO real differences.
        //
        // ⚠️ TWO, NOT ONE. An earlier version of this comment said "drop that
        // single record and the sequences are byte-identical". The INBOUND
        // records are -- measured, 0 of 160 differ once run 1's `F_SETFL` is
        // removed -- but the `F_GETFL` RESULT differs as well, `Ok(32769)`
        // against `Ok(33793)`, because that is the flag word this defect is
        // about. Caught by `agent(hermit-dbg)`. The distinction matters: the
        // claim as written invited a reader to check inbound records only, find
        // them clean, and conclude the harness was blameless.
        //
        // The one-line demonstration, before this fix: `2>file` gave rc=125
        // and 20 mismatches; `2>>file` -- the same run with O_APPEND already
        // set, so awk skips the SETFL in BOTH runs -- gave rc=0 and 0
        // mismatches. One bit on one descriptor decided the verdict.
        //
        // ⚠️ RESTORE, DO NOT SANITISE. Clearing the flags outright would change
        // what the guest observes; this puts back exactly what run 1 was
        // handed, so run 2 sees the same starting state and nothing else moves.
        // Best-effort by construction: if the flags cannot be read or restored
        // we leave the descriptor alone rather than fail a verification over
        // housekeeping, and the comparison reports the divergence as before.
        restore_standard_fd_status_flags(fd_flags_before_run1);

        crate::tracing::diagnostic_eprintln!(":: {}", "Run2...".yellow().bold());
        let VerificationRunOutput {
            output: out2,
            skid_overshoots: skid_overshoots_run2,
            latches: latches2,
            #[cfg(feature = "dbt")]
                dbt: dbt2,
        } = match run_verification_execution(
            self.verify_json.as_deref(),
            VerificationRun::Run2,
            || {
                execute(
                    &run2_options,
                    log2_file,
                    &log2_path,
                    forwarded2_for_run,
                    VerificationRun::Run2,
                )
            },
        ) {
            Ok(result) => result,
            Err(mut error) => {
                if let Some(overshoot) = error.downcast_ref::<SkidOvershootError>()
                    && let Some(path) = &self.verify_json
                {
                    let summary2 = summary2_path.and_then(read_verify_summary);
                    let count = skid_overshoots_run1.saturating_add(overshoot.count());
                    if let Err(report_error) = write_skid_overshoot_without_comparison_json(
                        path,
                        count,
                        verification_runtime_from_summaries(summary1.as_ref(), summary2.as_ref()),
                        Some(out1.status),
                    ) {
                        error = retain_verification_error(
                            error,
                            "publishing skid overshoot",
                            report_error,
                        );
                    }
                }
                error =
                    publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run2, error);
                if self.keep_logs {
                    error = retain_logs_after_verification_error(
                        error,
                        [("run 1", log1_path), ("run 2", log2_path)],
                    );
                }
                return Err(error);
            }
        };
        let mut out2 = out2;
        if self.selected_backend() == Backend::Dbt {
            signal_reports.prepare("run 2", out2.status, &log2_path);
        }
        if let Err(error) = latches2.refuse_comparison("run 2") {
            let error =
                publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run2, error);
            if self.keep_logs {
                retain_verification_logs([("run 1", log1_path), ("run 2", log2_path)])?;
            }
            return Err(error);
        }
        if let Some(forwarded_syscalls1) = forwarded_syscalls1 {
            let backend = if self.selected_backend() == Backend::Sabre {
                "SaBRe"
            } else {
                "LiteInst"
            };
            let forwarded_syscalls2 = match self
                .take_forwarded_detlogs(&log2_path, &mut out2.stderr, forwarded2)
                .and_then(|count| {
                    count.context("run 2 forwarded no DETLOG records where run 1 did")
                }) {
                Ok(count) => count,
                Err(error) => {
                    if self.keep_logs {
                        retain_verification_logs([("run 1", log1_path), ("run 2", log2_path)])?;
                    }
                    return Err(error);
                }
            };
            if forwarded_syscalls1 == 0 || forwarded_syscalls2 == 0 {
                if self.keep_logs {
                    retain_verification_logs([("run 1", log1_path), ("run 2", log2_path)])?;
                }
                return Err(Error::msg(format!(
                    "{backend} verification captured no syscall DETLOG records: run1={forwarded_syscalls1}, run2={forwarded_syscalls2}"
                )));
            }
            eprintln!(
                ":: {backend} syscall DETLOG records included: run1={forwarded_syscalls1}, run2={forwarded_syscalls2}"
            );
        }

        if self.selected_backend() != Backend::Dbt {
            signal_reports.prepare("run 2", out2.status, &log2_path);
        }

        #[cfg(feature = "dbt")]
        let dbt2 = match dbt2
            .map(|facts| facts.finish(&out2, VerificationRun::Run2))
            .transpose()
        {
            Ok(facts) => facts,
            Err(error) => {
                let mut error =
                    publish_run_failure(self.verify_json.as_deref(), VerificationRun::Run2, error);
                if self.keep_logs {
                    error = retain_logs_after_verification_error(
                        error,
                        [("run 1", log1_path), ("run 2", log2_path)],
                    );
                }
                return Err(error);
            }
        };
        #[cfg(feature = "dbt")]
        let dbt_comparison = dbt1
            .as_ref()
            .zip(dbt2.as_ref())
            .map(|(first, second)| super::backends::DbtVerificationComparison::new(first, second));

        let summary2 = summary2_path.and_then(read_verify_summary);
        let outcome = conclude_verification(
            VerificationConclusion {
                verify_json: self.verify_json.as_deref(),
                comparison_options: self.verification_comparison_options(),
                #[cfg(feature = "dbt")]
                dbt: dbt_comparison,
                backend: self.selected_backend(),
                passthru_opt: self.det_opts.det_config.passthru_opt,
            },
            CompletedVerificationRun {
                output: &out1,
                log: log1_path,
                skid_overshoots: skid_overshoots_run1,
                summary: summary1,
                host_inputs: host_inputs1,
            },
            CompletedVerificationRun {
                output: &out2,
                log: log2_path,
                skid_overshoots: skid_overshoots_run2,
                summary: summary2,
                host_inputs: host_inputs_path.as_deref().map(read_host_inputs),
            },
        )?;
        drop(host_inputs_file);

        // On divergence, still return the nonzero status and skip
        // the backend banner — but EMIT THE GUEST'S OUTPUT FIRST when both runs
        // agreed on it.
        //
        // ⚠️ THE HISTORICAL BEHAVIOUR DESTROYED THE EVIDENCE IT EXISTED TO
        // PRESENT. Dropping the output made a diverging run indistinguishable at
        // the CLI from a run that produced nothing, which is a far more alarming
        // and completely different failure. Measured 2026-08-25: a KVM
        // divergence on `awk 'BEGIN { print 42 }'` was investigated, escalated,
        // and reported to the project owner as "the guest produced no output".
        // The guest produced `42`; both runs produced `42`; the harness threw it
        // away. A diagnostic that hides the guest's behaviour misleads precisely
        // when someone is investigating, and it did.
        //
        // WHY EMITTING IS UNAMBIGUOUS HERE, and why this is narrow: the
        // comparator ALREADY prints a labelled diff of both runs whenever
        // stdout or stderr differ. So the only case reaching this point with
        // output to show is the one where BOTH RUNS AGREED — there is no
        // question of which to print, and nothing is being chosen on the
        // reader's behalf. Where they disagree the diff above is the report and
        // this stays silent, exactly as before.
        //
        // The exit status is unchanged, so anything keying on the process
        // result is unaffected; only the diagnostic gains the bytes it was
        // discarding.
        if !outcome.verified() {
            emit_compared_guest_output(false, &out1, &out2)?;
            return outcome.into_exit_status();
        }
        signal_reports.verified();
        let status = outcome.guest_status;

        let backend_banner = match self.selected_backend() {
            Backend::Kvm => Some("KVM (reverie-kvm KvmGuest<Detcore>)"),
            Backend::Liteinst
            | Backend::InGuestTrap
            | Backend::Ptrace
            | Backend::Dbt
            | Backend::Sabre
            | Backend::E9patch => None,
        };
        if let Some(backend_banner) = backend_banner {
            eprintln!(":: Backend: {backend_banner}");
        }
        emit_compared_guest_output(true, &out1, &out2)?;
        Ok(status)
    }

    /// The `--bind`s the DBT adapter checks, as (source, target) pairs: those
    /// with a target under guest `/tmp`, which is where [`Self::mounts`] applies
    /// binds for every backend. It warns about any other bind, which has no
    /// effect.
    #[cfg(feature = "dbt")]
    pub(super) fn dbt_binds(&self) -> Vec<(PathBuf, PathBuf)> {
        let mut binds = Vec::with_capacity(self.bind.len());
        for bind in &self.bind {
            let source = PathBuf::from(OsStr::from_bytes(bind.source.to_bytes()));
            let target = PathBuf::from(OsStr::from_bytes(bind.target.to_bytes()));
            if target.starts_with(TMP_DIR) {
                binds.push((source, target));
            }
        }
        binds
    }

    /// These options with the DBT adapter's own container inputs added after
    /// the caller's, only for this physical launch.
    #[cfg(feature = "dbt")]
    pub(super) fn with_dbt_mounts(&self, binds: &[Bind], mounts: Vec<Mount>) -> Self {
        let mut options = self.clone();
        options.backend_mounts.0 += mounts.len();
        options.backend_mounts.1 += binds.len();
        options.bind.extend_from_slice(binds);
        options.mount.extend(mounts);
        options
    }

    /// These options with `mount` added after the caller's own, as one of
    /// them (shown in the guest's mount table): the DBT adapter's tmpfs at
    /// the test workdir, which the guest uses as its working directory.
    #[cfg(feature = "dbt")]
    pub(super) fn with_guest_mount(&self, mount: Mount) -> Self {
        let mut options = self.clone();
        options.mount.push(mount);
        options
    }

    /// Whether the caller's `--mount`s install a fresh tmpfs at guest path
    /// `target` (a mount of type tmpfs: setting that type changes nothing).
    #[cfg(feature = "dbt")]
    pub(super) fn mounts_tmpfs_at(&self, target: &Path) -> bool {
        self.mount
            .iter()
            .any(|mount| mount.get_target() == target && mount.clone().fstype("tmpfs") == *mount)
    }

    /// Whether the guest runs in the common container, with its own PID
    /// namespace and private /tmp, rather than as a plain child.
    #[cfg(feature = "dbt")]
    pub(super) fn uses_container(&self) -> bool {
        !self.no_namespace
    }

    /// Returns the mounts to be used with the container, in the order they are
    /// installed: the identity-hardening mounts, the caller's `--mount`s and
    /// `--bind`s (a backend adapter's own last, marked as a backend's), the
    /// e9patch overlay (a backend's own), and the private `/tmp`.
    fn mounts(&self, tmpfs: &Path) -> Result<PreparedMounts, Error> {
        let (mut identity_mounts, identity_sources) = identity_hardening_mounts()?;
        let mut identity_sources = identity_sources;
        let mut explicit_tmp_mount = false;
        let mut user_mounts = Vec::with_capacity(self.mount.len() + self.bind.len());
        let backend_mounts_from = self.mount.len().saturating_sub(self.backend_mounts.0);
        let backend_binds_from = self.bind.len().saturating_sub(self.backend_mounts.1);
        let planned = |mount: Mount, backend: bool| {
            if backend {
                PlannedMount::backend(mount)
            } else {
                PlannedMount::hermit(mount)
            }
        };

        for (index, mount) in self.mount.iter().enumerate() {
            let backend = index >= backend_mounts_from;
            let user_target = mount.get_target();
            identity_sources.discard_mounts_shadowed_by(&mut identity_mounts, user_target);
            let staging = mount
                .get_target()
                .strip_prefix(TMP_DIR)
                .ok()
                .map(|path| tmpfs.join(path));
            if mount.get_source().is_some() && super::container::is_bind_mount(mount) {
                identity_sources.add_user_bind(user_target, staging.as_deref());
            }
            if let Ok(path) = mount.get_target().strip_prefix(TMP_DIR) {
                explicit_tmp_mount |= path.as_os_str().is_empty();
                // If the target is in /tmp, change it so it goes to our
                // temporary /tmp instead.
                user_mounts.push(planned(
                    mount.clone().target(tmpfs.join(path)).touch_target(),
                    backend,
                ));
            } else {
                user_mounts.push(planned(mount.clone(), backend));
            }
        }

        for (index, bind) in self.bind.iter().enumerate() {
            let backend = index >= backend_binds_from;
            let mount = Mount::from(bind.clone()).rshared();

            // Bind mounts currently only make sense for things in `/tmp` since
            // that is the only directory we overlay.
            if let Ok(relative_path) = mount.get_target().strip_prefix(TMP_DIR) {
                // Discard provenance only for a bind we actually retain. An
                // ignored outside-/tmp bind must not suppress the real
                // identity-hardening mount at that target.
                explicit_tmp_mount |= relative_path.as_os_str().is_empty();
                identity_sources
                    .discard_mounts_shadowed_by(&mut identity_mounts, mount.get_target());
                let target = tmpfs.join(relative_path);
                identity_sources.add_user_bind(mount.get_target(), Some(&target));
                user_mounts.push(planned(mount.target(target).touch_target(), backend));
            } else {
                warn_bind_outside_tmp(bind);
            }
        }

        if self.tmp.is_none() {
            if explicit_tmp_mount {
                // The user mount or bind is installed on the generated staging
                // path, then exposed at `/tmp` by the final bind below. Preserve
                // the user's root and translate only that internal mountpoint.
                identity_sources.add_translated_tmp_mountpoint(tmpfs);
            } else {
                // Add this after explicit mounts. A user mount at `/` shadows
                // group/nscd, but the final `/tmp` bind below is later and
                // remains active, so its provenance must survive.
                identity_sources.add_private_tmp(tmpfs)?;
            }
        }

        let mut mounts = identity_mounts
            .into_iter()
            .map(PlannedMount::hermit)
            .collect::<Vec<_>>();
        mounts.extend(user_mounts);

        if let Some(overlay) = &self.e9patch_overlay {
            let target = if let Ok(relative_path) = overlay.target.strip_prefix(TMP_DIR) {
                tmpfs.join(relative_path)
            } else {
                overlay.target.clone()
            };
            mounts.push(PlannedMount::backend(
                Mount::bind(&overlay.source, &target)
                    .readonly()
                    .touch_target(),
            ));
            mounts.push(PlannedMount::backend(Mount::new(target).flags(
                MountFlags::MS_BIND | MountFlags::MS_REMOUNT | MountFlags::MS_RDONLY,
            )));
        }
        // Bind the /tmp/tmpXXXXXX tmpfs mount over /tmp to hide it. This way,
        // we still preserve the files or directories bind-mounted inside of it
        // while hiding the real /tmp.
        mounts.push(PlannedMount::hermit(Mount::bind(tmpfs, TMP_DIR).rshared()));

        Ok(PreparedMounts {
            mounts,
            identity_sources,
        })
    }

    /// Returns a configured container to run a function in.
    ///
    /// The container's setup makes its namespaces, (for `--network=local`)
    /// its sysfs, and then its mount plan, the container's `/proc` first,
    /// which the container's init records for the guest's container mount
    /// table (`IdentityGuard::record_plan`). A native exec domain's container
    /// follows the plan with its declared-input mounts, and has no table.
    fn container(&self, tmpfs: &Path) -> Result<(Container, IdentityGuard), Error> {
        // PROTOTYPE: when an OCI image is requested, the guest runs against the
        // image's materialized rootfs (deterministic file inputs) rather than
        // the host filesystem. This replaces the default namespace+mounts setup
        // with a chroot into the pinned image root.
        if let Some(image) = &self.image {
            let rootfs = crate::image::materialize_rootfs(image)?;
            let (mut container, identity_sources) =
                image_container(&rootfs, tmpfs, self.pin_threads, self.tmp.is_none())?;
            self.network
                .configure(&mut container, self.analyze_networking);
            return Ok((container, identity_sources));
        }

        let mut container = namespace_container(self.pin_threads);
        self.network
            .configure(&mut container, self.analyze_networking);

        let PreparedMounts {
            mounts,
            mut identity_sources,
        } = self.mounts(tmpfs)?;
        let mut plan = vec![PlannedMount::hermit(container_proc_mount())];
        plan.extend(mounts);
        identity_sources.set_plan(&mut container, plan)?;
        #[cfg(feature = "native-exec")]
        if self.native_exec_capture.is_some() {
            identity_sources.forget_plan();
        }

        Ok((container, identity_sources))
    }

    #[cfg(feature = "dbt")]
    fn dbt_invocation(&self) -> Result<super::backends::DbtInvocation, Error> {
        super::backends::DbtInvocation::new(
            &self.program,
            &self.args,
            &hermit::prepare_backend_config(self.effective_det_config(), Backend::Dbt),
            self.guest_command()?.get_captured_envs(),
            self.workdir.as_deref().map(Path::new),
            self.dbt_binds(),
            self,
        )
    }

    fn run_verify(
        &self,
        log_file: fs::File,
        _log_path: &Path,
        forwarded_detlogs: ForwardedDetlogPlan,
        global: &GlobalOpts,
        _run: VerificationRun,
        #[cfg(feature = "dbt")] dbt: Option<&mut super::backends::DbtVerification>,
    ) -> Result<VerificationRunOutput, Error> {
        #[cfg(feature = "dbt")]
        if let Some(dbt) = dbt {
            return dbt.run(
                log_file,
                _log_path,
                _run,
                global.log,
                self.verify_verbose,
                self.verify_json.as_deref(),
            );
        }
        let mut options = self.clone();
        let network_trace = options.open_network_trace()?;
        let global = global.clone();
        let resources = format!(
            "verification log{}{} descriptors",
            if network_trace.is_some() {
                ", network trace"
            } else {
                ""
            },
            if forwarded_detlogs.requires_socket() {
                ", forwarded DETLOG"
            } else {
                ""
            },
        );
        self.launch_in_container(
            (Some(log_file), network_trace, forwarded_detlogs),
            &resources,
            None,
            move |(log, _, forwarded), identity, native| {
                options.run_verify_in_container(log, forwarded, &global, identity, native)
            },
        )
        .map(
            |((output, skid_overshoots, latches), _guards)| VerificationRunOutput {
                output,
                skid_overshoots,
                latches,
                #[cfg(feature = "dbt")]
                dbt: None,
            },
        )
    }

    fn merge_from_env_settings(&self, command: &mut Command) -> anyhow::Result<()> {
        for (var, m_val) in &self.env {
            if let Some(val) = m_val {
                command.env(var, val);
            } else if let Ok(value) = std::env::var(var) {
                command.env(var, &value);
            } else {
                anyhow::bail!(
                    "Attempt to pass through env var {}, but it is not set in the host environment",
                    var
                )
            }
        }
        Ok(())
    }

    fn guest_command(&self) -> Result<Command, Error> {
        self.build_guest_command(true)
    }

    fn namespace_only_guest_command(&self) -> Result<Command, Error> {
        // Namespace-only bypasses instrumentation, so preserve the caller's
        // sanitizer environment instead of installing the leak-disable overrides.
        self.build_guest_command(false)
    }

    /// The guest's working directory as `--workdir` names it, if given
    /// (relative to Hermit's own, as the guest command takes it).
    pub(super) fn launch_workdir(&self) -> Option<&Path> {
        self.workdir.as_deref().map(Path::new)
    }

    fn build_guest_command(
        &self,
        disable_sanitizer_leak_detection_for_guest: bool,
    ) -> Result<Command, Error> {
        let program = self.e9patch_program.as_ref().unwrap_or(&self.program);
        let mut command = Command::new(program);
        command.args(&self.args);
        if self.e9patch_program.is_some() {
            command.arg0(&self.program);
        }
        // PROTOTYPE (--image): the guest lives inside the OCI rootfs, so the
        // guest working directory must be one that exists under the image root.
        // Default it to the image's declared `WorkingDir`, else `/` (a bare
        // chroot leaves cwd pointing at the — now unreachable — host cwd, which
        // makes `getcwd` fail inside the guest). An explicit `--workdir` wins.
        if let Some(current_dir) = &self.workdir {
            command.current_dir(current_dir);
        } else if let Some(image) = &self.image {
            let cfg = crate::image::read_image_config(image)?;
            command.current_dir(cfg.workdir.as_deref().unwrap_or("/"));
        }

        // PROTOTYPE (--image): an OCI rootfs is a self-contained filesystem, so
        // leaking the host environment (a host `PATH` full of paths absent from
        // the image) both breaks usability and undermines determinism. Instead
        // apply the image's *own* declared `Env` — pinned by the image digest,
        // hence deterministic — over an otherwise empty base, then merge user
        // `--env` on top. If the image declares no `PATH`/`HOME` we fall back to
        // the same hermetic defaults `--base-env=minimal` uses.
        if let Some(image) = &self.image {
            command.env_clear();
            let cfg = crate::image::read_image_config(image)?;
            let declares_path = cfg.env.iter().any(|(k, _)| k == "PATH");
            let declares_home = cfg.env.iter().any(|(k, _)| k == "HOME");
            command.env("HOSTNAME", "hermetic-container.local");
            if !declares_path {
                command.env(
                    "PATH",
                    "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                );
            }
            if !declares_home {
                command.env("HOME", "/root");
            }
            for (key, value) in &cfg.env {
                command.env(key, value);
            }
            self.merge_from_env_settings(&mut command)?;
            return Ok(command);
        }

        apply_base_and_explicit_environment(&mut command, &self.base_env, &self.env)?;
        if disable_sanitizer_leak_detection_for_guest {
            disable_sanitizer_leak_detection(&mut command);
        }

        Ok(command)
    }

    /// Whether this invocation asked for `--save-config`.
    pub(crate) fn saves_config(&self) -> bool {
        self.save_config.is_some()
    }

    /// The run config option this invocation gave, if any, for the commands
    /// that embed `run`'s options but cannot honour them.
    pub(crate) fn run_config_option(&self) -> Option<&'static str> {
        if self.config.is_some() {
            Some("--config")
        } else if self.save_config.is_some() {
            Some("--save-config")
        } else {
            None
        }
    }

    /// The top-level parser replaces `hermit run --config FILE` with the
    /// file's options before parsing (`crate::run_config::expand_argv`), so a
    /// `--config` still present here was never applied.
    fn refuse_unapplied_config(&self) -> Result<(), Error> {
        match &self.config {
            Some(path) => Err(Error::msg(format!(
                "--config {} was not applied: only a top-level `hermit run` invocation loads a \
                 run config. Run `hermit [GLOBAL OPTIONS] run --config {} [OPTIONS]`.",
                path.display(),
                path.display()
            ))),
            None => Ok(()),
        }
    }

    /// Hands over the options the top-level parser captured for
    /// `--save-config`.
    pub(crate) fn set_config_capture(&mut self, config: crate::run_config::RunConfig) {
        self.config_capture = Some(config);
    }

    /// Retain source identity independently of YAML capture, which may fail
    /// for a non-UTF-8 argument and does not run for embedded OCI commands.
    pub(crate) fn capture_max_timeslice_source(&mut self, matches: &clap::ArgMatches) {
        self.max_timeslice_explicit =
            matches.value_source("max_timeslice") != Some(clap::parser::ValueSource::DefaultValue);
    }

    fn resolve_preemption_settings(&self) -> Result<(), Error> {
        // Namespace-only runs do not dispatch an instrumentation backend.
        if self.namespace_only {
            return Ok(());
        }
        // The inherited maximum also chooses Detcore's clock accounting and
        // cooperative deadline. Checking a timer request must not rewrite it.
        hermit::preemption_admission::refuse_unsupported_preemption(
            &self.det_opts.det_config,
            self.selected_backend(),
            self.max_timeslice_explicit,
            self.skid_margin.is_some(),
        )
        .map_err(|refusal| Error::new(PolicyRefusal).context(refusal))
    }

    fn preemption_summary(&self) -> detcore_model::summary::PreemptionSummary {
        let maximum = self.det_opts.det_config.max_timeslice;
        detcore_model::summary::PreemptionSummary {
            max_timeslice_ns: maximum.map(|maximum| maximum.get()),
            timer_enabled: Some(
                !self.namespace_only
                    && maximum.is_some()
                    && hermit::backend_delivers_preemption_timer(self.selected_backend()),
            ),
        }
    }

    /// The run config `--save-config` writes: the captured options with the
    /// implicit inputs this run resolved written out, so that loading it
    /// reproduces the run rather than resolving them again.
    pub(crate) fn saved_run_config(&self) -> Result<crate::run_config::RunConfig, Error> {
        use crate::run_config::EPOCH_KEY;
        use crate::run_config::SEED_FROM_KEY;
        use crate::run_config::SEED_KEY;

        let mut config = self.config_capture.clone().ok_or_else(|| {
            Error::msg(
                "--save-config is written only by a `hermit run` invocation, whose parser \
                 captures the options it was given",
            )
        })?;
        if self.epoch_captured_from_host || self.epoch_from_recording {
            config
                .run
                .insert(EPOCH_KEY.to_owned(), self.epoch_rfc3339().into());
        }
        if let Some(seed) = self.seed_from_resolved {
            config.run.remove(SEED_FROM_KEY);
            config.run.insert(SEED_KEY.to_owned(), seed.into());
        }
        Ok(config)
    }

    fn write_saved_config(&self) -> Result<(), Error> {
        match &self.save_config {
            Some(path) => crate::run_config::write(path, &self.saved_run_config()?),
            None => Ok(()),
        }
    }

    /// The inputs this run drew from the host, by option long name, each
    /// with where it came from: an epoch from the host clock, a seed from
    /// `--seed-from=SystemRandom`, and the preemption timer turned off
    /// because this host has no usable performance counter. A seed derived
    /// from the arguments (`--seed-from=Args`) is not drawn from the host.
    fn host_drawn_inputs(&self) -> BTreeMap<String, String> {
        let mut drawn = BTreeMap::new();
        if self.timer_downgrade.is_some() {
            drawn.insert(
                crate::manifest::MAX_TIMESLICE_KEY.to_owned(),
                "no-usable-performance-counter".to_owned(),
            );
        }
        if self.epoch_captured_from_host {
            drawn.insert(
                crate::run_config::EPOCH_KEY.to_owned(),
                "host-now".to_owned(),
            );
        }
        if self.seed_from_resolved.is_some()
            && matches!(self.seed_from, Some(SeedFrom::SystemRandom))
        {
            drawn.insert(
                crate::run_config::SEED_KEY.to_owned(),
                "SystemRandom".to_owned(),
            );
        }
        drawn
    }

    /// `--strict` promises that the arguments alone determine the run, so a
    /// strict run that would draw an input from the host clock or the host's
    /// randomness is refused before the guest starts: it could be reproduced
    /// only from a recording, which is what `--strict` says the run does not
    /// need. Each refusal names the option that supplies the input. An epoch
    /// adopted from the recording a run replays is not drawn from the host and
    /// is not refused.
    ///
    /// The preemption timer a host without a usable performance counter turns
    /// off is also recorded as host-drawn, but is not refused here: every
    /// strict run on such a host (the hosted CI runners among them) would stop,
    /// and a run on one host draws the same value every time.
    fn refuse_strict_with_host_drawn_inputs(&self) -> Result<(), Error> {
        if !self.strict {
            return Ok(());
        }
        let mut drawn = self.host_drawn_inputs();
        drawn.remove(crate::manifest::MAX_TIMESLICE_KEY);
        if drawn.is_empty() {
            return Ok(());
        }
        let remedies = drawn
            .keys()
            .map(|key| match key.as_str() {
                crate::run_config::EPOCH_KEY => {
                    // The host sample this run took, to whole seconds, as an
                    // example a user can paste.
                    let example = self.det_opts.det_config.epoch.format("%Y-%m-%dT%H:%M:%SZ");
                    format!(
                        "the virtual-time epoch, from the host clock: pass --epoch (for example \
                         --epoch={example}) or set HERMIT_EPOCH"
                    )
                }
                crate::run_config::SEED_KEY => "the seed, from --seed-from=SystemRandom: pass \
                     --seed=N, or --seed-from=Args"
                    .to_owned(),
                other => format!("{other}: pass it explicitly"),
            })
            .collect::<Vec<_>>()
            .join("; ");
        anyhow::bail!(
            "--strict requires every input of the run on the command line, but this run would \
             draw {remedies}"
        )
    }

    /// Warns, in one line, that this run drew inputs from the host and so
    /// cannot be rerun from its command line, and says how to rerun it: from
    /// the recording that saved them, or with the options that pass them.
    /// A network recording's own line already names its replay. Nothing is
    /// said of an input the command line gave, such as an explicit epoch, or
    /// one a replayed recording supplied.
    fn warn_of_host_drawn_inputs(
        &self,
        global: &GlobalOpts,
        recording: Option<(hermit::Id, crate::manifest::Kind)>,
    ) -> Result<(), Error> {
        use crate::manifest;
        use crate::run_config::EPOCH_KEY;
        use crate::run_config::SEED_KEY;

        let drawn = self.host_drawn_inputs();
        let what = match drawn.keys().map(String::as_str).collect::<Vec<_>>()[..] {
            [] => return Ok(()),
            [EPOCH_KEY] => "its epoch",
            [SEED_KEY] => "its seed",
            [manifest::MAX_TIMESLICE_KEY] => "its preemption timer setting",
            _ => "settings",
        };
        match recording {
            Some((_, manifest::Kind::Network)) => Ok(()),
            Some((id, _)) => global.report_event(
                ::tracing::Level::WARN,
                format_args!(
                    // `hermit show` alone shows `last`, which a run manifest does not
                    // move, so the warning names `last-run`.
                    "this run drew {what} from the host; its inputs are saved as a recording in \
                     {}/; rerun it with: hermit replay {id} (hermit show last-run)",
                    home_relative(&manifest::data_dir())
                ),
            ),
            None => {
                let options = drawn
                    .keys()
                    .map(|key| match key.as_str() {
                        EPOCH_KEY => format!("--epoch={}", self.epoch_rfc3339()),
                        SEED_KEY => format!("--seed={}", self.seed_from_resolved.unwrap_or(0)),
                        manifest::MAX_TIMESLICE_KEY => "--max-timeslice=disabled".to_owned(),
                        other => format!("--{other}"),
                    })
                    .collect::<Vec<_>>()
                    .join(" ");
                global.report_event(
                    ::tracing::Level::WARN,
                    format_args!(
                        "this run drew {what} from the host and saved no recording; rerun it \
                         with: {options}"
                    ),
                )
            }
        }
    }

    /// Writes this run's manifest when the policy asks for one (see
    /// `crate::manifest`), and remembers its path for `finish_manifest`.
    /// Returns the recording's id and kind when it wrote one. Only a
    /// top-level `hermit run`, whose parser captured the options it was
    /// given, writes one.
    fn begin_manifest(
        &mut self,
        global: &GlobalOpts,
    ) -> Result<Option<(hermit::Id, crate::manifest::Kind)>, Error> {
        use crate::manifest;

        if self.config_capture.is_none() {
            return Ok(None);
        }
        let user_config = match manifest::user_config_path() {
            Some(path) => manifest::read_user_config(&path)?,
            None => manifest::UserConfig::default(),
        };
        let policy = manifest::resolve_policy(
            self.manifest,
            &user_config,
            std::env::var(manifest::POLICY_ENV).ok().as_deref(),
        )?;
        let host_drawn = self.host_drawn_inputs();
        // A network recording is one the user asked for: it always gets its
        // manifest, which names the trace and holds the seeds and command
        // the trace itself does not (the design note's section 5).
        let network_trace = self
            .record_networking
            .as_deref()
            .map(std::path::absolute)
            .transpose()
            .context("cannot resolve the network trace path")?;
        let kind = match (&network_trace, policy, host_drawn.is_empty()) {
            (Some(_), _, _) => manifest::Kind::Network,
            (None, manifest::ManifestPolicy::Never, _)
            | (None, manifest::ManifestPolicy::NonreproducibleOnly, true) => return Ok(None),
            (None, _, false) => manifest::Kind::InputsOnly,
            (None, manifest::ManifestPolicy::Always, true) => manifest::Kind::History,
        };
        let config = self.saved_run_config()?;
        let (mut global_inputs, mut run_inputs) = crate::run_config::to_manifest_parts(&config)?;
        manifest::drop_outputs(&mut global_inputs, &mut run_inputs);
        if self.timer_downgrade.is_some() {
            run_inputs.insert(
                manifest::MAX_TIMESLICE_KEY.to_owned(),
                serde_json::Value::from("disabled"),
            );
        }
        let id = hermit::Id::unique();
        let mut document = manifest::Manifest::new(
            id,
            kind,
            manifest::Command {
                program: config.program.clone(),
                args: config.args.clone(),
                cwd: std::env::current_dir()
                    .ok()
                    .and_then(|dir| dir.to_str().map(str::to_owned)),
            },
            manifest::Inputs {
                global: global_inputs,
                run: run_inputs,
                host_drawn,
            },
        );
        if !self.namespace_only {
            document.preemption = Some(self.preemption_summary());
        }
        let path = match &network_trace {
            // The trace stays where its user named it, with its manifest
            // beside it (a coordinator default for the design note's open
            // choice 3).
            Some(trace) => {
                document.artifacts = Some(manifest::Artifacts {
                    network_trace: Some(manifest::NetworkTrace {
                        path: trace
                            .file_name()
                            .and_then(|name| name.to_str())
                            .ok_or_else(|| {
                                anyhow::anyhow!(
                                    "network trace name {} is not UTF-8",
                                    trace.display()
                                )
                            })?
                            .to_owned(),
                        format: manifest::NETWORK_TRACE_FORMAT.to_owned(),
                        version: None,
                        sha256: None,
                        bytes: None,
                    }),
                    syscall_recording: None,
                });
                manifest::network_manifest_path(trace)
            }
            None => manifest::data_dir()
                .join(id.to_string())
                .join(manifest::MANIFEST_NAME),
        };
        // A network recording's manifest is written once its trace is: a
        // run that fails before writing one must not replace the manifest of
        // a trace still at that path.
        if kind == manifest::Kind::Network {
            self.pending_network_manifest = Some(document.clone());
        } else {
            manifest::write(&path, &document)?;
        }
        if kind.pruned() {
            manifest::prune(&manifest::data_dir(), manifest::KEEP_MANIFEST_ONLY);
        }
        if kind == manifest::Kind::Network {
            global.write_controller_diagnostic(format_args!(
                "hermit: the network recording's manifest is written to {} when the run ends, \
                 as recording {id}; replay it offline with: hermit replay {id}",
                path.display(),
            ))?;
        }
        self.manifest_path = Some(path);
        Ok(Some((id, kind)))
    }

    /// Records how the guest ended in this run's manifest, if it wrote one.
    /// Best effort: the manifest without an exit already reproduces the run.
    fn finish_manifest(&mut self, status: ExitStatus) {
        let Some(path) = self.manifest_path.take() else {
            return;
        };
        let exit = crate::manifest::Exit::from_status(status);
        let pending = self.pending_network_manifest.take();
        let document = match pending {
            Some(document) => Ok(document),
            None => crate::manifest::read(&path),
        };
        let result = document.and_then(|mut document| {
            document.exit = Some(exit);
            // The tracer writes a network trace once the run ends; record
            // what it wrote, so a rerun can tell a truncated or replaced one.
            if let Some(trace) = document
                .artifacts
                .as_mut()
                .and_then(|artifacts| artifacts.network_trace.as_mut())
            {
                let file = path.with_file_name(&trace.path);
                let (sha256, bytes) = crate::manifest::digest_and_size(&file)?;
                trace.version = Some(crate::manifest::network_trace_version(&file)?);
                trace.sha256 = Some(sha256);
                trace.bytes = Some(bytes);
            }
            crate::manifest::write(&path, &document)?;
            Ok(document)
        });
        let document = match result {
            Ok(document) => document,
            Err(error) => {
                crate::tracing::diagnostic_eprintln!(
                    "hermit: could not record the exit status in {}: {error:#}",
                    path.display()
                );
                return;
            }
        };
        if document.kind != crate::manifest::Kind::Network {
            // A run's manifest is the newest run, `last-run`, once the run
            // has ended; `last` stays with the recording the user made.
            if let Ok(id) = document.id.parse() {
                note_latest(&crate::manifest::data_dir(), id, document.kind.moves_last());
            }
            return;
        }
        // A copy in the data directory, naming the trace by its absolute
        // path, makes the recording one that `hermit replay`, `hermit list`
        // and `last` know by its ID.
        let data_dir = crate::manifest::data_dir();
        if let Err(error) = store_network_manifest(&data_dir, &path, document) {
            crate::tracing::diagnostic_eprintln!(
                "hermit: could not add the network recording to {}: {error:#}; replay it with: \
                 hermit run --from {}",
                data_dir.display(),
                path.display()
            );
        }
    }

    /// `hermit analyze` keeps a debugging dump of each trial's options in
    /// its workspace. Trials are built by the program, not parsed from a
    /// command line, so this is Rust's `Debug` rendering and not a run config
    /// that `--config` can load.
    pub(crate) fn write_debug_options_dump(&self) -> Result<(), Error> {
        if let Some(path) = &self.save_config {
            let mut file = File::create(path)?;
            file.write_all(format!("{:#?}\n", self).as_bytes())?;
        }
        Ok(())
    }

    fn effective_det_config(&self) -> DetConfig {
        let mut config = self.det_opts.det_config.clone();
        if !self.allow_unsupported_syscalls
            && std::env::var(FAIL_CLOSED_ENV).is_ok_and(|value| value == "1")
        {
            config.panic_on_unsupported_syscalls = true;
        }
        config.shutdown_on_unsupported_syscall = config.panic_on_unsupported_syscalls;
        // Hand the scheduler the resolved happens-before program (already resolved
        // against the guest binary in `main()`). `#[serde(skip)]` on the field means
        // this is in-process only; it reaches the ptrace backend directly and is not
        // carried through the DBT JSON config or `--save-config`.
        config.happens_before = self.resolved_happens_before.clone();
        config.record_host_inputs = self.host_input_log.is_some();
        config.host_input_log = self.host_input_log.clone();
        config.untraced_code_range = untraced_code_range(self.selected_backend());
        config.fatal_core_capture = self.fatal_core_capture();
        config
    }

    /// Where and within what bounds the tracer keeps fatal cores, or `None`,
    /// the default, to keep none.
    fn fatal_core_capture(&self) -> Option<detcore::FatalCoreCapture> {
        let handle = self.fatal_core_dir_handle.as_ref()?;
        Some(detcore::FatalCoreCapture {
            dir: descriptor_path(handle),
            file_prefix: self.fatal_core_file_prefix(),
            max_core_bytes: self.fatal_core_max_bytes,
            max_total_bytes: self.fatal_core_total_max_bytes,
            time_limit: FATAL_CORE_TIME_LIMIT,
        })
    }

    /// The name prefix of every core this run writes.
    fn fatal_core_file_prefix(&self) -> String {
        match self.fatal_core_run_label {
            Some(label) => format!("hermit-{}-{label}-", self.fatal_core_owner),
            None => format!("hermit-{}-", self.fatal_core_owner),
        }
    }

    /// Opens `--fatal-core-dir`, creating it, so that the guest's run can
    /// reach it. Called once every refusal that needs no guest has passed.
    fn open_fatal_core_dir(&mut self) -> Result<(), Error> {
        if let Some(dir) = &self.fatal_core_dir {
            fs::create_dir_all(dir)
                .with_context(|| format!("creating --fatal-core-dir {}", dir.display()))?;
            let handle = File::open(dir)
                .with_context(|| format!("opening --fatal-core-dir {}", dir.display()))?;
            self.fatal_core_dir_handle = Some(std::sync::Arc::new(handle));
            self.fatal_core_owner = fatal_core_owner_token();
        }
        Ok(())
    }

    /// A run that succeeded keeps no cores: removes every file in
    /// `--fatal-core-dir` that this invocation named, including any temporary
    /// file a capture left behind.
    fn discard_fatal_cores_after_success(&self) {
        let (Some(dir), Some(_)) = (&self.fatal_core_dir, &self.fatal_core_dir_handle) else {
            return;
        };
        let removed = remove_fatal_core_files(dir, &self.fatal_core_owner);
        if removed > 0 {
            eprintln!("hermit: the run exited 0, so its {removed} fatal core file(s) were removed");
        }
    }

    /// The `--timeout` bound, if the caller asked for one.
    ///
    /// Mirrors `StartOpts::record_timeout` so the two spellings of a hermit
    /// deadline are read the same way.
    pub(super) fn run_timeout(&self) -> Option<Duration> {
        self.timeout
            .map(|seconds| Duration::from_secs(seconds.get()))
    }

    /// `--strict` promises a deterministic run, and on the ptrace and e9patch
    /// backends the virtual clock and the preemption points are the guest's
    /// retired conditional branches, read from a performance counter. Where
    /// that counter miscounts, two runs of one program diverge by a few
    /// branches: measured on an AMD EPYC 9D64 (family 0x19, model 0xA0), around
    /// locked instructions (<https://github.com/rrnewton/hermit/issues/3794>).
    /// Refuse rather than run a strict guest on a clock that is not exact.
    /// Runs without `--strict` go ahead, and Reverie logs the failed
    /// validation.
    ///
    /// A run with `--max-timeslice=disabled` does not depend on the counter
    /// being exact: Detcore reads it only to advance logical time and to place
    /// preemption points, and does neither without a timeslice
    /// (`DetConfig::use_rcb_time`, `Detcore::update_logical_time_rcbs`).
    /// Reverie still opens, calibrates and incidentally reads the counters,
    /// but none of those reads reaches logical time, a preemption point or the
    /// guest (the post-facto review of
    /// <https://github.com/rrnewton/hermit/issues/4291>). So
    /// such a run is not refused; that is what lets a test run at the relaxed
    /// strictness level on a host whose counter miscounts
    /// (<https://github.com/rrnewton/hermit/issues/4291>).
    fn refuse_strict_with_inexact_branch_counter(&self) -> Result<(), Error> {
        if !self.strict || !self.reads_the_branch_counter() {
            return Ok(());
        }
        refuse_an_inexact_branch_counter(self.selected_backend(), self.inexact_branch_counter)
    }

    /// The one-line stderr warning for a run that goes on without `--strict`
    /// while reading a retired-branch counter that failed Reverie's validation,
    /// which `--strict` refuses: the run proceeds on a degraded capability, so
    /// it says so (https://github.com/rrnewton/hermit/issues/4515). Reverie
    /// validates the counters once per process, on its first timer, so asking
    /// here costs nothing more.
    fn inexact_branch_counter_warning(&self) -> Option<String> {
        // A `--strict` run never gets here with such a counter:
        // `admit_branch_counter` refuses it first.
        if !self.reads_the_branch_counter() {
            return None;
        }
        (self.inexact_branch_counter)().map(|reason| {
            // Reverie's message can span lines (`HardwareCountersNotWorking`
            // embeds two newlines); the warning stays one line.
            let reason = reason.split_whitespace().collect::<Vec<_>>().join(" ");
            format!(
                "WARNING: this host's performance counters failed Reverie's validation \
                 ({reason}); preemption by retired branches may not repeat, so a run may \
                 not replay or verify. `hermit run --strict` refuses here.\n"
            )
        })
    }

    /// `main`'s branch-counter check: a `--strict` run on a counter that failed
    /// Reverie's validation is refused, and any other run that reads it passes
    /// [`Self::inexact_branch_counter_warning`] to `warn` (stderr in `main`).
    fn admit_branch_counter(&self, warn: &mut dyn FnMut(&str)) -> Result<(), Error> {
        self.refuse_strict_with_inexact_branch_counter()?;
        if let Some(warning) = self.inexact_branch_counter_warning() {
            warn(&warning);
        }
        Ok(())
    }

    /// Whether this run reads the retired-conditional-branch counter that
    /// [`Self::refuse_strict_with_inexact_branch_counter`] guards: on a
    /// backend that arms Reverie's ptrace PMU timer, with a timeslice.
    fn reads_the_branch_counter(&self) -> bool {
        self.arms_reverie_ptrace_pmu_timer() && self.det_opts.det_config.max_timeslice.is_some()
    }

    /// [`Self::refuse_strict_with_inexact_branch_counter`] for an `analyze` or
    /// `bisect` trial (`AnalyzeOpts::refuse_strict_with_inexact_branch_counter`).
    /// Trials start through `RunOpts::run` and never pass through `main`
    /// (<https://github.com/rrnewton/hermit/issues/3810>), so `--namespace-only`
    /// (alias `--lite`) does not reach `run_with_namespace_only`: the trial
    /// still runs on the backend's runtime and its counter, and is not exempt.
    pub(crate) fn refuse_strict_trial_with_inexact_branch_counter(&self) -> Result<(), Error> {
        if !self.strict
            || !self.backend_arms_reverie_ptrace_pmu_timer()
            || self.det_opts.det_config.max_timeslice.is_none()
        {
            return Ok(());
        }
        refuse_an_inexact_branch_counter(self.selected_backend(), self.inexact_branch_counter)
    }

    /// The run options set here that only `RunOpts::main` applies, as the
    /// spellings a user would write. A trial started through `RunOpts::run`,
    /// as `hermit analyze` and `hermit bisect` start theirs, would accept them
    /// and run without them, while its printed reproducer still carried them:
    ///
    /// - `--namespace-only`: only `main` dispatches to `run_with_namespace_only`;
    ///   `run` launches the backend's runtime.
    /// - `--verify` (and every option that requires it): only `main`
    ///   dispatches to `verify()`; `run` is a single run.
    /// - `--happens-before` (and `--hb-list-events`): only `main` resolves the
    ///   specification, so `run` hands the scheduler none.
    /// - `--verify-run`: only `main` dispatches to `verify_run()`.
    /// - `--backend-engagement-json`: only `main` writes it.
    /// - `--cpu-profile x86-64-v3`: only `main` runs the host qualification
    ///   and admits the profile (<https://github.com/rrnewton/hermit/issues/4243>).
    ///
    /// `--skid-margin` is not listed: `hermit analyze` and `hermit bisect`
    /// install it for their trials themselves (`install_pmu_config`).
    pub(crate) fn options_only_main_applies(&self) -> Vec<&'static str> {
        [
            (self.namespace_only, "--namespace-only"),
            (self.verify, "--verify"),
            // Only `main` runs the host qualification the profile admits with.
            (
                !self.det_opts.det_config.cpu_profile.is_default(),
                "--cpu-profile x86-64-v3",
            ),
            (self.verify_run.is_some(), "--verify-run"),
            (self.happens_before.is_some(), "--happens-before"),
            (
                self.backend_engagement_json.is_some(),
                "--backend-engagement-json",
            ),
        ]
        .into_iter()
        .filter_map(|(set, option)| set.then_some(option))
        .collect()
    }

    /// Replace the host's retired-branch-counter probe, for a `RunOpts` built
    /// outside clap's parse of `run`, such as `hermit analyze`'s trial options.
    pub(crate) fn set_inexact_branch_counter(&mut self, probe: fn() -> Option<String>) {
        self.inexact_branch_counter = probe;
    }

    /// Refuse `--timeout` on a backend where it has not been shown to bound the
    /// run, instead of accepting a flag that does nothing.
    ///
    /// ⚠️ MEASURED PER BACKEND, 2026-08-26, `--timeout 3` against a guest that
    /// never exits, two runs each and reproducible:
    ///
    /// | backend    | elapsed | marker                        |
    /// |------------|---------|-------------------------------|
    /// | `ptrace`   | 3s      | `class=run-timeout`           |
    /// | `liteinst` | 3s      | `class=run-timeout`           |
    /// | `kvm`      | 13s     | `HERMIT_RUN_TIMEOUT_FALLBACK` |
    /// | `sabre`    | 40s     | none -- killed by the harness |
    /// | `dbt`      | 20s     | none -- killed by the harness |
    ///
    /// The `liteinst` row measured the ptrace-hosted hybrid, which no longer
    /// exists. In-guest LiteInst refuses `--timeout` earlier, in
    /// `refuse_unqualified_liteinst_in_guest_options`, so it never reaches this
    /// check.
    ///
    /// ⚠️ `sabre` AND `dbt` ARE NOT MERELY UNTESTED -- THEY STRUCTURALLY CANNOT
    /// HONOUR THE FLAG TODAY, and the difference decides what fixing them means.
    /// Neither BOUNDED THE RUN AT ALL: the elapsed times are the outer harness's
    /// own deadline, and the absence of a marker is precisely the "exit 124 with
    /// no marker means no inner bound fired" reading in docs/TIMEOUT_LADDER.md.
    /// Both run fine WITHOUT the flag, so it is the bound that fails.
    ///
    /// The mechanism is visible on `sabre`, which panicked in
    /// `reverie-rpc-transport`'s blocking client after 69 seconds with a broken
    /// pipe: a BLOCKING call cannot yield to the single `current_thread` tokio
    /// runtime that `tokio::time::timeout` needs in order to fire, so the primary
    /// path is never reached. `dbt` shows the same total absence of a bound and
    /// is a launch adapter around DynamoRIO, so it is plausibly the same class --
    /// but that has NOT been traced and must not be asserted.
    ///
    /// So do not "qualify" one of these by running the flag once and seeing it
    /// accepted; acceptance is exactly what already happens and it does nothing.
    ///
    /// `kvm` is excluded for a different and softer reason: it does bound the
    /// run, but ONLY through the hard `_exit` fallback, ten seconds late and
    /// with no unwind. Allowing it would mean the marker that is supposed to
    /// mean "the unwind failed" fires on every single KVM timeout, which
    /// destroys the signal the marker exists to carry. Qualify it by finding out
    /// why the runtime never reaches the timer, not by widening this list.
    ///
    /// Fail-closed, so a NEW backend must be qualified deliberately rather than
    /// inheriting a guarantee nobody measured for it.
    pub(crate) fn ensure_timeout_supported(&self) -> Result<(), Error> {
        if self.timeout.is_none() {
            return Ok(());
        }
        let backend = self.runtime_backend();
        // in-guest-trap runs the in-guest LiteInst runtime, so it takes
        // liteinst's answer here; both are refused `--timeout` earlier by
        // `refuse_unqualified_liteinst_in_guest_options`.
        if matches!(
            backend,
            Backend::Ptrace | Backend::Liteinst | Backend::InGuestTrap
        ) {
            return Ok(());
        }
        Err(Error::new(PolicyRefusal).context(format!(
            "--timeout is not qualified on the `{backend:?}` backend and hermit will not \
             accept a bound it cannot enforce. Measured 2026-08-26 with `--timeout 3` on a \
             guest that never exits: ptrace and liteinst stopped at 3s and reported \
             `class=run-timeout`; kvm stopped only via the hard fallback at 13s; sabre and \
             dbt did not stop the run at all. Use an outer bound (the cell's \
             `timeout_seconds`, or `bin/safehermit --sh-deadline`) on this backend, and see \
             docs/TIMEOUT_LADDER.md."
        )))
    }

    fn run_in_container(
        &self,
        global: &GlobalOpts,
        capture_output: bool,
        identity_sources: Option<&IdentityGuard>,
    ) -> Result<(ExitStatus, Option<Output>), Error> {
        let _guard = global.init_tracing_for_backend(self.runtime_backend());
        hermit::proc_mount::warn_if_readonly_proc();

        let backend = self.runtime_backend();
        let command = self.guest_command()?;
        // The command has no `pre_exec` callback, so it installs no seccomp
        // filter.
        let config = complete_container_config(
            self.effective_det_config(),
            identity_sources,
            self.launch_workdir(),
        )?;

        let timeout = self.run_timeout();
        let summary_json = self.summary_json.clone();
        let result = if capture_output {
            let out = hermit::run_with_output_backend_timeout(
                command,
                config,
                self.summary,
                &summary_json,
                backend,
                timeout,
            )?;
            (out.status, Some(out))
        } else {
            let status = hermit::run_with_backend_timeout(
                command,
                config,
                self.summary,
                &summary_json,
                backend,
                timeout,
            )?;
            (status, None)
        };
        self.relabel_e9patch_dispatch_stats(&summary_json)?;
        Ok(result)
    }

    /// The e9patch spelling runs on the ptrace runtime, which records its
    /// dispatch as ptrace's. Attribute that record to e9patch, with the
    /// sites the rewrite measured; the tracer's stop counts stand, since a
    /// patched site still reaches it through a ptrace stop.
    fn relabel_e9patch_dispatch_stats(&self, summary_json: &Option<PathBuf>) -> Result<(), Error> {
        let (Some(path), Some(sites)) = (summary_json, self.e9patch_sites) else {
            return Ok(());
        };
        let mut summary: RunSummary = serde_json::from_slice(
            &fs::read(path)
                .with_context(|| format!("reading the e9patch run summary {}", path.display()))?,
        )
        .with_context(|| format!("parsing the e9patch run summary {}", path.display()))?;
        let Some(record) = summary.dispatch_stats.as_mut() else {
            return Ok(());
        };
        record.backend = Backend::E9patch.as_str().to_owned();
        record.sites = sites;
        fs::write(path, serde_json::to_string_pretty(&summary)? + "\n")
            .with_context(|| format!("writing the e9patch run summary {}", path.display()))
    }

    fn run_verify_in_container(
        &self,
        log_file: &mut Option<fs::File>,
        forwarded_detlogs: &mut ForwardedDetlogPlan,
        global: &GlobalOpts,
        identity_sources: Option<&IdentityGuard>,
        native: Option<NativeContainerRun>,
    ) -> Result<(Output, u64, RunLatches), Error> {
        let mut forwarded_detlogs = forwarded_detlogs.open_in_container()?;
        hermit::proc_mount::warn_if_readonly_proc();

        // HACK: Use interior mutability to workaround not being able to pass
        // `log_file` by value. Guaranteed by caller to never panic.
        let log_file = log_file.take().unwrap();

        let strictness = self.verification_strictness();
        let level = verification_log_level(global.log, strictness, self.verify_verbose);

        // Bound this log too. `hermit run --verify` opens its own file and
        // calls `init_file_tracing` directly instead of going through
        // `GlobalOpts::init_tracing`, so without this wrapper the bound that
        // was measured on exactly these `--verify` comparison logs would not
        // apply to the path that produces them: a livelocked run here could
        // still fill the disk.
        let limit = log_max_bytes().map_err(Error::msg)?;
        // SYNCHRONOUS, so a fatal diagnostic in the tail survives the run that
        // emitted it. The non-blocking appender loses whatever has not drained
        // when a fail-closed guest dies, which is precisely the line naming the
        // cause -- measured 0 of 18 runs versus 4 of 4. See
        // `init_sync_file_tracing`.
        // The coordinator writes forwarded records through this same writer, so
        // a record and a tracing event never share a line.
        //
        // `--max-log-bytes` counts these logs too, forwarded records as well
        // as tracing events, and its counter is shared across the verify runs,
        // so the cap is a total for the invocation.
        let log = verification_log(log_file, limit, global.log_budget());
        let _guard = init_sync_file_tracing(Some(level), log.clone(), self.runtime_backend());

        let command = self.guest_command()?;

        // The command has no `pre_exec` callback.
        let config = complete_container_config(
            self.effective_det_config(),
            identity_sources,
            self.launch_workdir(),
        )?;

        #[cfg(feature = "native-exec")]
        if let Some(native) = native {
            let (sender, receiver) = forwarded_detlogs.take().ok_or_else(|| {
                Error::msg("native exec requires the actual verification DETLOG source")
            })?;
            detcore::detlog::set_forwarded_source(receiver, log.record_sink());
            let policy = hermit::in_guest_detlog_forward_policy_for_native();
            let mut config = hermit::prepare_backend_config(config, Backend::InGuestTrap);
            config.in_guest_site_patching_off = true;
            config.in_guest_detlog_forward_policy = Some(policy.encode());
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()?;
            let result = runtime.block_on(super::native_exec_run::run(
                super::native_exec_run::PhysicalRun {
                    command,
                    config,
                    root: native.root,
                    runtime_files: native.runtime_files,
                    artifacts: native.artifacts,
                    endpoints: native.endpoints,
                    detlog_sender: sender,
                    print_summary: self.summary,
                    summary_json: self.summary_json.clone(),
                },
            ));
            detcore::detlog::clear_forwarded_source();
            let output = result?;
            let _ = log.clone().flush();
            let latches = RunLatches {
                determinism_loss: detcore::detlog::determinism_loss(),
                log_sink_failure: log.failure(),
            };
            return Ok((output, 0, latches));
        }
        #[cfg(not(feature = "native-exec"))]
        let _ = native;
        let forwarding = forwarded_detlogs.take().map(|(sender, receiver)| {
            hermit::forward_in_guest_detlogs_to(sender);
            detcore::detlog::set_forwarded_source(receiver, log.record_sink());
        });
        let result = hermit::run_with_output_backend_timeout_and_skid_overshoots(
            command,
            config,
            self.summary,
            &self.summary_json,
            self.runtime_backend(),
            None,
        );
        if forwarding.is_some() {
            // Records sent after the guest's last request, then close the socket.
            detcore::detlog::clear_forwarded_source();
        }
        let (output, skid_overshoots) = result?;
        self.relabel_e9patch_dispatch_stats(&self.summary_json)?;
        // A flush error counts too.
        let _ = log.clone().flush();
        let latches = RunLatches {
            determinism_loss: detcore::detlog::determinism_loss(),
            log_sink_failure: log.failure(),
        };
        Ok((output, skid_overshoots, latches))
    }
}

/// The error that ends a verification whose first run's status `verify_allow`
/// rejects, after publishing its report to `verify_json`, or `None` when the
/// status is allowed. A rejected run that overshot its PMU skid is that
/// infrastructure error; otherwise the report records the rejected
/// disposition, so it is not mistaken for a run that never started. Shared by
/// `run --verify`, which then does not start a second run, and `hermit
/// log-diff --verify-json`, which then does not compare.
pub(super) fn reject_first_run(
    verify_json: Option<&Path>,
    verify_allow: VerifyAllow,
    out1: &Output,
    skid_overshoots_run1: u64,
    summary1: Option<&RunSummary>,
) -> Option<Error> {
    if verify_allow.satisfies(out1.status) {
        return None;
    }
    if skid_overshoots_run1 > 0 {
        if let Some(path) = verify_json
            && let Err(error) = write_skid_overshoot_without_comparison_json(
                path,
                skid_overshoots_run1,
                verification_runtime_from_summaries(summary1, None),
                Some(out1.status),
            )
        {
            return Some(error);
        }
        return Some(Error::new(SkidOvershootError::new(skid_overshoots_run1)));
    }
    let status = describe_exit_status(out1.status);
    eprintln!(
        "First run errored during --verify, not continuing to a second.\nExit status: {status}\nStdout:\n{}\nStderr:\n{}",
        String::from_utf8_lossy(&out1.stdout),
        String::from_utf8_lossy(&out1.stderr),
    );
    // ⚠️ RECORD THE DISPOSITION HERE, WHERE IT IS KNOWN. The pre-stamped
    // `no_result` record was previously left untouched on this path -- so the
    // artifact reported `guest_exit_code: null` for a guest whose exit code we
    // had. That made this refusal byte-identical to a container that never
    // ran the guest, and 14 rotating e2e failures were undiagnosable as a
    // direct result. A best-effort write: an unwritable artifact must not
    // convert a rejected first run into a different error.
    if let Some(path) = verify_json {
        let report =
            first_run_rejected_report(out1, verification_runtime_from_summaries(summary1, None));
        if let Err(error) = write_report_json(path, &report) {
            eprintln!(
                "WARNING: could not record the rejected first run in {}: {}",
                path.display(),
                error
            );
        }
    }
    Some(Error::msg(format!("First run during --verify {status}")))
}

/// How a `--verify-run` execution that returned `error` ended, classified as
/// `run --verify` classifies the same error of one of its runs.
pub(super) fn verify_run_outcome_of(error: &Error) -> verify_run::VerifyRunOutcome {
    if let Some(overshoot) = error.downcast_ref::<SkidOvershootError>() {
        return verify_run::VerifyRunOutcome::SkidOvershoot {
            count: overshoot.count(),
        };
    }
    if let Some(disposition) = super::verify::container_failure_of(error) {
        return verify_run::VerifyRunOutcome::ContainerFailed { disposition };
    }
    if let Some(failure) = super::verify::run_failure_of(error) {
        // A determinism loss names its run (`RunLatches::refuse_comparison`);
        // the comparison names it again by its place in the pair.
        let detail = match error.downcast_ref::<DeterminismLossRecorded>() {
            Some(loss) => format!("determinism loss recorded: {}", loss.reason),
            None => format!("{error:#}"),
        };
        return verify_run::VerifyRunOutcome::RunFailed { failure, detail };
    }
    verify_run::VerifyRunOutcome::Error {
        detail: format!("{error:#}"),
    }
}

/// One completed execution of a two-run verification: what
/// [`conclude_verification`] compares.
pub(super) struct CompletedVerificationRun<'a> {
    pub(super) output: &'a Output,
    /// The run's verification log, which the comparison consumes.
    pub(super) log: tempfile::TempPath,
    pub(super) skid_overshoots: u64,
    pub(super) summary: Option<RunSummary>,
    /// The host files the run's guest opened (`hermit::host_input_change`).
    pub(super) host_inputs: Option<std::io::Result<HostInputs>>,
}

/// How a two-run verification is concluded once both runs completed.
pub(super) struct VerificationConclusion<'a> {
    pub(super) verify_json: Option<&'a Path>,
    pub(super) comparison_options: ComparisonOptions,
    /// Completed backend facts supplement the common comparison.
    #[cfg(feature = "dbt")]
    pub(super) dbt: Option<super::backends::DbtVerificationComparison>,
    /// The backend both runs used.
    pub(super) backend: Backend,
    /// Whether both runs used `--passthru-opt`.
    pub(super) passthru_opt: bool,
}

/// Compare two completed verification runs, publish the report to the
/// conclusion's `verify_json`, and announce the outcome. This is the one
/// conclusion of a verification whose two runs completed: `run --verify`
/// reaches it after its second run, and `hermit log-diff --verify-json` after
/// reading two `--verify-run` directories. A skid overshoot in either run is
/// published as the infrastructure error it is and returned as one.
pub(super) fn conclude_verification(
    conclusion: VerificationConclusion<'_>,
    run1: CompletedVerificationRun<'_>,
    run2: CompletedVerificationRun<'_>,
) -> Result<VerificationOutcome, Error> {
    let VerificationConclusion {
        verify_json,
        mut comparison_options,
        #[cfg(feature = "dbt")]
        dbt,
        backend,
        passthru_opt,
    } = conclusion;
    let out1 = run1.output;
    let out2 = run2.output;
    let log1_path = run1.log;
    let log2_path = run2.log;
    let summary1 = run1.summary;
    let summary2 = run2.summary;
    // Say what was actually established. Buffer hashing is ON BY DEFAULT, so
    // this qualification is now reachable only when the caller has asked for
    // the weaker comparison with `--no-detlog-io-buffers`. With it, the
    // compared records carry no syscall output-buffer CONTENT -- Reverie
    // types many output buffers as bare pointers, so the record shows the
    // address and not the bytes -- and two runs whose buffers differ while
    // their return values agree compare equal. Measured on a netlink
    // `recvmsg` that returns a stable `Ok(1468)` while four payload bytes
    // vary, back when hashing was opt-in: this path reported "Determinism
    // verified" on a run that the same command with hashing enabled
    // reports as diverged. Claiming
    // determinism there was the defect, so the sentence now names its limit.
    let success_message = if !comparison_options.compare_io_buffers {
        // The "Determinism verified" marker is RETAINED verbatim and the
        // qualification appended after it. That is not politeness: ~95
        // Rust integration-test files under hermit-cli/tests assert on
        // that exact substring, so replacing the sentence would be a
        // project-wide contract change rather than a wording fix. Appending
        // keeps every consumer working while the reader still learns the
        // limit.
        "Success: deterministic. Determinism verified. NOTE: syscall \
         output-buffer CONTENT was not compared because \
         --no-detlog-io-buffers was given, so a divergence confined to a \
         buffer whose length is stable would not have been seen; drop that \
         flag to include it."
    } else {
        "Success: deterministic. Determinism verified."
    };
    let failure_message = "Failure: nondeterministic.";
    let skid_overshoots = run1.skid_overshoots.saturating_add(run2.skid_overshoots);
    if skid_overshoots > 0
        && let Some(path) = verify_json
    {
        write_skid_overshoot_without_comparison_json(
            path,
            skid_overshoots,
            verification_runtime_from_summaries(summary1.as_ref(), summary2.as_ref()),
            Some(out1.status),
        )?;
    }
    // A skid overshoot makes this verification an infrastructure error
    // below, whatever the comparison finds, so a log match is not the
    // verdict. `--keep-logs` then retains both logs, as every other error
    // path does, instead of the single golden log kept after a match.
    comparison_options.match_overridden |= skid_overshoots > 0;
    #[cfg(feature = "dbt")]
    if let Some(comparison) = &dbt {
        comparison.configure(&mut comparison_options);
    }
    // The comparison consumes both logs, so a host file change is placed
    // in its run's log now, and judged against the divergence below.
    let host_input_change = if skid_overshoots == 0 {
        run1.host_inputs
            .zip(run2.host_inputs)
            .and_then(|(first, second)| {
                place_host_input_change(first, second, [&log1_path, &log2_path])
            })
    } else {
        None
    };
    let mut outcome = compare_two_runs(
        ComparedRun {
            output: out1,
            log: log1_path,
            // Accurate on this path: `verify` calls `run_verify` twice, and
            // each call builds its own container and guest command and
            // reaches a separate tracer spawn, so these really are two
            // fresh executions of the guest.
            label: "run 1",
        },
        ComparedRun {
            output: out2,
            log: log2_path,
            label: "run 2",
        },
        comparison_options,
    )?;
    #[cfg(feature = "dbt")]
    let dbt_messages = dbt.map(|comparison| comparison.apply(&mut outcome));
    outcome.runtime = verification_runtime_from_summaries(summary1.as_ref(), summary2.as_ref());

    // A divergence that a host file changing during one run explains is
    // named as such: only a divergence is examined, and only a change
    // found before the divergence, by a comparison that compared
    // everything, explains it. On a backend that can run guest code
    // before Hermit observes it, an identical log prefix does not show
    // that the guest did not make the change itself, so the change is
    // reported without being named as the cause.
    let host_input_change = host_input_change
        .filter(|_| outcome.verdict == Verdict::Diverged)
        .filter(|(_, positions)| {
            explains_divergence(
                outcome.comparison.is_bitwise_parity(),
                *positions,
                outcome.first_divergent_record_positions,
            )
        })
        .map(|(difference, _)| difference.into_infrastructure_error())
        .filter(|change| {
            let unobserved = unobserved_guest_execution(backend, passthru_opt);
            if let Some(reason) = unobserved {
                eprintln!("HERMIT_HOST_INPUT_CHANGE_UNATTRIBUTED {change}; not named as the cause: {reason}");
            }
            unobserved.is_none()
        });

    // Emit the machine-readable verdict (if requested) before collapsing the
    // outcome to the historical exit-code convention. The verdict is recorded
    // whether or not the runs matched, and independent of the guest's own
    // exit status.
    if let Some(path) = verify_json {
        if skid_overshoots > 0 {
            write_skid_overshoot_verification_json(path, &outcome, skid_overshoots)?;
        } else if let Some(change) = &host_input_change {
            write_host_input_change_verification_json(path, &outcome, change.clone())?;
        } else {
            write_verification_json(path, &outcome)?;
        }
    }
    if skid_overshoots > 0 {
        return Err(Error::new(SkidOvershootError::new(skid_overshoots)));
    }
    #[cfg(feature = "dbt")]
    if let Some(messages) = dbt_messages {
        for message in messages {
            eprintln!(":: {message}");
        }
        eprintln!(":: DBT path confirmed: DynamoRIO client reported tool=Detcore");
    }
    announce_verification_outcome(&outcome, SecondRun::Rerun, success_message, failure_message);
    if let Some(change) = &host_input_change {
        // The divergence stays a failure; this names its cause.
        eprintln!("HERMIT_HOST_INPUT_CHANGED {change}");
    }
    Ok(outcome)
}

/// Represents a tmpfs location. There are different ways to construct `/tmp` for
/// the container and this encapsulates all of them.
enum Tmpfs {
    /// Use an existing path as `/tmp`.
    Path(PathBuf),

    /// Use a new temporary directory as `/tmp`.
    Temp(tempfile::TempDir),
}

impl Tmpfs {
    /// Returns the path to `/tmp`.
    pub fn path(&self) -> &Path {
        match self {
            Self::Path(path) => path,
            Self::Temp(temp) => temp.path(),
        }
    }
}

/// Complete `config` inside the container whose identity mounts are
/// `identity_sources`, or, with none (`--no-namespace`), in this process's own
/// namespace, on every backend. Either way the config gets a container mount
/// table, so Detcore renders the guest's mount files. The guest inherits this thread's
/// seccomp filters, as Hermit installs none besides the backend's own.
pub(super) fn complete_container_config(
    mut config: DetConfig,
    identity_sources: Option<&IdentityGuard>,
    launch_workdir: Option<&Path>,
) -> Result<DetConfig, Error> {
    config.inherited_seccomp = detcore::InheritedSeccomp::measure();
    // Each run of `--verify` is its own container, whose namespace numbers
    // its mounts afresh, so each builds its own table, from the same plan and
    // the same host facts. The table, the identity order and the namespace
    // they name come from one read (`IdentityGuard::container_mount_view`),
    // the snapshot a backend that checks its provenance keeps.
    let view = identity_sources
        .map(IdentityGuard::container_mount_view)
        .transpose()?;
    config.mount_id_assignment_order.clear();
    config.mountinfo_mount_ids_captured = true;
    match view {
        Some(view) => {
            config.mountinfo_root_rewrites = view.root_rewrites;
            config.mountinfo_mount_ids = view.order;
            config.mountinfo_mount_namespace = Some(view.namespace);
            config.container_mount_table = view.table;
        }
        // No container (`--no-namespace`): the guest runs in this process's
        // own namespace, where Hermit installed no mount, so its table is
        // that namespace's launch mounts (the guest's working directory's and
        // /tmp's) and base mountpoints, with the order from the same read.
        // Nothing here changes this process's namespace.
        None => {
            let namespace = hermit::current_mount_namespace()?;
            // `--workdir`, or the working directory the guest inherits ("."),
            // resolved as the guest's chdir resolves it: an absolute one
            // without Hermit's own working directory, and neither by asking
            // that directory for its name (it may have been removed).
            let launch_cwd = launch_workdir.unwrap_or(Path::new("."));
            let (table, order) = hermit::unplanned_container_mount_table(launch_cwd)?;
            config.mountinfo_root_rewrites = Vec::new();
            config.mountinfo_mount_ids = order;
            config.mountinfo_mount_namespace = Some(namespace);
            config.container_mount_table = Some(table);
        }
    }
    Ok(config)
}

/// Names recording `id` as the newest in `data_dir` (see
/// [`hermit::HermitData::note_latest`]). Best effort: the recording stays
/// reachable by its ID.
fn note_latest(data_dir: &Path, id: hermit::Id, asked: bool) {
    if let Err(error) = hermit::HermitData::with_dir(data_dir).note_latest(&id, asked) {
        crate::tracing::diagnostic_eprintln!(
            "hermit: could not name recording {id} as the newest in {}: {error:#}",
            data_dir.display()
        );
    }
}

/// Writes `DATA/<id>/manifest.json` for the network recording whose
/// manifest is `sibling`, naming its trace by absolute path, and names it
/// the newest recording.
fn store_network_manifest(
    data_dir: &Path,
    sibling: &Path,
    mut document: crate::manifest::Manifest,
) -> Result<(), Error> {
    let trace = document
        .artifacts
        .as_mut()
        .and_then(|artifacts| artifacts.network_trace.as_mut())
        .ok_or_else(|| anyhow::anyhow!("the network manifest names no trace"))?;
    let file = std::path::absolute(sibling.with_file_name(&trace.path))?;
    trace.path = file
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("network trace path {} is not UTF-8", file.display()))?
        .to_owned();
    let id: hermit::Id = document
        .id
        .parse()
        .with_context(|| format!("the manifest's id {:?} is not a recording ID", document.id))?;
    crate::manifest::write(
        &data_dir
            .join(id.to_string())
            .join(crate::manifest::MANIFEST_NAME),
        &document,
    )?;
    note_latest(data_dir, id, document.kind.moves_last());
    crate::manifest::prune(data_dir, crate::manifest::KEEP_MANIFEST_ONLY);
    Ok(())
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory;

    use super::*;

    fn forwarding_plan_options(forwarded: bool) -> RunOpts {
        let backend = if forwarded { "in-guest-trap" } else { "ptrace" };
        run_opts_for(&["hermit", "--backend", backend, "run", "--", "/bin/true"])
    }

    fn assert_channel_record(sender: &OwnedFd, receiver: &OwnedFd, record: &[u8]) {
        let sent = unsafe {
            libc::send(
                sender.as_raw_fd(),
                record.as_ptr().cast(),
                record.len(),
                libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
            )
        };
        assert_eq!(sent, record.len() as isize, "send exact channel record");
        let mut bytes = [0u8; 128];
        let received = unsafe {
            libc::recv(
                receiver.as_raw_fd(),
                bytes.as_mut_ptr().cast(),
                bytes.len(),
                libc::MSG_DONTWAIT,
            )
        };
        assert_eq!(received, record.len() as isize, "receive complete record");
        assert_eq!(&bytes[..record.len()], record);
    }

    fn assert_channel_empty_with_writer(receiver: &OwnedFd) {
        let mut poll = libc::pollfd {
            fd: receiver.as_raw_fd(),
            events: libc::POLLIN | libc::POLLHUP,
            revents: 0,
        };
        assert_eq!(unsafe { libc::poll(&mut poll, 1, 0) }, 0);
        assert_eq!(poll.revents, 0, "a live writer must prevent HUP");
        let mut byte = 0u8;
        let received = unsafe {
            libc::recv(
                receiver.as_raw_fd(),
                (&raw mut byte).cast(),
                1,
                libc::MSG_DONTWAIT,
            )
        };
        assert_eq!(received, -1, "an empty live source is not EOF");
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::EAGAIN)
        );
    }

    fn assert_channel_eof_after_last_writer(receiver: &OwnedFd) {
        let mut poll = libc::pollfd {
            fd: receiver.as_raw_fd(),
            events: libc::POLLIN | libc::POLLHUP,
            revents: 0,
        };
        assert_eq!(
            unsafe { libc::poll(&mut poll, 1, 250) },
            1,
            "last writer retirement must become observable while ancestor waits"
        );
        assert_ne!(
            poll.revents & libc::POLLHUP,
            0,
            "last writer must yield HUP"
        );
        assert_eq!(poll.revents & (libc::POLLERR | libc::POLLNVAL), 0);
        let mut byte = 0u8;
        assert_eq!(
            unsafe {
                libc::recv(
                    receiver.as_raw_fd(),
                    (&raw mut byte).cast(),
                    1,
                    libc::MSG_DONTWAIT,
                )
            },
            0,
            "last writer must yield actual recv EOF"
        );
    }

    #[test]
    fn forwarded_detlog_plan_record_reaches_eof_while_parent_waits() {
        let options = forwarding_plan_options(true);
        let plan = options.forwarded_detlog_plan().unwrap();
        assert!(plan.requires_socket());
        let ((), _guards) = options
            .launch_in_container(plan, "forwarded DETLOG test plan", None, |plan, _, _| {
                let (sender, receiver) = plan.open_in_container()?.expect("forwarded pair");
                assert_channel_record(
                    &sender,
                    &receiver,
                    &detcore::detlog::tagged_forwarded_message(
                        unsafe { libc::syscall(libc::SYS_gettid) as i32 },
                        1,
                        b"DETLOG retained record\n",
                    ),
                );
                drop(sender);
                assert_channel_eof_after_last_writer(&receiver);
                assert!(
                    plan.open_in_container().is_err(),
                    "one physical stream only"
                );
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn forwarded_detlog_plan_duplicate_writer_blocks_eof() {
        use std::os::fd::FromRawFd;

        let options = forwarding_plan_options(true);
        let plan = options.forwarded_detlog_plan().unwrap();
        let ((), _guards) = options
            .launch_in_container(plan, "duplicated forwarding writer", None, |plan, _, _| {
                let (sender, receiver) = plan.open_in_container()?.expect("forwarded pair");
                let raw = unsafe { libc::fcntl(sender.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) };
                assert!(raw >= 0);
                let duplicate = unsafe { OwnedFd::from_raw_fd(raw) };
                assert_channel_record(
                    &sender,
                    &receiver,
                    &detcore::detlog::tagged_forwarded_message(
                        unsafe { libc::syscall(libc::SYS_gettid) as i32 },
                        1,
                        b"DETLOG before last writer\n",
                    ),
                );
                drop(sender);
                assert_channel_empty_with_writer(&receiver);
                drop(duplicate);
                assert_channel_eof_after_last_writer(&receiver);
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn forwarded_detlog_plan_nonforwarded_opens_no_channel() {
        let options = forwarding_plan_options(false);
        let plan = options.forwarded_detlog_plan().unwrap();
        assert!(!plan.requires_socket());
        let ((), _guards) = options
            .launch_in_container(plan, "nonforwarding test plan", None, |plan, _, _| {
                assert!(!plan.requires_socket());
                assert!(plan.open_in_container()?.is_none());
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn forwarded_detlog_plan_two_runs_keep_streams_independent() {
        let options = forwarding_plan_options(true);
        let plans = (
            options.forwarded_detlog_plan().unwrap(),
            options.forwarded_detlog_plan().unwrap(),
        );
        let ((), _guards) = options
            .launch_in_container(
                plans,
                "independent forwarding plans",
                None,
                |(first, second), _, _| {
                    let (sender1, receiver1) = first.open_in_container()?.expect("first pair");
                    let (sender2, receiver2) = second.open_in_container()?.expect("second pair");
                    let first_identity =
                        detcore::detlog::socket_identity(receiver1.as_raw_fd()).unwrap();
                    let second_identity =
                        detcore::detlog::socket_identity(receiver2.as_raw_fd()).unwrap();
                    assert_ne!(first_identity, second_identity);
                    assert_channel_record(
                        &sender1,
                        &receiver1,
                        &detcore::detlog::tagged_forwarded_message(
                            unsafe { libc::syscall(libc::SYS_gettid) as i32 },
                            1,
                            b"DETLOG physical run one\n",
                        ),
                    );
                    assert_channel_empty_with_writer(&receiver2);
                    assert_channel_record(
                        &sender2,
                        &receiver2,
                        &detcore::detlog::tagged_forwarded_message(
                            unsafe { libc::syscall(libc::SYS_gettid) as i32 },
                            1,
                            b"DETLOG physical run two\n",
                        ),
                    );
                    assert_channel_empty_with_writer(&receiver1);
                    drop(sender1);
                    assert_channel_eof_after_last_writer(&receiver1);
                    assert_channel_empty_with_writer(&receiver2);
                    drop(sender2);
                    assert_channel_eof_after_last_writer(&receiver2);
                    Ok(())
                },
            )
            .unwrap();
    }

    #[test]
    #[cfg(feature = "native-exec")]
    fn native_observer_plan_reaches_eof_while_parent_waits() {
        let options = forwarding_plan_options(true);
        let staging = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();
        let endpoints =
            super::super::native_exec_run::NativeEndpoints::bind(staging.path()).unwrap();
        let ((), _guards) = options
            .launch_in_container(
                (staging, endpoints),
                "native observer test plan",
                None,
                |(_, endpoints), _, _| {
                    let (receiver, sender) = endpoints.open_observer_in_container()?;
                    assert_channel_record(&sender, &receiver, b"observer retained record");
                    drop(sender);
                    assert_channel_eof_after_last_writer(&receiver);
                    assert!(
                        endpoints.open_observer_in_container().is_err(),
                        "one observer stream only"
                    );
                    Ok(())
                },
            )
            .unwrap();
    }

    #[test]
    fn host_base_env_keeps_hermits_own_variables_from_the_guest() {
        let mut command = Command::new("/bin/true");
        apply_base_and_explicit_environment(&mut command, &BaseEnv::Host, &[]).unwrap();
        let removed: Vec<_> = command
            .get_envs()
            .filter(|(_, value)| value.is_none())
            .map(|(name, _)| name.to_owned())
            .collect();
        for name in [
            super::super::verify::VERIFY_TMPDIR_ENV,
            DAP_LISTEN_INNER_ENV,
        ] {
            assert!(
                removed.iter().any(|removed| removed == name),
                "{name} must not reach a guest with the host environment: removed {removed:?}"
            );
        }
    }

    #[test]
    fn a_green_run_removes_only_its_own_fatal_cores() {
        let dir = tempfile::tempdir().unwrap();
        let mine = fatal_core_owner_token();
        let theirs = fatal_core_owner_token();
        // Same controller process ID, as after PID reuse or in another PID
        // namespace sharing the directory, but a different invocation.
        assert_ne!(mine, theirs);
        assert_eq!(mine.split('-').next(), theirs.split('-').next());
        let files = [
            format!("hermit-{mine}-core.3.3.SIGSEGV.zst"),
            format!(".hermit-{mine}-core.4.4.SIGABRT.zst.tmp"),
            format!("hermit-{theirs}-core.3.3.SIGSEGV.zst"),
            format!(".hermit-{theirs}-core.4.4.SIGABRT.zst.tmp"),
            "unrelated".to_string(),
        ];
        for file in &files {
            fs::write(dir.path().join(file), b"x").unwrap();
        }
        assert_eq!(remove_fatal_core_files(dir.path(), &mine), 2);
        let mut left: Vec<_> = fs::read_dir(dir.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect();
        left.sort();
        let mut expected = files[2..].to_vec();
        expected.sort();
        assert_eq!(left, expected);
    }

    /// Fails its first write and accepts every later one.
    struct FailsOnce {
        failed: bool,
        written: std::sync::Arc<std::sync::Mutex<Vec<u8>>>,
    }

    impl Write for FailsOnce {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if !self.failed {
                self.failed = true;
                return Err(std::io::Error::other("injected write failure"));
            }
            self.written.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// The design's fault injection: the loss notice's write fails once and
    /// later writes recover, so the log reads complete apart from the notice.
    /// Verification must still refuse, from the latch.
    #[test]
    fn a_failed_log_write_refuses_comparison_after_later_writes_recover() {
        let written = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let log = SharedLog::new(FailsOnce {
            failed: false,
            written: written.clone(),
        });
        let mut sink = log.record_sink();
        sink(
            format!(
                "{} 0 0 lost under test\n",
                detcore::detlog::FORWARDING_LOSS_NOTICE
            )
            .as_bytes(),
        );
        sink(b"INFO detcore DETLOG [syscall] write(1, 0x1000, 5) = 5\n");
        let mut tracing_writer = log.clone();
        tracing_writer
            .write_all(b"a later tracing event\n")
            .unwrap();
        // The notice is gone from the log, and the later writes are there.
        let text = String::from_utf8(written.lock().unwrap().clone()).unwrap();
        assert!(!text.contains("lost under test"), "{text}");
        assert!(text.contains("DETLOG [syscall]"), "{text}");
        let latches = RunLatches {
            determinism_loss: None,
            log_sink_failure: log.failure(),
        };
        let refusal = latches.refuse_comparison("run 1").unwrap_err().to_string();
        assert!(
            refusal.contains("log sink failure: injected write failure"),
            "{refusal}"
        );
    }

    #[test]
    fn a_recorded_determinism_loss_refuses_comparison() {
        assert!(RunLatches::default().refuse_comparison("run 1").is_ok());
        let latches = RunLatches {
            determinism_loss: Some("in-guest process 7 exited without deregistering".to_string()),
            log_sink_failure: None,
        };
        let refusal = latches.refuse_comparison("run 2").unwrap_err().to_string();
        assert_eq!(
            refusal,
            "run 2: determinism loss recorded: in-guest process 7 exited without deregistering"
        );
    }

    /// https://github.com/rrnewton/hermit/pull/3686, restacked onto a main
    /// whose verification log is one writer shared by the tracing subscriber
    /// and the coordinator's forwarded in-guest records: `--max-log-bytes`
    /// charges the forwarded records too. Records alone, with no tracing
    /// event, cross the cap and end the process with the cap's exit code, and
    /// the log holds only what was written before the crossing.
    #[test]
    fn forwarded_records_alone_cross_the_log_cap() {
        let budget = super::super::tracing::LogBudget::new(100).unwrap();
        let file = tempfile::NamedTempFile::new().unwrap();
        let mut sink =
            verification_log(file.reopen().unwrap(), 1 << 20, Some(budget)).record_sink();
        let record = b"INFO detcore DETLOG [syscall] write(1, 0x1000, 5) = 5\n";
        // SAFETY: the child only calls the sink, which formats one line into a
        // new Vec, takes the uncontended mutex created above and writes to the
        // file, and then _exits.
        let child = unsafe { libc::fork() };
        assert!(
            child >= 0,
            "fork failed: {}",
            std::io::Error::last_os_error()
        );
        if child == 0 {
            // SAFETY: plain descriptor calls. The cap's final message goes to
            // stderr, so point it away from the test runner's.
            unsafe {
                let null = libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY);
                libc::dup2(null, 2);
            }
            for _ in 0..10 {
                sink(record);
            }
            // SAFETY: _exit has no preconditions.
            unsafe { libc::_exit(0) }
        }
        let mut status = 0;
        // SAFETY: waitpid writes only `status`.
        assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child);
        assert!(libc::WIFEXITED(status), "status {status:#x}");
        assert_eq!(
            libc::WEXITSTATUS(status),
            hermit::HERMIT_LOG_CAP_EXIT,
            "ten forwarded records of {} bytes each, against a cap of 100 bytes, did not end \
             the process with the log cap's exit code",
            record.len() + NORMALIZED_FORWARDED_DETLOG_TIMESTAMP.len() + 1
        );
        let mut expected = format!("{NORMALIZED_FORWARDED_DETLOG_TIMESTAMP} ").into_bytes();
        expected.extend_from_slice(record);
        assert_eq!(
            String::from_utf8_lossy(&fs::read(file.path()).unwrap()),
            String::from_utf8_lossy(&expected),
            "the log holds the one record admitted before the crossing, and not the crossing one"
        );
    }

    #[test]
    fn real_returned_guest_disposition_still_uses_first_run_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("verify.json");
        write_pending_verification_json(&path).unwrap();
        let output = run_verification_execution(Some(&path), VerificationRun::Run1, || {
            super::super::container::classify_container_result(Container::new().run(|| {
                Ok::<_, hermit::SerializableError>(Output {
                    status: ExitStatus::Signaled(reverie::process::Signal::SIGALRM, false),
                    stdout: b"returned guest output".to_vec(),
                    stderr: Vec::new(),
                })
            }))
        })
        .unwrap();
        let options = RunOpts::parse_from(["run", "--", "/bin/true"]);
        assert!(!options.verify_allow.satisfies(output.status));
        let report = first_run_rejected_report(&output, None);
        write_report_json(&path, &report).unwrap();
        let parsed = VerificationReport::from_current_json_slice(&fs::read(path).unwrap()).unwrap();
        assert!(matches!(
            parsed.no_result_reason,
            Some(NoResultReason::FirstRunRejected {
                signal: Some(libc::SIGALRM),
                ..
            })
        ));
        assert_eq!(parsed.guest_signal, Some(libc::SIGALRM));
        assert!(parsed.comparison.is_none());
    }

    #[test]
    fn first_run_rejected_report_keeps_available_guest_exit_code() {
        let output = Output {
            status: ExitStatus::Exited(23),
            stdout: b"out".to_vec(),
            stderr: b"error".to_vec(),
        };

        let report = first_run_rejected_report(&output, None);
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("verification.json");
        write_report_json(&path, &report).unwrap();
        let persisted = VerificationReport::from_current_json_value(
            serde_json::from_slice(&fs::read(path).unwrap()).unwrap(),
        )
        .unwrap();

        assert_eq!(persisted.guest_exit_code, Some(23));
        assert_eq!(persisted.guest_signal, None);
        assert_eq!(
            persisted.no_result_reason,
            Some(NoResultReason::FirstRunRejected {
                exit_code: Some(23),
                signal: None,
                stdout_bytes: 3,
                stderr_bytes: 5,
            })
        );
    }

    #[test]
    fn run_one_summary_is_empty_again_before_run_two() -> Result<(), Error> {
        let file = tempfile::NamedTempFile::new().unwrap();
        let summary = RunSummary {
            sched_turns: 12,
            virttime_elapsed: 34,
            syscalls: Some(5),
            ..Default::default()
        };
        fs::write(
            file.path(),
            serde_json::to_vec(&summary).expect("summary fixture serializes"),
        )
        .unwrap();

        let captured = take_verify_summary_before_next_run(file.path())?
            .expect("run one summary remains readable");
        assert_eq!(captured.sched_turns, 12);
        assert_eq!(captured.virttime_elapsed, 34);
        assert_eq!(captured.syscalls, Some(5));
        assert_eq!(fs::read(file.path()).unwrap(), b"");

        Ok::<(), Error>(())
    }

    #[test]
    fn ptrace_engagement_record_reads_the_typed_run_summary() {
        let summary_file = tempfile::NamedTempFile::new().unwrap();
        let engagement_file = tempfile::NamedTempFile::new().unwrap();
        let mut options = run_opts_for(&["hermit", "--backend=ptrace", "run", "/bin/true"]);
        options.summary_json = Some(summary_file.path().to_owned());
        options.backend_engagement_json = Some(engagement_file.path().to_owned());

        for scheduler_turns in [12, 13] {
            let summary = RunSummary {
                sched_turns: scheduler_turns,
                ..Default::default()
            };
            fs::write(summary_file.path(), serde_json::to_vec(&summary).unwrap()).unwrap();
            options.write_backend_engagement_after_run().unwrap();
            let report: BackendEngagementReport =
                serde_json::from_slice(&fs::read(engagement_file.path()).unwrap()).unwrap();
            assert_eq!(
                report.engagement,
                BackendEngagement::Ptrace { scheduler_turns }
            );
        }
    }

    #[test]
    fn e9patch_engagement_record_follows_the_preparation_value() {
        let engagement_file = tempfile::NamedTempFile::new().unwrap();
        let mut options = run_opts_for(&["hermit", "--backend=e9patch", "run", "/bin/true"]);
        options.backend_engagement_json = Some(engagement_file.path().to_owned());

        for (candidate_sites, mapped_sites, b0_sites) in [(0, 0, 0), (2, 2, 0)] {
            options.e9patch_engagement = Some(BackendEngagement::E9patch {
                candidate_sites,
                mapped_sites,
                b0_sites,
            });
            options.write_backend_engagement_after_run().unwrap();
            let report: BackendEngagementReport =
                serde_json::from_slice(&fs::read(engagement_file.path()).unwrap()).unwrap();
            assert_eq!(
                report.engagement,
                BackendEngagement::E9patch {
                    candidate_sites,
                    mapped_sites,
                    b0_sites,
                }
            );
        }
    }

    #[test]
    fn exit_status_diagnostic_reports_guest_exit_code_and_signal() {
        assert_eq!(
            describe_exit_status(ExitStatus::Exited(23)),
            "exited with code 23"
        );
        assert_eq!(
            describe_exit_status(ExitStatus::Signaled(
                reverie::process::Signal::SIGTERM,
                false,
            )),
            "terminated by signal 15 (SIGTERM)"
        );
        assert_eq!(
            describe_exit_status(ExitStatus::Signaled(
                reverie::process::Signal::SIGSEGV,
                true,
            )),
            "terminated by signal 11 (SIGSEGV) (core dumped)"
        );
    }

    #[test]
    fn verification_report_is_published_before_success_is_announced() {
        // Search only the code before this test module. Searching the whole
        // file let the literals below match themselves, so the ordering check
        // passed whatever the code did.
        let source = include_str!("run.rs")
            .split_once("#[cfg(test)]\nmod tests {")
            .expect("test module")
            .0;
        let verification = source
            .split_once("let mut outcome = compare_two_runs(")
            .expect("verification comparison")
            .1;
        let publish = verification
            .find("write_verification_json(path, &outcome)")
            .expect("verification report publication");
        let announce = verification
            .find("announce_verification_outcome(&outcome")
            .expect("verification announcement");
        assert!(publish < announce);
        // Run mode compares two independent runs, never a replay, so its match
        // line must not use the replay wording for the time note.
        let call = &verification[announce..];
        let call = &call[..call.find(");").expect("end of announcement call")];
        assert!(call.contains("SecondRun::Rerun"), "{call}");
    }

    /// A skid overshoot turns whatever the comparison finds into an
    /// infrastructure error (`SkidOvershootError`), so a log match is not the
    /// verdict, and `--keep-logs` must keep both logs, as every other error
    /// path does, instead of the golden log alone
    /// (https://github.com/rrnewton/hermit/issues/3301). `verify` says so by
    /// setting `match_overridden` on the options it compares with; verify.rs's
    /// `an_overridden_match_keeps_both_logs_in_the_failure_directory` and the
    /// overridden rows of `verification_log_retention_matches_the_cli_contract`
    /// pin what an overridden match retains. A skid overshoot cannot be
    /// provoked on demand, so the statement is pinned in the source.
    #[test]
    fn skid_overshoot_overrides_a_log_match_for_retention() {
        let source = include_str!("run.rs");
        // Search only the production code: this test names the statements it
        // looks for, so the whole file always contains them.
        let production = source
            .split_once("\n#[cfg(test)]\nmod tests {")
            .expect("run.rs has a test module")
            .0;
        let total =
            "let skid_overshoots = run1.skid_overshoots.saturating_add(run2.skid_overshoots);";
        let overridden = "comparison_options.match_overridden |= skid_overshoots > 0;";
        let compared = "let mut outcome = compare_two_runs(";
        for statement in [total, overridden, compared] {
            assert_eq!(
                production.matches(statement).count(),
                1,
                "run.rs must contain `{statement}` exactly once"
            );
        }
        let total_at = production.find(total).unwrap();
        let overridden_at = production.find(overridden).unwrap();
        let compared_at = production.find(compared).unwrap();
        assert!(
            total_at < overridden_at && overridden_at < compared_at,
            "the skid total must mark the match overridden before the runs are compared"
        );
        // The DBT facts may add an override but must preserve a prior one;
        // the facts test exercises both initial values. No other mutation of
        // the comparison options belongs between the skid override and use.
        let between = &production[overridden_at + overridden.len()..compared_at];
        let add_backend_facts = "comparison.configure(&mut comparison_options);";
        assert_eq!(between.matches(add_backend_facts).count(), 1);
        assert!(
            !between
                .replace(add_backend_facts, "")
                .contains("comparison_options"),
            "only the OR-preserving backend facts may update the options before comparison"
        );
        let call = &production[compared_at..];
        let call = &call[..call.find(")?;").expect("the comparison call ends")];
        assert!(
            call.trim_end().ends_with("comparison_options,"),
            "the runs must be compared with the options that carry the override:\n{call}"
        );
    }

    #[test]
    fn verification_log_flags_are_discoverable_and_old_print_spelling_still_parses() {
        let current = RunOpts::try_parse_from([
            "run",
            "--verify",
            "--print-verify-logs",
            "--keep-logs",
            "--verify-log-dir",
            "/tmp/logs",
            "/bin/true",
        ])
        .unwrap();
        assert!(current.print_verify_logs);
        assert!(current.keep_logs);
        assert_eq!(current.verify_log_dir, Some(PathBuf::from("/tmp/logs")));

        let compatible =
            RunOpts::try_parse_from(["run", "--verify", "--verify-logs", "/bin/true"]).unwrap();
        assert!(compatible.print_verify_logs);

        let mut help = Vec::new();
        RunOpts::command().write_long_help(&mut help).unwrap();
        let help = String::from_utf8(help).unwrap();
        assert!(help.contains("--print-verify-logs"));
        assert!(help.contains("--keep-logs"));
        assert!(help.contains("--verify-log-dir"));
        assert!(!help.contains("--verify-logs"));

        assert!(
            RunOpts::try_parse_from([
                "run",
                "--verify",
                "--verify-log-dir",
                "/tmp/logs",
                "/bin/true",
            ])
            .is_err(),
            "a retention directory without --keep-logs must be refused"
        );
    }

    #[test]
    fn user_selected_retention_directory_is_resolved_and_created() {
        let parent = tempfile::tempdir().unwrap();
        let requested = parent.path().join("retained");
        let options = RunOpts::try_parse_from([
            "run",
            "--verify",
            "--keep-logs",
            "--verify-log-dir",
            requested.to_str().unwrap(),
            "/bin/true",
        ])
        .unwrap();
        assert_eq!(
            options.retained_verify_log_dir().unwrap(),
            Some(fs::canonicalize(requested).unwrap())
        );
    }

    #[test]
    fn extracts_forwarded_detlogs_and_preserves_guest_stderr() {
        let coordinator = "2026-08-02T00:00:00.000000Z INFO detcore: coordinator message\n";
        let log = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(log.path(), coordinator).unwrap();
        // SaBRe: records share the guest's stderr and are found by their text, as
        // before; every other line stays.
        let mut stderr = b"guest stderr\n INFO detcore: inbound syscall: getpid() = ?\n\
              INFO detcore: DETLOG scheduler event\n\
              INFO detcore: DETLOG [syscall] finish syscall #1: getpid() = Ok(3)\n"
            .to_vec();
        let syscall_records = extract_forwarded_detlogs(log.path(), &mut stderr, 0, false).unwrap();
        assert_eq!(syscall_records, 1);
        assert_eq!(
            stderr,
            b"guest stderr\n INFO detcore: inbound syscall: getpid() = ?\n"
        );
        assert_eq!(
            std::fs::read_to_string(log.path()).unwrap(),
            format!(
                "{coordinator}\
                 1970-01-01T00:00:00.000000Z INFO detcore: DETLOG scheduler event\n\
                 1970-01-01T00:00:00.000000Z INFO detcore: DETLOG [syscall] finish syscall #1: getpid() = Ok(3)\n"
            ),
        );

        // In-guest LiteInst: the socket carries nothing but records.
        let log = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(log.path(), coordinator).unwrap();
        let mut records = b"INFO detcore::tool_local: DETLOG local state\n\
              INFO detcore: DETLOG [syscall] finish syscall #2: getppid() = Ok(1)\n"
            .to_vec();
        assert_eq!(
            extract_forwarded_detlogs(log.path(), &mut records, 0, true).unwrap(),
            1
        );
        assert!(records.is_empty());

        // A record the Tool could not send, or anything else, refuses the run.
        for (stream, expected) in [
            (
                format!(
                    "INFO detcore: DETLOG [syscall] kept\n{} 16777300 90\n",
                    detcore::detlog::FORWARDING_LOSS_NOTICE
                ),
                "could not forward 1 DETLOG record",
            ),
            (
                "INFO detcore: DETLOG [syscall] kept\nstray\n".to_owned(),
                "bytes outside any record",
            ),
        ] {
            let log = tempfile::NamedTempFile::new().unwrap();
            std::fs::write(log.path(), coordinator).unwrap();
            let mut stream = stream.into_bytes();
            let error = extract_forwarded_detlogs(log.path(), &mut stream, 0, true).unwrap_err();
            assert!(error.to_string().contains(expected), "{error:#}");
        }
    }

    /// Forwarded records are appended within the log's size bound, counting the
    /// bytes already in it, and the log still ends in the truncation marker the
    /// comparators look for, so a run whose records were cut compares as no
    /// result. A log the bound already truncated gets nothing appended.
    #[test]
    fn forwarded_detlogs_respect_the_log_bound_and_keep_its_truncation_marker() {
        let records = |count: usize| {
            let mut bytes = Vec::new();
            for index in 0..count {
                bytes.extend_from_slice(
                    format!("INFO detcore: DETLOG [syscall] finish syscall #{index}\n").as_bytes(),
                );
            }
            bytes
        };
        let coordinator = "2026-08-02T00:00:00.000000Z INFO detcore: coordinator message\n";

        // Records that would cross the bound are cut, and the marker ends the log.
        let log = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(log.path(), coordinator).unwrap();
        let mut stream = records(100);
        let limit = coordinator.len() as u64 + 200;
        assert_eq!(
            extract_forwarded_detlogs(log.path(), &mut stream, limit, true).unwrap(),
            100
        );
        let text = std::fs::read_to_string(log.path()).unwrap();
        assert!(detcore::logdiff::log_was_truncated(&text), "{text}");
        assert!(text.starts_with(coordinator), "{text}");

        // A log the bound already truncated keeps the marker on its last line.
        let truncated = std::fs::read(log.path()).unwrap();
        let mut stream = records(3);
        extract_forwarded_detlogs(log.path(), &mut stream, 0, true).unwrap();
        assert_eq!(std::fs::read(log.path()).unwrap(), truncated);

        // Within the bound nothing is cut.
        let log = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(log.path(), coordinator).unwrap();
        let mut stream = records(2);
        extract_forwarded_detlogs(log.path(), &mut stream, 1 << 20, true).unwrap();
        let text = std::fs::read_to_string(log.path()).unwrap();
        assert!(!detcore::logdiff::log_was_truncated(&text), "{text}");
        assert_eq!(text.lines().count(), 3);
    }

    /// The four branches of [`summary_dir_under`].
    ///
    /// ⚠️ THESE EXIST BECAUSE THE FIRST VERSION OF THIS CHANGE HAD NO TEST THAT
    /// COULD REACH IT. Its tests lived in `hermit-manifest-plan` and asserted
    /// that a file under `ignored/` is not enumerated as source -- true, useful,
    /// and silent about whether anything ever writes one there. A private
    /// `src/bin` item is not importable from another crate, so that surface
    /// could not name this function even in principle. Two readers found it; I
    /// had already found and fixed a narrower blind spot in the same tests and
    /// still missed that the whole set was inert. Hence: same file, same crate,
    /// driving the function itself.
    #[test]
    fn summary_dir_is_the_work_tree_disposable_directory() {
        let tmp = tempfile::tempdir().expect("fixture root");
        let root = tmp.path();
        std::fs::create_dir(root.join(".git")).expect("fixture work tree");
        std::fs::write(root.join(".gitignore"), "/ignored/\n").expect("fixture ignore rule");

        // From the root.
        let chosen = summary_dir_under(root).expect("resolving from the work-tree root");
        assert_eq!(chosen, root.join("ignored"));
        assert!(chosen.is_dir(), "the disposable directory was not created");

        // From a subdirectory: the enumeration is rooted at the work tree, so a
        // summary in a tracked subdirectory would still be counted as source.
        let nested = root.join("hermit-cli").join("src");
        std::fs::create_dir_all(&nested).expect("fixture subdirectory");
        assert_eq!(
            summary_dir_under(&nested).expect("resolving from a subdirectory"),
            root.join("ignored"),
            "a summary resolved relative to the subdirectory rather than the work tree"
        );
    }

    #[test]
    fn summary_dir_outside_a_work_tree_is_unchanged() {
        let tmp = tempfile::tempdir().expect("fixture root");
        let plain = tmp.path().join("not-a-checkout");
        std::fs::create_dir(&plain).expect("fixture directory");
        assert_eq!(
            summary_dir_under(&plain).expect("resolving outside a work tree"),
            plain,
            "the previous behaviour must be kept where nothing enumerates source"
        );
    }

    /// A `.git` in an ancestor that does not ignore `ignored/` must be skipped.
    ///
    /// MEASURED on this host: `/tmp/.git` exists. An earlier version of this
    /// walk accepted any ancestor carrying a `.git`, so a run started in any
    /// temporary directory resolved its work tree to `/tmp` and would have
    /// written the summary to `/tmp/ignored` -- not the project, and not
    /// visible to both run containers, which is the property the whole
    /// arrangement exists to preserve. This test found it; I had not predicted
    /// it.
    #[test]
    fn a_stray_git_that_does_not_ignore_the_directory_is_not_a_work_tree() {
        let tmp = tempfile::tempdir().expect("fixture root");
        let stray = tmp.path();
        std::fs::create_dir(stray.join(".git")).expect("fixture stray git");
        // No .gitignore at all, as in the real /tmp/.git case.
        let nested = stray.join("scratch");
        std::fs::create_dir(&nested).expect("fixture directory");
        assert_eq!(
            summary_dir_under(&nested).expect("resolving under a stray git"),
            nested,
            "a stray .git without an ignore rule was mistaken for the work tree"
        );

        // And one that DOES ignore it is accepted, so the check discriminates
        // rather than refusing everything.
        std::fs::write(stray.join(".gitignore"), "/ignored/\n").expect("fixture ignore rule");
        assert_eq!(
            summary_dir_under(&nested).expect("resolving under a real work tree"),
            stray.join("ignored"),
            "a work tree that does ignore the directory was rejected"
        );
    }

    /// Serialises the two tests that change the process working directory.
    ///
    /// `private_verify_summary` reads the cwd through `private_summary_dir`, so
    /// exercising the WRITER means setting it. That is process-global, so it
    /// cannot run beside another test that also depends on it.
    static CWD_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Both writers must route through the resolver, not merely agree with it.
    ///
    /// ⚠️ THIS IS THE THIRD LEVEL OF THE SAME DEFECT ON THIS CHANGE, and the
    /// reviewer found it by mutation: reverting BOTH writers to
    /// `tempfile_in(current_dir())` left every test green. The resolver tests
    /// prove `summary_dir_under` computes the right directory; they say nothing
    /// about whether anything calls it. A future writer, or a revert of either
    /// existing one, would restore the original defect undetected.
    ///
    /// The earlier two levels were: the first test could not see the real
    /// .gitignore, and then ALL of them sat in a crate that cannot reach a
    /// private `src/bin` item. Each level was found by a different reader.
    ///
    /// So this calls the writers and looks at where the file actually landed.
    /// Under the mutation the parent is the work tree itself rather than its
    /// disposable directory, and both assertions below fail.
    #[test]
    fn both_writers_put_their_summary_in_the_disposable_directory() {
        let _guard = CWD_GUARD
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let tmp = tempfile::tempdir().expect("fixture root");
        let root = tmp.path().canonicalize().expect("canonical fixture root");
        std::fs::create_dir(root.join(".git")).expect("fixture work tree");
        std::fs::write(root.join(".gitignore"), "/ignored/\n").expect("fixture ignore rule");

        let previous = std::env::current_dir().expect("saving the working directory");
        std::env::set_current_dir(&root).expect("entering the fixture work tree");
        let produced = [
            ("verification", private_verify_summary()),
            ("backend engagement", private_backend_engagement_summary()),
        ];
        std::env::set_current_dir(&previous).expect("restoring the working directory");

        let expected = root.join("ignored");
        for (what, result) in produced {
            let file = result.unwrap_or_else(|error| panic!("{what} summary: {error:#}"));
            let parent = file
                .path()
                .parent()
                .expect("a summary has a parent")
                .canonicalize()
                .expect("canonical summary parent");
            assert_eq!(
                parent,
                expected,
                "the {what} summary was written to {} rather than the disposable \
                 directory, so it is counted as prepared source again",
                parent.display()
            );
        }
    }

    /// The control, and the reviewer's own case: a regular FILE named `ignored`.
    ///
    /// `create_dir_all` fails, and the first version answered by returning the
    /// work tree itself -- silently putting the summary back exactly where the
    /// defect was. Refusing is the only safe direction inside a work tree.
    #[test]
    fn summary_dir_refuses_rather_than_falling_back_into_the_work_tree() {
        let tmp = tempfile::tempdir().expect("fixture root");
        let root = tmp.path();
        std::fs::create_dir(root.join(".git")).expect("fixture work tree");
        std::fs::write(root.join(".gitignore"), "/ignored/\n").expect("fixture ignore rule");
        std::fs::write(root.join("ignored"), b"not a directory").expect("fixture file");

        let error = summary_dir_under(root)
            .expect_err("a work tree that cannot hold the disposable directory must refuse");
        let rendered = format!("{error:#}");
        assert!(
            rendered.contains("refusing to fall back"),
            "the refusal did not say why it refused: {rendered}"
        );
    }
}