hermit-run 0.4.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
/*
 * 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.
 */

// Treat all Clippy warnings as errors.
#![deny(clippy::all)]
#![allow(clippy::uninlined_format_args)]

mod backend_stats;
pub mod build_info;
pub mod canonical_verdict;
mod chroot;
mod consts;
mod desync;
pub mod logdiff_report;
// TODO-HUMAN-REVIEW(PR-594): Review the public e9patch preprocessing API.
pub mod e9patch;
mod error;
mod event;
mod event_stream;
mod fd;
pub mod happens_before;
mod id;
pub mod instruction_map;
mod interp;
pub mod liteinst_bootstrap;
pub mod liteinst_record;
mod metadata;
pub mod proc_mount;
mod ptrace_completion;
pub mod run_evidence;

pub use canonical_verdict::Verdict;

/// Whether record/replay verification hashes syscall output buffers, and
/// therefore whether its log comparison can see buffer CONTENT at all.
///
/// ONE CONSTANT BECAUSE TWO INDEPENDENT SWITCHES HAD TO AGREE AND SILENTLY DID
/// NOT MATTER. Record/replay carried this decision twice: `metadata.rs`'s
/// `record_or_replay_config` decided whether the recorder EMITS the hash, and
/// `record_start.rs`'s `ComparisonOptions` decided whether the comparator READS
/// it. Both were hard-coded `false`, neither was reachable from the command
/// line, and nothing related them. Setting either alone achieves nothing: hash
/// without compare is dead weight, compare without hash finds nothing. Naming
/// the decision once makes the pair impossible to desynchronize, and makes
/// changing it a one-line edit in a place a reader can find.
pub const RECORD_REPLAY_HASHES_IO_BUFFERS: bool = true;

/// Whether record/replay virtualizes time. FALSE, DELIBERATELY, AND THAT IS WHY
/// A GREEN RECORD/REPLAY VERDICT IS NOT A DETERMINISM RESULT.
///
/// Named for the same reason as [`RECORD_REPLAY_HASHES_IO_BUFFERS`] directly
/// above: the decision was about to be carried twice. `metadata.rs`'s
/// `record_or_replay_config` sets the config the recorder and replayer run
/// under, and `record_start.rs`'s `ComparisonOptions` now discloses that setting
/// in the verdict. If those two disagreed, the report would describe a time
/// policy the run did not use — which is precisely the class of defect the
/// disclosure exists to close, reintroduced one layer up.
///
/// `hermit run --verify` reads its value from the live `det_config` instead,
/// because `--no-virtualize-time` makes it a genuine runtime choice there. Only
/// the record/replay path is a fixed decision, so only it gets a constant.
pub const RECORD_REPLAY_VIRTUALIZES_TIME: bool = false;

/// Exit status for a completed comparison that found a divergence.
///
/// This is the conventional `diff` result: zero means equal and one means
/// different. The verification JSON distinguishes it from a guest that exits
/// one of its own accord.
pub const HERMIT_VERIFICATION_DIVERGENCE_EXIT: i32 = 1;

/// Exit status for a failure of HERMIT ITSELF, as distinct from the guest's.
///
/// ⚠️ EVERY CLI ERROR USED TO BE `Exited(1)`, WHICH IS THE SINGLE MOST COMMON
/// GUEST FAILURE CODE. A tracer panic and a guest that exited 1 of its own
/// accord were therefore INDISTINGUISHABLE from `$?` alone — and every harness,
/// gate and script on this project decides pass/fail from exactly that value.
/// The information was not missing, only discarded: reverie's container reports
/// the child's real status as a typed `ExitStatus`, and hermit collapsed it to
/// prose and then to `1`.
///
/// WHY THIS DOES NOT BREAK THE "hermit's exit IS the guest's exit" CONTRACT.
/// That contract describes the case where the guest RAN AND EXITED, and it is
/// untouched: a guest status still flows through `raise_or_exit` unchanged, and
/// only the `Err` arm — where there is NO guest exit code, because hermit failed
/// before or instead of producing one — uses this value. The contract did not
/// cover that case; it does now.
///
/// WHY 125. It is the established convention for "the wrapper tool itself
/// failed" — GNU `env`, `chroot` and `timeout` all reserve 125 for exactly this,
/// leaving 126/127 for exec-level problems. It is not a value hermit emits
/// anywhere else.
///
/// ⚠️ THIS REDUCES A COLLISION, IT DOES NOT REMOVE ONE. A guest is free to exit
/// 125 deliberately, and every value in 0..=255 is a legal guest status, so no
/// code can be reserved outright. What it removes is the GUARANTEED collision
/// with the most common failure code. For an unambiguous signal, read the
/// `HERMIT_TASK_PANIC` marker on stderr or the verification JSON; this makes the
/// cheap check — `$?` — stop actively lying.
///
/// ⚠️ IT LIVES IN THE LIBRARY, NOT IN `main.rs`, AND THAT PLACEMENT IS THE FIX
/// FOR HOW IT WENT STALE. It was a private `const` inside the binary, so
/// `tests/cli.rs` — the only thing that asserts on it — could not name it and
/// wrote the number out by hand instead. When hermit#2558 moved the value from
/// `1` to `125`, the definition moved and the sixteen copies did not: eight cli
/// tests went red on main and stayed red, each failing an assertion about the
/// exit code rather than about the behaviour it exists to check. Same shape as
/// [`RECORD_REPLAY_HASHES_IO_BUFFERS`] above — a decision carried in two places
/// that had to agree and had no way to. Exported here, the tests move with it.
///
/// ⚠️ DO NOT FLIP EVERY `Some(1)` YOU FIND. `tests/stress_suite.rs`
/// asserts `Some(1)` as THE GUEST'S OWN SIGNAL, not as a stale copy of this
/// constant: there `Some(1) => GuestOutcome::Exposed`, and
/// `status.code() == Some(1)` IS the `exposes_bug` predicate. It is
/// pattern-identical to the tests that DID go stale, and it is the OPPOSITE
/// case -- the assertion is CORRECT and must not move with this constant.
///
/// ⚠️ ITS FAILURE MODE IS SILENT SUCCESS. Changing it to 125 would not
/// turn the stress suite red; it would make `exposes_bug` NEVER FIRE, so the
/// suite would report no bug exposed forever and pass while blind. A red is
/// recoverable; a green that cannot fail is not.
///
/// REVIEWER RULE: a change to `tests/stress_suite.rs` inside an exit-code head
/// SHOULD BE REFUSED ON SIGHT AND QUESTIONED.
pub const HERMIT_INTERNAL_FAILURE_EXIT: i32 = 125;

/// A deadline hermit itself was asked to enforce expired: **124**.
///
/// The status the container init exits with when a hermit-owned bound ends the
/// run -- `run --timeout`'s SIGALRM fallback here, and `record --record-timeout`'s
/// handler in `record_start.rs`, which has always used this value. 124 is the
/// established code for "a deadline fired" across GNU `timeout`, `safehermit`'s
/// wall bound and both hermit spellings, so this names an existing convention
/// rather than claiming a new number.
///
/// ⚠️ IT MUST BE READ AT THE CONTAINER BOUNDARY OR IT IS SILENTLY REWRITTEN TO
/// 125. Found only by forcing the fallback to fire, 2026-08-26: the init exited
/// 124, `classify_container_result` had no arm for it, and it fell through to
/// `ContainerChildExit` -- so the run reported `exit 125` and
/// `class=container-child-exit`, "the child died with a status it did not
/// pick", for a deadline hermit chose to enforce. Identical in shape to the
/// refusal that arrives as 122 and needs its own arm for the same reason.
pub const HERMIT_DEADLINE_EXIT: i32 = 124;

/// The guest program could not be found at all: **127**.
///
/// Exported for the same reason as [`HERMIT_INTERNAL_FAILURE_EXIT`] and with the
/// same history one step behind it. `GuestProgramFault::exit_code` wrote `127`
/// and `126` as bare literals, and `tests/cli.rs` had no way to name either, so
/// a test meaning "not found" and a test meaning "hermit refused" were asserted
/// with the same helper and the same number until the values diverged.
///
/// ⚠️ THIS IS NOT A SUBDIVISION OF HERMIT'S OWN FAILURE, AND THAT IS THE WHOLE
/// DISTINCTION. 125 says *hermit* broke; 127 and 126 say *the guest program* was
/// unusable and hermit correctly declined to start it. A caller that cannot tell
/// those apart cannot tell "fix my tooling" from "fix my command line".
pub const GUEST_PROGRAM_NOT_FOUND_EXIT: i32 = 127;

/// The guest program exists but cannot be executed as given: **126**.
///
/// See [`GUEST_PROGRAM_NOT_FOUND_EXIT`]. 127/126 are the GNU `env`/`chroot`/
/// `timeout` convention that 125 itself came from, so the three sit in one
/// scheme rather than being three unrelated numbers.
pub const GUEST_PROGRAM_NOT_EXECUTABLE_EXIT: i32 = 126;

// ⚠️ THE VALUES THEMSELVES ARE PINNED, NOT ONLY THEIR NAMES.
//
// Naming a constant makes every consumer agree with the definition; it does not
// make the definition right. Once `tests/cli.rs` asserts `Some(THE_CONSTANT)`
// everywhere, the whole suite is self-consistent and completely unanchored -- a
// one-character edit here would move all sixteen assertions with it and nothing
// would fail. That is the exact shape of the defect this scheme exists to close,
// displaced one level up, and it is why these are compile-time assertions rather
// than a comment: a deliberate edit "would be noticed" is the argument that
// already failed once, when hermit#2558 moved 1 -> 125 and sixteen copies went
// stale.
//
// WHY EACH VALUE AND NOT ANOTHER. GNU `env`, `chroot` and `timeout` reserve 125
// for "the wrapper itself failed", 127 for "command not found" and 126 for
// "found but not executable". Borrowing the whole scheme rather than one number
// is what keeps the three answers distinguishable from each other.
//
// ⚠️ THE EXIT-CODE ALLOCATION FOR THE `hermit` BINARY. ONE TABLE, HERE.
//
// Five separate exit-code defects were found in one evening and every one of
// them came from a value being chosen, copied or rewritten somewhere that could
// not see the others. This is the single place the space is allocated; anything
// that emits or rewrites a hermit exit status is a consumer OF this table and
// must not invent its own reading of it.
//
//   0          success.
//   1          HERMIT_VERIFICATION_DIVERGENCE_EXIT, matching `diff`; also a
//              legal guest status. Read the verification JSON to distinguish.
//   2 ..= 121  THE GUEST'S OWN STATUS, passed through untouched. (The range
//              stops at 121 because 122 is reserved below; a guest may still
//              CHOOSE any value, see the caveat at the end.)
//   122        HERMIT_POLICY_REFUSAL_EXIT -- hermit REFUSED the run under a
//              fail-closed policy. Hermit WORKED; the run was stopped on
//              purpose and the reason was printed. Distinct from 125 because
//              "hermit refused" and "hermit broke" demand opposite responses:
//              read the refusal and change your program or flags, versus file a
//              bug. Defined in `detcore-model` because `detcore` emits it and
//              this crate recognises it, and that is the only crate both
//              depend on.
//   123        DO NOT USE. dev-hermit's `bin/safehermit` LOG BYTE CAP kill.
//              It moved here FROM 125 so it would stop colliding with the line
//              below; taking 123 back would undo that.
//   124        DO NOT USE. GNU `timeout`'s deadline, and dev-hermit's
//              `bin/safehermit` WALL DEADLINE kill. `tests/cli.rs` asserts
//              `assert_ne!(code, Some(124))` on the awk-mincore probe.
//   125        HERMIT_INTERNAL_FAILURE_EXIT -- hermit itself failed, no guest
//              ran. Sole meaning as of 2026-08-25: `bin/safehermit` previously
//              also emitted 125 for its byte-cap kill, so a run through that
//              wrapper produced one number for two faults with opposite
//              remedies. SAFEHERMIT MOVED, NOT HERMIT, because that wrapper is
//              the only layer that knows which happened -- it relays hermit's
//              status otherwise -- and because 125/126/127 is one GNU scheme
//              that cannot be broken up. Tracked as `hermit_s_125_collides`.
//   126        GUEST_PROGRAM_NOT_EXECUTABLE_EXIT.
//   127        GUEST_PROGRAM_NOT_FOUND_EXIT -- the ABSOLUTE-PATH form. The
//              bare-name-on-guest-PATH form currently exits 125 instead, which
//              is an inconsistency tracked as `hermit_reports_a_missing`, not a
//              second meaning for 127.
//   128 + N    killed by signal N (shell convention). Hermit does not emit these
//              deliberately; a wrapper reporting a signal death must use them
//              rather than borrow a code that already means something.
//
// ⚠️ NO CODE IS EXCLUSIVELY HERMIT'S. Every value in 0..=255 is a legal guest
// status, so a guest may return 125 or 127 of its own accord and this table
// cannot stop it. The table removes GUARANTEED collisions, not possible ones.
// The only unambiguous discriminator is the `HERMIT_INTERNAL_FAILURE` marker on
// stderr, present exactly when hermit itself failed. Any consumer deciding on
// `$?` alone is guessing, and should say so.
//
// ⚠️ THE SAME ARGUMENT APPLIES TO 124, AND MORE SHARPLY, BECAUSE FIVE
// MECHANISMS PRODUCE IT. `hermit run --timeout`, its unwind fallback, `hermit
// record --record-timeout`, the `timeout(1)` wrapped around a manifest cell, and
// `safehermit`'s wall deadline all exit 124, and GNU `timeout` uses it for the
// same event. They demand different responses -- a slow guest, a wedged
// teardown inside hermit, a cell bound set too low, a run that escaped every
// inner bound -- so `$?` cannot route the reader to any of them.
//
// The discriminator is again the marker on stderr, and it is a CONTRACT rather
// than a diagnostic nicety: `class=run-timeout` for hermit's own bound (which
// also states the bound in seconds), `HERMIT_RUN_TIMEOUT_FALLBACK` for the
// unwind failing to complete, `safehermit: bound.wall=` for the cgroup reap.
// EXIT 124 WITH NO MARKER AT ALL MEANS NO INNER BOUND FIRED -- something outside
// hermit killed the run -- which is a configuration error and not a slow guest.
// The full picture, including which rung bounds which quantity and the
// strict-inequality invariant between them, is docs/TIMEOUT_LADDER.md.
//
// ⚠️ DO NOT CLAMP INTO THIS RANGE. `scripts/hermit-code-coverage.rs` used
// `clamp(1, 125)` and so rewrote 127 and 126 into 125 -- turning "your program is
// missing" into "hermit broke" and pointing the reader at the wrong project.
// Truncating a status does not lose information here, it MANUFACTURES a false
// attribution, because the ceiling is itself a meaning.
//
// ⚠️ WHAT EACH VALUE MUST NOT COLLIDE WITH -- AND 125 ALREADY DOES.
//
//   0    success. Never a failure code; see the nonzero pin below.
//   1    the commonest guest exit status. Sharing it is the collision
//        hermit#2558 introduced 125 to escape, so 125 must never drift back.
//   124  GNU `timeout`'s "deadline fired", and dev-hermit's `bin/safehermit`
//        uses it for its WALL DEADLINE kill. `tests/cli.rs` asserts
//        `assert_ne!(code, Some(124))` on the awk-mincore probe for that reason.
//   126  hermit's own GUEST_PROGRAM_NOT_EXECUTABLE_EXIT.
//   127  hermit's own GUEST_PROGRAM_NOT_FOUND_EXIT -- already in use for the
//        ABSOLUTE-PATH form of a missing guest program. Note the bare-name form
//        resolved against the guest PATH exits 125 instead, which is an
//        inconsistency filed separately, not a licence to reuse 127.
//
//   125  ⚠️ NOT FREE. dev-hermit's `bin/safehermit` exits 125 to mean "the LOG
//        BYTE CAP fired: safehermit killed the run through its cgroup"
//        (`demos/lib/demo_common.py`'s SAFEHERMIT_EXIT_REASON). Any hermit run
//        launched through that wrapper -- which is how the demos and the repeat
//        harness run it -- can therefore produce 125 for two unrelated reasons:
//        hermit refused, or the wrapper killed it for log volume. They demand
//        opposite responses (fix the invocation vs raise the cap), and `$?`
//        cannot tell them apart. This is a LIVE ambiguity, not a hypothetical:
//        demo 5 has been observed reporting `exited with status 125` when the
//        cap fired. It is recorded here rather than resolved because changing
//        either value is a cross-repository decision.
//
//        The discriminator meanwhile is the same one that separates hermit's 125
//        from a guest's own 125: the `HERMIT_INTERNAL_FAILURE` marker on stderr,
//        present only when hermit itself failed. safehermit writes its verdict
//        to its `--sh-report` file instead. Read one of those, never the number
//        alone.
//
// ⚠️ 0 IS THE DANGEROUS DRIFT, NOT 126 OR 127. Every one of these is asserted as
// `assert_eq!(code, Some(CONST))`. At 0 those assertions would stop demanding a
// FAILURE and start demanding a SUCCESS, and would still pass -- sixteen tests
// silently inverted. `tests/cli.rs` also asserts `!status.success()` beside the
// code for that reason; this pin is the second of the two locks.
const _: () = assert!(
    HERMIT_VERIFICATION_DIVERGENCE_EXIT == 1,
    "1 is the established diff-style result for a completed comparison that diverged"
);
const _: () = assert!(
    HERMIT_INTERNAL_FAILURE_EXIT == 125,
    "125 is the GNU wrapper-failed convention; 1 is the commonest guest status and 0 is success"
);
const _: () = assert!(
    GUEST_PROGRAM_NOT_FOUND_EXIT == 127,
    "127 is the GNU command-not-found convention and must stay distinct from 125 and 126"
);
const _: () = assert!(
    GUEST_PROGRAM_NOT_EXECUTABLE_EXIT == 126,
    "126 is the GNU found-but-not-executable convention and must stay distinct from 125 and 127"
);
const _: () = assert!(
    HERMIT_VERIFICATION_DIVERGENCE_EXIT != 0
        && HERMIT_INTERNAL_FAILURE_EXIT != 0
        && GUEST_PROGRAM_NOT_FOUND_EXIT != 0
        && GUEST_PROGRAM_NOT_EXECUTABLE_EXIT != 0,
    "a failure code of 0 would invert every assert_eq!(code, Some(CONST)) into demanding success"
);
mod record;
mod record_replay_path;
mod recorder;
mod replay;
mod replayer;
mod sabre_bootstrap;
mod sabre_ptrace;
mod script;

use std::ffi::OsStr;
use std::fs;
use std::io;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use std::time::Instant;

use anyhow::anyhow;
use clap::ValueEnum;
use consts::METADATA_NAME;
pub use detcore::Config as DetConfig;
pub use detcore::Detcore;
pub use detcore::RecordOrReplay;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_background_init_v2;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_name;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_pre_syscall;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_ready;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_thread_exit;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_thread_init;
#[doc(hidden)]
#[cfg(feature = "dbt")]
pub use detcore_dbt::reverie_dbt_runtime_totals;
pub use error::Context;
pub use error::Error;
pub use error::FailureKind;
pub use error::SerializableError;
use goblin::elf::Elf;
use goblin::elf::header;
use goblin::elf::section_header;
pub use id::Id;
use metadata::Metadata;
pub use ptrace_completion::HermitCleanupStage;
pub use ptrace_completion::HermitCleanupUnconfirmed;
pub use ptrace_completion::HermitPtraceFailure;
pub use ptrace_completion::RecoveryRefusal;
use record::Record;
use replay::Replay;
pub use reverie::ExitStatus;
use reverie::GlobalTool;
pub use reverie::process;
pub use reverie::process::Command;
pub use reverie::process::Mount;
pub use reverie::process::Namespace;
pub use reverie::process::Output;
pub use reverie::process::Stdio;
pub use script::Shebang;
use serde::Deserialize;
use serde::Serialize;

fn read_iovecs<M: reverie::syscalls::MemoryAccess>(
    memory: &M,
    message: &libc::msghdr,
) -> Result<Vec<libc::iovec>, reverie::Errno> {
    if message.msg_iovlen == 0 {
        return Ok(Vec::new());
    }
    let address = reverie::syscalls::Addr::from_raw(message.msg_iov as usize)
        .ok_or(reverie::Errno::EFAULT)?;
    let mut iovecs = vec![
        libc::iovec {
            iov_base: std::ptr::null_mut(),
            iov_len: 0,
        };
        message.msg_iovlen
    ];
    memory.read_values(address, &mut iovecs)?;
    Ok(iovecs)
}

fn vectored_offset(low: u64, high: u64) -> i64 {
    if std::mem::size_of::<usize>() == 8 {
        low as i64
    } else {
        ((high << 32) | (low & u32::MAX as u64)) as i64
    }
}

enum KvmStdinReservation {
    Open(fs::File),
    Closed,
}

static KVM_STDIN_RESERVATION: Mutex<Option<KvmStdinReservation>> = Mutex::new(None);

/// Saves stdin captured before Rust's process startup can reuse a closed fd 0.
pub fn reserve_kvm_stdin(stdin: Option<fs::File>) -> io::Result<()> {
    let mut reservation = KVM_STDIN_RESERVATION
        .lock()
        .map_err(|_| io::Error::other("KVM stdin reservation lock is poisoned"))?;
    if reservation.is_some() {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "KVM stdin is already reserved",
        ));
    }
    *reservation = Some(match stdin {
        Some(file) => KvmStdinReservation::Open(file),
        None => KvmStdinReservation::Closed,
    });
    Ok(())
}

fn duplicate_current_stdin() -> io::Result<Option<fs::File>> {
    // SAFETY: F_DUPFD_CLOEXEC duplicates fd 0 without taking ownership of it.
    let duplicate = unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_DUPFD_CLOEXEC, 3) };
    if duplicate >= 0 {
        // SAFETY: F_DUPFD_CLOEXEC returned a new owned descriptor.
        return Ok(Some(unsafe { fs::File::from_raw_fd(duplicate) }));
    }
    let error = io::Error::last_os_error();
    if error.raw_os_error() == Some(libc::EBADF) {
        Ok(None)
    } else {
        Err(error)
    }
}

fn ensure_kvm_stdin_reserved() -> io::Result<()> {
    let mut reservation = KVM_STDIN_RESERVATION
        .lock()
        .map_err(|_| io::Error::other("KVM stdin reservation lock is poisoned"))?;
    if reservation.is_none() {
        *reservation = Some(match duplicate_current_stdin()? {
            Some(file) => KvmStdinReservation::Open(file),
            None => KvmStdinReservation::Closed,
        });
    }
    Ok(())
}

fn reserved_kvm_stdin() -> Result<Option<fs::File>, Error> {
    ensure_kvm_stdin_reserved()?;
    let reservation = KVM_STDIN_RESERVATION
        .lock()
        .map_err(|_| io::Error::other("KVM stdin reservation lock is poisoned"))?;
    match reservation.as_ref() {
        Some(KvmStdinReservation::Open(file)) => Ok(Some(file.try_clone()?)),
        Some(KvmStdinReservation::Closed) => Ok(None),
        None => unreachable!("stdin reservation was initialized above"),
    }
}

/// A replayable snapshot of the guest's stdin for the output-capturing backends.
///
/// `hermit run --verify` executes the guest twice and compares the two runs. The
/// output-capturing backends historically fed the guest `Stdio::null()`, so any
/// data piped into hermit (`echo prog | hermit run --strict --verify -- ...`)
/// was silently dropped. Both runs then saw identical *empty* input and hermit
/// reported a false "deterministic" success even though the guest never received
/// its input. `Seekable` holds a read-only, rewindable file so both runs receive
/// the exact same bytes without being able to modify the caller's input; `None`
/// means stdin should be `/dev/null` (nothing to replay, or a terminal that
/// cannot be replayed identically to two runs).
enum StdinSnapshot {
    Seekable(fs::File),
    None,
}

static OUTPUT_STDIN_SNAPSHOT: Mutex<Option<StdinSnapshot>> = Mutex::new(None);

/// Records a rewindable snapshot of the process stdin so the output-capturing
/// backends can replay identical input to each run of `hermit run --verify`.
///
/// `stdin` is the descriptor captured before Rust startup could reuse a closed
/// fd 0 (see the binary's `startup_stdin`). A regular-file redirect is reopened
/// read-only; a pipe/fifo/socket is drained once into a seekable temporary file
/// and that file is reopened read-only. A terminal (or absent stdin) is treated
/// as `/dev/null` because a live terminal cannot be replayed identically to two
/// runs.
pub fn reserve_output_stdin_snapshot(stdin: Option<fs::File>) -> io::Result<()> {
    let snapshot = match stdin {
        None => StdinSnapshot::None,
        Some(mut file) => {
            // SAFETY: as_raw_fd borrows the descriptor without taking ownership.
            let is_tty = unsafe { libc::isatty(file.as_raw_fd()) } == 1;
            if is_tty {
                StdinSnapshot::None
            } else {
                let replay = if file.stream_position().is_ok() {
                    // Already seekable (e.g. `< file`): retain it below through
                    // a read-only descriptor with an independent file offset.
                    file
                } else {
                    // Non-seekable (pipe/fifo/socket): buffer once into a
                    // seekable temporary file so both --verify runs receive
                    // identical input.
                    //
                    // NAME THE WAIT BEFORE ENTERING IT. This `io::copy` reads to
                    // EOF, so a stdin that never reaches EOF -- an inherited socket,
                    // a fifo whose writer stays open -- blocks here FOREVER, before
                    // the guest has started. Measured: the process wedges with ZERO
                    // bytes on stdout and stderr and is only cleared by killing it,
                    // which is indistinguishable from a slow run. That
                    // indistinguishability is the whole harm; an unbounded wait that
                    // says what it is waiting for is merely slow, and a reader can
                    // act on it.
                    //
                    // Deliberately UNCONDITIONAL rather than emitted after a delay:
                    // a message that appears only once N seconds have passed makes
                    // hermit's own stderr depend on timing, and this project does
                    // not accept timing-dependent output. Deliberately NOT a
                    // deadline either -- a 12s slow producer is legitimate and
                    // delivers, and nothing can separate "slow" from "never" except
                    // by waiting. This changes no control flow: every input that
                    // worked before still works, byte for byte, on stdout.
                    eprintln!(
                        "hermit: --verify is buffering stdin from a non-seekable stream so both \
                         runs receive identical input. If this appears to hang, stdin has not \
                         reached end-of-file; pass `< /dev/null` when the guest needs no input."
                    );
                    let mut buffered = tempfile::tempfile()?;
                    io::copy(&mut file, &mut buffered)?;
                    buffered.seek(SeekFrom::Start(0))?;
                    buffered
                };

                // A duplicate would keep the original access mode. Reopen the
                // reserved descriptor read-only so neither verification run
                // can modify the caller's stdin or the next run's input.
                let replay_path = format!("/proc/self/fd/{}", replay.as_raw_fd());
                StdinSnapshot::Seekable(fs::File::open(replay_path)?)
            }
        }
    };
    let mut reservation = OUTPUT_STDIN_SNAPSHOT
        .lock()
        .map_err(|_| io::Error::other("output stdin snapshot lock is poisoned"))?;
    if reservation.is_some() {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "output stdin snapshot is already reserved",
        ));
    }
    *reservation = Some(snapshot);
    Ok(())
}

/// Returns a rewound descriptor for the reserved stdin snapshot, if any.
///
/// Each call rewinds the snapshot and hands back a fresh descriptor, so
/// repeated `--verify` runs read identical input from the start. Returns `None`
/// when no snapshot was reserved or the reserved stdin is a terminal/absent
/// (nothing to replay). Runs are sequential (each executes in its own forked
/// container child), so resetting the shared open file description's offset here
/// is safe.
fn output_backend_stdin_reservation() -> Result<(bool, Option<fs::File>), Error> {
    let mut reservation = OUTPUT_STDIN_SNAPSHOT
        .lock()
        .map_err(|_| io::Error::other("output stdin snapshot lock is poisoned"))?;
    match reservation.as_mut() {
        Some(StdinSnapshot::Seekable(file)) => {
            file.seek(SeekFrom::Start(0))?;
            Ok((true, Some(file.try_clone()?)))
        }
        Some(StdinSnapshot::None) => Ok((true, None)),
        None => Ok((false, None)),
    }
}

fn output_backend_stdin_file() -> Result<Option<fs::File>, Error> {
    Ok(output_backend_stdin_reservation()?.1)
}

/// Returns the stdin to hand a guest run in an output-capturing backend.
///
/// When [`reserve_output_stdin_snapshot`] has stored a replayable snapshot the
/// file is rewound and a fresh descriptor handed to the guest, so each
/// `--verify` run reads identical input. Otherwise (no snapshot reserved, or a
/// terminal/absent stdin) the guest gets `/dev/null`, matching the previous
/// behavior for callers that do not reserve a snapshot.
fn output_backend_stdin() -> Result<Stdio, Error> {
    match output_backend_stdin_file()? {
        Some(file) => Ok(Stdio::from(file)),
        None => Ok(Stdio::null()),
    }
}

/// The result of recording a command.
#[derive(Debug, Serialize, Deserialize)]
pub struct Recording {
    /// The unique ID of the recording.
    pub id: Id,

    /// The exit code of the command.
    pub exit_status: ExitStatus,
}

#[derive(Clone, Copy)]
enum CapabilityProbe {
    Namespaces,
    Ptrace,
    Seccomp,
}

fn run_capability_probe(probe: CapabilityProbe) -> Result<bool, Error> {
    // SAFETY: The child calls only async-signal-safe syscalls and exits immediately.
    let pid = unsafe { libc::fork() };
    if pid == -1 {
        return Err(std::io::Error::last_os_error()).context("Failed to fork capability probe");
    }
    if pid == 0 {
        let supported = match probe {
            CapabilityProbe::Namespaces => unsafe {
                libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWPID) == 0
            },
            CapabilityProbe::Ptrace => {
                // SAFETY: PTRACE_TRACEME ignores the pid and address arguments.
                unsafe {
                    libc::ptrace(
                        libc::PTRACE_TRACEME,
                        0,
                        std::ptr::null_mut::<libc::c_void>(),
                        std::ptr::null_mut::<libc::c_void>(),
                    ) != -1
                }
            }
            CapabilityProbe::Seccomp => {
                let mut filter = libc::sock_filter {
                    code: 0x06, // BPF_RET | BPF_K
                    jt: 0,
                    jf: 0,
                    k: 0x7fff0000, // SECCOMP_RET_ALLOW
                };
                let program = libc::sock_fprog {
                    len: 1,
                    filter: &mut filter,
                };
                // SAFETY: The filter is an allow-all program with a valid one-element lifetime.
                unsafe {
                    libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0
                        && libc::syscall(
                            libc::SYS_seccomp,
                            1, // SECCOMP_SET_MODE_FILTER
                            0,
                            &program,
                        ) == 0
                }
            }
        };
        // SAFETY: Avoid running Rust destructors after fork.
        unsafe { libc::_exit(i32::from(!supported)) }
    }

    let mut status = 0;
    loop {
        // SAFETY: pid is the child created above and status points to valid storage.
        let result = unsafe { libc::waitpid(pid, &mut status, 0) };
        if result == pid {
            return Ok(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0);
        }
        if result == -1 {
            let error = std::io::Error::last_os_error();
            if error.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(error).context("Failed to wait for capability probe");
        }
    }
}

fn validate_tracing_environment() -> Result<(), Error> {
    if !run_capability_probe(CapabilityProbe::Namespaces)? {
        anyhow::bail!(
            "Hermit cannot create its required user and PID namespaces: \
             unshare(CLONE_NEWUSER | CLONE_NEWPID) was denied. Allow unprivileged user namespaces \
             and the unshare syscall in the host/container policy."
        );
    }
    if !run_capability_probe(CapabilityProbe::Ptrace)? {
        anyhow::bail!(
            "Hermit cannot use ptrace in this environment: a child PTRACE_TRACEME probe was \
             denied. Allow same-UID parent-child ptrace in the container seccomp and host \
             Yama/LSM policy; CAP_SYS_PTRACE is normally not required. Use --namespace-only for \
             a sandbox smoke test without syscall interception."
        );
    }
    if !run_capability_probe(CapabilityProbe::Seccomp)? {
        anyhow::bail!(
            "Hermit cannot install its tracee seccomp filter: \
             seccomp(SECCOMP_SET_MODE_FILTER) was denied. Allow seccomp and \
             prctl(PR_SET_NO_NEW_PRIVS) in the container policy, or use --namespace-only for a \
             sandbox smoke test without syscall interception."
        );
    }
    Ok(())
}

#[cfg(feature = "dbt")]
fn is_dynamorio_sdk(path: &Path) -> bool {
    path.join("include/dr_api.h").is_file()
        || path.join("DynamoRIOConfig.cmake").is_file()
        || path.join("cmake/DynamoRIOConfig.cmake").is_file()
}

#[cfg(feature = "dbt")]
fn dynamorio_sdk_available() -> bool {
    if hermit_resources::resource("dynamorio/bin64/drrun")
        .is_ok_and(|path| path.is_some_and(|path| path.is_file()))
    {
        return true;
    }
    if reverie_dbt::bundled_drrun_path().is_file() {
        return true;
    }
    const DEFAULT_ROOTS: [&str; 3] = [
        "/usr/lib/cmake/DynamoRIO",
        "/usr/local/lib/cmake/DynamoRIO",
        "/opt/dynamorio",
    ];

    ["DYNAMORIO_HOME", "DynamoRIO_DIR"]
        .into_iter()
        .filter_map(std::env::var_os)
        .map(PathBuf::from)
        .chain(DEFAULT_ROOTS.into_iter().map(PathBuf::from))
        .any(|path| is_dynamorio_sdk(&path))
}

#[cfg(feature = "dbt")]
fn dbt_runtime_unavailable_reason() -> Option<String> {
    dbt_runtime_unavailable_reason_from(detcore_dbt::runtime_library_path())
}

#[cfg(feature = "dbt")]
fn dbt_runtime_unavailable_reason_from(runtime: io::Result<PathBuf>) -> Option<String> {
    runtime.err().map(|error| {
        format!(
            "the Detcore DBT runtime is unavailable: {error}; build the hermit binary and \
             cdylib in the same target directory"
        )
    })
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(#688): Review LiteInst runtime discovery.
/// Refuse a staged LiteInst runtime that was not built from the pin this binary
/// was built from.
///
/// ⚠️ THE STAGED RUNTIME CAN BE ARBITRARILY STALE AND NOTHING REPORTED IT. Two
/// independent causes, both silent: `hermit-install/build.rs` did not list the
/// pin-carrying manifests among its rerun triggers, so a pin bump left the
/// script "fresh"; and staging only runs under `PROFILE == release`, while the
/// e2e harness runs `target/debug/hermit`, so the ordinary loop never restaged.
/// The first is fixed at the trigger list. THIS is the guard for the second and
/// for any third cause nobody has found: it does not care WHY the artifact is
/// stale, only that it is.
///
/// A verdict produced against a stale runtime is a measurement of the old binary
/// published as a statement about the new pin. That is worse than a failure,
/// because it is a green.
fn liteinst_runtime_pin_matches(path: &Path) -> io::Result<()> {
    let expected = env!("HERMIT_REVERIE_PIN");
    if expected == "unknown" {
        // The build could not read the pin. Say nothing rather than assert a
        // match we cannot establish.
        return Ok(());
    }
    // Append rather than `with_extension("so.revision")`: the latter REPLACES the
    // final extension, so a caller-supplied `HERMIT_LITEINST_RUNTIME` pointing at
    // a versioned soname like `libreverie_liteinst.so.1` would look for
    // `libreverie_liteinst.so.so.revision` and refuse a correctly staged runtime.
    let marker = PathBuf::from(format!("{}.revision", path.display()));
    let staged = match fs::read_to_string(&marker) {
        Ok(text) => text.trim().to_owned(),
        Err(error) if error.kind() == io::ErrorKind::NotFound => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "the staged LiteInst runtime {} records no Reverie revision, so it cannot be \
                     shown to match the pin this binary was built from ({expected}). It was staged \
                     by a build that predates revision recording, which is exactly the case where a \
                     stale runtime went unnoticed. Restage it with `cargo build --release -p \
                     hermit-install` -- staging is release-only.",
                    path.display()
                ),
            ));
        }
        Err(error) => return Err(error),
    };
    if staged != expected {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "the staged LiteInst runtime {} was built from Reverie {staged}, but this binary \
                 was built from {expected}. Running it would measure the OLD runtime and report a \
                 verdict about the NEW pin. Restage with `cargo build --release -p hermit-install`.",
                path.display()
            ),
        ));
    }
    Ok(())
}

fn validate_liteinst_runtime_library(path: &Path) -> io::Result<PathBuf> {
    liteinst_runtime_pin_matches(path)?;
    validate_preload_constructor_library(
        path,
        "LiteInst runtime",
        &[
            "reverie_liteinst_initialize",
            "reverie_liteinst_site_trap_count",
            "reverie_liteinst_site_hook_count",
        ],
        "reverie_liteinst_initialize",
    )
}

/// Checks that `path` is an x86-64 shared object that exports every name in
/// `required` and registers `initializer_name` in its constructor array, so
/// that preloading it runs that initializer. `label` names the library in every
/// error message. Returns the canonical path.
fn validate_preload_constructor_library(
    path: &Path,
    label: &str,
    required: &[&str],
    initializer_name: &str,
) -> io::Result<PathBuf> {
    let bytes = fs::read(path).map_err(|error| {
        io::Error::new(
            error.kind(),
            format!("failed to read {label} {}: {error}", path.display()),
        )
    })?;
    let elf = Elf::parse(&bytes).map_err(|error| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{label} {} is not an ELF DSO: {error}", path.display()),
        )
    })?;
    if elf.header.e_type != header::ET_DYN || elf.header.e_machine != header::EM_X86_64 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{label} {} is not an x86-64 shared object", path.display()),
        ));
    }

    for &name in required {
        if !elf
            .dynsyms
            .iter()
            .any(|symbol| elf.dynstrtab.get_at(symbol.st_name) == Some(name))
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "{label} {} is missing required export {name}",
                    path.display()
                ),
            ));
        }
    }
    let (initializer_index, initializer) = elf
        .dynsyms
        .iter()
        .enumerate()
        .find(|(_, symbol)| elf.dynstrtab.get_at(symbol.st_name) == Some(initializer_name))
        .ok_or_else(|| {
            io::Error::other(format!(
                "checked {label} initializer {initializer_name} disappeared"
            ))
        })?;
    let init_array = elf
        .section_headers
        .iter()
        .find(|section| section.sh_type == section_header::SHT_INIT_ARRAY)
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("{label} {} has no constructor array", path.display()),
            )
        })?;
    let init_start = init_array.sh_addr;
    let init_end = init_start.saturating_add(init_array.sh_size);
    let relocated_initializer = elf
        .dynrelas
        .iter()
        .chain(elf.dynrels.iter())
        .any(|relocation| {
            (init_start..init_end).contains(&relocation.r_offset)
                && relocation.r_sym == initializer_index
        });
    let init_bytes = usize::try_from(init_array.sh_offset)
        .ok()
        .and_then(|start| {
            usize::try_from(init_array.sh_size)
                .ok()
                .and_then(|size| bytes.get(start..start.checked_add(size)?))
        })
        .unwrap_or_default();
    let direct_initializer = init_bytes
        .as_chunks::<8>()
        .0
        .iter()
        .any(|entry| u64::from_le_bytes(*entry) == initializer.st_value);
    if !relocated_initializer && !direct_initializer {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "{label} {} does not register {initializer_name} as a preload constructor",
                path.display()
            ),
        ));
    }
    path.canonicalize()
}

/// Returns the LiteInst preload cdylib produced beside the Hermit binary.
#[doc(hidden)]
pub fn liteinst_runtime_library_path() -> io::Result<PathBuf> {
    if let Some(path) = std::env::var_os("HERMIT_LITEINST_RUNTIME") {
        let path = PathBuf::from(path);
        if !path.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "HERMIT_LITEINST_RUNTIME does not name a regular file",
            ));
        }
        return validate_liteinst_runtime_library(&path).map_err(|error| {
            io::Error::new(
                error.kind(),
                format!("HERMIT_LITEINST_RUNTIME is invalid: {error}"),
            )
        });
    }

    let executable = std::env::current_exe()?;
    let directory = executable.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "Hermit executable has no parent directory",
        )
    })?;
    if let Some(path) = [
        directory.join("libreverie_liteinst.so"),
        directory.join("deps/libreverie_liteinst.so"),
    ]
    .into_iter()
    .find(|path| path.is_file())
    {
        return validate_liteinst_runtime_library(&path);
    }
    if let Some(path) = hermit_resources::resource("libreverie_liteinst.so")?
        && path.is_file()
    {
        return validate_liteinst_runtime_library(&path);
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        format!(
            "libreverie_liteinst.so was not built beside {} or staged as an installed resource",
            executable.display()
        ),
    ))
}

/// Environment variable that selects where `--backend=liteinst` runs Detcore.
///
/// Unset keeps the ptrace-hosted hybrid, which is still the default. `1` runs
/// Detcore's Tool inside the guest through the `detcore-liteinst` preload, with
/// no ptrace tracer on the syscall path
/// (<https://github.com/rrnewton/hermit/issues/3520>). Any other value is
/// refused.
pub const LITEINST_IN_GUEST_ENV: &str = "HERMIT_LITEINST_IN_GUEST";

/// Environment variable naming the in-guest Detcore preload
/// (`libdetcore_liteinst.so`) explicitly.
pub const LITEINST_TOOL_RUNTIME_ENV: &str = "HERMIT_LITEINST_TOOL_RUNTIME";

/// Where `--backend=liteinst` runs Detcore's Tool.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum LiteinstRuntime {
    /// Detcore runs in the Hermit process under a ptrace tracer; the guest
    /// preload patches sites and unpatched syscalls stop in ptrace.
    HostHybrid,
    /// Detcore's Tool runs in the guest (`detcore-liteinst`) and reaches its
    /// global state in Hermit over the coordinator socket.
    InGuest,
}

impl LiteinstRuntime {
    /// Parses a value of [`LITEINST_IN_GUEST_ENV`]; `None` means unset.
    pub fn parse(value: Option<&OsStr>) -> Result<Self, Error> {
        match value {
            None => Ok(Self::HostHybrid),
            Some(value) if value == OsStr::new("1") => Ok(Self::InGuest),
            Some(value) => Err(anyhow!(
                "{LITEINST_IN_GUEST_ENV}={:?} is not a LiteInst runtime selection: leave it unset \
                 for the ptrace-hosted hybrid, or set it to 1 for in-guest Detcore",
                value
            )),
        }
    }

    /// Reads [`LITEINST_IN_GUEST_ENV`] from this process's environment.
    pub fn from_env() -> Result<Self, Error> {
        Self::parse(std::env::var_os(LITEINST_IN_GUEST_ENV).as_deref())
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-3635): Review in-guest Detcore runtime discovery.
/// Returns the in-guest Detcore preload built beside the Hermit binary by
/// `cargo build -p detcore-liteinst`, or the one [`LITEINST_TOOL_RUNTIME_ENV`]
/// names.
///
/// Unlike the hybrid runtime, this library records no Reverie revision yet, so
/// a stale build is not detected. Staging it with a revision marker is part of
/// making in-guest the default (<https://github.com/rrnewton/hermit/issues/3520>).
#[doc(hidden)]
pub fn liteinst_tool_runtime_library_path() -> io::Result<PathBuf> {
    if let Some(path) = std::env::var_os(LITEINST_TOOL_RUNTIME_ENV) {
        let path = PathBuf::from(path);
        if !path.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("{LITEINST_TOOL_RUNTIME_ENV} does not name a regular file"),
            ));
        }
        return validate_liteinst_tool_runtime_library(&path).map_err(|error| {
            io::Error::new(
                error.kind(),
                format!("{LITEINST_TOOL_RUNTIME_ENV} is invalid: {error}"),
            )
        });
    }

    let executable = std::env::current_exe()?;
    let directory = executable.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "Hermit executable has no parent directory",
        )
    })?;
    if let Some(path) = [
        directory.join("libdetcore_liteinst.so"),
        directory.join("deps/libdetcore_liteinst.so"),
    ]
    .into_iter()
    .find(|path| path.is_file())
    {
        return validate_liteinst_tool_runtime_library(&path);
    }
    Err(io::Error::new(
        io::ErrorKind::NotFound,
        format!(
            "libdetcore_liteinst.so was not built beside {}",
            executable.display()
        ),
    ))
}

fn validate_liteinst_tool_runtime_library(path: &Path) -> io::Result<PathBuf> {
    validate_preload_constructor_library(
        path,
        "in-guest Detcore runtime",
        &["detcore_liteinst_initialize"],
        "detcore_liteinst_initialize",
    )
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-3635): Review the in-guest LiteInst library refusals.
/// In-guest LiteInst refused a run before starting its guest, because the
/// runtime cannot honour the request or could not monitor the program.
///
/// A type rather than a message, because it crosses the container error
/// boundary as [`error::FailureKind::PolicyRefusal`] (exit 122).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiteinstInGuestRefusal {
    reason: String,
}

impl LiteinstInGuestRefusal {
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
        }
    }
}

impl std::fmt::Display for LiteinstInGuestRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{LITEINST_IN_GUEST_ENV}=1 (in-guest LiteInst) refuses this run: {}",
            self.reason
        )
    }
}

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

/// Refuses, before the guest starts, an in-guest LiteInst run that the runtime
/// cannot honour or could not monitor.
///
/// - A maximum timeslice. Reverie's in-guest Tool host has no preemption timer:
///   its `set_timer` refuses with `ENOSYS`, and Detcore treats a failed
///   `set_timer` as fatal (`.expect("Failed to set timer")`), so the guest
///   would panic at its first scheduling point. The CLI refuses
///   `--max-timeslice` earlier; this covers library callers.
/// - A guest program that would run code before, or without, the runtime's
///   constructor ([`in_guest_liteinst_program_gap`]).
///
/// This runs where the guest is spawned (inside the container for the CLI),
/// so it resolves the program in the filesystem the guest sees. It pins the
/// resolved program on `command` ([`pin_spawn_program`]), so the launch
/// executes the same path this check inspected.
#[cfg(feature = "liteinst")]
fn refuse_in_guest_liteinst_run(command: &mut Command, config: &DetConfig) -> Result<(), Error> {
    let reason = if config.max_timeslice.is_some() {
        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"
                .to_owned(),
        )
    } else {
        in_guest_liteinst_program_gap(command)?
    };
    match reason {
        Some(reason) => Err(Error::new(LiteinstInGuestRefusal::new(reason))),
        None => Ok(()),
    }
}

/// How many `#!` interpreters [`in_guest_liteinst_program_gap`] follows before
/// it refuses the program. The kernel has its own small limit (`exec_binprm` in
/// `fs/exec.c`); a chain this check stops following is refused, not run, so the
/// check fails closed whichever limit is lower.
#[cfg(feature = "liteinst")]
const MAX_INTERPRETER_DEPTH: usize = 4;

/// Why the guest program would run code before, or without, the in-guest
/// runtime, or `None` when it would not.
///
/// The runtime is an `LD_PRELOAD` library whose constructor installs Detcore.
/// The dynamic loader never loads it into a statically linked image or an image
/// of another architecture, and ignores `LD_PRELOAD` in secure-execution mode
/// (set-user-ID, set-group-ID, or file capabilities). An executable's
/// `DT_PREINIT_ARRAY` runs before every library constructor. Each of those
/// would run guest code unmonitored, so each is refused. `#!` scripts are
/// checked through their interpreter, read as the kernel's script handler
/// reads it ([`script::KernelScript`]). A program or interpreter that is not a
/// regular file is refused before it is opened: the kernel executes only
/// regular files, opening a device can act on it, opening a socket fails, and
/// reading a FIFO that has no writer would block the check.
///
/// Every fact about one file (its type, header, ELF headers, mode bits and
/// capabilities) is read through one open descriptor, so they all describe
/// the same file. The check is still advisory, not containment: the `execve`
/// opens the path again, and a file replaced at that path in between is not
/// checked again.
///
/// Not covered, and recorded on
/// <https://github.com/rrnewton/hermit/issues/3520>:
/// - The loader itself, the C library's initialization, the executable's
///   `IFUNC` resolvers and the constructors of the executable's own shared
///   libraries all run before the runtime's constructor in every guest.
/// - Secure-execution mode that a security module or a parent with differing
///   real and effective IDs imposes; only the file's own mode bits and
///   capabilities are checked.
/// - Whether the `PT_INTERP` loader honours `LD_PRELOAD` at all.
/// - A `binfmt_misc` rule, which the kernel consults before its ELF and script
///   handlers, and which can hand a file this check accepted to another
///   interpreter (for example an emulator).
/// - A runtime library the loader fails to load: the loader continues without
///   it, and only the launch's check that the guest connected before it exited
///   reports the failure, after the guest ran.
/// - A `pre_exec` callback on `command` that changes the working directory or
///   the root directory: the check resolves paths against the working
///   directory `command` is configured with, in Hermit's root, before any
///   such callback runs.
#[cfg(feature = "liteinst")]
fn in_guest_liteinst_program_gap(command: &mut Command) -> Result<Option<String>, Error> {
    use std::io::Read;
    use std::os::unix::fs::OpenOptionsExt;

    use script::KernelScript;

    let mut path = pin_spawn_program(command)?;
    for _ in 0..=MAX_INTERPRETER_DEPTH {
        let shown = path.display().to_string();
        let not_regular = || {
            Ok(Some(format!(
                "{shown} is not a regular file, and the kernel executes only regular files"
            )))
        };
        if !fs::metadata(&path)
            .with_context(|| format!("cannot read guest program {shown}"))?
            .is_file()
        {
            return not_regular();
        }
        // The path can change type after the check above. O_NONBLOCK then keeps
        // the open of a FIFO that has no writer from blocking, and O_NOCTTY
        // keeps a terminal from becoming Hermit's controlling terminal; neither
        // changes how a regular file is read. The descriptor's own type is
        // checked again below.
        let mut file = fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY)
            .open(&path)
            .with_context(|| format!("cannot read guest program {shown}"))?;
        if !file
            .metadata()
            .with_context(|| format!("cannot read guest program {shown}"))?
            .is_file()
        {
            return not_regular();
        }
        let mut header = Vec::new();
        (&file)
            .take(256)
            .read_to_end(&mut header)
            .with_context(|| format!("cannot read guest program {shown}"))?;
        match KernelScript::from_buf(&header) {
            KernelScript::Interpreter(interpreter) => {
                // The kernel opens a relative interpreter against the working
                // directory of the process calling execve.
                path = match command.get_current_dir() {
                    Some(directory) => directory.join(interpreter),
                    None => interpreter,
                };
                continue;
            }
            KernelScript::Declined => {
                return Ok(Some(format!(
                    "{shown} starts with #! but the kernel's script handler declines it (it \
                     names no interpreter, or the interpreter path fills the first 256 bytes), \
                     so the kernel would fail the execve or hand the file to another handler \
                     that need not load the runtime"
                )));
            }
            KernelScript::NotScript => {}
        }
        let Some(startup) = interp::elf_startup(&mut file)
            .with_context(|| format!("cannot read the ELF headers of guest program {shown}"))?
        else {
            return Ok(Some(format!(
                "{shown} is neither an ELF executable nor a #! script, so the kernel would hand \
                 it to a handler that need not load the runtime"
            )));
        };
        let reason = if !startup.x86_64 {
            "is not a 64-bit x86-64 ELF image, so the dynamic loader cannot load the 64-bit \
             runtime into it"
        } else if !startup.has_interp {
            "is statically linked (it has no PT_INTERP), so no dynamic loader runs to load the \
             runtime"
        } else if is_secure_execution_image(&file, &shown)? {
            "is set-user-ID, set-group-ID or has file capabilities, so the kernel runs it in \
             secure-execution mode, where the dynamic loader ignores LD_PRELOAD"
        } else if startup.has_preinit_array {
            "has a DT_PREINIT_ARRAY, whose functions run before the runtime's constructor"
        } else {
            return Ok(None);
        };
        return Ok(Some(format!(
            "guest program {shown} {reason}, so it would run unmonitored if Hermit launched it"
        )));
    }
    Ok(Some(format!(
        "the #! interpreters of guest program {} nest more than {MAX_INTERPRETER_DEPTH} deep",
        Path::new(command.get_program()).display()
    )))
}

/// Resolves the program `command` executes with Reverie's
/// [`Command::find_program`], the call the in-guest launch makes, and pins the
/// result on `command`, keeping `argv[0]`.
///
/// The result is absolute, so the launch's own `find_program` returns it
/// unchanged and the launch executes the same path the check inspected,
/// whatever `PATH` or working directory either side would otherwise use. The
/// path, not its contents: a file replaced at that path in between is not
/// checked again (see [`in_guest_liteinst_program_gap`]). A program the launch
/// could not find is an error here, as it would be at launch.
#[cfg(feature = "liteinst")]
fn pin_spawn_program(command: &mut Command) -> Result<PathBuf, Error> {
    let arg0 = command.get_arg0().to_owned();
    let program = command.find_program().with_context(|| {
        format!(
            "cannot find guest program {}",
            Path::new(command.get_program()).display()
        )
    })?;
    command.program(&program).arg0(arg0);
    Ok(program)
}

/// Whether executing `file` (shown as `shown`) puts the kernel in
/// secure-execution mode (`AT_SECURE`): set-user-ID, set-group-ID (with group
/// execute, as the kernel requires), or a `security.capability` attribute.
#[cfg(feature = "liteinst")]
fn is_secure_execution_image(file: &fs::File, shown: &str) -> Result<bool, Error> {
    let mode = file
        .metadata()
        .with_context(|| format!("cannot stat guest program {shown}"))?
        .permissions()
        .mode();
    if mode & 0o4000 != 0 || mode & 0o2010 == 0o2010 {
        return Ok(true);
    }
    // SAFETY: the descriptor is open for the call, the name is NUL-terminated,
    // and a zero-sized query writes no value.
    let size = unsafe {
        libc::fgetxattr(
            file.as_raw_fd(),
            c"security.capability".as_ptr(),
            std::ptr::null_mut(),
            0,
        )
    };
    if size >= 0 {
        return Ok(true);
    }
    match io::Error::last_os_error().raw_os_error() {
        Some(libc::ENODATA) | Some(libc::ENOTSUP) => Ok(false),
        _ => Err(Error::new(io::Error::last_os_error()).context(format!(
            "cannot read the file capabilities of guest program {shown}"
        ))),
    }
}

/// Refuses a wall-clock bound on an in-guest LiteInst run. The bound drops the
/// run's future, and dropping it neither kills the guest nor stops the
/// blocking task that waits for it.
#[cfg(feature = "liteinst")]
fn refuse_in_guest_liteinst_timeout(
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<(), Error> {
    if backend == Backend::Liteinst
        && timeout.is_some()
        && LiteinstRuntime::from_env()? == LiteinstRuntime::InGuest
    {
        return Err(Error::new(LiteinstInGuestRefusal::new(
            "a wall-clock timeout has not been qualified for the in-guest runtime, whose run \
             future does not kill the guest when it is dropped",
        )));
    }
    Ok(())
}

#[cfg(not(feature = "liteinst"))]
fn refuse_in_guest_liteinst_timeout(
    _backend: Backend,
    _timeout: Option<Duration>,
) -> Result<(), Error> {
    Ok(())
}

#[cfg(feature = "liteinst")]
fn liteinst_unavailable_reason() -> Option<String> {
    liteinst_runtime_unavailable_reason()
}

// LiteInst is an experimental backend whose architecture is not settled, so the
// published crate leaves it out: `reverie-liteinst` (and through it `liteinst2`)
// is an optional dependency behind the `liteinst` feature, which
// `third-party-backends` enables for every validation build.
#[cfg(not(feature = "liteinst"))]
fn liteinst_unavailable_reason() -> Option<String> {
    Some("this build was compiled without the liteinst backend: the `liteinst` feature is not enabled; rebuild with `--features liteinst` (or `--features third-party-backends`). This says nothing about whether LiteInst works on this machine -- it has not been checked".to_owned())
}

#[cfg(feature = "liteinst")]
fn liteinst_runtime_unavailable_reason() -> Option<String> {
    match LiteinstRuntime::from_env() {
        Err(error) => Some(error.to_string()),
        Ok(LiteinstRuntime::InGuest) => liteinst_tool_runtime_library_path().err().map(|error| {
            format!(
                "the in-guest Detcore runtime is unavailable: {error}; build it with `cargo build -p detcore-liteinst` in the target directory of this hermit binary, or name it with {LITEINST_TOOL_RUNTIME_ENV}"
            )
        }),
        Ok(LiteinstRuntime::HostHybrid) => liteinst_runtime_library_path().err().map(|error| {
            format!(
                "the LiteInst preload runtime is unavailable: {error}; build the locked liteinst-runtime-build manifest and stage its constructor-enabled DSO beside hermit"
            )
        }),
    }
}

fn kvm_device_unavailable_reason(path: &Path) -> Option<String> {
    fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .err()
        .map(|error| {
            format!(
                "cannot open {} read-write: {error}; grant access through the device owner/group \
                 or root",
                path.display()
            )
        })
}

/// Process instrumentation backend used to run a Hermit guest.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, ValueEnum)]
pub enum Backend {
    /// Use Reverie's ptrace backend.
    #[default]
    Ptrace,
    /// Use the DynamoRIO backend.
    Dbt,
    /// Use the ptrace-hosted LiteInst hybrid with one Detcore Tool.
    Liteinst,
    /// Use the SaBRe static binary rewriting backend.
    Sabre,
    /// Use the KVM backend.
    Kvm,
    /// Preprocess the main ELF with e9patch, then use the ptrace runtime.
    // TODO-HUMAN-REVIEW(PR-594): Review the CLI-only hybrid backend selection.
    E9patch,
}

/// A requested backend could not start because its required runtime support is absent.
///
/// Keep this as a typed error until the top-level command records its failure class.
/// The human-readable message is for the operator; consumers must use the class line
/// emitted by the command rather than matching this prose.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct BackendUnavailable {
    backend: Backend,
    reason: String,
}

impl BackendUnavailable {
    pub fn new(backend: Backend, reason: impl Into<String>) -> Self {
        Self {
            backend,
            reason: reason.into(),
        }
    }

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

    pub fn reason(&self) -> &str {
        &self.reason
    }
}

impl std::fmt::Display for BackendUnavailable {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "backend `{}` is unavailable: {}",
            self.backend.as_str(),
            self.reason
        )
    }
}

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

impl Backend {
    const ALL: [Self; 6] = [
        Self::Ptrace,
        Self::Dbt,
        Self::Liteinst,
        Self::Sabre,
        Self::Kvm,
        Self::E9patch,
    ];

    /// Returns the command-line spelling for this backend.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ptrace => "ptrace",
            Self::Dbt => "dbt",
            Self::Liteinst => "liteinst",
            Self::Sabre => "sabre",
            Self::Kvm => "kvm",
            Self::E9patch => "e9patch",
        }
    }

    fn uses_ptrace_pmu_timers(self) -> bool {
        let liteinst_runtime = if self == Self::Liteinst {
            LiteinstRuntime::from_env().unwrap_or(LiteinstRuntime::HostHybrid)
        } else {
            LiteinstRuntime::HostHybrid
        };
        self.uses_ptrace_pmu_timers_for_liteinst_runtime(liteinst_runtime)
    }

    /// [`Self::uses_ptrace_pmu_timers`] with the LiteInst runtime given
    /// explicitly rather than read from [`LITEINST_IN_GUEST_ENV`]. Other
    /// backends ignore it.
    fn uses_ptrace_pmu_timers_for_liteinst_runtime(
        self,
        liteinst_runtime: LiteinstRuntime,
    ) -> bool {
        match self {
            Self::Ptrace | Self::E9patch => true,
            // In-guest Detcore has no ptrace tracer to arm the PMU timer from.
            Self::Liteinst => liteinst_runtime != LiteinstRuntime::InGuest,
            Self::Dbt | Self::Sabre | Self::Kvm => false,
        }
    }

    /// Returns backends whose Hermit integration prerequisites are met.
    ///
    /// Some integrations use CLI launch adapters rather than direct
    /// [`run_with_backend`] dispatch.
    pub fn available() -> impl Iterator<Item = Self> {
        Self::ALL
            .into_iter()
            .filter(|backend| backend.is_available())
    }

    /// Returns whether this backend's integration prerequisites are met.
    pub fn is_available(self) -> bool {
        self.unavailable_reason().is_none()
    }

    /// Returns an actionable error when this backend's prerequisites are not met.
    pub fn ensure_available(self) -> Result<(), Error> {
        if let Some(reason) = self.unavailable_reason() {
            Err(Error::new(BackendUnavailable::new(self, reason)))
        } else {
            Ok(())
        }
    }

    fn unavailable_reason(self) -> Option<String> {
        match self {
            Self::Ptrace => validate_tracing_environment()
                .err()
                .map(|error| error.to_string()),
            Self::Dbt => dbt_unavailable_reason(),
            Self::Liteinst => liteinst_unavailable_reason(),
            // TODO-HUMAN-REVIEW(#589): Review SaBRe backend availability reporting.
            Self::Sabre => sabre_unavailable_reason(),
            Self::Kvm => kvm_device_unavailable_reason(Path::new("/dev/kvm")),
            Self::E9patch => e9patch_unavailable_reason(),
        }
    }
}

struct SkidOvershootReport {
    enabled: bool,
}

/// A ptrace-backed run observed late precise-timer delivery, so Hermit refuses
/// to treat the completed execution as deterministic evidence.
///
/// This is a type rather than a message match because it crosses the container
/// error boundary as [`error::FailureKind::PolicyRefusal`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SkidOvershootError {
    count: u64,
}

impl SkidOvershootError {
    pub fn new(count: u64) -> Self {
        assert!(
            count > 0,
            "a skid-overshoot refusal requires a positive count"
        );
        Self { count }
    }

    pub fn count(&self) -> u64 {
        self.count
    }
}

impl std::fmt::Display for SkidOvershootError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "observed {} {} report(s); refusing the result because precise PMU timer \
             delivery passed its target and deterministic execution was not established",
            self.count,
            reverie::SKID_OVERSHOOT_MARKER
        )
    }
}

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

fn take_skid_overshoot_error() -> Option<SkidOvershootError> {
    let count = reverie::take_skid_overshoot_count();
    (count > 0).then(|| SkidOvershootError::new(count))
}

impl SkidOvershootReport {
    fn begin(enabled: bool) -> Self {
        if enabled {
            // A previous invocation in this process must not qualify this one.
            let _ = reverie::take_skid_overshoot_count();
        }
        Self { enabled }
    }

    fn finish<T>(self, result: Result<T, Error>) -> Result<T, Error> {
        if !self.enabled {
            return result;
        }

        let Some(overshoot) = take_skid_overshoot_error() else {
            return result;
        };
        match result {
            Ok(_) => Err(Error::new(overshoot)),
            Err(error) => Err(error.context(overshoot)),
        }
    }

    fn finish_with_count<T>(self, result: Result<T, Error>) -> Result<(T, u64), Error> {
        if !self.enabled {
            return result.map(|value| (value, 0));
        }

        let count = reverie::take_skid_overshoot_count();
        match result {
            Ok(value) => Ok((value, count)),
            Err(error) if count > 0 => Err(error.context(SkidOvershootError::new(count))),
            Err(error) => Err(error),
        }
    }
}

// SaBRe and e9patch add no third-party Rust dependencies to `hermit-cli` (SaBRe
// shells out to an external loader plus `libdetcore_sabre.so`, and e9patch shells
// out to `e9tool`/`e9patch`). They are still gated behind the `sabre` and
// `e9patch` cargo features so the default `hermit` binary reports them as absent
// and only the `third-party-backends` build offers them. The reverie-sabre Rust
// dependency lives in the `detcore-sabre` crate, which is excluded from the
// workspace's `default-members`.
#[cfg(feature = "sabre")]
fn sabre_unavailable_reason() -> Option<String> {
    sabre_runtime_unavailable_reason()
}

#[cfg(not(feature = "sabre"))]
fn sabre_unavailable_reason() -> Option<String> {
    Some("the `sabre` feature is not enabled in this build; rebuild with `--features sabre` (or `--features third-party-backends`). This says nothing about whether SaBRe works on this machine -- it has not been checked".to_owned())
}

#[cfg(feature = "e9patch")]
fn e9patch_unavailable_reason() -> Option<String> {
    validate_tracing_environment()
        .err()
        .map(|error| error.to_string())
        .or_else(e9patch::unavailable_reason)
}

#[cfg(not(feature = "e9patch"))]
fn e9patch_unavailable_reason() -> Option<String> {
    Some("the `e9patch` feature is not enabled in this build; rebuild with `--features e9patch` (or `--features third-party-backends`). This says nothing about whether e9patch works on this machine -- it has not been checked".to_owned())
}

#[cfg(feature = "dbt")]
fn dbt_unavailable_reason() -> Option<String> {
    if !dynamorio_sdk_available() {
        return Some(
            "the DynamoRIO runtime was not found; build target/install_pkg, set HERMIT_INSTALL_DIR, or set DYNAMORIO_HOME/DynamoRIO_DIR to a valid SDK"
                .to_owned(),
        );
    }
    dbt_runtime_unavailable_reason()
}

#[cfg(not(feature = "dbt"))]
// TODO-HUMAN-REVIEW(PR-1150): Review the default-on DBT compile-time feature boundary.
fn dbt_unavailable_reason() -> Option<String> {
    Some("the `dbt` feature is not enabled in this build; rebuild with `--features dbt` (or `--features third-party-backends`). This says nothing about whether DynamoRIO works on this machine -- it has not been checked".to_owned())
}

const SABRE_BINARY_ENV: &str = "HERMIT_SABRE_BINARY";

fn is_executable_file(path: &Path) -> bool {
    fs::metadata(path)
        .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
}

// TODO-HUMAN-REVIEW(PR-739): Review SaBRe loader discovery and executable validation.
fn resolve_sabre_binary_from(
    override_path: Option<&OsStr>,
    packaged_path: Option<&Path>,
    executable: &Path,
    path_env: &OsStr,
) -> Result<PathBuf, Error> {
    if let Some(requested) = override_path {
        if requested.is_empty() {
            return Err(anyhow!("{SABRE_BINARY_ENV} is empty"));
        }
        let path = PathBuf::from(requested);
        return is_executable_file(&path)
            .then_some(path.clone())
            .ok_or_else(|| {
                anyhow!(
                    "{SABRE_BINARY_ENV}={} is not an executable file",
                    path.display()
                )
            });
    }

    if let Some(path) = packaged_path
        && is_executable_file(path)
    {
        return Ok(path.to_path_buf());
    }

    let directory = executable
        .parent()
        .ok_or_else(|| anyhow!("Hermit executable has no parent directory"))?;
    let sibling = directory.join("sabre");
    let target_build = directory.parent().map(|target| target.join("sabre/sabre"));

    if is_executable_file(&sibling) {
        return Ok(sibling);
    }
    if let Some(candidate) = &target_build
        && is_executable_file(candidate)
    {
        return Ok(candidate.clone());
    }
    if !path_env.is_empty()
        && let Some(candidate) = std::env::split_paths(path_env)
            .map(|directory| directory.join("sabre"))
            .find(|candidate| is_executable_file(candidate))
    {
        return Ok(candidate);
    }

    Err(anyhow!(
        "SaBRe executable was not found in the Hermit installation, beside {}, or in PATH; set {} or {SABRE_BINARY_ENV}",
        executable.display(),
        hermit_resources::INSTALL_DIR_ENV
    ))
}

fn resolve_sabre_binary() -> Result<PathBuf, Error> {
    let executable =
        std::env::current_exe().context("failed to locate running Hermit executable")?;
    let override_path = std::env::var_os(SABRE_BINARY_ENV);
    let packaged_path = hermit_resources::resource("sabre")?;
    let path_env = std::env::var_os("PATH").unwrap_or_default();
    resolve_sabre_binary_from(
        override_path.as_deref(),
        packaged_path.as_deref(),
        &executable,
        &path_env,
    )
}

const SABRE_RPC_SOCKET_ENV: &str = "REVERIE_SABRE_HERMIT_RPC_SOCKET";
const SABRE_DETLOG_FORWARD_ENV: &str = "REVERIE_SABRE_HERMIT_FORWARD_DETLOG";
const SABRE_PATH_EVIDENCE_ENV: &str = "HERMIT_SABRE_PATH_EVIDENCE";
const SABRE_STAGING_DIRECTORY: &str = "/dev/shm";

struct StagedSabreProgram {
    path: PathBuf,
}

impl Drop for StagedSabreProgram {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

fn sabre_program_needs_neutral_name(program: &Path) -> bool {
    program
        .file_name()
        .is_some_and(|name| name.as_bytes().starts_with(b"ld"))
}

// TODO-HUMAN-REVIEW(PR-845): Review the neutral-name workaround for SaBRe's
// dynamic-loader prefix collision.
fn stage_sabre_program_in(
    program: &Path,
    staging_directory: &Path,
) -> Result<Option<StagedSabreProgram>, Error> {
    if !sabre_program_needs_neutral_name(program) {
        return Ok(None);
    }

    let path = staging_directory.join(format!("hermit-sabre-program-{}", std::process::id()));
    let mut source = fs::File::open(program).map_err(|error| {
        anyhow!(
            "failed to open SaBRe guest executable {} for neutral-name staging: {error}",
            program.display()
        )
    })?;
    let mut staged = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o700)
        .open(&path)
        .map_err(|error| {
            anyhow!(
                "failed to stage SaBRe guest executable {} as {}: {error}",
                program.display(),
                path.display()
            )
        })?;
    if let Err(error) = io::copy(&mut source, &mut staged) {
        let _ = fs::remove_file(&path);
        return Err(anyhow!(
            "failed to stage SaBRe guest executable {} as {}: {error}",
            program.display(),
            path.display()
        ));
    }
    drop(staged);

    Ok(Some(StagedSabreProgram { path }))
}

// TODO-HUMAN-REVIEW(PR-738): Review controller/plugin artifact separation.
fn sabre_runtime_library_path() -> io::Result<PathBuf> {
    if let Some(path) = hermit_resources::resource("libdetcore_sabre.so")?
        && path.is_file()
    {
        return Ok(path);
    }

    let executable = std::env::current_exe()?;
    let directory = executable.parent().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            "Hermit executable has no parent directory",
        )
    })?;
    [
        directory.join("libdetcore_sabre.so"),
        directory.join("deps/libdetcore_sabre.so"),
    ]
    .into_iter()
    .find(|path| path.is_file())
    .ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            format!(
                "libdetcore_sabre.so was not built beside {}",
                executable.display()
            ),
        )
    })
}

#[cfg(feature = "sabre")]
fn sabre_runtime_unavailable_reason() -> Option<String> {
    if let Err(error) = resolve_sabre_binary() {
        return Some(error.to_string());
    }
    sabre_runtime_library_path().err().map(|error| {
        format!(
            "the Detcore SaBRe plugin is unavailable: {error}; build detcore-sabre and hermit in the same target directory"
        )
    })
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-774): Review the bounded SaBRe RPC disconnect drain.
const SABRE_RPC_DISCONNECT_TIMEOUT: Duration = Duration::from_secs(1);

async fn wait_for_sabre_rpc_disconnects<T>(
    global: &Arc<T>,
    timeout: Duration,
) -> Result<(), usize> {
    let disconnected = tokio::time::timeout(timeout, async {
        while Arc::strong_count(global) > 1 {
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    })
    .await;

    if disconnected.is_ok() {
        return Ok(());
    }

    let live_references = Arc::strong_count(global).saturating_sub(1);
    if live_references == 0 {
        Ok(())
    } else {
        Err(live_references)
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-782): Review SaBRe RPC server shutdown errors.
async fn stop_sabre_rpc_server<E>(
    server_task: tokio::task::JoinHandle<Result<(), E>>,
) -> Result<(), Error>
where
    E: std::fmt::Display,
{
    server_task.abort();
    match server_task.await {
        Err(error) if error.is_cancelled() => Ok(()),
        Err(error) => Err(anyhow!("SaBRe coordinator task failed: {error}")),
        Ok(Err(error)) => Err(anyhow!("SaBRe coordinator server failed: {error}")),
        Ok(Ok(())) => Err(anyhow!("SaBRe coordinator server stopped unexpectedly")),
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-789): Review complete SaBRe RPC shutdown ordering.
async fn shutdown_sabre_rpc<T, E>(
    server_task: tokio::task::JoinHandle<Result<(), E>>,
    global: &Arc<T>,
    timeout: Duration,
) -> Result<(), Error>
where
    E: std::fmt::Display,
{
    let server_result = stop_sabre_rpc_server(server_task).await;
    let disconnect_result = wait_for_sabre_rpc_disconnects(global, timeout).await;

    server_result?;
    disconnect_result.map_err(|live_references| {
        anyhow!("SaBRe coordinator stopped with {live_references} live RPC reference(s)")
    })
}

fn ensure_backend_dispatch(backend: Backend) -> Result<(), Error> {
    // The CLI probes ptrace readiness before entering its container; repeating
    // the namespace probe here would test nested namespaces instead of the host.
    if backend == Backend::Ptrace {
        return Ok(());
    }
    if backend == Backend::E9patch {
        return Err(anyhow!(
            "backend `e9patch` requires CLI preprocessing; library callers must use \
             e9patch::prepare and then select `ptrace`"
        ));
    }
    // KVM and DBT have dedicated dispatches (`run_kvm` and `run_dbt`); neither
    // must reach this generic rejection path.
    backend.ensure_available()?;
    Err(anyhow!(
        "backend `{}` has no Hermit dispatch implementation",
        backend.as_str()
    ))
}

/// Run one command with the Detcore tool executing inside a SaBRe plugin and
/// the single GlobalState held by this Hermit coordinator process.
// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-738): Review SaBRe coordinator lifetime and artifact loading.
async fn run_sabre(
    mut command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    capture_output: bool,
) -> Result<Output, Error> {
    let path_evidence_file = std::env::var_os(SABRE_PATH_EVIDENCE_ENV).map(PathBuf::from);
    let sabre = resolve_sabre_binary()?;
    let plugin = sabre_runtime_library_path()
        .map_err(|error| anyhow!("failed to locate the Detcore SaBRe plugin: {error}"))?;
    let program = command.find_program().map_err(|error| {
        anyhow!(
            "failed to resolve SaBRe guest executable {:?}: {error}",
            command.get_program()
        )
    })?;
    let staged_program = stage_sabre_program_in(&program, Path::new(SABRE_STAGING_DIRECTORY))?;
    let launch_program = staged_program
        .as_ref()
        .map_or(program.as_path(), |staged| staged.path.as_path());

    let bootstrap_launch =
        sabre_bootstrap::Launch::new(Path::new(&sabre), launch_program, &config)?;

    // This runs after Hermit enters the guest mount namespace, where `/tmp`
    // names the container-visible temporary filesystem. Do not inherit a
    // host-side nested TMPDIR: validation commonly sets TMPDIR=/tmp/<run>/tmp,
    // but that parent path is hidden once the private `/tmp` mount is active.
    // The SaBRe plugin and coordinator must name the socket through the same
    // namespace-visible path.
    let socket_dir = tempfile::Builder::new()
        .prefix("hermit-sabre-rpc-")
        .tempdir_in(Path::new("/tmp"))?;
    let socket_path = socket_dir.path().join("coordinator.sock");
    let fallback_ready = Arc::new(AtomicBool::new(false));
    let global = Arc::new(detcore::GlobalState::init_global_state(&config).await);
    let server = reverie_rpc_transport::RpcServer::bind_with_readiness(
        &socket_path,
        global.clone(),
        config.clone(),
        fallback_ready.clone(),
    )
    .map_err(|error| anyhow!("failed to start SaBRe coordinator RPC: {error}"))?;
    let server_task = tokio::spawn(async move { server.serve().await });

    command.prepend_args([
        plugin.as_os_str(),
        OsStr::new("--"),
        launch_program.as_os_str(),
    ]);
    command.program(&sabre);
    command.env(SABRE_RPC_SOCKET_ENV, &socket_path);
    command.env_remove(sabre_bootstrap::ENVIRONMENT);
    if bootstrap_launch.initializes_random() {
        command.env(sabre_bootstrap::ENVIRONMENT, "1");
    }
    // Publish the configuration and clock RPC fingerprint for this coordinator.
    // The plugin is a separate artifact in the same target directory, so it can
    // be stale without looking it. Its check before connecting names the mismatch
    // instead of failing to decode Config or a later DetTime request field.
    // See detcore_model::config_wire_fingerprint.
    command.env(
        detcore::CONFIG_FINGERPRINT_ENV,
        detcore::config_wire_fingerprint(),
    );
    command.env_remove(SABRE_PATH_EVIDENCE_ENV);
    command.env_remove(SABRE_DETLOG_FORWARD_ENV);
    if tracing::enabled!(target: "detcore", tracing::Level::INFO) {
        command.env(SABRE_DETLOG_FORWARD_ENV, "1");
    }
    command.env_remove("SABRE_BINARY");
    command.env_remove("SABRE_PLUGIN");
    // Always collect: the statistics page is a descriptor the guest can see,
    // so creating it only when a summary or DEBUG log is requested would make
    // those flags change the guest's view. The plugin takes the variable out
    // of the guest environment, and the descriptor sits above the plugin's
    // fixed RPC socket.
    let stats = reverie_sabre_stats::SabreStats::create(reverie::BackendStatsRequest::ENABLED)
        .map_err(|error| anyhow!("failed to create the SaBRe statistics page: {error}"))?
        .expect("an enabled request creates the statistics page");
    command.env(
        reverie_sabre_stats::BACKEND_STATS_ENV,
        stats.raw_fd().to_string(),
    );

    // THE SOCKET PATH IS DELIBERATELY RANDOM AND MUST NOT BE COMPARED.
    //
    // `tempfile` appends a random 6-character suffix to the directory above, so
    // the absolute path differs on every launch by design -- that is what keeps
    // concurrent hermit invocations on a shared host from binding the same
    // coordinator socket. Emitting it at INFO put per-launch randomness into the
    // INFO stream, which `--verify-strict` compares:
    //
    //   Mismatch at log messages 2 (run 1) and 2 (run 2):
    //   < socket=/tmp/hermit-sabre-rpc-Gw6tUi/coordinator.sock
    //   > socket=/tmp/hermit-sabre-rpc-7SZ94p/coordinator.sock
    //
    // That fails EVERY SaBRe verify cell before the guest executes an
    // instruction, for a host-side value with no guest-visible content. The
    // defect was in the oracle, not the backend.
    //
    // WHY THE VALUE IS DROPPED FROM INFO RATHER THAN MADE DETERMINISTIC: the two
    // `--verify` runs execute in SEPARATE CHILD PROCESSES, so any path stable
    // across both would have to be derived from state shared between them. That
    // trades `tempfile`'s guaranteed-fresh directory for a reused one, and a
    // run1 that dies holding the socket would then make run2 fail to bind -- a
    // real new failure mode in exchange for a cosmetic field. The path keeps its
    // randomness; only the compared stream stops carrying it.
    //
    // This is NOT a comparator relaxation. No normalization envelope is widened,
    // so any future randomness leaking into this banner still fails the
    // comparison. The full path remains available one level down.
    tracing::debug!(
        target: "hermit::sabre",
        socket = %socket_path.display(),
        "SaBRe coordinator RPC socket (per-launch temp path, deliberately not at INFO)",
    );
    tracing::info!(
        target: "hermit::sabre",
        guest = %program.display(),
        plugin = %plugin.display(),
        "launching Detcore guest through SaBRe with coordinator RPC",
    );

    let supervised = match sabre_ptrace::run(
        command.into_std_lossy(),
        PathBuf::from(&sabre),
        plugin.clone(),
        fallback_ready,
        global.clone(),
        bootstrap_launch,
        stats.clone(),
        capture_output,
    )
    .await
    {
        Ok(supervised) => supervised,
        Err(error) => {
            global.release_all_physical_process_exits();
            global.force_shutdown_with_error();
            let _ = shutdown_sabre_rpc(server_task, &global, SABRE_RPC_DISCONNECT_TIMEOUT).await;
            return Err(error);
        }
    };
    // The supervisor returns only after every tracee reached a final kernel wait status. Release
    // the root process's barrier (and any intentionally unreaped child barriers) before scheduler
    // shutdown; no guest thread remains that could race timer fast-forward here.
    global.release_all_physical_process_exits();
    // A SaBRe execution in which no guest thread ever reached the coordinator
    // is an execution in which Detcore was never loaded as a Reverie tool: the
    // guest ran on bare Linux. Treat it exactly like a failed run so the
    // scheduler is torn down here instead of blocking forever in `clean_up`
    // below, waiting for a guest thread that will never register.
    let detcore_never_engaged = !supervised.path_evidence.guest_rpc_observed;
    let requires_forced_shutdown = !supervised.status.success() || detcore_never_engaged;
    if requires_forced_shutdown {
        global.force_shutdown_with_error();
    }
    // Emit one unconditional, machine-readable per-run fact instead of a
    // free-form warning. SaBRe loads the guest interpreter before the Detcore
    // plugin, so pre-plugin loader syscalls are structurally absent from its
    // observation envelope. Versioning that fact lets scorecard consumers
    // reject old or incomplete records rather than infer coverage from silence.
    //
    // Keep this in the controller-diagnostic stream rather than writing
    // directly to the process stderr that also carries captured guest stderr.
    // WARN is Hermit's default tracing level, and `--log-file` can therefore
    // separate the unconditional controller fact from guest output without a
    // comparator exception. A missing record remains distinct from a record
    // whose counters are zero.
    let backend_evidence = sabre_backend_evidence_line(&supervised.path_evidence);
    tracing::warn!(target: "hermit::sabre", "{backend_evidence}");
    if let Some(path) = path_evidence_file {
        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .mode(0o600)
            .open(&path)
            .map_err(|error| {
                anyhow!(
                    "failed to open SaBRe path evidence {}: {error}",
                    path.display()
                )
            })?;
        serde_json::to_writer(&mut file, &supervised.path_evidence)?;
        writeln!(file)?;
    }
    let output = Output {
        status: supervised.status.into(),
        stdout: supervised.stdout,
        stderr: supervised.stderr,
    };

    shutdown_sabre_rpc(server_task, &global, SABRE_RPC_DISCONNECT_TIMEOUT).await?;
    let mut global = Arc::try_unwrap(global).map_err(|global| {
        anyhow!(
            "SaBRe coordinator stopped with {} live RPC reference(s)",
            Arc::strong_count(&global) - 1
        )
    })?;
    if requires_forced_shutdown {
        global.cancel_internal_scheduler().await;
    }
    let dispatch_stats = backend_stats::report(
        Backend::Sabre,
        backend_stats::request(print_summary_to_json_file),
        &stats,
    );
    global
        .clean_up_with_dispatch_stats(print_summary, print_summary_to_json_file, dispatch_stats)
        .await;
    tracing::info!(
        target: "hermit::sabre::fallback",
        ptrace_fallback_sites = supervised.path_evidence.ptrace_fallback_sites,
        trusted_shared_object_sites = supervised.path_evidence.trusted_shared_object_sites,
        guest_rpc_observed = supervised.path_evidence.guest_rpc_observed,
        "SaBRe ptrace fallback completed",
    );
    if detcore_never_engaged {
        return Err(anyhow!(
            "{}",
            sabre_uninstrumented_guest_message(&output.status)
        ));
    }
    Ok(output)
}

/// Classify the existing SaBRe reach evidence without collapsing "never
/// engaged" into the same zero-valued state as a fully exercised run.
fn sabre_reach_state(guest_rpc_observed: bool, ptrace_fallback_sites: usize) -> &'static str {
    match (guest_rpc_observed, ptrace_fallback_sites) {
        (false, _) => "no-detcore-reached",
        (true, 1..) => "degraded-ptrace-fallback",
        (true, 0) => "sabre-exercised",
    }
}

/// Produce the versioned SaBRe backend fact consumed by compatibility reports.
///
/// `preplugin_coverage=absent` is a property of SaBRe's launch order: the guest
/// interpreter runs before the Detcore plugin is loaded. It is recorded rather
/// than inferred from counters because the ptrace fallback cannot observe that
/// interval either.
///
/// Preserve the originating #1725 measurement as provenance for that field:
/// on its measurement host, `/bin/true` produced 3 COMMITs under SaBRe versus
/// 14 under ptrace; the 11 absent records were the loader's libc.so.6 path
/// resolution. The launch-order fact, not that host-specific count, is the
/// runtime contract.
fn sabre_backend_evidence_line(evidence: &sabre_ptrace::PathEvidence) -> String {
    format!(
        ":: Backend: sabre static rewriting + ptrace runtime; run_mode=run; \
         evidence_schema={}; preplugin_coverage=absent; ptrace_fallback_sites={}; \
         trusted_shared_object_sites={}; guest_rpc_observed={}; reach_state={}",
        evidence.schema,
        evidence.ptrace_fallback_sites,
        evidence.trusted_shared_object_sites,
        evidence.guest_rpc_observed,
        sabre_reach_state(evidence.guest_rpc_observed, evidence.ptrace_fallback_sites),
    )
}

/// Explain a SaBRe run whose guest never reached the Detcore coordinator.
///
/// `guest_rpc_observed` is set by the coordinator RPC listener the first time a
/// SaBRe-loaded guest connects. When it stays false the guest completed without
/// Detcore intercepting anything, so the run carries no determinism guarantee
/// whatsoever -- its timing, scheduling, PIDs, and clock reads all came from the
/// host. Reporting that as a successful `hermit run` would be a fail-open
/// determinism hole, so the caller turns it into a hard error and this function
/// supplies the diagnosis.
///
/// The dominant cause is a guest whose syscall sites SaBRe never rewrote. A
/// statically linked ELF is the sharp edge: it has no dynamic loader and no
/// shared library through which SaBRe could regain control, so an unrewritten
/// static client runs entirely on bare Linux with no second chance.
fn sabre_uninstrumented_guest_message(status: &ExitStatus) -> String {
    format!(
        "the SaBRe backend finished ({status:?}) without the guest ever reaching the Detcore \
         coordinator: no syscall was intercepted, so this run applied no determinization at all \
         and its result is not a Hermit guarantee. This means SaBRe rewrote no syscall site in \
         the guest -- most often a statically linked ELF, whose syscall sites SaBRe must patch \
         in the client image itself because there is no dynamic loader to intercept."
    )
}

/// Guest-physical memory available to the single-process KVM personality.
// The KVM personality is a sparse MAP_NORESERVE address space. QEMU needs room
// for its own ELF mappings in addition to the nested machine's RAM mapping.
const KVM_GUEST_MEMORY_BYTES: usize = 1024 * 1024 * 1024;

/// Maximum `#!` interpreter indirection levels, matching the Linux kernel's
/// `BINPRM_MAX_RECURSION` limit for chained script interpreters.
const MAX_SHEBANG_DEPTH: usize = 4;

/// Resolve `#!` interpreter scripts before the reverie-kvm ELF loader runs.
///
/// The KVM ELF loader can only map ELF images, so a guest program that is
/// actually a `#!`-script (for example `/usr/local/bin/file` -> `#!/bin/bash`,
/// or `/usr/bin/pkg-config` -> `#!/usr/bin/sh`) must be rewritten to launch its
/// interpreter, exactly as the kernel's `execve(2)` `binfmt_script` handler
/// does. On success the returned image is an ELF and `argv` has the interpreter,
/// its shebang arguments, and the script path prepended in kernel order:
/// `[interp, shebang_args.., script_path, <original argv[1..]>]`.
///
/// The interpreter line is parsed with hermit's shared [`Shebang`] so the KVM
/// backend matches how the ptrace backend and recorder treat `#!`-scripts.
fn resolve_kvm_shebang(
    resolved_program: &Path,
    mut argv: Vec<String>,
) -> Result<(PathBuf, Vec<String>, Vec<u8>), Error> {
    let mut load_path = resolved_program.to_path_buf();
    let mut image = fs::read(&load_path)
        .map_err(|error| anyhow!("failed to read KVM guest executable {load_path:?}: {error}"))?;

    let mut depth = 0;
    while image.starts_with(b"#!") {
        depth += 1;
        if depth > MAX_SHEBANG_DEPTH {
            return Err(anyhow!(
                "too many levels of `#!` interpreter indirection loading {resolved_program:?}"
            ));
        }
        let (interpreter, shebang_args) = Shebang::from_buf(&image)
            .ok_or_else(|| anyhow!("malformed `#!` interpreter line in {load_path:?}"))?
            .into_parts();
        let interpreter_str = interpreter
            .to_str()
            .ok_or_else(|| anyhow!("non-UTF-8 `#!` interpreter path in {load_path:?}"))?
            .to_owned();

        // Rewrite argv in kernel order. The prior argv[0] (the script's own
        // name) is dropped on the first level; on deeper levels the previous
        // interpreter path is preserved as a positional argument, matching
        // `binfmt_script`.
        let mut rewritten = Vec::with_capacity(argv.len() + shebang_args.len() + 2);
        rewritten.push(interpreter_str);
        for arg in &shebang_args {
            rewritten.push(
                arg.to_str()
                    .ok_or_else(|| anyhow!("non-UTF-8 `#!` interpreter argument in {load_path:?}"))?
                    .to_owned(),
            );
        }
        rewritten.push(load_path.to_string_lossy().into_owned());
        rewritten.extend_from_slice(&argv[1..]);
        argv = rewritten;

        load_path = interpreter;
        image = fs::read(&load_path).map_err(|error| {
            anyhow!(
                "failed to read `#!` interpreter {load_path:?} for {resolved_program:?}: {error}"
            )
        })?;
    }

    Ok((load_path, argv, image))
}

/// The container replaces this host directory with a private, empty tmpfs, so
/// nothing beneath it is visible to the guest. Kept next to the diagnostic that
/// depends on it; `run.rs` has its own `TMP_DIR` for the mount itself.
const CONTAINER_REPLACED_TMP: &str = "/tmp";

/// Explain why a working directory that plainly exists on the host could not be
/// resolved for the guest.
///
/// ⚠️ THIS FUNCTION EXISTS BECAUSE THE BARE ERROR CAUSED A MISDIAGNOSIS, not to
/// be tidy. `fs::canonicalize` runs after the container's mounts are applied, and
/// the container bind-mounts a fresh empty tmpfs over `/tmp`
/// (`bin/hermit/container.rs`). So a cwd beneath `/tmp` is genuinely absent from
/// the guest's mount namespace and `canonicalize` returns a perfectly correct
/// `NotFound` -- for a directory the user can `ls`.
///
/// Reported 2026-08-25 as "run_kvm_ cli tests fail from a git worktree". They do
/// not. Measured across five working directories with one binary: a PLAIN
/// directory under `/tmp` with no git in it FAILS, and a linked git worktree
/// under `/home` WORKS. The only property that tracks the failure is "the cwd is
/// under /tmp"; `/tmp` itself resolves because the mount POINT exists. The git
/// hypothesis cost real investigation time, and it came from this message saying
/// only "No such file or directory".
///
/// It mattered more than a stray report because the historical landing recipe
/// placed detached worktrees below `/tmp`, exactly where this fires. Current
/// dev-hermit worktrees are created through wrkslots below `worktrees/`, but the
/// diagnostic remains necessary for arbitrary callers and older checkouts.
///
/// The message names the mechanism and both ways out. It deliberately does NOT
/// silently fall back to `/`: changing the guest's working directory out from
/// under a caller who asked for a specific one would trade a loud, correct
/// failure for a quiet, wrong success.
fn kvm_cwd_resolution_error(requested_cwd: &Path, error: &std::io::Error) -> Error {
    let under_replaced_tmp = requested_cwd.starts_with(CONTAINER_REPLACED_TMP)
        && requested_cwd != Path::new(CONTAINER_REPLACED_TMP);
    if error.kind() == std::io::ErrorKind::NotFound && under_replaced_tmp {
        anyhow!(
            "failed to resolve KVM guest working directory {:?}: {error}\n\
             \n\
             This directory may well exist on the host. The container replaces \
             {CONTAINER_REPLACED_TMP} with a private, empty tmpfs, so nothing beneath \
             {CONTAINER_REPLACED_TMP} is visible to the guest, and resolving the working \
             directory happens inside that mount namespace.\n\
             Either run from a directory outside {CONTAINER_REPLACED_TMP}, or pass \
             --workdir with a path that exists inside the guest.",
            requested_cwd
        )
    } else {
        anyhow!(
            "failed to resolve KVM guest working directory {:?}: {error}",
            requested_cwd
        )
    }
}

/// Bind KVM's raw mountinfo and fdinfo to the same filesystem namespace.
///
/// The CLI supplies IdentityGuard provenance from the completed container.
/// Recapture that full row/parent order before ELF installation, which snapshots
/// the same namespace in the backend, and refuse stale producer provenance.
/// Library and no-namespace callers without provenance retain this capture.
/// KVM does not permit guest namespace changes. Later guest-visible mountinfo
/// views still use Detcore's existing ordered-subset validation.
fn prepare_kvm_mountinfo_config(
    config: &mut DetConfig,
    capture: impl FnOnce() -> Result<Vec<u64>, Error>,
) -> Result<(), Error> {
    if !config.mountinfo_mount_ids_captured
        && (!config.mountinfo_mount_ids.is_empty() || !config.fdinfo_unlisted_mount_ids.is_empty())
    {
        anyhow::bail!("KVM mount identities have no producer-captured namespace");
    }
    let order = capture().context("failed to capture the KVM backend mount namespace")?;
    if config.mountinfo_mount_ids_captured {
        if config.mountinfo_mount_ids != order {
            anyhow::bail!(
                "KVM producer-captured mount identities do not match the backend namespace"
            );
        }
    } else {
        config.mountinfo_mount_ids = order;
        config.mountinfo_mount_ids_captured = true;
    }
    // The backend now exposes the actual namespace's devices. There is no
    // synthetic 0:1 root device to translate; stat and mountinfo use the same
    // raw identities before entering Detcore's shared DevicePool.
    config.mountinfo_device_rewrites.clear();
    Ok(())
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(https://github.com/rrnewton/hermit/issues/3695): Review
// host metadata timestamps for KVM runs.
/// Whether a KVM run asks the backend for the timestamps the kernel stored
/// rather than its fixed value.
///
/// With virtual metadata, Detcore rewrites every timestamp that a stat call
/// returns to the guest, and it reads the stored host values for its own
/// checks: `set_file_times` confirms that `utimensat` stored the requested
/// mtime. KVM replaces those timestamps with a fixed value unless the run asks
/// for the stored ones. The backend refuses this setting unless Detcore owns
/// every guest thread. The stored values sit in the guest's buffer until
/// Detcore rewrites them, so the run must also sequentialize threads: then no
/// other guest thread runs in that interval.
fn kvm_reports_stored_metadata_timestamps(config: &DetConfig) -> bool {
    config.virtualize_metadata
        && config.backend_dispatches_thread_tools
        && config.sequentialize_threads
}

/// Dispatch a command onto the real reverie-kvm Tool runtime.
async fn run_kvm(
    command: &Command,
    mut config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    capture_output: bool,
) -> Result<Output, Error> {
    let dispatch_started = Instant::now();
    prepare_kvm_mountinfo_config(&mut config, capture_mountinfo_identity_order)?;
    let stdin = if capture_output {
        let (snapshot_reserved, snapshot) = output_backend_stdin_reservation()?;
        if snapshot_reserved {
            snapshot
        } else {
            // Public KVM output-capture callers do not pass through the CLI's
            // verify setup. Preserve their existing stdin behavior instead of
            // silently replacing it with /dev/null merely because output is
            // captured.
            reserved_kvm_stdin()?
        }
    } else {
        reserved_kvm_stdin()?
    };
    let requested_cwd = command
        .get_current_dir()
        .map(Path::to_owned)
        .unwrap_or(std::env::current_dir()?);
    let cwd = fs::canonicalize(&requested_cwd)
        .map_err(|error| kvm_cwd_resolution_error(&requested_cwd, &error))?;
    let program = command
        .get_program()
        .to_str()
        .ok_or_else(|| anyhow!("KVM guest executable path is not valid UTF-8"))?
        .to_owned();
    if !cwd.is_dir() {
        return Err(anyhow!(
            "KVM guest working directory is not a directory: {:?}",
            cwd
        ));
    }
    let resolved_program = command.find_program().map_err(|error| {
        anyhow!("failed to resolve KVM guest executable {program:?} in the guest PATH: {error}")
    })?;
    let mut argv = Vec::with_capacity(1 + command.get_args().count());
    argv.push(program.clone());
    for argument in command.get_args() {
        argv.push(
            argument
                .to_str()
                .ok_or_else(|| anyhow!("KVM guest argument is not valid UTF-8"))?
                .to_owned(),
        );
    }

    // Rewrite `#!`-scripts to their interpreter before the ELF loader sees them.
    let (_interpreter_path, argv, image) = resolve_kvm_shebang(&resolved_program, argv)?;
    // After shebang resolution the executable is the interpreter (argv[0]).
    let program = argv.first().cloned().unwrap_or(program);
    let envp = command
        .get_captured_envs()
        .into_iter()
        .map(|(key, value)| {
            let key = key
                .to_str()
                .ok_or_else(|| anyhow!("KVM guest environment key is not valid UTF-8"))?;
            let value = value
                .to_str()
                .ok_or_else(|| anyhow!("KVM guest environment value is not valid UTF-8"))?;
            Ok(format!("{key}={value}"))
        })
        .collect::<Result<Vec<_>, Error>>()?;
    tracing::info!(
        target: "hermit::kvm",
        program = %program,
        argv = ?argv,
        cwd = %cwd.display(),
        env_count = envp.len(),
        "launching guest through reverie-kvm",
    );
    let argv = argv.iter().map(String::as_str).collect::<Vec<_>>();
    let envp = envp.iter().map(String::as_str).collect::<Vec<_>>();

    let setup_started = Instant::now();
    config.cpuid_virtualized_by_backend = true;
    config.backend_supports_madvise = false;
    // KVM does not enter Hermit's UTS namespace, so Detcore must provide the
    // same synthetic identity that the namespace-backed ptrace path exposes.
    // TODO-HUMAN-REVIEW(PR-998): Review KVM UTS namespace parity.
    config.has_uts_namespace = false;
    let random_seed = config.rng_seed();
    let mut backend = reverie_kvm::KvmBackend::new_with_stdin(KVM_GUEST_MEMORY_BYTES, stdin)
        .map_err(|error| anyhow!("failed to initialize reverie-kvm: {error}"))?;
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1120): Review KVM's canonical Detcore root identity.
    backend
        .set_root_pid(detcore::ROOT_DETPID.as_raw())
        .map_err(|error| anyhow!("failed to configure KVM root PID: {error}"))?;
    backend
        .install_static_elf_with_context(&image, &argv, &envp, &cwd)
        .map_err(|error| anyhow!("failed to load KVM guest executable {program:?}: {error}"))?;
    backend
        .set_random_seed(random_seed)
        .map_err(|error| anyhow!("failed to configure KVM guest random seed: {error}"))?;
    // The KVM backend now defaults to Tool-owned guest threads: CLONE_THREAD
    // workers are driven through the Detcore tool loop and their futex/CLEARTID
    // synchronization routes to Detcore, matching the golden ptrace model
    // ("follow children"). Detcore's own clone logic treats a CLONE_THREAD as
    // backend-uninstrumented iff `backend_dispatches_thread_tools` is false (see
    // detcore/src/syscalls/threads.rs), so in exactly that case opt the backend
    // out to host-owned threads to keep worker execution and futex ownership in
    // one synchronization domain (mixing them deadlocks pthread_join). In the
    // default (true) case the backend already follows children, so no call is
    // needed.
    if !config.backend_dispatches_thread_tools {
        backend.unmonitored_threads();
    }
    if kvm_reports_stored_metadata_timestamps(&config) {
        backend
            .set_host_metadata_timestamps(true)
            .map_err(|error| anyhow!("failed to configure KVM metadata timestamps: {error}"))?;
    }

    let execution_started = Instant::now();
    let completion = backend
        .run_static_elf_with_tool_completion::<Detcore>(config, capture_output)
        .await
        .map_err(|error| kvm_execution_error(error, None))?;
    let cleanup_started = Instant::now();
    let result =
        finish_kvm_tool_completion(completion, print_summary, print_summary_to_json_file).await;
    let teardown_started = Instant::now();
    // Drop explicitly so the host's KVM VM teardown cost remains observable.
    drop(backend);
    let teardown_finished = Instant::now();
    let (code, stdout, stderr) = result?;

    // Every field below is a host wall-clock duration. Keep this diagnostic at
    // DEBUG so it remains available for backend profiling without entering the
    // INFO stream exposed to canonical comparison. KVM's built-in verification
    // is still output/status-only; this classification does not claim KVM L2.
    tracing::debug!(
        target: "hermit::kvm",
        prepare_us = setup_started.duration_since(dispatch_started).as_micros() as u64,
        setup_us = execution_started.duration_since(setup_started).as_micros() as u64,
        execution_us = cleanup_started.duration_since(execution_started).as_micros() as u64,
        cleanup_us = teardown_started.duration_since(cleanup_started).as_micros() as u64,
        teardown_us = teardown_finished.duration_since(teardown_started).as_micros() as u64,
        lifecycle_us = teardown_finished.duration_since(dispatch_started).as_micros() as u64,
        "reverie-kvm lifecycle phase timings",
    );

    if !capture_output {
        std::io::stdout().write_all(&stdout)?;
        std::io::stderr().write_all(&stderr)?;
    }

    Ok(Output {
        status: ExitStatus::Exited(code),
        stdout,
        stderr,
    })
}

// A runtime error still owns GlobalState. Finish its terminal daemon before
// returning the typed cause to the CLI's error classifier.
async fn finish_kvm_tool_completion(
    completion: reverie_kvm::ToolRunCompletion<detcore::GlobalState>,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
) -> Result<(i32, Vec<u8>, Vec<u8>), Error> {
    match completion.result {
        Ok(output) => {
            completion
                .global_state
                .clean_up(print_summary, print_summary_to_json_file)
                .await;
            Ok(output)
        }
        Err(error) => {
            let cleanup = completion
                .global_state
                .clean_up_after_backend_failure()
                .await;
            Err(kvm_execution_error(error, Some(cleanup)))
        }
    }
}

fn kvm_execution_error(
    primary: reverie_kvm::Error,
    cleanup: Option<detcore::BackendFailureCleanup>,
) -> Error {
    // The manifest runner retains the first Error line. Keep the cause there,
    // as well as the typed backend and optional scheduler errors in the chain.
    let message = format!("KVM guest execution failed: {primary}");
    let mut error = Error::new(primary);
    if let Some(cleanup) = cleanup {
        if let Err(recording) = cleanup.preemption_recording {
            error = error.context(format!("partial preemption recording failed: {recording}"));
        }
        if let Err(scheduler) = cleanup.scheduler {
            error = error.context(scheduler);
        }
    }
    error.context(message)
}

#[cfg(test)]
mod kvm_failure_tests;

#[cfg(all(test, feature = "kvm-execution-tests"))]
mod kvm_execution_tests;

// TODO-HUMAN-REVIEW(PR-743): Review bounded relaunch before DBT guest execution.
#[cfg(feature = "dbt")]
fn dbt_client_thread_start_failed(status: &std::process::ExitStatus) -> bool {
    status.code() == Some(reverie_dbt::CLIENT_THREAD_START_FAILURE_EXIT_CODE)
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-737): Review public DBT dispatch and child environment ownership.
/// Dispatch a command onto the Detcore-linked reverie-dbt runtime.
#[cfg(feature = "dbt")]
async fn run_dbt(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    capture_output: bool,
) -> Result<Output, Error> {
    if !config.sequentialize_threads {
        return Err(anyhow!(
            "the dbt backend requires sequentialized threads; remove \
             --no-sequentialize-threads (or --strace-only) to run under --backend dbt"
        ));
    }

    let config_json = serde_json::to_string(&config)
        .map_err(|error| anyhow!("failed to serialize the Detcore config for DBT: {error}"))?;
    let panic_on_unsupported_syscalls = config.panic_on_unsupported_syscalls;
    let (drrun, client) = detcore_dbt::prepare_native_client()
        .map_err(|error| anyhow!("failed to prepare the Detcore DynamoRIO client: {error}"))?;
    let mut runner = reverie_dbt::DbtRunner::new(&drrun, &client)
        .map_err(|error| {
            anyhow!(
                "failed to configure the DynamoRIO DBT runner (drrun={}, client={}): {error}",
                drrun.display(),
                client.display()
            )
        })?
        .summary(print_summary)
        .isolated_process_group(panic_on_unsupported_syscalls);
    if panic_on_unsupported_syscalls {
        runner = runner.client_argument("-panic-on-unsupported-syscalls");
    }

    let program = command.get_program().to_owned();
    let mut environment = command.get_captured_envs();
    environment.insert(detcore_dbt::DETCONFIG_ENV.into(), config_json.into());
    let guest = command.into_std_lossy();
    tracing::info!(
        target: "hermit::dbt",
        program = ?program,
        drrun = %drrun.display(),
        client = %client.display(),
        "launching guest through reverie-dbt with Detcore<DbtGuest>",
    );

    let (status, stdout, stderr, mut global) = if capture_output {
        let launch = || {
            runner.output_with_environment_and_global::<detcore::GlobalState>(
                &guest,
                &environment,
                config.clone(),
            )
        };
        let (mut output, mut global) = launch()
            .await
            .map_err(|error| anyhow!("failed to launch drrun ({}): {error}", drrun.display()))?;
        if dbt_client_thread_start_failed(&output.status) {
            tracing::warn!(
                target: "hermit::dbt",
                "DynamoRIO client thread failed before guest start; retrying once",
            );
            global.force_shutdown_with_error();
            global.cancel_internal_scheduler().await;
            global.clean_up(false, &None).await;
            (output, global) = launch().await.map_err(|error| {
                anyhow!("failed to launch drrun ({}): {error}", drrun.display())
            })?;
        }
        (output.status, output.stdout, output.stderr, global)
    } else {
        let launch = || {
            runner.status_with_environment_and_global::<detcore::GlobalState>(
                &guest,
                &environment,
                config.clone(),
            )
        };
        let (mut status, mut global) = launch()
            .await
            .map_err(|error| anyhow!("failed to launch drrun ({}): {error}", drrun.display()))?;
        if dbt_client_thread_start_failed(&status) {
            tracing::warn!(
                target: "hermit::dbt",
                "DynamoRIO client thread failed before guest start; retrying once",
            );
            global.force_shutdown_with_error();
            global.cancel_internal_scheduler().await;
            global.clean_up(false, &None).await;
            (status, global) = launch().await.map_err(|error| {
                anyhow!("failed to launch drrun ({}): {error}", drrun.display())
            })?;
        }
        (status, Vec::new(), Vec::new(), global)
    };

    if !status.success() {
        global.force_shutdown_with_error();
        global.cancel_internal_scheduler().await;
    }
    global.clean_up(print_summary, &None).await;
    Ok(Output {
        status: status.into(),
        stdout,
        stderr,
    })
}

// NOTE: A single-threaded executor is used here so that the tokio threads
// themselves wouldn't contribute non-determinism to the PID namespace. This
// could also be changed to a specific number of threads and that would be
// deterministic, but it shouldn't be based on the number of cores. When the
// thread count is based off of the number of cores in the machine, then two
// runs on different machines with a different number of cores will not be the
// same.
/// Run the given command as deterministically as possible.
pub fn run(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
) -> Result<ExitStatus, Error> {
    run_with_backend(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        Backend::Ptrace,
    )
}

/// Run the given command using the selected instrumentation backend.
pub fn run_with_backend(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
) -> Result<ExitStatus, Error> {
    run_with_backend_timeout(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        None,
    )
}

/// [`run_with_backend`] with a hermit-enforced wall-clock bound on the guest.
///
/// This library never installs a process alarm. Ordinary ptrace keeps the
/// original runtime, operation, failed GlobalState and backing guards when a
/// finite cleanup attempt is unconfirmed; downcast [`HermitCleanupUnconfirmed`]
/// and recover it on the original process/thread. A timeout is measured before
/// startup and is not a certificate of cleanup. `None` leaves execution
/// unbounded, but fatal cleanup attempts remain finite. Nonordinary backends
/// retain their existing cooperative timeout/drop semantics. Synchronous stalls
/// require caller-owned supervision; only the CLI owns its hard alarm fallback.
///
/// ⚠️ NOT PART OF `DetConfig`, DELIBERATELY. A wall-clock bound is host state,
/// and `DetConfig` is the determinism configuration that is serialized to disk
/// and reasoned about as guest-visible. Threading a real-time deadline through
/// it would put a nondeterministic quantity inside the structure whose entire
/// job is to exclude them.
pub fn run_with_backend_timeout(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<ExitStatus, Error> {
    if backend == Backend::Ptrace {
        let summary_path = print_summary_to_json_file.clone();
        return ptrace_completion::run(timeout, move |control| async move {
            let report = SkidOvershootReport::begin(true);
            let config = prepare_backend_config(config, backend);
            let result = dispatch_backend(
                command,
                config,
                print_summary,
                &summary_path,
                backend,
                Some(control),
            )
            .await;
            report.finish(result)
        });
    }
    let skid_overshoot_report = SkidOvershootReport::begin(backend.uses_ptrace_pmu_timers());
    if backend == Backend::Kvm {
        ensure_kvm_stdin_reserved()?;
    }
    let config = prepare_backend_config(config, backend);
    let result = run_with_backend_inner(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        timeout,
    );
    skid_overshoot_report.finish(result)
}

// TODO-HUMAN-REVIEW(PR-749): Review LiteInst backend configuration normalization.
#[doc(hidden)]
pub fn prepare_backend_config(config: DetConfig, backend: Backend) -> DetConfig {
    // An unrecognized selector value configures the hybrid here; the run refuses
    // that value before it dispatches.
    let liteinst_runtime = if backend == Backend::Liteinst {
        LiteinstRuntime::from_env().unwrap_or(LiteinstRuntime::HostHybrid)
    } else {
        LiteinstRuntime::HostHybrid
    };
    prepare_backend_config_for_liteinst_runtime(config, backend, liteinst_runtime)
}

/// [`prepare_backend_config`] with the LiteInst runtime given explicitly rather
/// than read from [`LITEINST_IN_GUEST_ENV`]. Other backends ignore it.
#[doc(hidden)]
pub fn prepare_backend_config_for_liteinst_runtime(
    mut config: DetConfig,
    backend: Backend,
    liteinst_runtime: LiteinstRuntime,
) -> DetConfig {
    let in_guest_liteinst =
        backend == Backend::Liteinst && liteinst_runtime == LiteinstRuntime::InGuest;
    config.discover_live_file_metadata = backend == Backend::Sabre;
    // Guest-visible wall and monotonic clocks must stay in the same global
    // virtual-time domain as timers, sleeps, and timeout deadlines. SaBRe's
    // per-thread execution clock does not advance when the scheduler skips
    // global time while a thread is blocked.
    config.use_thread_local_clock_reads = false;
    config.detect_host_clock_futex_timeouts = backend == Backend::Sabre;
    config.syscall_clobbers_virtualized_by_backend = backend == Backend::Sabre;
    // Wake pending RPCs on logical removal, reject stale requests, and account
    // the eventual deregistration exactly once. KVM has no native task exit
    // that can resolve a removed thread's pending Tool future, and in-guest
    // LiteInst, like DBT, has no ptrace exit-group teardown to resolve it.
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-3635): Review in-guest LiteInst killed-thread RPC cancellation.
    config.cancel_killed_thread_rpcs =
        in_guest_liteinst || matches!(backend, Backend::Sabre | Backend::Dbt | Backend::Kvm);
    config.backend_reports_physical_process_exits = backend == Backend::Sabre;
    // TODO-HUMAN-REVIEW(PR-1122): Review concurrent KVM process-child scheduling.
    config.backend_serializes_fork_children = false;
    config.backend_dispatches_thread_tools = true;
    config.backend_tracks_process_children = backend != Backend::Dbt;
    // Ptrace reports the task exit after Linux has atomically updated every
    // robust owner word. DBT and SaBRe report tool exit before executing the
    // native exit syscall, while KVM does not execute a native task exit, so
    // none of those backends can safely defer Detcore's modeled transition.
    config.backend_runs_exit_robust_list = backend == Backend::Ptrace;
    config.backend_requires_thread_directed_process_signals = backend == Backend::Dbt;
    config.backend_is_kvm = backend == Backend::Kvm;
    config.kvm_shared_dequeue_timers = config.backend_is_kvm && config.sequentialize_threads;
    // E9patch preprocesses the guest and then uses the ptrace builder. LiteInst,
    // DBT, KVM, and SaBRe re-invoke the Tool callback on ERESTARTSYS instead of
    // resuming through the kernel's ptrace syscall-restart frame.
    config.backend_supports_parked_write_signal_interruption =
        matches!(backend, Backend::Ptrace | Backend::E9patch);
    config.backend_virtualizes_capability_prctls = backend == Backend::Kvm;
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1152): KVM defers the vfork child spawn, so the child
    // registers its vfork barrier only after the parent posts BlockedExternalContinue. ptrace keeps
    // the parent kernel-blocked until the child registers, so this stays false there.
    config.backend_defers_vfork_child_registration = backend == Backend::Kvm;
    config
}

// TODO-HUMAN-REVIEW(PR-736): Review reserved LiteInst runtime failure statuses.
//
// ⚠️ THIS PREDICATE AND THE CLASSIFIER MUST AGREE ABOUT THE SIGNAL BAND, AND A
// HARD-CODED RANGE CANNOT. They do NOT cover the same statuses and are not meant
// to -- see the table below for what each covers. It is the SIGNAL half that has
// to move together, because both readers derive it from the same fact. When the reserved set grew to include the signal
// band, `Exited(130)` fell outside `122..=127` and is NOT `Signaled(_, _)` --
// it is a status hermit CHOSE, not an actual signal death -- so LiteInst
// skipped the forced shutdown and `clean_up` could wait forever on
// `handle.await` (detcore/src/tool_global.rs). The reserved set had grown past
// the range this hard-coded, and nothing connected the two.
//
// Keying the SIGNAL HALF on `signal_from_exit_status` -- the same predicate
// `classify_container_result` uses -- is what stops that half drifting again: a
// change to the band moves both readers or neither.
//
// ⚠️ THE TWO PREDICATES ARE NOT THE SAME SET, AND AN EARLIER VERSION OF THIS
// COMMENT SAID THEY WERE. agent(hermit-007)'s codex lane caught the overclaim.
// They deliberately differ:
//
//   this predicate            122..=127  +  signal band  +  real Signaled
//   classify_container_result 122        +  signal band
//
// 123..=127 force a LiteInst shutdown and are classified as NEITHER a refusal
// nor a signal death -- 123 is safehermit's log cap, 124 a deadline, 125 hermit
// itself, 126/127 exec-level, and each has a different producer. Only the signal
// half is shared, and only the signal half is protected from drift. Do not
// "simplify" this by assuming the two agree; the `122..=127` bound here is still
// hard-coded and still needs a human to widen it if the reserved set grows
// again.
#[cfg(feature = "liteinst")]
fn liteinst_requires_forced_shutdown(status: ExitStatus) -> bool {
    match status {
        // A real signal death: the process never chose a status at all.
        ExitStatus::Signaled(_, _) => true,
        ExitStatus::Exited(code) => {
            // The 122..=127 reserved band, plus any status hermit emits to mean
            // "killed by signal N".
            (122..=127).contains(&code) || detcore_model::signal_from_exit_status(code).is_some()
        }
    }
}

/// The guest outlived the wall-clock bound the caller asked hermit to enforce.
///
/// A DISTINCT TYPE, NOT A STRING, because `failure_exit_code` and
/// `classify_failure` both have to recognise it and a prose match would break
/// silently the first time the wording changed.
#[derive(Debug)]
pub struct GuestTimedOut {
    /// The bound that was exceeded, as the caller spelled it.
    pub limit: Duration,
}

impl std::fmt::Display for GuestTimedOut {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Guest exceeded the --timeout bound of {} seconds",
            self.limit.as_secs()
        )
    }
}

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

/// Nonordinary backends retain their existing cooperative timeout behavior.
/// There is no process-wide alarm in this library. A caller needing a bound on
/// synchronous stalls must own external supervision; the CLI arms its own
/// separate init-process fallback before invoking the library. Ordinary ptrace
/// uses the retained whole-operation driver instead of cancelling this future.
async fn with_run_deadline<F>(timeout: Option<Duration>, guest: F) -> Result<ExitStatus, Error>
where
    F: std::future::Future<Output = Result<ExitStatus, Error>>,
{
    match timeout {
        None => guest.await,
        Some(limit) => match tokio::time::timeout(limit, guest).await {
            Ok(result) => result,
            Err(_) => Err(Error::new(GuestTimedOut { limit })),
        },
    }
}

#[tokio::main(flavor = "current_thread")]
async fn run_with_backend_inner(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<ExitStatus, Error> {
    refuse_in_guest_liteinst_timeout(backend, timeout)?;
    // Keep the large backend future off the container supervisor's stack
    // before the deadline and Tokio wrappers capture it. Polling and dropping
    // stay inline, including the backend teardown on timeout.
    let guest = Box::pin(dispatch_backend(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        None,
    ));
    with_run_deadline(timeout, guest).await
}

async fn dispatch_backend(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    control: Option<std::rc::Rc<ptrace_completion::Control>>,
) -> Result<ExitStatus, Error> {
    if backend == Backend::Kvm {
        return Ok(run_kvm(
            &command,
            config,
            print_summary,
            print_summary_to_json_file,
            false,
        )
        .await?
        .status);
    }
    if backend == Backend::Dbt {
        #[cfg(feature = "dbt")]
        {
            return Ok(run_dbt(command, config, print_summary, false).await?.status);
        }
        #[cfg(not(feature = "dbt"))]
        {
            backend.ensure_available()?;
            unreachable!("DBT availability must fail when the feature is disabled");
        }
    }
    if backend == Backend::Sabre {
        return Ok(run_sabre(
            command,
            config,
            print_summary,
            print_summary_to_json_file,
            false,
        )
        .await?
        .status);
    }
    if backend == Backend::Liteinst {
        #[cfg(feature = "liteinst")]
        {
            let stats_request = backend_stats::request(print_summary_to_json_file);
            let (exit_status, mut global_state, dispatch_stats) = match LiteinstRuntime::from_env()?
            {
                LiteinstRuntime::InGuest => {
                    let mut command = command;
                    refuse_in_guest_liteinst_run(&mut command, &config)?;
                    let preload = liteinst_tool_runtime_library_path()?;
                    if stats_request.is_enabled() {
                        let (exit_status, global_state, source) =
                            reverie_liteinst::LiteinstBackend::run_with_preload_and_stats::<Detcore>(
                                command, config, preload,
                            )
                            .await?;
                        let dispatch_stats = backend_stats::report(backend, stats_request, &source);
                        (exit_status, global_state, dispatch_stats)
                    } else {
                        let (exit_status, global_state) =
                            reverie_liteinst::LiteinstBackend::run_with_preload::<Detcore>(
                                command, config, preload,
                            )
                            .await?;
                        (exit_status, global_state, None)
                    }
                }
                LiteinstRuntime::HostHybrid => {
                    let preload = liteinst_runtime_library_path()?;
                    if stats_request.is_enabled() {
                        let (exit_status, global_state, source) =
                            reverie_liteinst::LiteinstBackend::run_host_with_preload_and_stats::<
                                Detcore,
                            >(command, config, preload)
                            .await?;
                        let dispatch_stats = backend_stats::report(backend, stats_request, &source);
                        (exit_status, global_state, dispatch_stats)
                    } else {
                        let (exit_status, global_state) =
                            reverie_liteinst::LiteinstBackend::run_host_with_preload::<Detcore>(
                                command, config, preload,
                            )
                            .await?;
                        (exit_status, global_state, None)
                    }
                }
            };
            if liteinst_requires_forced_shutdown(exit_status) {
                global_state.force_shutdown_with_error();
                global_state.cancel_internal_scheduler().await;
            }
            global_state
                .clean_up_with_dispatch_stats(
                    print_summary,
                    print_summary_to_json_file,
                    dispatch_stats,
                )
                .await;
            return Ok(exit_status);
        }
        #[cfg(not(feature = "liteinst"))]
        {
            backend.ensure_available()?;
            unreachable!("LiteInst availability must fail when the feature is disabled");
        }
    }
    ensure_backend_dispatch(backend)?;

    let stats_request = backend_stats::request(print_summary_to_json_file);
    let mut builder = reverie_ptrace::TracerBuilder::<Detcore>::new(command).config(config.clone());
    if config.gdbserver {
        builder = builder.gdbserver(config.gdbserver_port);
        if config.sequentialize_threads {
            // Inform gdbserver not to serialize guests because this is
            // done by detcore already. Without this the gdbserver freezes
            // the other threads around a breakpoint stop and waits for each
            // to report, but under detcore they are parked in its scheduler
            // rather than blocked in the kernel, so they cannot answer until
            // the scheduler runs them -- which it cannot while the stopped
            // thread holds its turn. The replay path already does this.
            builder = builder.sequentialized_guest();
        }
    }
    let control = control
        .ok_or_else(|| Error::msg("ordinary ptrace requires its retained operation owner"))?;
    let tracer = builder.backend_stats(stats_request).spawn().await?;
    let stats_source = tracer.backend_stats();
    let (exit_status, global_state) = ptrace_completion::wait(tracer, control).await?;
    let dispatch_stats =
        backend_stats::report_if_collected(backend, stats_request, stats_source.as_ref());
    global_state
        .clean_up_with_dispatch_stats(print_summary, print_summary_to_json_file, dispatch_stats)
        .await; // Before it's dropped by this function.
    Ok(exit_status)
}

/// Variant of `run` that also captures stdout/stderr.
pub fn run_with_output(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
) -> Result<Output, Error> {
    run_with_output_backend(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        Backend::Ptrace,
    )
}

/// Variant of [`run_with_backend`] that also captures stdout/stderr.
pub fn run_with_output_backend(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
) -> Result<Output, Error> {
    if backend == Backend::Kvm {
        ensure_kvm_stdin_reserved()?;
    }
    run_with_output_backend_timeout(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        None,
    )
}

/// [`run_with_output_backend`] with a hermit-enforced wall-clock bound.
///
/// See [`run_with_backend_timeout`]; the teardown semantics are identical.
pub fn run_with_output_backend_timeout(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<Output, Error> {
    if backend == Backend::Ptrace {
        let summary_path = print_summary_to_json_file.clone();
        return ptrace_completion::run(timeout, move |control| async move {
            let report = SkidOvershootReport::begin(true);
            let result = dispatch_output_backend(
                command,
                prepare_backend_config(config, backend),
                print_summary,
                &summary_path,
                backend,
                Some(control),
            )
            .await;
            report.finish(result)
        });
    }
    let (output, skid_overshoots) = run_with_output_backend_timeout_and_skid_overshoots(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        timeout,
    )?;
    if skid_overshoots > 0 {
        return Err(Error::new(SkidOvershootError::new(skid_overshoots)));
    }
    Ok(output)
}

/// Run with captured output and return the number of precise PMU timer
/// overshoots alongside it instead of refusing before a caller can inspect the
/// completed output. The `--verify` path uses this to finish and publish its
/// comparison before it refuses the overshoot-tainted result.
#[doc(hidden)]
pub fn run_with_output_backend_timeout_and_skid_overshoots(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<(Output, u64), Error> {
    if backend == Backend::Ptrace {
        let summary_path = print_summary_to_json_file.clone();
        return ptrace_completion::run(timeout, move |control| async move {
            let report = SkidOvershootReport::begin(true);
            let result = dispatch_output_backend(
                command,
                prepare_backend_config(config, backend),
                print_summary,
                &summary_path,
                backend,
                Some(control),
            )
            .await;
            report.finish_with_count(result)
        });
    }
    let skid_overshoot_report = SkidOvershootReport::begin(backend.uses_ptrace_pmu_timers());
    if backend == Backend::Kvm {
        // Reserve before the Tokio runtime can reuse a closed fd 0. KVM
        // verification consumes the explicit output snapshot in `run_kvm`;
        // public output-capture callers without one retain this reservation.
        ensure_kvm_stdin_reserved()?;
    }
    let config = prepare_backend_config(config, backend);
    let result = run_with_output_backend_inner(
        command,
        config,
        print_summary,
        print_summary_to_json_file,
        backend,
        timeout,
    );
    skid_overshoot_report.finish_with_count(result)
}

#[tokio::main(flavor = "current_thread")]
async fn run_with_output_backend_inner(
    command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    timeout: Option<Duration>,
) -> Result<Output, Error> {
    refuse_in_guest_liteinst_timeout(backend, timeout)?;
    let Some(limit) = timeout else {
        return dispatch_output_backend(
            command,
            config,
            print_summary,
            print_summary_to_json_file,
            backend,
            None,
        )
        .await;
    };
    match tokio::time::timeout(
        limit,
        dispatch_output_backend(
            command,
            config,
            print_summary,
            print_summary_to_json_file,
            backend,
            None,
        ),
    )
    .await
    {
        Ok(result) => result,
        Err(_elapsed) => Err(Error::new(GuestTimedOut { limit })),
    }
}

async fn dispatch_output_backend(
    mut command: Command,
    config: DetConfig,
    print_summary: bool,
    print_summary_to_json_file: &Option<PathBuf>,
    backend: Backend,
    control: Option<std::rc::Rc<ptrace_completion::Control>>,
) -> Result<Output, Error> {
    if backend == Backend::Kvm {
        return run_kvm(
            &command,
            config,
            print_summary,
            print_summary_to_json_file,
            true,
        )
        .await;
    }
    if backend == Backend::Dbt {
        #[cfg(feature = "dbt")]
        {
            return run_dbt(command, config, print_summary, true).await;
        }
        #[cfg(not(feature = "dbt"))]
        {
            backend.ensure_available()?;
            unreachable!("DBT availability must fail when the feature is disabled");
        }
    }
    if backend == Backend::Sabre {
        command.stdin(output_backend_stdin()?);
        command.stdout(Stdio::piped());
        command.stderr(Stdio::piped());
        return run_sabre(
            command,
            config,
            print_summary,
            print_summary_to_json_file,
            true,
        )
        .await;
    }
    if backend == Backend::Liteinst {
        #[cfg(feature = "liteinst")]
        {
            command.stdin(output_backend_stdin()?);
            let stats_request = backend_stats::request(print_summary_to_json_file);
            let (output, mut global_state, dispatch_stats) = match LiteinstRuntime::from_env()? {
                LiteinstRuntime::InGuest => {
                    refuse_in_guest_liteinst_run(&mut command, &config)?;
                    let preload = liteinst_tool_runtime_library_path()?;
                    let (output, global_state, dispatch_stats) = if stats_request.is_enabled() {
                        let (output, global_state, source) =
                            reverie_liteinst::LiteinstBackend::run_with_output_and_preload_and_stats::<
                                Detcore,
                            >(command, config, preload)
                            .await?;
                        let dispatch_stats = backend_stats::report(backend, stats_request, &source);
                        (output, global_state, dispatch_stats)
                    } else {
                        let (output, global_state) =
                            reverie_liteinst::LiteinstBackend::run_with_output_and_preload::<
                                Detcore,
                            >(command, config, preload)
                            .await?;
                        (output, global_state, None)
                    };
                    let output = Output {
                        status: output.status.into(),
                        stdout: output.stdout,
                        stderr: output.stderr,
                    };
                    (output, global_state, dispatch_stats)
                }
                LiteinstRuntime::HostHybrid => {
                    let preload = liteinst_runtime_library_path()?;
                    if stats_request.is_enabled() {
                        let (output, global_state, source) =
                            reverie_liteinst::LiteinstBackend::run_host_with_output_and_preload_and_stats::<
                                Detcore,
                            >(command, config, preload)
                            .await?;
                        let dispatch_stats = backend_stats::report(backend, stats_request, &source);
                        (output, global_state, dispatch_stats)
                    } else {
                        let (output, global_state) =
                            reverie_liteinst::LiteinstBackend::run_host_with_output_and_preload::<
                                Detcore,
                            >(command, config, preload)
                            .await?;
                        (output, global_state, None)
                    }
                }
            };
            let status = output.status;
            if liteinst_requires_forced_shutdown(status) {
                global_state.force_shutdown_with_error();
                global_state.cancel_internal_scheduler().await;
            }
            global_state
                .clean_up_with_dispatch_stats(
                    print_summary,
                    print_summary_to_json_file,
                    dispatch_stats,
                )
                .await;
            return Ok(Output {
                status,
                stdout: output.stdout,
                stderr: output.stderr,
            });
        }
        #[cfg(not(feature = "liteinst"))]
        {
            backend.ensure_available()?;
            unreachable!("LiteInst availability must fail when the feature is disabled");
        }
    }
    ensure_backend_dispatch(backend)?;

    let stats_request = backend_stats::request(print_summary_to_json_file);
    command.stdin(output_backend_stdin()?);
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());
    let mut builder = reverie_ptrace::TracerBuilder::<Detcore>::new(command).config(config.clone());
    if config.gdbserver {
        builder = builder.gdbserver(config.gdbserver_port);
        if config.sequentialize_threads {
            // Inform gdbserver not to serialize guests because this is
            // done by detcore already. Without this the gdbserver freezes
            // the other threads around a breakpoint stop and waits for each
            // to report, but under detcore they are parked in its scheduler
            // rather than blocked in the kernel, so they cannot answer until
            // the scheduler runs them -- which it cannot while the stopped
            // thread holds its turn. The replay path already does this.
            builder = builder.sequentialized_guest();
        }
    }
    let control = control
        .ok_or_else(|| Error::msg("ordinary ptrace requires its retained operation owner"))?;
    let tracer = builder.backend_stats(stats_request).spawn().await?;
    let stats_source = tracer.backend_stats();
    let (output, global_state) = ptrace_completion::wait_with_output(tracer, control).await?;
    let dispatch_stats =
        backend_stats::report_if_collected(backend, stats_request, stats_source.as_ref());
    global_state
        .clean_up_with_dispatch_stats(print_summary, print_summary_to_json_file, dispatch_stats)
        .await;
    Ok(output)
}

/// Holds the context necessary to run high-level hermit functions.
pub struct HermitData {
    // The data directory. Defaults to `~/.cache/hermit`. Note that we shouldn't
    // expect this to exist in any of the functions that are called.
    data_dir: PathBuf,
}

fn collect_recording_ids(
    entries: impl IntoIterator<Item = io::Result<fs::DirEntry>>,
    data_dir: &Path,
    mut file_type: impl FnMut(&fs::DirEntry) -> io::Result<fs::FileType>,
) -> Result<Vec<Id>, Error> {
    let mut recordings = Vec::new();
    for entry in entries {
        let entry = entry.with_context(|| {
            format!(
                "Failed to read an entry in recording inventory {}",
                data_dir.display()
            )
        })?;
        let path = entry.path();
        if file_type(&entry)
            .with_context(|| {
                format!(
                    "Failed to inspect recording inventory entry {}",
                    path.display()
                )
            })?
            .is_dir()
            && let Some(id) = entry
                .file_name()
                .to_str()
                .and_then(|name| name.parse::<Id>().ok())
        {
            recordings.push(id);
        }
    }
    Ok(recordings)
}

impl Default for HermitData {
    fn default() -> Self {
        Self::new()
    }
}

impl HermitData {
    /// Creates an instance of `HermitData` using `~/.cache/hermit` as the data
    /// directory.
    pub fn new() -> Self {
        Self::with_dir(
            dirs::cache_dir()
                .map_or_else(|| PathBuf::from("/tmp/hermit"), |dir| dir.join("hermit")),
        )
    }

    /// Creates a `HermitData` using the given directory as the base path for
    /// storing recording data.
    pub fn with_dir<P>(data_dir: P) -> Self
    where
        P: Into<PathBuf>,
    {
        Self {
            data_dir: data_dir.into(),
        }
    }

    /// Returns the path to the data directory where recordings are stored.
    pub fn data_dir(&self) -> &Path {
        &self.data_dir
    }

    /// Records the execution of the given command, returning its `Recording`.
    ///
    /// If recording failed, then an error is returned. Note that if the command
    /// itself failed, then we still return a successful recording, but its exit
    /// status will be non-zero.
    ///
    /// This low-level API does not create a Hermit container, so it has no
    /// authenticated private-mount provenance to supply. Detcore derives mount
    /// identities from the completed guest namespace. CLI container callers
    /// with producer-owned root provenance must use
    /// [`Self::record_with_mountinfo`].
    pub fn record(&self, command: Command) -> Result<Recording, Error> {
        let store = Self {
            data_dir: self.data_dir.clone(),
        };
        ptrace_completion::run(None, move |control| async move {
            let data = store.create_recording_dir()?;
            let exit_status =
                record_to_async(command, data.path(), Vec::new(), None, None, control).await?;
            store.commit_recording(data, exit_status)
        })
    }

    /// Records with mountinfo provenance captured from the active container.
    pub fn record_with_mountinfo(
        &self,
        command: Command,
        mountinfo_root_rewrites: Vec<detcore_model::config::MountInfoRootRewrite>,
    ) -> Result<Recording, Error> {
        let store = Self {
            data_dir: self.data_dir.clone(),
        };
        ptrace_completion::run(None, move |control| async move {
            let data = store.create_recording_dir()?;
            let mount_ids = capture_mountinfo_identity_order()?;
            let exit_status = record_to_async(
                command,
                data.path(),
                mountinfo_root_rewrites,
                Some(mount_ids),
                None,
                control,
            )
            .await?;
            store.commit_recording(data, exit_status)
        })
    }

    /// Creates a temporary directory for a recording that has not been committed yet.
    pub fn create_recording_dir(&self) -> Result<tempfile::TempDir, Error> {
        let tmp_data_dir = self.data_dir.join("tmp");

        fs::create_dir_all(&tmp_data_dir).with_context(|| {
            format!(
                "Failed to create recording directory: {}",
                self.data_dir.display()
            )
        })?;

        Ok(tempfile::TempDir::new_in(tmp_data_dir)?)
    }

    /// Commits a completed temporary recording to the recording store.
    pub fn commit_recording(
        &self,
        data: tempfile::TempDir,
        exit_status: ExitStatus,
    ) -> Result<Recording, Error> {
        let id = Id::unique();

        // Atomically move the temporary recording to its final location.
        fs::rename(data.keep(), self.data_dir.join(id.to_string()))?;

        self.update_last_id(&id)
            .with_context(|| format!("Failed to update {:?}", self.data_dir.join("last")))?;

        Ok(Recording { id, exit_status })
    }

    /// Replays the given recording ID.
    pub fn replay(&self, id: Id) -> Result<ExitStatus, Error> {
        let data = self.data_dir.join(id.to_string());
        replay_from(&data)
    }

    /// Replays the given recording ID with a gdbserver available to attach to.
    pub fn replay_with_gdbserver(&self, id: Id, port: u16) -> Result<ExitStatus, Error> {
        let data = self.data_dir.join(id.to_string());
        replay_with_gdbserver(&data, port)
    }

    /// Returns an iterator over the recordings.
    ///
    /// Use [`Self::recording_metadata`] to get more information about a recording.
    pub fn recordings(&self) -> impl Iterator<Item = Id> + use<> {
        fs::read_dir(&self.data_dir)
            .ok()
            .into_iter()
            .flatten()
            .filter_map(|entry| {
                let entry = entry.ok()?;

                if entry.file_type().ok()?.is_dir() {
                    Some(entry.file_name().to_str()?.parse::<Id>().ok()?)
                } else {
                    None
                }
            })
    }

    /// Returns all recordings, or an error if the data directory cannot be
    /// enumerated completely.
    ///
    /// A missing data directory has no recordings. Other filesystem errors are
    /// returned rather than being mistaken for an empty or partial inventory.
    pub fn try_recordings(&self) -> Result<Vec<Id>, Error> {
        let entries = match fs::read_dir(&self.data_dir) {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => {
                return Err(error).with_context(|| {
                    format!(
                        "Failed to read recording inventory in {}",
                        self.data_dir.display()
                    )
                });
            }
        };

        collect_recording_ids(entries, &self.data_dir, fs::DirEntry::file_type)
    }

    /// Returns the metadata of a recording.
    pub fn recording_metadata(&self, id: Id) -> Result<Metadata, Error> {
        Metadata::load(&self.data_dir.join(id.to_string()))
    }

    /// Deletes a recording.
    pub fn remove(&self, id: Id) -> Result<(), Error> {
        let path = self.data_dir.join(id.to_string());

        // Before deleting anything, make sure this file exists. This may not be a
        // recording if this file does not exist.
        let metadata_path = path.join(METADATA_NAME);
        let metadata = fs::metadata(&metadata_path)
            .with_context(|| format!("Failed to find {:?}", metadata_path))?;

        if !metadata.is_file() {
            return Err(anyhow!("{:?} is not a file", metadata_path));
        }

        // Do a recursive delete on the directory. Note that this does not follow
        // symlinks.
        fs::remove_dir_all(path)?;

        Ok(())
    }

    /// Returns the last recorded ID.
    pub fn last_id(&self) -> Result<Id, Error> {
        Ok(fs::read_to_string(self.data_dir.join("last"))?.parse()?)
    }

    /// Atomically updates the last recording ID.
    fn update_last_id(&self, id: &Id) -> Result<(), Error> {
        let mut file = tempfile::NamedTempFile::new_in(self.data_dir.join("tmp"))?;
        write!(file, "{}", id)?;
        file.persist(self.data_dir.join("last"))?;
        Ok(())
    }
}

/// Capture the current mount namespace's raw IDs in the exact row/parent order
/// used by Detcore's canonical mountinfo mapping.
pub fn capture_mountinfo_identity_order() -> Result<Vec<u64>, Error> {
    mountinfo_identity_order_from(&fs::read("/proc/self/mountinfo")?)
}

fn mountinfo_identity_order_from(contents: &[u8]) -> Result<Vec<u64>, Error> {
    use std::collections::BTreeSet;

    let rows = detcore_model::procfs::parse_mountinfo(contents)
        .ok_or_else(|| anyhow!("malformed /proc/self/mountinfo"))?;
    let mut visible = Vec::new();
    let mut parents = Vec::new();
    let mut seen = BTreeSet::new();
    for row in rows {
        seen.insert(row.raw_mount_id);
        visible.push(row.raw_mount_id);
        parents.push(row.raw_parent_id);
    }
    for parent in parents {
        if seen.insert(parent) {
            visible.push(parent);
        }
    }
    Ok(visible)
}

impl<'a> From<Option<&'a PathBuf>> for HermitData {
    fn from(data_dir: Option<&'a PathBuf>) -> Self {
        data_dir.map_or_else(Self::new, Self::with_dir)
    }
}

/// Records to an existing directory. The caller must keep its backing resources
/// alive through any [`HermitCleanupUnconfirmed`] recovery. [`HermitData::record`]
/// owns its temporary recording directory inside the retained operation.
pub fn record_to(command: Command, dir: &Path) -> Result<ExitStatus, Error> {
    let dir = dir.to_owned();
    ptrace_completion::run(None, move |control| async move {
        record_to_async(command, &dir, Vec::new(), None, None, control).await
    })
}

/// Records with producer-owned mountinfo provenance. The directory-lifetime
/// obligation is the same as [`record_to`]. `local_networking` is stored in
/// the recording's `metadata.json`, and an autopilot replay uses that network.
pub fn record_to_with_mountinfo(
    command: Command,
    dir: &Path,
    mountinfo_root_rewrites: Vec<detcore_model::config::MountInfoRootRewrite>,
    local_networking: bool,
) -> Result<ExitStatus, Error> {
    let dir = dir.to_owned();
    ptrace_completion::run(None, move |control| async move {
        let mount_ids = capture_mountinfo_identity_order()?;
        record_to_async(
            command,
            &dir,
            mountinfo_root_rewrites,
            Some(mount_ids),
            Some(local_networking),
            control,
        )
        .await
    })
}

async fn record_to_async(
    command: Command,
    dir: &Path,
    mountinfo_root_rewrites: Vec<detcore_model::config::MountInfoRootRewrite>,
    mountinfo_mount_ids: Option<Vec<u64>>,
    local_networking: Option<bool>,
    control: std::rc::Rc<ptrace_completion::Control>,
) -> Result<ExitStatus, Error> {
    let report = SkidOvershootReport::begin(true);
    let result = async {
        Record::spawn_with_mountinfo(
            command,
            dir,
            mountinfo_root_rewrites,
            mountinfo_mount_ids,
            local_networking,
        )
        .await?
        .wait(control)
        .await
    }
    .await;
    report.finish(result)
}

/// Records and captures output. Keep the directory's backing resources alive
/// through any cleanup checkpoint, as for [`record_to`].
pub fn record_with_output(command: Command, dir: &Path) -> Result<Output, Error> {
    let dir = dir.to_owned();
    ptrace_completion::run(None, move |control| async move {
        record_with_output_async(command, &dir, Vec::new(), None, None, control).await
    })
}

/// Records with captured output and exact mountinfo provenance.
/// `local_networking` is as for [`record_to_with_mountinfo`].
pub fn record_with_output_with_mountinfo(
    command: Command,
    dir: &Path,
    mountinfo_root_rewrites: Vec<detcore_model::config::MountInfoRootRewrite>,
    local_networking: bool,
) -> Result<Output, Error> {
    let dir = dir.to_owned();
    ptrace_completion::run(None, move |control| async move {
        let mount_ids = capture_mountinfo_identity_order()?;
        record_with_output_async(
            command,
            &dir,
            mountinfo_root_rewrites,
            Some(mount_ids),
            Some(local_networking),
            control,
        )
        .await
    })
}

async fn record_with_output_async(
    mut command: Command,
    dir: &Path,
    mountinfo_root_rewrites: Vec<detcore_model::config::MountInfoRootRewrite>,
    mountinfo_mount_ids: Option<Vec<u64>>,
    local_networking: Option<bool>,
    control: std::rc::Rc<ptrace_completion::Control>,
) -> Result<Output, Error> {
    let report = SkidOvershootReport::begin(true);
    command.stdin(Stdio::null());
    command.stdout(Stdio::piped());
    command.stderr(Stdio::piped());
    let result = async {
        Record::spawn_with_mountinfo(
            command,
            dir,
            mountinfo_root_rewrites,
            mountinfo_mount_ids,
            local_networking,
        )
        .await?
        .wait_with_output(control)
        .await
    }
    .await;
    report.finish(result)
}

/// Replays an existing recording. Materialization and chroot guards remain with
/// the original runtime through any cleanup checkpoint.
pub fn replay_from(dir: &Path) -> Result<ExitStatus, Error> {
    replay_plain(dir, None, &[])
}

/// Replays with a gdb server.
pub fn replay_with_gdbserver(dir: &Path, port: u16) -> Result<ExitStatus, Error> {
    replay_plain(dir, Some(port), &[])
}

/// Replays with a gdb server and mounts inside the replay chroot.
pub fn replay_with_gdbserver_and_mounts(
    dir: &Path,
    port: u16,
    mounts: &[Mount],
) -> Result<ExitStatus, Error> {
    replay_plain(dir, Some(port), mounts)
}

fn replay_plain(dir: &Path, port: Option<u16>, mounts: &[Mount]) -> Result<ExitStatus, Error> {
    let dir = dir.to_owned();
    let mounts = mounts.to_vec();
    ptrace_completion::run(None, move |control| async move {
        let report = SkidOvershootReport::begin(true);
        let result = async {
            Replay::spawn(&dir, false, port, &mounts)
                .await?
                .wait(control)
                .await
        }
        .await;
        report.finish(result)
    })
}

/// Replays with captured output.
pub fn replay_with_output(dir: &Path) -> Result<Output, Error> {
    replay_with_output_and_mounts(dir, &[])
}

/// Replays with captured output and mounts inside the replay chroot.
pub fn replay_with_output_and_mounts(dir: &Path, mounts: &[Mount]) -> Result<Output, Error> {
    let dir = dir.to_owned();
    let mounts = mounts.to_vec();
    ptrace_completion::run(None, move |control| async move {
        let report = SkidOvershootReport::begin(true);
        let result = async {
            Replay::spawn(&dir, true, None, &mounts)
                .await?
                .wait_with_output(control)
                .await
        }
        .await;
        report.finish(result)
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    static SKID_OVERSHOOT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn kvm_mountinfo_config_preserves_captured_provenance() {
        let rewrite = detcore_model::config::MountInfoRootRewrite {
            raw_mount_id: 20,
            deterministic_root: b"/".to_vec(),
            raw_root_prefix: Some(b"/private-source".to_vec()),
            deterministic_root_prefix: Some(b"/tmp".to_vec()),
            raw_mountpoint_prefix: Some(b"/private-source".to_vec()),
            deterministic_mountpoint_prefix: Some(b"/tmp".to_vec()),
        };
        let mut config = DetConfig {
            mountinfo_mount_ids: vec![10, 20, 30],
            mountinfo_mount_ids_captured: true,
            fdinfo_unlisted_mount_ids: vec![700, 701],
            mountinfo_root_rewrites: vec![rewrite],
            mountinfo_device_rewrites: vec![(libc::makedev(0, 1), libc::makedev(8, 1))],
            ..DetConfig::default()
        };
        let mut expected = config.clone();
        expected.mountinfo_device_rewrites.clear();
        let mut captures = 0;
        prepare_kvm_mountinfo_config(&mut config, || {
            captures += 1;
            mountinfo_identity_order_from(
                b"10 30 8:1 / / rw - ext4 /dev/root rw\n\
                  20 10 0:7 / /test rw - tmpfs tmpfs rw\n",
            )
        })
        .unwrap();
        assert_eq!(
            captures, 1,
            "captured provenance must be checked before any guest read"
        );
        assert_eq!(
            serde_json::to_value(&config).unwrap(),
            serde_json::to_value(&expected).unwrap(),
            "root rewrites, listed/unlisted order and every other setting must remain intact"
        );

        let mut empty = DetConfig {
            mountinfo_mount_ids_captured: true,
            ..DetConfig::default()
        };
        let mut captures = 0;
        prepare_kvm_mountinfo_config(&mut empty, || {
            captures += 1;
            mountinfo_identity_order_from(b"")
        })
        .unwrap();
        assert_eq!(captures, 1);
        assert!(empty.mountinfo_mount_ids.is_empty());
        assert!(empty.mountinfo_mount_ids_captured);

        // Both captures describe the same completed namespace. An ordered
        // subset is valid for some later guest views, but not this boundary.
        for actual in [
            vec![10, 20],
            vec![10, 20, 30, 40],
            vec![20, 10, 30],
            vec![10, 20, 31],
            vec![10, 20, 20, 30],
            vec![],
        ] {
            let mut stale = config.clone();
            stale.mountinfo_device_rewrites = vec![(libc::makedev(0, 1), libc::makedev(8, 1))];
            let before = serde_json::to_value(&stale).unwrap();
            let error = prepare_kvm_mountinfo_config(&mut stale, || Ok(actual)).unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains("do not match the backend namespace")
            );
            assert_eq!(serde_json::to_value(&stale).unwrap(), before);
        }
        let before = serde_json::to_value(&empty).unwrap();
        let error = prepare_kvm_mountinfo_config(&mut empty, || Ok(vec![10])).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("do not match the backend namespace")
        );
        assert_eq!(serde_json::to_value(&empty).unwrap(), before);
    }

    #[test]
    fn kvm_mountinfo_config_captures_validated_ambient_namespace() {
        let contents = b"80 20 8:1 / / rw - ext4 /dev/root rw\n\
                         10 80 0:7 / /test rw - tmpfs tmpfs rw\n";
        let mut config = DetConfig::default();
        let mut expected = config.clone();
        expected.mountinfo_mount_ids = vec![80, 10, 20];
        expected.mountinfo_mount_ids_captured = true;
        prepare_kvm_mountinfo_config(&mut config, || mountinfo_identity_order_from(contents))
            .unwrap();
        assert_eq!(
            serde_json::to_value(&config).unwrap(),
            serde_json::to_value(&expected).unwrap(),
            "visible rows precede parent-only IDs and no guest setting changes"
        );
        assert!(detcore_model::procfs::mount_ids_are_ordered_subset(
            &[80, 10],
            &config.mountinfo_mount_ids
        ));
        assert!(!detcore_model::procfs::mount_ids_are_ordered_subset(
            &[10, 80],
            &config.mountinfo_mount_ids
        ));
        assert!(!detcore_model::procfs::mount_ids_are_ordered_subset(
            &[80, 99],
            &config.mountinfo_mount_ids
        ));
        assert!(!detcore_model::procfs::mount_ids_are_ordered_subset(
            &[80, 80],
            &config.mountinfo_mount_ids
        ));

        let mut empty = DetConfig::default();
        prepare_kvm_mountinfo_config(&mut empty, || mountinfo_identity_order_from(b"")).unwrap();
        assert!(empty.mountinfo_mount_ids.is_empty());
        assert!(empty.mountinfo_mount_ids_captured);
    }

    #[test]
    fn kvm_mountinfo_config_refuses_missing_or_malformed_capture() {
        let valid = b"10 20 8:1 / / rw - ext4 /dev/root rw\n";
        for captured in [false, true] {
            let config = DetConfig {
                mountinfo_mount_ids: if captured { vec![10, 20] } else { vec![] },
                mountinfo_mount_ids_captured: captured,
                fdinfo_unlisted_mount_ids: if captured { vec![700, 701] } else { vec![] },
                mountinfo_device_rewrites: vec![(libc::makedev(0, 1), libc::makedev(8, 1))],
                ..DetConfig::default()
            };
            for contents in [
                b"malformed".as_slice(),
                b"10 20 8:1 / / rw - ext4 /dev/root rw\n10 20 8:1 / / rw - ext4 /dev/root rw\n",
                b"10 20 8:1 / / rw unknown:7 - ext4 /dev/root rw\n",
            ] {
                let mut candidate = config.clone();
                let before = serde_json::to_value(&candidate).unwrap();
                let error = prepare_kvm_mountinfo_config(&mut candidate, || {
                    mountinfo_identity_order_from(contents)
                })
                .unwrap_err();
                assert!(format!("{error:#}").contains("malformed /proc/self/mountinfo"));
                assert_eq!(serde_json::to_value(&candidate).unwrap(), before);
            }
            let mut candidate = config;
            let before = serde_json::to_value(&candidate).unwrap();
            let error = prepare_kvm_mountinfo_config(&mut candidate, || {
                Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied).into())
            })
            .unwrap_err();
            assert!(
                error
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|error| error.kind() == std::io::ErrorKind::PermissionDenied)
            );
            assert_eq!(serde_json::to_value(&candidate).unwrap(), before);
        }
        assert_eq!(mountinfo_identity_order_from(valid).unwrap(), [10, 20]);
    }

    #[test]
    fn kvm_mountinfo_config_refuses_uncaptured_provenance_vectors() {
        for (listed, unlisted) in [(vec![10], vec![]), (vec![], vec![700])] {
            let mut config = DetConfig {
                mountinfo_mount_ids: listed,
                fdinfo_unlisted_mount_ids: unlisted,
                ..DetConfig::default()
            };
            let before = serde_json::to_value(&config).unwrap();
            let error = prepare_kvm_mountinfo_config(&mut config, || {
                panic!("must not overwrite incomplete provenance")
            })
            .unwrap_err();
            assert!(error.to_string().contains("no producer-captured namespace"));
            assert_eq!(serde_json::to_value(&config).unwrap(), before);
        }
    }

    #[test]
    fn skid_overshoot_report_covers_success_error_and_disabled_backends() {
        let _lock = SKID_OVERSHOOT_TEST_LOCK.lock().unwrap();
        let _ = reverie::take_skid_overshoot_count();

        reverie::record_skid_overshoot();
        let empty_run = SkidOvershootReport::begin(true);
        assert_eq!(
            reverie::take_skid_overshoot_count(),
            0,
            "begin must clear evidence from a previous invocation"
        );
        empty_run.finish(Ok::<_, Error>(())).unwrap();

        let success = SkidOvershootReport::begin(true);
        reverie::record_skid_overshoot();
        reverie::record_skid_overshoot();
        let error = success.finish(Ok::<_, Error>(7)).unwrap_err();
        assert_eq!(
            error
                .downcast_ref::<SkidOvershootError>()
                .expect("skid refusal must remain typed")
                .count(),
            2
        );
        assert!(
            error
                .to_string()
                .contains("observed 2 HERMIT_SKID_OVERSHOOT report(s)"),
            "{error:#}"
        );
        assert!(
            error
                .to_string()
                .contains("deterministic execution was not established"),
            "{error:#}"
        );
        assert_eq!(reverie::take_skid_overshoot_count(), 0);

        let error = SkidOvershootReport::begin(true);
        reverie::record_skid_overshoot();
        let error = error
            .finish(Err::<(), _>(anyhow!("guest failed")))
            .unwrap_err();
        assert!(error.downcast_ref::<SkidOvershootError>().is_some());
        let error = format!("{error:#}");
        assert!(error.contains("guest failed"), "{error}");
        assert!(
            error.contains("observed 1 HERMIT_SKID_OVERSHOOT report(s)"),
            "{error}"
        );
        assert_eq!(reverie::take_skid_overshoot_count(), 0);

        reverie::record_skid_overshoot();
        let disabled = SkidOvershootReport::begin(false);
        disabled.finish(Ok::<_, Error>(())).unwrap();
        assert_eq!(
            reverie::take_skid_overshoot_count(),
            1,
            "a backend that cannot produce ptrace PMU overshoots must not consume another run's evidence"
        );
    }

    #[test]
    fn only_ptrace_hosted_backends_consume_skid_overshoot_reports() {
        for runtime in [LiteinstRuntime::HostHybrid, LiteinstRuntime::InGuest] {
            for backend in [Backend::Ptrace, Backend::E9patch] {
                assert!(
                    backend.uses_ptrace_pmu_timers_for_liteinst_runtime(runtime),
                    "{backend:?} {runtime:?}"
                );
            }
            for backend in [Backend::Dbt, Backend::Sabre, Backend::Kvm] {
                assert!(
                    !backend.uses_ptrace_pmu_timers_for_liteinst_runtime(runtime),
                    "{backend:?} {runtime:?}"
                );
            }
        }
        // The hybrid hosts Detcore in the ptrace tracer, which arms the PMU
        // timer; in-guest Detcore has no tracer to arm it from.
        assert!(
            Backend::Liteinst
                .uses_ptrace_pmu_timers_for_liteinst_runtime(LiteinstRuntime::HostHybrid)
        );
        assert!(
            !Backend::Liteinst
                .uses_ptrace_pmu_timers_for_liteinst_runtime(LiteinstRuntime::InGuest)
        );
    }

    #[cfg(feature = "liteinst")]
    fn write_guest_program(directory: &Path, name: &str, bytes: &[u8], mode: u32) -> PathBuf {
        let path = directory.join(name);
        fs::write(&path, bytes).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap();
        // The kernel may clear a set-group-ID bit that this user cannot set;
        // a test that silently lost its bit would test nothing.
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o7777,
            mode,
            "{}",
            path.display()
        );
        path
    }

    #[cfg(feature = "liteinst")]
    fn shebang_to(interpreter: &Path) -> Vec<u8> {
        let mut script = b"#!".to_vec();
        script.extend_from_slice(interpreter.as_os_str().as_bytes());
        script.extend_from_slice(b" -e\necho script\n");
        script
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_runs_a_dynamically_linked_x86_64_program() {
        use interp::startup_fixtures::dynamic_executable;

        let directory = tempfile::tempdir().unwrap();
        let program = write_guest_program(
            directory.path(),
            "dynamic",
            &dynamic_executable(false),
            0o755,
        );
        assert_eq!(
            in_guest_liteinst_program_gap(&mut Command::new(&program)).unwrap(),
            None
        );
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_refuses_programs_that_start_before_the_runtime() {
        use interp::startup_fixtures::*;

        let directory = tempfile::tempdir().unwrap();
        let cases: [(&str, Vec<u8>, &str); 4] = [
            (
                "static",
                elf(EM_X86_64, &[(PT_LOAD, b"code")]),
                "is statically linked",
            ),
            (
                "preinit",
                dynamic_executable(true),
                "has a DT_PREINIT_ARRAY",
            ),
            (
                "aarch64",
                elf(EM_AARCH64, &[(PT_INTERP, INTERP)]),
                "is not a 64-bit x86-64 ELF image",
            ),
            (
                "text",
                b"plain text, no #! line\n".to_vec(),
                "is neither an ELF executable nor a #! script",
            ),
        ];
        for (name, bytes, reason) in cases {
            let program = write_guest_program(directory.path(), name, &bytes, 0o755);
            let gap = in_guest_liteinst_program_gap(&mut Command::new(&program))
                .unwrap()
                .unwrap_or_else(|| panic!("{name} was not refused"));
            assert!(
                gap.contains(reason) && gap.contains(&program.display().to_string()),
                "{name}: {gap}"
            );
        }
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_refuses_secure_execution_images() {
        use interp::startup_fixtures::dynamic_executable;

        let directory = tempfile::tempdir().unwrap();
        let bytes = dynamic_executable(false);
        let gap = |name: &str, mode: u32| {
            let program = write_guest_program(directory.path(), name, &bytes, mode);
            in_guest_liteinst_program_gap(&mut Command::new(&program)).unwrap()
        };
        for (name, mode) in [("setuid", 0o4755), ("setgid", 0o2755)] {
            let refusal = gap(name, mode).unwrap_or_else(|| panic!("{name} was not refused"));
            assert!(refusal.contains("secure-execution mode"), "{refusal}");
        }
        // Without group execute the kernel treats set-group-ID as mandatory
        // locking, not a credential change, so the loader honours LD_PRELOAD.
        assert_eq!(gap("setgid-no-group-exec", 0o2744), None);
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_checks_scripts_through_their_interpreter() {
        use interp::startup_fixtures::*;

        let directory = tempfile::tempdir().unwrap();
        let dynamic = write_guest_program(
            directory.path(),
            "dynamic",
            &dynamic_executable(false),
            0o755,
        );
        let static_elf = write_guest_program(
            directory.path(),
            "static",
            &elf(EM_X86_64, &[(PT_LOAD, b"code")]),
            0o755,
        );

        let script = write_guest_program(
            directory.path(),
            "to-static",
            &shebang_to(&static_elf),
            0o755,
        );
        let gap = in_guest_liteinst_program_gap(&mut Command::new(&script))
            .unwrap()
            .expect("a script run by a static interpreter was not refused");
        assert!(
            gap.contains(&static_elf.display().to_string()) && gap.contains("statically linked"),
            "{gap}"
        );

        // A relative interpreter resolves against the guest's working directory.
        let relative = write_guest_program(directory.path(), "relative", b"#!static\n", 0o755);
        let gap =
            in_guest_liteinst_program_gap(Command::new(&relative).current_dir(directory.path()))
                .unwrap()
                .expect("a relative static interpreter was not refused");
        assert!(gap.contains("statically linked"), "{gap}");

        // The kernel keeps a carriage return in the interpreter path, so a
        // script with CRLF line endings runs `interp\r`, not `interp`.
        write_guest_program(
            directory.path(),
            "interp",
            &dynamic_executable(false),
            0o755,
        );
        let interp_cr = write_guest_program(
            directory.path(),
            "interp\r",
            &elf(EM_X86_64, &[(PT_LOAD, b"code")]),
            0o755,
        );
        let mut crlf = b"#!".to_vec();
        crlf.extend_from_slice(directory.path().join("interp").as_os_str().as_bytes());
        crlf.extend_from_slice(b"\r\necho script\r\n");
        let crlf = write_guest_program(directory.path(), "crlf", &crlf, 0o755);
        let gap = in_guest_liteinst_program_gap(&mut Command::new(&crlf))
            .unwrap()
            .expect("a CRLF script run by a static interp\\r was not refused");
        assert!(
            gap.contains(&interp_cr.display().to_string()) && gap.contains("statically linked"),
            "{gap}"
        );

        // A #! line the kernel's script handler declines runs no interpreter:
        // the kernel fails the execve or tries another handler, so it is
        // refused.
        let mut truncated = b"#!/".to_vec();
        truncated.resize(256, b'a');
        for (name, bytes) in [
            ("empty", b"#! \t\nbody\n".to_vec()),
            ("truncated", truncated),
        ] {
            let program = write_guest_program(directory.path(), name, &bytes, 0o755);
            let gap = in_guest_liteinst_program_gap(&mut Command::new(&program))
                .unwrap()
                .unwrap_or_else(|| panic!("{name} was not refused"));
            assert!(
                gap.contains("the kernel's script handler declines it"),
                "{name}: {gap}"
            );
        }

        // Four nested scripts are followed to the ELF image; a fifth is refused.
        let mut target = dynamic;
        for level in 1..=5 {
            target = write_guest_program(
                directory.path(),
                &format!("level-{level}"),
                &shebang_to(&target),
                0o755,
            );
            let gap = in_guest_liteinst_program_gap(&mut Command::new(&target)).unwrap();
            if level <= MAX_INTERPRETER_DEPTH {
                assert_eq!(gap, None, "level {level}");
            } else {
                let gap = gap.expect("five nested scripts were not refused");
                assert!(gap.contains("nest more than 4 deep"), "{gap}");
            }
        }
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_refuses_a_fifo_without_blocking() {
        let directory = tempfile::tempdir().unwrap();
        let fifo = directory.path().join("fifo");
        let fifo_c = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o700) }, 0);
        let script = write_guest_program(directory.path(), "to-fifo", &shebang_to(&fifo), 0o755);
        // A socket cannot be opened at all (ENXIO), and opening a device can
        // act on it; both must be refused, not reported as unreadable.
        let socket = directory.path().join("socket");
        let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
        let to_socket =
            write_guest_program(directory.path(), "to-socket", &shebang_to(&socket), 0o755);
        let device = PathBuf::from("/dev/null");
        let to_device =
            write_guest_program(directory.path(), "to-device", &shebang_to(&device), 0o755);
        // `./fifo` reaches the check through find_program's working-directory
        // branch, which does not require a regular file; the scripts reach the
        // FIFO, the socket and the device as their interpreters. Nothing opens
        // the FIFO for writing, so a blocking open or read would never return:
        // each check runs on its own thread and must answer within 10 s.
        let cases = [
            (
                "program",
                PathBuf::from("./fifo"),
                Some(directory.path().to_owned()),
                fs::canonicalize(&fifo).unwrap(),
            ),
            ("interpreter", script, None, fifo.clone()),
            ("socket interpreter", to_socket, None, socket.clone()),
            ("device interpreter", to_device, None, device),
        ];
        for (name, program, current_dir, shown) in cases {
            let (sender, receiver) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                let mut command = Command::new(&program);
                if let Some(directory) = current_dir {
                    command.current_dir(directory);
                }
                let gap = in_guest_liteinst_program_gap(&mut command)
                    .map_err(|error| format!("{error:#}"));
                let _ = sender.send(gap);
            });
            let gap = receiver
                .recv_timeout(std::time::Duration::from_secs(10))
                .unwrap_or_else(|_| panic!("{name}: the check blocked on the FIFO"))
                .unwrap()
                .unwrap_or_else(|| panic!("{name}: the FIFO was not refused"));
            assert!(
                gap.contains(&format!("{} is not a regular file", shown.display())),
                "{name}: {gap}"
            );
        }
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn in_guest_liteinst_pins_the_program_the_launch_resolves() {
        use interp::startup_fixtures::*;

        let directory = tempfile::tempdir().unwrap();
        // A name that no host PATH directory holds.
        let name = "hermit-3520-static";
        let static_elf = write_guest_program(
            directory.path(),
            name,
            &elf(EM_X86_64, &[(PT_LOAD, b"code")]),
            0o755,
        );
        let search = format!("/nonexistent-directory:{}", directory.path().display());
        // The launch resolves the program with `find_program` on the command it
        // is given. Builds the command twice: once for the launch's own
        // resolution, once for the check, which must agree with it.
        let check = |build: &dyn Fn() -> Command| {
            let launch = build().find_program();
            let mut command = build();
            let arg0 = command.get_arg0().to_owned();
            let gap = in_guest_liteinst_program_gap(&mut command);
            match launch {
                Ok(program) => {
                    let gap = gap.unwrap().expect("the static image was not refused");
                    assert!(gap.contains("is statically linked"), "{gap}");
                    assert_eq!(Path::new(command.get_program()), program);
                    assert_eq!(command.get_arg0(), arg0);
                    // Pinned: the launch's own resolution returns it unchanged.
                    assert_eq!(command.find_program().unwrap(), program);
                    assert_eq!(
                        fs::canonicalize(&program).unwrap(),
                        fs::canonicalize(&static_elf).unwrap()
                    );
                    true
                }
                Err(_) => {
                    let error = gap.expect_err("the check found what the launch cannot");
                    assert!(
                        format!("{error:#}").contains("cannot find guest program"),
                        "{error:#}"
                    );
                    false
                }
            }
        };

        // A path with a slash resolves against the guest's working directory.
        assert!(check(&|| {
            let mut command = Command::new(format!("./{name}"));
            command.current_dir(directory.path());
            command
        }));
        // A bare name is searched for in the command's PATH once the base
        // environment is cleared, skipping entries without such a file.
        assert!(check(&|| {
            let mut command = Command::new(name);
            command.env_clear().env("PATH", &search);
            command
        }));
        // Without a cleared environment the launch searches Hermit's own PATH,
        // not the command's, so the static image is not found by either.
        assert!(!check(&|| {
            let mut command = Command::new(name);
            command.env("PATH", &search);
            command
        }));
        // A cleared environment without PATH (`--base-env=empty`) searches
        // Hermit's working directory, not the guest's and not /bin:/usr/bin.
        assert!(!check(&|| {
            let mut command = Command::new(name);
            command.env_clear().current_dir(directory.path());
            command
        }));
        // Not executable, or missing: the launch cannot run it, and neither
        // resolution finds it.
        fs::set_permissions(&static_elf, fs::Permissions::from_mode(0o644)).unwrap();
        assert!(!check(&|| {
            let mut command = Command::new(name);
            command.env_clear().env("PATH", &search);
            command
        }));
        assert!(!check(&|| Command::new(&static_elf)));
        assert!(!check(&|| Command::new("hermit-no-such-program-3520")));
    }

    #[test]
    fn skid_overshoot_error_refuses_a_successful_result() {
        let _lock = SKID_OVERSHOOT_TEST_LOCK.lock().unwrap();
        let _ = reverie::take_skid_overshoot_count();
        assert!(take_skid_overshoot_error().is_none());

        reverie::record_skid_overshoot();
        let error = take_skid_overshoot_error().expect("recorded overshoot must be reported");
        assert!(
            error
                .to_string()
                .contains("observed 1 HERMIT_SKID_OVERSHOOT report(s)")
        );
        assert!(
            error
                .to_string()
                .contains("deterministic execution was not established")
        );
        assert_eq!(reverie::take_skid_overshoot_count(), 0);
    }

    #[test]
    fn skid_overshoot_report_preserves_success_without_an_overshoot() {
        let _lock = SKID_OVERSHOOT_TEST_LOCK.lock().unwrap();
        let _ = reverie::take_skid_overshoot_count();

        let report = SkidOvershootReport::begin(true);
        assert_eq!(report.finish(Ok::<_, Error>(7)).unwrap(), 7);
        assert_eq!(reverie::take_skid_overshoot_count(), 0);
    }

    #[test]
    fn skid_overshoot_count_can_cross_the_verify_boundary_with_the_output() {
        let _lock = SKID_OVERSHOOT_TEST_LOCK.lock().unwrap();
        let _ = reverie::take_skid_overshoot_count();

        let report = SkidOvershootReport::begin(true);
        reverie::record_skid_overshoot();
        let (value, count) = report.finish_with_count(Ok::<_, Error>(7)).unwrap();
        assert_eq!(value, 7);
        assert_eq!(count, 1);
        assert_eq!(reverie::take_skid_overshoot_count(), 0);
    }

    /// ⚠️ THE REGRESSION agent(hermit-007)'s CODEX LANE CAUGHT, PINNED FOR THE
    /// SIGNAL BAND. This test fails if the signal half stops being covered; it
    /// does NOT prove the predicate can never drift again, because the
    /// `122..=127` half is still a hard-coded literal that a future reserved
    /// value would fall outside exactly as 130 did.
    /// `liteinst_requires_forced_shutdown` hard-coded
    /// `Exited(122..=127)`. When the reserved set grew to include the signal
    /// band, `Exited(130)` fell outside it and is not `Signaled(_, _)` -- it is a
    /// status hermit CHOSE -- so LiteInst skipped the forced shutdown and
    /// `clean_up` could wait forever on `handle.await`. A reachable hang,
    /// introduced by widening the reserved set in one place and not the other.
    ///
    /// The 130 and 143 rows are the ones with teeth: revert the predicate to the
    /// bare range and they fail.
    #[test]
    #[cfg(feature = "liteinst")]
    fn liteinst_forced_shutdown_covers_every_status_hermit_reserves() {
        // The signal band. Not `Signaled`: hermit CHOSE these codes, because a
        // namespace init cannot produce a genuine signalled wait status.
        assert!(
            liteinst_requires_forced_shutdown(ExitStatus::Exited(130)),
            "128+SIGINT"
        );
        assert!(
            liteinst_requires_forced_shutdown(ExitStatus::Exited(143)),
            "128+SIGTERM"
        );
        assert!(
            liteinst_requires_forced_shutdown(ExitStatus::Exited(129)),
            "128+SIGHUP"
        );

        // The pre-existing reserved band, unchanged.
        assert!(liteinst_requires_forced_shutdown(ExitStatus::Exited(122)));
        assert!(liteinst_requires_forced_shutdown(ExitStatus::Exited(125)));
        assert!(liteinst_requires_forced_shutdown(ExitStatus::Exited(127)));

        // A real signal death still forces shutdown.
        assert!(liteinst_requires_forced_shutdown(ExitStatus::Signaled(
            nix::sys::signal::Signal::SIGKILL,
            false
        )));

        // ⚠️ CONTROLS, so a predicate that simply returned `true` would fail
        // this test rather than pass it. An ordinary guest exit must NOT force a
        // shutdown; 128 is excluded because there is no signal 0, and 200 is
        // above SIGRTMAX so it is a guest's own number.
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(0)));
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(1)));
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(121)));
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(128)));
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(200)));
        // ⚠️ THE BAND EDGES, WHICH THIS TEST STOPPED SHORT OF. It went up to 143
        // and then jumped to 200, so `MAX_SIGNO` could shrink from 64 to 15 with
        // every row still green -- proved vacuous by agent(hermit-005)'s codex
        // lane. 192 is `128 + SIGRTMAX`, the last status in the band; 193 is the
        // first outside it. Testing a range in the middle pins nothing at either end.
        assert!(
            liteinst_requires_forced_shutdown(ExitStatus::Exited(192)),
            "128 + SIGRTMAX is still a signal death and must force shutdown"
        );
        assert!(
            !liteinst_requires_forced_shutdown(ExitStatus::Exited(193)),
            "above SIGRTMAX the status is the guest's own and must NOT force shutdown"
        );
    }

    /// ⚠️ The bare `NotFound` here was read as a git-worktree bug and cost real
    /// investigation time. The message must name the mount namespace, because
    /// the directory it is complaining about usually exists on the host.
    #[test]
    fn a_cwd_under_tmp_is_explained_by_the_container_tmpfs_not_by_a_missing_directory() {
        let error = std::io::Error::from(std::io::ErrorKind::NotFound);
        let rendered = format!(
            "{}",
            super::kvm_cwd_resolution_error(std::path::Path::new("/tmp/agent-checkout"), &error)
        );
        assert!(
            rendered.contains("private, empty tmpfs"),
            "must name the mechanism: {rendered}"
        );
        assert!(
            rendered.contains("--workdir"),
            "must name a way out: {rendered}"
        );
        assert!(
            rendered.contains("/tmp/agent-checkout"),
            "must still name the path asked for: {rendered}"
        );
    }

    /// The explanation must NOT be attached to failures it does not explain --
    /// an error that volunteers the wrong cause is what produced the original
    /// misdiagnosis, in the other direction.
    #[test]
    fn the_tmpfs_explanation_is_withheld_where_it_does_not_apply() {
        let not_found = std::io::Error::from(std::io::ErrorKind::NotFound);
        // ⚠️ A CONSTANT ABSOLUTE PATH, NOT ONE READ FROM THE ENVIRONMENT. The only
        // property this arm needs is "outside /tmp", and a literal that is outside
        // /tmp by construction supplies it without asking the runner anything.
        //
        // The earlier form wrote a developer-specific home path, which made
        // `scripts/check-portable-paths.sh` red on main -- correctly: that gate
        // rejects such a path anywhere in a tracked build or run file, tests and
        // COMMENTS included, so spelling one out even to explain this would trip
        // it. Replacing it by reading $HOME then made the test depend on the
        // runner instead: measured by `agent(codex-rev-2641)`, HOME unset, empty,
        // relative and /tmp-rooted gave three different fixtures and one failure.
        // A unit test that consults the environment is answering a question about
        // the environment.
        //
        // ⚠️ AND NO GUARD IS NEEDED HERE, WHICH IS THE POINT OF USING A CONSTANT.
        // The $HOME form carried `assert!(!outside_path.starts_with("/tmp"))` to
        // stop a /tmp-rooted HOME making this vacuous. That assertion could never
        // fire: the `!outside.contains("tmpfs")` check below sits ABOVE it in
        // source order and panics first in exactly that case. It was decorative,
        // and an assertion over a compile-time constant would be too, so there is
        // none. The fixture cannot drift into /tmp because nothing computes it.
        let outside_path = std::path::Path::new("/nonexistent-home/wt");
        let outside = format!(
            "{}",
            super::kvm_cwd_resolution_error(outside_path, &not_found)
        );
        assert!(!outside.contains("tmpfs"), "not a /tmp path: {outside}");

        // `/tmp` itself resolves in the guest -- the mount POINT exists -- so a
        // failure there is something else and must not be mislabelled.
        let tmp_itself = format!(
            "{}",
            super::kvm_cwd_resolution_error(std::path::Path::new("/tmp"), &not_found)
        );
        assert!(!tmp_itself.contains("tmpfs"), "/tmp itself: {tmp_itself}");

        // A different errno under /tmp is a different fault (permissions, say).
        let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
        let other = format!(
            "{}",
            super::kvm_cwd_resolution_error(std::path::Path::new("/tmp/x"), &denied)
        );
        assert!(!other.contains("tmpfs"), "not NotFound: {other}");
    }

    /// A build-flag message must not assert a machine condition it never tested.
    ///
    /// ⚠️ THIS IS THE FOURTH DIAGNOSTIC TONIGHT THAT NAMED AN UNESTABLISHED CAUSE,
    /// after the sigpipe checker, the manifest gate and the LiteInst pidfd error.
    /// "DBT support was not included in this build" reads as "this machine cannot
    /// run DBT", and cost four or five unnecessary abstentions across the fleet --
    /// agents declined to make DBT claims on a box where DynamoRIO is installed
    /// and `--features dbt` builds and runs. The absence is a build flag, and the
    /// message must say which flag and admit what it did not check.
    #[test]
    fn an_unbuilt_backend_names_the_flag_and_claims_nothing_about_the_machine() {
        let feature_disabled_backends: &[(Backend, &str)] = &[
            #[cfg(not(feature = "dbt"))]
            (Backend::Dbt, "dbt"),
            #[cfg(not(feature = "sabre"))]
            (Backend::Sabre, "sabre"),
            #[cfg(not(feature = "e9patch"))]
            (Backend::E9patch, "e9patch"),
            #[cfg(not(feature = "liteinst"))]
            (Backend::Liteinst, "liteinst"),
        ];

        for &(backend, feature) in feature_disabled_backends {
            let reason = backend
                .unavailable_reason()
                .expect("a feature-disabled backend must report why it is unavailable");
            assert!(
                reason.contains(feature),
                "{backend:?}: a build-flag message must name the flag to rebuild with, got: {reason}"
            );
            assert!(
                reason.contains("has not been checked"),
                "{backend:?}: a build-flag message must not imply the machine was tested, got: {reason}"
            );
        }
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn a_cold_dbt_runtime_diagnostic_is_not_feature_absence() {
        let reason = dbt_runtime_unavailable_reason_from(Err(io::Error::new(
            io::ErrorKind::NotFound,
            "Hermit DBT runtime was not built beside /cold-target/hermit or in its deps directory",
        )))
        .expect("a missing cold-target runtime must remain unavailable");

        assert!(reason.contains("was not built beside"));
        assert!(reason.contains("build the hermit binary and cdylib"));
        assert!(!reason.contains("not enabled in this build"));
        assert!(!reason.contains("has not been checked"));
    }
    use std::ffi::OsStr;
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;
    use std::sync::Arc;
    use std::time::Duration;

    use super::Backend;
    use super::ExitStatus;
    use super::HermitData;
    use super::Id;
    use super::LITEINST_IN_GUEST_ENV;
    use super::LiteinstRuntime;
    use super::SABRE_RPC_SOCKET_ENV;
    use super::collect_recording_ids;
    #[cfg(feature = "dbt")]
    use super::dbt_runtime_unavailable_reason;
    #[cfg(feature = "dbt")]
    use super::dbt_runtime_unavailable_reason_from;
    #[cfg(feature = "dbt")]
    use super::dynamorio_sdk_available;
    use super::ensure_backend_dispatch;
    #[cfg(feature = "dbt")]
    use super::is_dynamorio_sdk;
    use super::kvm_device_unavailable_reason;
    #[cfg(feature = "liteinst")]
    use super::liteinst_requires_forced_shutdown;
    #[cfg(feature = "dbt")]
    use super::liteinst_unavailable_reason;
    use super::output_backend_stdin_file;
    use super::prepare_backend_config;
    use super::prepare_backend_config_for_liteinst_runtime;
    use super::reserve_output_stdin_snapshot;
    use super::resolve_kvm_shebang;
    use super::resolve_sabre_binary_from;
    use super::sabre_backend_evidence_line;
    use super::sabre_program_needs_neutral_name;
    use super::sabre_reach_state;
    use super::sabre_uninstrumented_guest_message;
    use super::shutdown_sabre_rpc;
    use super::stage_sabre_program_in;
    use super::stop_sabre_rpc_server;
    use super::wait_for_sabre_rpc_disconnects;

    #[test]
    fn recording_inventory_preserves_missing_and_non_recording_cases() {
        let parent = tempfile::tempdir().expect("failed to create recording inventory parent");
        let missing = parent.path().join("missing");
        assert!(
            HermitData::with_dir(&missing)
                .try_recordings()
                .expect("a missing data directory should be empty")
                .is_empty()
        );

        let inventory = parent.path().join("inventory");
        fs::create_dir(&inventory).expect("failed to create recording inventory");
        let recording: Id = "0123456789abcdef0123456789abcdef"
            .parse()
            .expect("valid recording ID");
        fs::create_dir(inventory.join(recording.to_string()))
            .expect("failed to create recording directory");
        fs::create_dir(inventory.join("not-a-recording"))
            .expect("failed to create invalid-name directory");
        fs::write(
            inventory.join("fedcba9876543210fedcba9876543210"),
            b"not a directory",
        )
        .expect("failed to create valid-looking non-directory");

        assert_eq!(
            HermitData::with_dir(&inventory)
                .try_recordings()
                .expect("recording inventory should be readable"),
            vec![recording]
        );
        assert_eq!(
            HermitData::with_dir(&inventory)
                .recordings()
                .collect::<Vec<_>>(),
            vec![recording]
        );
    }

    #[test]
    fn recording_inventory_rejects_an_error_after_a_valid_entry() {
        let inventory = tempfile::tempdir().expect("failed to create recording inventory");
        let recording: Id = "0123456789abcdef0123456789abcdef"
            .parse()
            .expect("valid recording ID");
        fs::create_dir(inventory.path().join(recording.to_string()))
            .expect("failed to create recording directory");
        let valid_entry = fs::read_dir(inventory.path())
            .expect("failed to open recording inventory")
            .next()
            .expect("missing recording entry")
            .expect("failed to read recording entry");

        let entries = vec![
            Ok(valid_entry),
            Err(std::io::Error::other("injected entry failure")),
        ];
        let error = collect_recording_ids(entries, inventory.path(), fs::DirEntry::file_type)
            .expect_err("a partial inventory must not be returned");
        assert!(
            error
                .to_string()
                .contains("Failed to read an entry in recording inventory"),
            "unexpected error: {error:#}"
        );
    }

    #[test]
    fn recording_inventory_rejects_an_entry_inspection_error() {
        let inventory = tempfile::tempdir().expect("failed to create recording inventory");
        let recording = inventory.path().join("0123456789abcdef0123456789abcdef");
        fs::create_dir(&recording).expect("failed to create recording directory");
        let entry = fs::read_dir(inventory.path())
            .expect("failed to open recording inventory")
            .next()
            .expect("missing recording entry")
            .expect("failed to read recording entry");

        let error = collect_recording_ids([Ok(entry)], inventory.path(), |_| {
            Err(std::io::Error::other("injected inspection failure"))
        })
        .expect_err("an uninspectable entry must fail the inventory");
        assert!(
            error
                .to_string()
                .contains("Failed to inspect recording inventory entry"),
            "unexpected error: {error:#}"
        );
    }

    /// Regression test for the `hermit run --verify` empty-stdin bug: a pipe
    /// (non-seekable) fed to hermit must be buffered and replayed *identically*
    /// to every run of `--verify`. Before the fix the output-capturing backend
    /// used `Stdio::null()`, so piped input was silently dropped and both runs
    /// saw empty input (a false "deterministic" pass, e.g. `gcc -x c -`
    /// compiling nothing). This asserts the reserved snapshot replays the exact
    /// bytes twice.
    #[test]
    fn output_stdin_snapshot_replays_pipe_to_repeated_runs() {
        use std::io::Read;
        use std::io::Write;
        use std::os::fd::FromRawFd;

        // A pipe is non-seekable, exercising the buffer-into-tempfile path that
        // matches the real `echo prog | hermit run --verify` scenario.
        let mut fds = [0i32; 2];
        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
        // SAFETY: pipe(2) just returned two fresh owned descriptors.
        let read_end = unsafe { fs::File::from_raw_fd(fds[0]) };
        let mut write_end = unsafe { fs::File::from_raw_fd(fds[1]) };

        let payload = b"int main(){return 0;}\n";
        write_end.write_all(payload).unwrap();
        // Close the write end so draining the pipe hits EOF.
        drop(write_end);

        reserve_output_stdin_snapshot(Some(read_end)).unwrap();

        // Two successive runs (as `--verify` performs) must each read the full
        // payload from the start.
        for run in 0..2 {
            let mut file = output_backend_stdin_file()
                .unwrap()
                .unwrap_or_else(|| panic!("run {run}: expected a replayable stdin snapshot"));
            let mut got = Vec::new();
            file.read_to_end(&mut got).unwrap();
            assert_eq!(got, payload, "run {run} stdin replay mismatch");
        }

        let mut file = output_backend_stdin_file().unwrap().unwrap();
        let error = file
            .write_all(b"guest-must-not-change-the-snapshot")
            .expect_err("the replayed stdin must be read-only");
        assert_eq!(error.raw_os_error(), Some(libc::EBADF));
    }

    #[test]
    #[cfg(feature = "liteinst")]
    fn liteinst_reserved_failures_require_scheduler_cancellation() {
        for status in 122..=127 {
            assert!(liteinst_requires_forced_shutdown(ExitStatus::Exited(
                status
            )));
        }
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(121)));
        assert!(!liteinst_requires_forced_shutdown(ExitStatus::Exited(128)));
    }

    /// A SaBRe guest that never reaches the coordinator ran with no Detcore in
    /// the loop at all. The diagnosis must say so in those terms -- a
    /// zero-syscall SaBRe run is not a weak result, it is *no* result -- and it
    /// must name the statically linked ELF case, which is the shape that
    /// reaches this path in practice because a static client has no dynamic
    /// loader through which SaBRe could regain control.
    #[test]
    fn uninstrumented_sabre_guest_is_reported_as_no_determinization() {
        let message = sabre_uninstrumented_guest_message(&ExitStatus::Exited(0));
        assert!(
            message.contains("no determinization at all"),
            "must not present an uninstrumented run as a weaker guarantee: {message}"
        );
        assert!(
            message.contains("Detcore coordinator"),
            "must name the authority that was never reached: {message}"
        );
        assert!(
            message.contains("statically linked ELF"),
            "must name the dominant cause so the reader can act: {message}"
        );
        // The exit status is carried because a successful-looking status is
        // exactly what makes this failure mode dangerous.
        assert!(
            message.contains("Exited(0)"),
            "must carry the observed status: {message}"
        );
        assert!(
            sabre_uninstrumented_guest_message(&ExitStatus::Exited(139)).contains("Exited(139)"),
            "must carry a failing status too"
        );
    }

    /// The old two-way banner treated both `guest_rpc_observed=false` and an
    /// engaged zero-fallback run as `sabre-exercised`. Assert the three states
    /// together so no pair can collapse back onto one value.
    #[test]
    fn sabre_reach_states_are_pairwise_distinct() {
        let no_detcore = sabre_reach_state(false, 0);
        let degraded = sabre_reach_state(true, 1);
        let exercised = sabre_reach_state(true, 0);

        assert_eq!(no_detcore, "no-detcore-reached");
        assert_eq!(degraded, "degraded-ptrace-fallback");
        assert_eq!(exercised, "sabre-exercised");
        assert_ne!(no_detcore, degraded);
        assert_ne!(no_detcore, exercised);
        assert_ne!(degraded, exercised);
        assert_eq!(
            sabre_reach_state(false, 9),
            "no-detcore-reached",
            "absence of a guest RPC must dominate any fallback count"
        );
    }

    #[test]
    fn sabre_backend_fact_is_versioned_and_names_preplugin_coverage() {
        let exercised = super::sabre_ptrace::PathEvidence {
            schema: 1,
            guest_rpc_observed: true,
            ptrace_fallback_sites: 0,
            trusted_shared_object_sites: 2,
            trusted_shared_objects: vec!["/usr/lib/libc.so.6".to_owned()],
        };
        assert_eq!(
            sabre_backend_evidence_line(&exercised),
            ":: Backend: sabre static rewriting + ptrace runtime; run_mode=run; \
             evidence_schema=1; preplugin_coverage=absent; ptrace_fallback_sites=0; \
             trusted_shared_object_sites=2; guest_rpc_observed=true; \
             reach_state=sabre-exercised"
        );

        let unengaged = super::sabre_ptrace::PathEvidence {
            guest_rpc_observed: false,
            ..exercised
        };
        let fact = sabre_backend_evidence_line(&unengaged);
        assert!(fact.contains("preplugin_coverage=absent"));
        assert!(fact.contains("reach_state=no-detcore-reached"));
        assert!(!fact.contains("reach_state=sabre-exercised"));
    }

    #[test]
    fn liteinst_host_backend_preserves_ptrace_rcb_timeslices() {
        let config = super::DetConfig::default();
        assert!(config.max_timeslice.is_some());
        assert!(
            prepare_backend_config(config.clone(), Backend::Liteinst)
                .max_timeslice
                .is_some()
        );
        assert!(
            prepare_backend_config(config, Backend::Ptrace)
                .max_timeslice
                .is_some()
        );
    }

    #[test]
    fn liteinst_runtime_selector_accepts_only_unset_or_one() {
        assert_eq!(
            LiteinstRuntime::parse(None).unwrap(),
            LiteinstRuntime::HostHybrid
        );
        assert_eq!(
            LiteinstRuntime::parse(Some(std::ffi::OsStr::new("1"))).unwrap(),
            LiteinstRuntime::InGuest
        );
        for value in ["", "0", "true", "yes", " 1", "1 "] {
            let error = LiteinstRuntime::parse(Some(std::ffi::OsStr::new(value))).unwrap_err();
            let message = error.to_string();
            assert!(
                message.contains(LITEINST_IN_GUEST_ENV) && message.contains(&format!("{value:?}")),
                "{value:?}: {message}"
            );
        }
    }

    #[test]
    fn in_guest_liteinst_cancels_killed_thread_rpcs() {
        let config = super::DetConfig::default();
        assert!(
            prepare_backend_config_for_liteinst_runtime(
                config.clone(),
                Backend::Liteinst,
                LiteinstRuntime::InGuest,
            )
            .cancel_killed_thread_rpcs
        );
        assert!(
            !prepare_backend_config_for_liteinst_runtime(
                config.clone(),
                Backend::Liteinst,
                LiteinstRuntime::HostHybrid,
            )
            .cancel_killed_thread_rpcs
        );
        // The LiteInst runtime selection changes no other backend.
        assert!(
            !prepare_backend_config_for_liteinst_runtime(
                config,
                Backend::Ptrace,
                LiteinstRuntime::InGuest,
            )
            .cancel_killed_thread_rpcs
        );
    }

    #[test]
    fn sabre_backend_configures_process_local_capabilities() {
        let config = super::DetConfig::default();
        let sabre = prepare_backend_config(config.clone(), Backend::Sabre);
        assert!(sabre.discover_live_file_metadata);
        assert!(!sabre.use_thread_local_clock_reads);
        assert!(sabre.detect_host_clock_futex_timeouts);
        assert!(sabre.syscall_clobbers_virtualized_by_backend);
        assert!(sabre.cancel_killed_thread_rpcs);
        assert!(sabre.backend_reports_physical_process_exits);
        assert!(!sabre.backend_serializes_fork_children);
        assert!(sabre.backend_dispatches_thread_tools);
        assert!(sabre.backend_tracks_process_children);
        assert!(!sabre.backend_runs_exit_robust_list);
        assert!(!sabre.backend_requires_thread_directed_process_signals);
        assert!(!sabre.backend_virtualizes_capability_prctls);
        assert!(!sabre.backend_defers_vfork_child_registration);
        let ptrace = prepare_backend_config(config, Backend::Ptrace);
        assert!(!ptrace.discover_live_file_metadata);
        assert!(!ptrace.use_thread_local_clock_reads);
        assert!(!ptrace.detect_host_clock_futex_timeouts);
        assert!(!ptrace.syscall_clobbers_virtualized_by_backend);
        assert!(!ptrace.cancel_killed_thread_rpcs);
        assert!(!ptrace.backend_reports_physical_process_exits);
        assert!(!ptrace.backend_serializes_fork_children);
        assert!(ptrace.backend_dispatches_thread_tools);
        assert!(ptrace.backend_tracks_process_children);
        assert!(ptrace.backend_runs_exit_robust_list);
        assert!(!ptrace.backend_requires_thread_directed_process_signals);
        assert!(!ptrace.backend_virtualizes_capability_prctls);
        assert!(!ptrace.backend_defers_vfork_child_registration);
    }

    #[test]
    fn kvm_reports_stored_metadata_timestamps_only_for_sequential_tool_threads() {
        let sequential = prepare_backend_config(
            super::DetConfig {
                sequentialize_threads: true,
                virtualize_metadata: true,
                ..super::DetConfig::default()
            },
            Backend::Kvm,
        );
        assert!(sequential.backend_dispatches_thread_tools);
        assert!(super::kvm_reports_stored_metadata_timestamps(&sequential));

        // Another guest thread could read the stored values before Detcore
        // rewrites them.
        let concurrent = super::DetConfig {
            sequentialize_threads: false,
            ..sequential.clone()
        };
        assert!(!super::kvm_reports_stored_metadata_timestamps(&concurrent));

        // Nothing rewrites the stored values.
        let host_metadata = super::DetConfig {
            virtualize_metadata: false,
            ..sequential.clone()
        };
        assert!(!super::kvm_reports_stored_metadata_timestamps(
            &host_metadata
        ));

        // The backend owns the threads, so no Detcore rewrite runs on them.
        let host_threads = super::DetConfig {
            backend_dispatches_thread_tools: false,
            ..sequential
        };
        assert!(!super::kvm_reports_stored_metadata_timestamps(
            &host_threads
        ));
    }

    #[test]
    fn kvm_backend_config_marks_concurrent_process_children() {
        let defaults = super::DetConfig::default();
        assert!(!defaults.sequentialize_threads);
        let nonsequential = prepare_backend_config(defaults, Backend::Kvm);
        assert!(nonsequential.backend_is_kvm);
        assert!(!nonsequential.kvm_shared_dequeue_timers);

        let config = super::DetConfig {
            sequentialize_threads: true,
            ..super::DetConfig::default()
        };
        let kvm = prepare_backend_config(config, Backend::Kvm);
        assert!(kvm.cancel_killed_thread_rpcs);
        assert!(kvm.kvm_shared_dequeue_timers);
        assert!(!kvm.backend_serializes_fork_children);
        assert!(kvm.backend_dispatches_thread_tools);
        assert!(kvm.backend_tracks_process_children);
        assert!(!kvm.backend_runs_exit_robust_list);
        assert!(!kvm.backend_requires_thread_directed_process_signals);
        assert!(kvm.backend_virtualizes_capability_prctls);
        assert!(kvm.backend_defers_vfork_child_registration);
    }

    #[test]
    fn dbt_backend_config_translates_process_signals_to_host_threads() {
        let config = prepare_backend_config(super::DetConfig::default(), Backend::Dbt);
        assert!(config.cancel_killed_thread_rpcs);
        assert!(!config.backend_tracks_process_children);
        assert!(!config.backend_runs_exit_robust_list);
        assert!(config.backend_requires_thread_directed_process_signals);
        assert!(!config.backend_defers_vfork_child_registration);
    }

    #[test]
    fn backend_write_signal_contract_is_explicit() {
        for (backend, supports_interruption) in [
            (Backend::Ptrace, true),
            (Backend::Dbt, false),
            (Backend::Kvm, false),
            (Backend::Sabre, false),
            (Backend::Liteinst, false),
            (Backend::E9patch, true),
        ] {
            let config = prepare_backend_config(super::DetConfig::default(), backend);
            assert_eq!(
                config.backend_supports_parked_write_signal_interruption, supports_interruption,
                "unexpected parked-write signal support for {backend:?}"
            );
        }
    }

    #[test]
    fn liteinst_public_dispatch_runs_ptrace_host_hybrid() {
        if Backend::Liteinst.ensure_available().is_err() {
            return;
        }

        let mut command = super::Command::new("/bin/echo");
        command.arg("hello");
        let output = super::run_with_output_backend(
            command,
            super::DetConfig::default(),
            false,
            &None,
            Backend::Liteinst,
        )
        .expect("run /bin/echo through the ptrace-hosted LiteInst hybrid");
        // Include captured output so a failed backend launch reports its diagnostics.
        assert_eq!(
            output.status,
            super::ExitStatus::Exited(0),
            "guest did not exit 0.\n--- guest stderr ---\n{}\n--- guest stdout ---\n{}",
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout),
        );
        assert_eq!(output.stdout, b"hello\n");

        let status = super::run_with_backend(
            super::Command::new("/bin/true"),
            super::DetConfig::default(),
            false,
            &None,
            Backend::Liteinst,
        )
        .expect("run /bin/true through the ptrace-hosted LiteInst hybrid");
        assert_eq!(status, super::ExitStatus::Exited(0));
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn default_and_available_backends_reflect_host_probes() {
        assert_eq!(Backend::default(), Backend::Ptrace);
        let available = Backend::available().collect::<Vec<_>>();
        assert_eq!(
            available.contains(&Backend::Ptrace),
            Backend::Ptrace.is_available()
        );
        assert_eq!(
            available.contains(&Backend::Dbt),
            dynamorio_sdk_available() && dbt_runtime_unavailable_reason().is_none()
        );
        assert_eq!(
            available.contains(&Backend::Liteinst),
            liteinst_unavailable_reason().is_none()
        );
        assert_eq!(
            available.contains(&Backend::Sabre),
            Backend::Sabre.is_available()
        );
        assert_eq!(
            available.contains(&Backend::Kvm),
            kvm_device_unavailable_reason(std::path::Path::new("/dev/kvm")).is_none(),
        );
        assert_eq!(
            available.contains(&Backend::E9patch),
            Backend::E9patch.is_available()
        );
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn dependency_probes_require_usable_paths() {
        let temp = tempfile::tempdir().unwrap();
        assert!(!is_dynamorio_sdk(temp.path()));
        fs::create_dir(temp.path().join("include")).unwrap();
        fs::write(temp.path().join("include/dr_api.h"), b"/* marker */").unwrap();
        assert!(is_dynamorio_sdk(temp.path()));

        let reason = kvm_device_unavailable_reason(temp.path())
            .expect("a directory must not pass the read-write KVM device probe");
        assert!(reason.contains("read-write"));
    }

    fn write_test_executable(path: &std::path::Path) {
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, b"test loader").unwrap();
        let mut permissions = fs::metadata(path).unwrap().permissions();
        permissions.set_mode(0o700);
        fs::set_permissions(path, permissions).unwrap();
    }

    #[test]
    fn sabre_rpc_socket_uses_private_exec_environment() {
        assert!(SABRE_RPC_SOCKET_ENV.starts_with("REVERIE_SABRE_"));
    }

    #[test]
    fn sabre_stages_program_names_that_collide_with_loader_prefix() {
        assert!(sabre_program_needs_neutral_name(
            PathBuf::from("/usr/bin/ld").as_path()
        ));
        assert!(sabre_program_needs_neutral_name(
            PathBuf::from("/usr/bin/ld.bfd").as_path()
        ));
        assert!(!sabre_program_needs_neutral_name(
            PathBuf::from("/usr/bin/gold").as_path()
        ));
    }

    #[test]
    fn sabre_neutral_name_staging_preserves_program_bytes_and_cleans_up() {
        let temp = tempfile::tempdir().unwrap();
        let program = temp.path().join("ld.test");
        fs::write(&program, b"linker image").unwrap();

        let staged = stage_sabre_program_in(&program, temp.path())
            .unwrap()
            .expect("ld-prefixed program should be staged");
        let staged_path = staged.path.clone();
        assert_eq!(fs::read(&staged_path).unwrap(), b"linker image");
        assert!(
            staged_path
                .file_name()
                .unwrap()
                .as_encoded_bytes()
                .starts_with(b"hermit-sabre-program-")
        );

        drop(staged);
        assert!(!staged_path.exists());
    }

    #[tokio::test(start_paused = true)]
    async fn sabre_rpc_disconnect_wait_observes_delayed_release() {
        let global = Arc::new(());
        let connection = global.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(10)).await;
            drop(connection);
        });

        assert_eq!(
            wait_for_sabre_rpc_disconnects(&global, Duration::from_millis(50)).await,
            Ok(())
        );
    }

    #[tokio::test(start_paused = true)]
    async fn sabre_rpc_disconnect_wait_reports_stuck_connection() {
        let global = Arc::new(());
        let _connection = global.clone();

        assert_eq!(
            wait_for_sabre_rpc_disconnects(&global, Duration::from_millis(10)).await,
            Err(1)
        );
    }

    #[tokio::test]
    async fn sabre_rpc_server_intentional_abort_is_clean() {
        let server_task = tokio::spawn(std::future::pending::<Result<(), &'static str>>());

        assert!(stop_sabre_rpc_server(server_task).await.is_ok());
    }

    #[tokio::test]
    async fn sabre_rpc_server_failure_is_reported() {
        let server_task = tokio::spawn(async { Err::<(), _>("accept failed") });
        while !server_task.is_finished() {
            tokio::task::yield_now().await;
        }

        let error = stop_sabre_rpc_server(server_task).await.unwrap_err();
        assert!(error.to_string().contains("accept failed"));
    }

    #[tokio::test(start_paused = true)]
    async fn sabre_rpc_shutdown_drains_connections_after_server_failure() {
        let global = Arc::new(());
        let connection = global.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(10)).await;
            drop(connection);
        });
        let server_task = tokio::spawn(async { Err::<(), _>("accept failed") });
        while !server_task.is_finished() {
            tokio::task::yield_now().await;
        }

        let error = shutdown_sabre_rpc(server_task, &global, Duration::from_millis(50))
            .await
            .unwrap_err();
        assert!(error.to_string().contains("accept failed"));
        assert_eq!(Arc::strong_count(&global), 1);
    }

    #[test]
    fn sabre_binary_resolver_finds_cargo_target_build() {
        let temp = tempfile::tempdir().unwrap();
        let executable = temp.path().join("target/release/hermit");
        let loader = temp.path().join("target/sabre/sabre");
        write_test_executable(&loader);

        assert_eq!(
            resolve_sabre_binary_from(None, None, &executable, OsStr::new("")).unwrap(),
            loader
        );
    }

    #[test]
    fn sabre_binary_resolver_uses_packaged_loader() {
        let temp = tempfile::tempdir().unwrap();
        let executable = temp.path().join("target/release/hermit");
        let packaged = temp.path().join("install_pkg/rsrcs/sabre");
        write_test_executable(&packaged);

        assert_eq!(
            resolve_sabre_binary_from(None, Some(&packaged), &executable, OsStr::new("")).unwrap(),
            packaged
        );
    }

    #[test]
    fn sabre_binary_resolver_prefers_and_validates_override() {
        let temp = tempfile::tempdir().unwrap();
        let executable = temp.path().join("target/release/hermit");
        let discovered = temp.path().join("target/sabre/sabre");
        let requested = temp.path().join("requested-sabre");
        write_test_executable(&discovered);
        write_test_executable(&requested);

        assert_eq!(
            resolve_sabre_binary_from(
                Some(requested.as_os_str()),
                Some(&discovered),
                &executable,
                OsStr::new(""),
            )
            .unwrap(),
            requested
        );

        let mut permissions = fs::metadata(&requested).unwrap().permissions();
        permissions.set_mode(0o600);
        fs::set_permissions(&requested, permissions).unwrap();
        let error = resolve_sabre_binary_from(
            Some(requested.as_os_str()),
            Some(&discovered),
            &executable,
            OsStr::new(""),
        )
        .unwrap_err();
        assert!(error.to_string().contains("is not an executable file"));
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn optional_backends_report_accurate_availability() {
        match Backend::Dbt.ensure_available() {
            Ok(()) => assert!(
                dynamorio_sdk_available() && dbt_runtime_unavailable_reason().is_none(),
                "DBT reported available without its SDK and runtime"
            ),
            Err(dbt_error) => {
                let message = dbt_error.to_string();
                assert!(
                    message.contains("DynamoRIO runtime")
                        || message.contains("Detcore DBT runtime"),
                    "unexpected DBT availability error: {message}"
                );
            }
        }
        assert_eq!(
            Backend::Liteinst.ensure_available().is_ok(),
            liteinst_unavailable_reason().is_none()
        );

        match Backend::Kvm.ensure_available() {
            Ok(()) => assert!(
                kvm_device_unavailable_reason(std::path::Path::new("/dev/kvm")).is_none(),
                "KVM reported available without a usable /dev/kvm",
            ),
            Err(kvm_error) => {
                let message = kvm_error.to_string();
                assert!(
                    message.contains("/dev/kvm"),
                    "unexpected KVM availability error: {message}",
                );
                assert!(!message.contains("requires root privileges"));
            }
        }
    }

    #[test]
    fn public_backend_dispatch_rejects_unprepared_e9patch() {
        let error = ensure_backend_dispatch(Backend::E9patch).unwrap_err();
        assert!(
            error.to_string().contains("requires CLI preprocessing"),
            "unexpected error: {error}"
        );
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn dbt_retries_only_the_pre_guest_bootstrap_failure() {
        use std::os::unix::process::ExitStatusExt as _;

        let failure = std::process::ExitStatus::from_raw(
            reverie_dbt::CLIENT_THREAD_START_FAILURE_EXIT_CODE << 8,
        );
        assert!(super::dbt_client_thread_start_failed(&failure));
        assert!(!super::dbt_client_thread_start_failed(
            &std::process::ExitStatus::from_raw(1 << 8)
        ));
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn dbt_public_dispatch_requires_sequentialized_threads() {
        let command = super::Command::new("/bin/true");
        let config = super::DetConfig {
            sequentialize_threads: false,
            ..Default::default()
        };

        let error = super::run_with_output_backend(command, config, false, &None, Backend::Dbt)
            .expect_err("DBT must reject non-sequentialized execution");
        assert!(
            error
                .to_string()
                .contains("dbt backend requires sequentialized threads"),
            "unexpected error: {error}"
        );
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn dbt_public_dispatch_runs_echo_through_detcore() {
        use clap::Parser;

        if Backend::Dbt.ensure_available().is_err() {
            return;
        }

        let mut command = super::Command::new("/bin/echo");
        command.arg("hello");
        let mut config = super::DetConfig::parse_from(["hermit-dbt-test"]);
        config.sequentialize_threads = true;
        config.validate();
        let output = super::run_with_output_backend(command, config, true, &None, Backend::Dbt)
            .expect("run /bin/echo through DbtGuest<Detcore>");

        // Include captured output so a failed backend launch reports its diagnostics.
        assert_eq!(
            output.status,
            super::ExitStatus::Exited(0),
            "guest did not exit 0.\n--- guest stderr ---\n{}\n--- guest stdout ---\n{}",
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout),
        );
        assert_eq!(output.stdout, b"hello\n");
        assert!(
            String::from_utf8_lossy(&output.stderr)
                .lines()
                .any(|line| line.starts_with("reverie-dbt: tool=Detcore ")),
            "DBT native summary did not prove Detcore dispatch: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    #[cfg(feature = "dbt")]
    fn dbt_public_status_dispatch_runs_true_through_detcore() {
        use clap::Parser;

        if Backend::Dbt.ensure_available().is_err() {
            return;
        }

        let command = super::Command::new("/bin/true");
        let mut config = super::DetConfig::parse_from(["hermit-dbt-test"]);
        config.sequentialize_threads = true;
        config.validate();
        let status = super::run_with_backend(command, config, true, &None, Backend::Dbt)
            .expect("run /bin/true through DbtGuest<Detcore>");

        assert_eq!(status, super::ExitStatus::Exited(0));
    }

    #[test]
    fn kvm_runs_dynamic_echo_through_detcore() {
        use clap::Parser;

        if kvm_device_unavailable_reason(std::path::Path::new("/dev/kvm")).is_some() {
            return;
        }

        let mut command = super::Command::new("/bin/echo");
        command.arg("hello");
        let mut config = super::DetConfig::parse_from(["hermit-kvm-test"]);
        config.validate();
        let output = super::run_with_output_backend(command, config, false, &None, Backend::Kvm)
            .expect("run dynamic /bin/echo through KvmGuest<Detcore>");

        // Include captured output so a failed backend launch reports its diagnostics.
        assert_eq!(
            output.status,
            super::ExitStatus::Exited(0),
            "guest did not exit 0.\n--- guest stderr ---\n{}\n--- guest stdout ---\n{}",
            String::from_utf8_lossy(&output.stderr),
            String::from_utf8_lossy(&output.stdout),
        );
        assert_eq!(output.stdout, b"hello\n");
        assert!(output.stderr.is_empty());
    }

    // Keep the low-level vmcall transport covered independently from the ELF
    // process personality. Requires /dev/kvm; skips cleanly otherwise.
    #[test]
    fn detcore_drives_kvm_guest_for_synthetic_syscall() {
        use clap::Parser;

        const MEMORY_SIZE: usize = 0x10_000;
        const ENTRY_POINT: u64 = 0x1000;
        const FRAME_ADDRESS: u64 = 0x2000;

        let mut backend = match reverie_kvm::KvmBackend::new(MEMORY_SIZE) {
            Ok(backend) => backend,
            Err(error) => {
                eprintln!("skipping KVM Detcore experiment: cannot init VM: {error}");
                return;
            }
        };

        // A guest that issues one `getpid` through the vmcall transport, then HLTs.
        backend
            .install_syscall(
                ENTRY_POINT,
                FRAME_ADDRESS,
                reverie_kvm::SyscallRequest::new(libc::SYS_getpid as u64, [0; 6]),
            )
            .expect("install synthetic getpid guest");

        // Minimal deterministic Detcore config with RCB preemption disabled.
        let mut config =
            super::DetConfig::parse_from(["hermit-kvm-test", "--max-timeslice=disabled"]);
        config.validate();

        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build tokio runtime");

        let outcome = runtime.block_on(async {
            backend
                .run_with_tool::<super::Detcore, _>(
                    config,
                    // Executor: forward anything Detcore injects to the host.
                    |request: &reverie_kvm::SyscallRequest, _memory: &reverie_kvm::GuestMemory| {
                        // SAFETY: forwarding a register-only syscall (getpid) to the
                        // host; no guest pointers are dereferenced by the kernel.
                        unsafe {
                            libc::syscall(
                                request.number() as libc::c_long,
                                request.args()[0],
                                request.args()[1],
                                request.args()[2],
                                request.args()[3],
                                request.args()[4],
                                request.args()[5],
                            ) as i64
                        }
                    },
                )
                .await
        });

        // The point of the experiment is to observe whether Detcore can be driven
        // to completion over KvmGuest at all; assert it did not error.
        outcome.expect("Detcore drove the synthetic KVM guest to completion");
    }

    // Minimal fake ELF payload: the loader only needs the image to NOT start
    // with `#!`, and a real ELF magic makes the intent obvious.
    const FAKE_ELF: &[u8] = b"\x7fELF\x02\x01\x01\x00 fake elf body";

    fn shebang_tmpdir(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "hermit-shebang-test-{}-{}",
            std::process::id(),
            tag
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn resolve_shebang_plain_elf_is_unchanged() {
        let dir = shebang_tmpdir("plain");
        let prog = dir.join("prog");
        fs::write(&prog, FAKE_ELF).unwrap();

        let argv = vec!["prog".to_owned(), "-a".to_owned()];
        let (path, out_argv, image) = resolve_kvm_shebang(&prog, argv).unwrap();
        assert_eq!(path, prog);
        assert_eq!(out_argv, vec!["prog".to_owned(), "-a".to_owned()]);
        assert_eq!(image, FAKE_ELF);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_shebang_single_level_kernel_order() {
        let dir = shebang_tmpdir("single");
        let interp = dir.join("fakebash");
        fs::write(&interp, FAKE_ELF).unwrap();
        let script = dir.join("script");
        // Interpreter with a single optional argument.
        fs::write(&script, format!("#!{} -x\necho hi\n", interp.display())).unwrap();

        let argv = vec!["script".to_owned(), "arg1".to_owned()];
        let (path, out_argv, image) = resolve_kvm_shebang(&script, argv).unwrap();
        assert_eq!(path, interp);
        // Kernel order: [interp, optarg, script_path, original args after argv[0]].
        assert_eq!(
            out_argv,
            vec![
                interp.to_string_lossy().into_owned(),
                "-x".to_owned(),
                script.to_string_lossy().into_owned(),
                "arg1".to_owned(),
            ]
        );
        assert_eq!(image, FAKE_ELF);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_shebang_nested_accumulates_like_binfmt_script() {
        let dir = shebang_tmpdir("nested");
        let interp = dir.join("fakebash");
        fs::write(&interp, FAKE_ELF).unwrap();
        let mid = dir.join("mid"); // a #!-interpreter that is itself a script
        fs::write(&mid, format!("#!{}\n", interp.display())).unwrap();
        let script = dir.join("script");
        fs::write(&script, format!("#!{} -e\n", mid.display())).unwrap();

        let argv = vec!["script".to_owned(), "arg1".to_owned()];
        let (path, out_argv, image) = resolve_kvm_shebang(&script, argv).unwrap();
        assert_eq!(path, interp);
        // Level 1: [mid, -e, script, arg1]; level 2 prepends [interp, mid].
        assert_eq!(
            out_argv,
            vec![
                interp.to_string_lossy().into_owned(),
                mid.to_string_lossy().into_owned(),
                "-e".to_owned(),
                script.to_string_lossy().into_owned(),
                "arg1".to_owned(),
            ]
        );
        assert_eq!(image, FAKE_ELF);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_shebang_rejects_infinite_recursion() {
        let dir = shebang_tmpdir("loop");
        let a = dir.join("a");
        let b = dir.join("b");
        fs::write(&a, format!("#!{}\n", b.display())).unwrap();
        fs::write(&b, format!("#!{}\n", a.display())).unwrap();

        let argv = vec!["a".to_owned()];
        assert!(resolve_kvm_shebang(&a, argv).is_err());
        fs::remove_dir_all(&dir).unwrap();
    }

    /// The pin guard shipped with zero tests, which made it deletable: replacing
    /// the call with `let _ = liteinst_runtime_pin_matches;` left the suite green
    /// and silently reverted the loader to the old "missing required export"
    /// path. That is the same shape as the defect the guard itself exists to
    /// prevent -- a mechanism nobody has watched refuse -- so it is bracketed
    /// here at the level that needs no CMake, no staged runtime and no box.
    mod liteinst_pin_guard {
        use std::fs;

        use crate::liteinst_runtime_pin_matches;

        /// The guard is inert by design when the build could not read a pin.
        /// Every case below asserts the *refusal*, so they would all pass
        /// vacuously in that configuration; skip loudly instead.
        fn pin_or_skip() -> Option<&'static str> {
            let pin = env!("HERMIT_REVERIE_PIN");
            (pin != "unknown").then_some(pin)
        }

        #[test]
        fn a_runtime_with_no_recorded_revision_is_refused() {
            let Some(_) = pin_or_skip() else { return };
            let dir = tempfile::tempdir().unwrap();
            let so = dir.path().join("libreverie_liteinst.so");
            let error = liteinst_runtime_pin_matches(&so).unwrap_err();
            let text = error.to_string();
            assert!(
                text.contains("records no Reverie revision"),
                "must say the runtime carries no revision, said: {text}"
            );
            // The message has to carry the way out, not just the complaint --
            // staging is release-only and nothing else restages.
            assert!(
                text.contains("cargo build --release -p hermit-install"),
                "must name the restage command, said: {text}"
            );
        }

        #[test]
        fn a_runtime_from_another_revision_is_refused_naming_both() {
            let Some(pin) = pin_or_skip() else { return };
            let dir = tempfile::tempdir().unwrap();
            let so = dir.path().join("libreverie_liteinst.so");
            let stale = "0".repeat(40);
            fs::write(dir.path().join("libreverie_liteinst.so.revision"), &stale).unwrap();
            let text = liteinst_runtime_pin_matches(&so).unwrap_err().to_string();
            // Naming BOTH is the point: a refusal that names only one revision
            // cannot tell the reader which side is stale.
            assert!(
                text.contains(&stale),
                "must name the staged revision: {text}"
            );
            assert!(text.contains(pin), "must name the binary's pin: {text}");
        }

        #[test]
        fn a_matching_runtime_is_accepted() {
            let Some(pin) = pin_or_skip() else { return };
            let dir = tempfile::tempdir().unwrap();
            let so = dir.path().join("libreverie_liteinst.so");
            // Trailing newline: this is exactly what the build script writes.
            fs::write(
                dir.path().join("libreverie_liteinst.so.revision"),
                format!("{pin}\n"),
            )
            .unwrap();
            assert!(
                liteinst_runtime_pin_matches(&so).is_ok(),
                "the guard must not block a correctly staged runtime"
            );
        }

        /// ⚠️ THE CALL SITE, NOT JUST THE FUNCTION. The reported defect was that
        /// replacing the call with `let _ = liteinst_runtime_pin_matches;` left the
        /// suite green -- so tests that only exercise the function directly would
        /// not have caught it. This one goes through `validate_liteinst_runtime_library`
        /// and asserts the PIN diagnosis specifically, because without the guard the
        /// same input still fails, just with the older "missing required export"
        /// message. Asserting `is_err()` here would pass either way.
        #[test]
        fn the_loader_consults_the_guard_before_anything_else() {
            let Some(pin) = pin_or_skip() else { return };
            let dir = tempfile::tempdir().unwrap();
            let so = dir.path().join("libreverie_liteinst.so");
            // A file that is not a valid DSO: if the guard is bypassed, the export
            // check rejects it for an unrelated reason and the test must notice.
            fs::write(&so, b"not an elf").unwrap();
            let stale = "0".repeat(40);
            fs::write(dir.path().join("libreverie_liteinst.so.revision"), &stale).unwrap();
            let text = crate::validate_liteinst_runtime_library(&so)
                .unwrap_err()
                .to_string();
            assert!(
                text.contains(&stale) && text.contains(pin),
                "the loader must refuse on the PIN, naming both revisions, before it \
                 reaches the export check; said: {text}"
            );
        }

        /// `HERMIT_LITEINST_RUNTIME` is caller-supplied, so the marker path has to
        /// survive a versioned soname. `with_extension("so.revision")` REPLACED the
        /// final extension and looked for `libreverie_liteinst.so.so.revision`,
        /// refusing a correctly staged runtime.
        #[test]
        fn a_versioned_soname_finds_its_marker() {
            let Some(pin) = pin_or_skip() else { return };
            let dir = tempfile::tempdir().unwrap();
            let so = dir.path().join("libreverie_liteinst.so.1");
            fs::write(
                dir.path().join("libreverie_liteinst.so.1.revision"),
                format!("{pin}\n"),
            )
            .unwrap();
            assert!(
                liteinst_runtime_pin_matches(&so).is_ok(),
                "the marker beside a versioned soname must be the one consulted"
            );
        }
    }

    /// The build scripts' pin reader, bracketed against the inputs that
    /// first-match-wins got wrong. Included rather than imported because the
    /// reader is build-script code with no library home.
    mod reverie_pin_reader {
        include!("../reverie_pin.rs");

        const A: &str = "1111111111111111111111111111111111111111";
        const B: &str = "2222222222222222222222222222222222222222";

        fn dep(rev: &str) -> String {
            format!(
                "reverie = {{ git = \"https://github.com/rrnewton/reverie.git\", rev = \"{rev}\" }}\n"
            )
        }

        #[test]
        fn a_single_revision_is_read() {
            assert_eq!(parse_reverie_pin(&dep(A)).as_deref(), Some(A));
        }

        #[test]
        fn agreeing_revisions_are_read_once() {
            let text = format!("{}{}", dep(A), dep(A));
            assert_eq!(parse_reverie_pin(&text).as_deref(), Some(A));
        }

        /// A manifest halfway through a bump names two revisions. First-match-wins
        /// silently returned the first; the canonical rule refuses to resolve it.
        #[test]
        fn disagreeing_revisions_are_refused() {
            let text = format!("{}{}", dep(A), dep(B));
            assert_eq!(parse_reverie_pin(&text), None);
        }

        /// The reported reproduction: ONE commented line above the live pin made
        /// the binary embed the comment's revision, so a correctly staged runtime
        /// would be refused by a guard naming a revision that was never the pin.
        #[test]
        fn a_commented_out_dependency_is_not_the_pin() {
            let text = format!("# {}{}", dep(B), dep(A));
            assert_eq!(
                parse_reverie_pin(&text).as_deref(),
                Some(A),
                "a commented-out revision must not win"
            );
        }

        #[test]
        fn a_manifest_naming_no_revision_yields_none() {
            assert_eq!(parse_reverie_pin("[dependencies]\nlibc = \"0.2\"\n"), None);
        }

        /// An unparseable Reverie line could be hiding a disagreement, so it makes
        /// the manifest ambiguous rather than being skipped as absent.
        #[test]
        fn an_unparseable_revision_is_ambiguous() {
            let text = format!(
                "{}reverie-x = {{ git = \"https://github.com/rrnewton/reverie.git\", rev = \"beef\" }}\n",
                dep(A)
            );
            assert_eq!(parse_reverie_pin(&text), None);
        }
    }
}