supermachine 0.7.98

Run any OCI/Docker image as a hardware-isolated microVM on macOS HVF (Linux KVM and Windows WHP in progress). Single library API, zero flags for the common case, sub-100 ms cold-restore from snapshot.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
//! High-level public API: [`Image`], [`Vm`], [`VmConfig`], [`Error`].
//!
//! These types wrap the lower-level [`crate::vmm`] primitives
//! (`WarmPool`, `VmResources`, …) into a small, stable surface
//! for embedders: load an image, start a VM, talk to its guest,
//! stop. The lower-level types remain available under
//! `#[doc(hidden)]` for the CLI / router / bench crates that
//! pre-date the narrowing.

use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
use std::os::unix::fs::PermissionsExt;
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
use std::process::ChildStdin;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use crate::assets::AssetPaths;
// VM-run types live in the macOS-gated VMM stack (until the KVM backend lands).
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
use crate::vmm::pool::{PoolClientError, WarmPool, WarmPoolError};
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
use crate::vmm::resources::VmResources;
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
use crate::vmm::runner::RunOptions;

/// All errors the high-level API can return. Designed to be
/// `match`able: the variants name *what failed*, not which
/// internal type produced it.
///
/// Each variant carries a human-readable `msg` plus an optional
/// typed `source: Option<Box<dyn std::error::Error + Send + Sync>>`
/// so callers can downcast to the underlying error
/// (`io::Error`, `WarmPoolError`, `PoolClientError`, ...) when
/// they need typed handling. `std::error::Error::source()` walks
/// this chain so `?` propagation preserves it through downstream
/// `Box<dyn Error>` conversions.
///
/// `#[non_exhaustive]` so future versions can add variants without
/// breaking exhaustive matches in consumer code.
#[non_exhaustive]
pub enum Error {
    /// The image / snapshot couldn't be loaded — bad path, bad
    /// magic bytes, or version mismatch.
    Image {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// VM start / restore failed. Includes `WarmPool` setup errors,
    /// HVF entitlement issues, missing assets, and pool-spawn
    /// failures. Downcast `source` to the typed cause where
    /// applicable.
    Vm {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// The configured assets (kernel, init shim) couldn't be
    /// located. Set [`VmConfig::with_assets`] explicitly to
    /// override auto-discovery.
    Assets {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// I/O on a vsock socket / file. The original `io::Error` is
    /// the variant payload — match `Error::Io(e)` and inspect
    /// `e.kind()` for typed handling.
    Io(std::io::Error),
    /// Registry pull failed — image manifest fetch, layer download,
    /// or auth handshake. Surface message includes the registry
    /// HTTP status / response body where available.
    Network {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// [`PullPolicy::Never`] was set but no usable cache exists.
    /// Switch to [`PullPolicy::Missing`] (the default) to allow a
    /// pull, or pre-bake via the `supermachine` CLI.
    CacheMiss { msg: String },
    /// A cached snapshot was found but isn't loadable on this
    /// binary — runtime SHA mismatch, snapshot format version
    /// mismatch, or corrupt/missing layer files. The error message
    /// names the specific reason. With [`PullPolicy::Missing`] /
    /// [`PullPolicy::Always`] the library auto-rebakes; only
    /// [`PullPolicy::Never`] surfaces this.
    CacheInvalid { msg: String },
    /// The bake step itself failed — snapshot capture timed out,
    /// the workload didn't bind a port within the readiness window,
    /// or the worker exited mid-bake. See `bake.log` in the
    /// snapshot dir for details.
    Bake {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// Registry returned 404 / "manifest unknown" for the
    /// requested image+tag — typo, deleted upstream, or wrong
    /// registry. The `image` field holds the full `host/repo:tag`
    /// reference as the user passed it, so callers can do
    /// `match e { Error::ImageNotFound { image, .. } => ... }`
    /// without re-parsing the string.
    ImageNotFound {
        image: String,
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// Registry returned 401 / 403 — bad credentials, expired
    /// token, or repo requires login. Set creds via
    /// `~/.docker/config.json` or `--registry-auth USER:PASS`.
    RegistryAuth {
        image: String,
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// Registry HTTP request failed at the network layer — DNS
    /// failure, connection refused, TLS handshake error, timeout
    /// on the wire. Distinct from [`Error::ImageNotFound`] /
    /// [`Error::RegistryAuth`] which surface registry-side errors
    /// after a successful connection.
    RegistryUnreachable {
        msg: String,
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
    /// Pool has reached its `max` worker count and the
    /// `acquire_timeout` elapsed before any peer dropped its
    /// `PooledVm`. Increase `max`, increase `acquire_timeout`,
    /// or retry. Carries the elapsed timeout + max in the
    /// message for diagnostics.
    PoolExhausted { msg: String },
    /// The in-guest Linux kernel panicked during the bake's boot
    /// or init phase. Detected by tailing the worker's serial
    /// console (`bake.log`) for known fatal banners
    /// (`Kernel panic`, `Internal error: Oops`, `Unable to handle
    /// kernel ...`, `Attempted to kill the idle task`). On detection
    /// the worker child is killed so the bake doesn't hang for the
    /// full timeout. `first_line` is the matched banner; `stack` is
    /// the next ~40 lines of the panic trace pulled from `bake.log`.
    KernelPanic {
        first_line: String,
        stack: Vec<String>,
    },
}

// Constructor helpers that callers in this crate use. Keeping
// the public surface field-style (struct variants) means new
// fields are non-breaking; the callers below all funnel through
// these so we can evolve the construction shape later without
// touching every call site.
//
// Public API is the variants themselves; these are pub(crate).
impl Error {
    pub(crate) fn image_msg(msg: impl Into<String>) -> Self {
        Error::Image {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn vm_msg(msg: impl Into<String>) -> Self {
        Error::Vm {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn assets_msg(msg: impl Into<String>) -> Self {
        Error::Assets {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn network_msg(msg: impl Into<String>) -> Self {
        Error::Network {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn bake_msg(msg: impl Into<String>) -> Self {
        Error::Bake {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn cache_miss(msg: impl Into<String>) -> Self {
        Error::CacheMiss { msg: msg.into() }
    }
    pub(crate) fn cache_invalid(msg: impl Into<String>) -> Self {
        Error::CacheInvalid { msg: msg.into() }
    }
    pub(crate) fn image_not_found(image: impl Into<String>, msg: impl Into<String>) -> Self {
        Error::ImageNotFound {
            image: image.into(),
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn registry_auth(image: impl Into<String>, msg: impl Into<String>) -> Self {
        Error::RegistryAuth {
            image: image.into(),
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn registry_unreachable(msg: impl Into<String>) -> Self {
        Error::RegistryUnreachable {
            msg: msg.into(),
            source: None,
        }
    }
    pub(crate) fn pool_exhausted(msg: impl Into<String>) -> Self {
        Error::PoolExhausted { msg: msg.into() }
    }
    pub(crate) fn kernel_panic(first_line: impl Into<String>, stack: Vec<String>) -> Self {
        Error::KernelPanic {
            first_line: first_line.into(),
            stack,
        }
    }

    /// True when the message looks like the agent-probe symptom
    /// of a multi-vCPU restore RCU-stall (probe timed out / EAGAIN
    /// in the underlying vsock read). Heuristic — used to
    /// downgrade probe failures to a warning when the snapshot
    /// was baked with vcpus > 1. Definitive stale-agent signals
    /// (the agent ack with an old protocol number) report a
    /// different message and are NOT covered.
    pub(crate) fn is_likely_multi_vcpu_restore_stall(&self) -> bool {
        let Error::Vm { msg, .. } = self else {
            return false;
        };
        // The probe's two failure modes that are indistinguishable
        // from a multi-vCPU RCU-stall:
        //   1. send_control_with_ack returns io::ErrorKind::Other
        //      with the underlying socket error string (most often
        //      "Resource temporarily unavailable" / EAGAIN, or a
        //      timeout phrase).
        //   2. The probe wrapper turned that into the
        //      "agent in this snapshot is from an older …" string;
        //      check for the embedded "(probe failed: …)".
        msg.contains("Resource temporarily unavailable")
            || msg.contains("os error 35")
            || msg.contains("os error 60") // ETIMEDOUT
            || msg.contains("timed out")
            || (msg.contains("probe failed") && !msg.contains("speaks protocol v"))
    }
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Image { msg, source } => f
                .debug_struct("Image")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::Vm { msg, source } => f
                .debug_struct("Vm")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::Assets { msg, source } => f
                .debug_struct("Assets")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::Io(e) => f.debug_tuple("Io").field(e).finish(),
            Error::Network { msg, source } => f
                .debug_struct("Network")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::CacheMiss { msg } => f.debug_struct("CacheMiss").field("msg", msg).finish(),
            Error::CacheInvalid { msg } => {
                f.debug_struct("CacheInvalid").field("msg", msg).finish()
            }
            Error::Bake { msg, source } => f
                .debug_struct("Bake")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::ImageNotFound { image, msg, source } => f
                .debug_struct("ImageNotFound")
                .field("image", image)
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::RegistryAuth { image, msg, source } => f
                .debug_struct("RegistryAuth")
                .field("image", image)
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::RegistryUnreachable { msg, source } => f
                .debug_struct("RegistryUnreachable")
                .field("msg", msg)
                .field("source", source)
                .finish(),
            Error::PoolExhausted { msg } => {
                f.debug_struct("PoolExhausted").field("msg", msg).finish()
            }
            Error::KernelPanic { first_line, stack } => f
                .debug_struct("KernelPanic")
                .field("first_line", first_line)
                .field("stack_lines", &stack.len())
                .finish(),
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Image { msg, .. } => write!(f, "image: {msg}"),
            Error::Vm { msg, .. } => write!(f, "vm: {msg}"),
            Error::Assets { msg, .. } => write!(f, "assets: {msg}"),
            Error::Io(e) => write!(f, "io: {e}"),
            Error::Network { msg, .. } => write!(f, "network: {msg}"),
            Error::CacheMiss { msg } => write!(f, "cache miss: {msg}"),
            Error::CacheInvalid { msg } => write!(f, "cache invalid: {msg}"),
            Error::Bake { msg, .. } => write!(f, "bake: {msg}"),
            Error::ImageNotFound { image, msg, .. } => {
                write!(f, "image not found ({image}): {msg}")
            }
            Error::RegistryAuth { image, msg, .. } => {
                write!(f, "registry auth failed for {image}: {msg}")
            }
            Error::RegistryUnreachable { msg, .. } => {
                write!(f, "registry unreachable: {msg}")
            }
            Error::PoolExhausted { msg } => write!(f, "pool exhausted: {msg}"),
            Error::KernelPanic { first_line, stack } => {
                writeln!(f, "kernel panic during bake: {first_line}")?;
                for line in stack {
                    writeln!(f, "  {line}")?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Image { source, .. }
            | Error::Vm { source, .. }
            | Error::Assets { source, .. }
            | Error::Network { source, .. }
            | Error::Bake { source, .. }
            | Error::ImageNotFound { source, .. }
            | Error::RegistryAuth { source, .. }
            | Error::RegistryUnreachable { source, .. } => source
                .as_ref()
                .map(|s| s.as_ref() as &(dyn std::error::Error + 'static)),
            Error::Io(e) => Some(e),
            Error::CacheMiss { .. }
            | Error::CacheInvalid { .. }
            | Error::PoolExhausted { .. }
            | Error::KernelPanic { .. } => None,
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
impl From<WarmPoolError> for Error {
    fn from(e: WarmPoolError) -> Self {
        Error::Vm {
            msg: e.to_string(),
            source: Some(Box::new(e)),
        }
    }
}

#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
impl From<PoolClientError> for Error {
    fn from(e: PoolClientError) -> Self {
        Error::Vm {
            msg: e.to_string(),
            source: Some(Box::new(e)),
        }
    }
}

/// How [`Image::from_oci`] decides whether to talk to the registry
/// or use a locally-cached snapshot. Same semantics as Docker's
/// `--pull` flag.
///
/// **The default is [`PullPolicy::Missing`]** — use the cache if
/// it exists; pull only if absent. Right for pinned tags or digest
/// references. For `:latest`-style mutable tags use
/// [`PullPolicy::Always`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PullPolicy {
    /// Pull manifest from the registry every time; rebake if the
    /// digest changed since the last bake. Right for `:latest`-style
    /// mutable tags.
    Always,
    /// Use the cached snapshot if it exists locally and is valid.
    /// Don't talk to the registry at all unless the cache is
    /// missing or invalid. **The default.**
    Missing,
    /// Use the cache or fail. Never pull. Right for offline /
    /// air-gapped environments.
    Never,
}

impl Default for PullPolicy {
    fn default() -> Self {
        Self::Missing
    }
}

impl PullPolicy {
    /// String form the underlying `bake` pipeline accepts. Mirror
    /// of the CLI's `--pull` argument values.
    fn as_bake_str(self) -> &'static str {
        match self {
            Self::Always => "always",
            Self::Missing => "missing",
            Self::Never => "never",
        }
    }
}

/// A baked OCI image: its restore snapshot plus the metadata
/// describing which kernel + virtio-blk layers it needs. Cheap
/// to clone.
///
/// Two ways to construct one:
///
/// - [`Image::from_oci`] — pull (or reuse cache) from a registry,
///   bake into a snapshot, return the resulting image. The
///   high-level "I have an image reference" entry point.
/// - [`Image::from_snapshot`] — load an already-baked snapshot
///   directory directly. Useful when you want to keep snapshots
///   under your own management or share one across processes.
/// Linux/KVM boot artifacts an [`Image`] carries when its `metadata.json` has
/// `"backend": "kvm"`. The [`Vm::start`] Linux path boots these directly via
/// [`crate::kvm::run::LinuxVm`] (kernel + agent PID-1 initramfs, with the
/// optional `disk` attached as `/dev/vda`). The HVF `restore.snap` /
/// virtio-fs-layer model does not apply — a KVM image boots cold.
#[derive(Debug, Clone)]
pub(crate) struct KvmImageParts {
    /// Cold-boot kernel (bzImage). `None` for snapshot-restore images.
    pub(crate) kernel: Option<PathBuf>,
    /// Cold-boot PID-1 agent initramfs. `None` for snapshot-restore images.
    pub(crate) initrd: Option<PathBuf>,
    /// Optional rootfs disk attached as `/dev/vda` (cold boot only).
    pub(crate) disk: Option<PathBuf>,
    /// A `VmSnapshot` file (SMSNAP03). When set, the VM is RESTORED from it
    /// (CoW mmap, ~ms) instead of cold-booting from kernel+initrd — produced
    /// by [`Vm::snapshot`].
    pub(crate) snapshot: Option<PathBuf>,
}

/// Artifacts for a `"backend":"sentry"` image (the no-virt process-isolation
/// backend — see [`crate::sentry`]). The sentry has no guest kernel and no
/// disk image: it serves the guest's files straight from an extracted rootfs
/// DIRECTORY via `openat2(RESOLVE_IN_ROOT)`, so the only artifact is that dir
/// plus a flag for whether a workload-launch script was baked into it.
#[derive(Debug, Clone)]
pub(crate) struct SentryImageParts {
    /// The extracted, layer-merged rootfs directory (the bake's output; NOT a
    /// squashfs). `crate::sentry::run` confines every guest path beneath it.
    pub(crate) rootfs: PathBuf,
    /// Whether `/.supermachine/run-workload` was staged into `rootfs` (i.e. the
    /// OCI image declared an Entrypoint/Cmd). When false, the image has no
    /// command to launch and [`Image::run_sentry`] is a no-op success.
    pub(crate) has_workload: bool,
    /// The baked image's `User` (`metadata.json["user"]`), parsed into a numeric
    /// `(uid, gid)` pair iff it was a numeric `uid` or `uid:gid` form. The sentry
    /// drops the guest cell to this uid/gid before sealing (defense in depth — a
    /// hostile guest is host-unprivileged). `None` for `root`/empty/username-only
    /// `User` values (the sentry can't resolve names without a passwd lookup, so it
    /// leaves the guest at the sentry's own uid in that case).
    pub(crate) user: Option<(u32, u32)>,
    /// The baked image environment (`metadata.json["image_env"]`, the OCI config's
    /// `Env` parsed at bake time) as `(KEY, VALUE)` pairs. Used as the env BASE for
    /// every `exec` against the sentry: a per-request env overlays it (request keys
    /// win), so a command run via `Vm::exec` sees the image's `PATH`/`LANG`/etc.
    /// just as it would inside a booted VM.
    pub(crate) image_env: Vec<(String, String)>,
    /// The effective workload argv recorded at bake (`metadata.json["cmd"]`, or
    /// `["entrypoint"]` when only an Entrypoint was declared). For a warm-daemon
    /// image this is the argv [`crate::sentry::Pool::warm`] parks at the SENTINEL
    /// checkpoint. Empty when the base image declared no Cmd/Entrypoint.
    pub(crate) cmd: Vec<String>,
    /// Whether this image was baked for the warm-daemon pool backend
    /// (`Image::builder(..).with_warm_daemon()`). Selects the `SentryPool` backend
    /// variant at pool-build time. `false` for legacy/base/ExecServer images.
    pub(crate) warm_daemon: bool,
}

/// Artifacts for a `"backend":"runsc"` image. This is the external no-KVM
/// backend path backed by gVisor/runsc systrap checkpoint/restore. It starts
/// from the same extracted OCI rootfs model as sentry, but runtime state is a
/// runsc container checkpoint rather than a sentry in-process cell snapshot.
#[derive(Debug, Clone)]
pub(crate) struct RunscImageParts {
    /// The extracted, layer-merged rootfs directory used as the OCI bundle root.
    pub(crate) rootfs: PathBuf,
    /// Metadata memory size preserved for API parity and snapshot round-trips.
    pub(crate) memory_mib: u32,
    /// Metadata vCPU count preserved for API parity and snapshot round-trips.
    pub(crate) vcpus: u32,
    /// Whether `/.supermachine/run-workload` was staged into `rootfs`.
    pub(crate) has_workload: bool,
    /// Numeric `User` parsed from metadata when available.
    pub(crate) user: Option<(u32, u32)>,
    /// The baked image environment (`metadata.json["image_env"]`).
    pub(crate) image_env: Vec<(String, String)>,
    /// The effective workload argv recorded at bake.
    pub(crate) cmd: Vec<String>,
    /// Whether this image was requested as a warm-daemon image.
    pub(crate) warm_daemon: bool,
    /// Optional runsc checkpoint captured by a build warmup.
    pub(crate) checkpoint: Option<PathBuf>,
    /// Host directory mounts to expose as OCI bind mounts.
    pub(crate) mounts: Vec<crate::vmm::resources::MountSpec>,
    /// Guest path of the staged supermachine agent binary.
    pub(crate) agent_path: String,
    /// Env var the agent reads to choose Unix-socket transport.
    pub(crate) agent_unix_env: String,
}

/// Artifacts for a `"backend":"kboxlike"` image. This is the native Rust
/// LKL/kbox-inspired no-KVM backend under construction. It intentionally uses
/// the same extracted OCI rootfs shape as sentry/runsc while the execution
/// layer is brought up behind the metadata boundary.
#[derive(Debug, Clone)]
pub(crate) struct KboxlikeImageParts {
    /// The extracted, layer-merged rootfs directory.
    pub(crate) rootfs: PathBuf,
    /// Metadata memory size preserved for API parity and snapshot round-trips.
    pub(crate) memory_mib: u32,
    /// Metadata vCPU count preserved for API parity and snapshot round-trips.
    pub(crate) vcpus: u32,
    /// Whether `/.supermachine/run-workload` was staged into `rootfs`.
    pub(crate) has_workload: bool,
    /// Numeric `User` parsed from metadata when available.
    pub(crate) user: Option<(u32, u32)>,
    /// The baked image environment (`metadata.json["image_env"]`).
    pub(crate) image_env: Vec<(String, String)>,
    /// The effective workload argv recorded at bake.
    pub(crate) cmd: Vec<String>,
    /// Whether this image was requested as a warm-daemon image.
    pub(crate) warm_daemon: bool,
    /// Host directory mounts preserved for the future kboxlike runtime.
    pub(crate) mounts: Vec<crate::vmm::resources::MountSpec>,
    /// Writable volumes persisted in metadata. The kboxlike no-virt runtime
    /// maps these as directory-backed bind mounts, matching the sentry backend.
    pub(crate) volumes: Vec<(PathBuf, String, u64, Option<PathBuf>)>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Debug)]
struct RunscRuntime {
    runsc_bin: PathBuf,
    runsc_root: PathBuf,
    network: String,
    build_netns: Option<RunscBuildNetwork>,
    container_id: String,
    bundle_dir: PathBuf,
    rootfs: PathBuf,
    parts: RunscImageParts,
    file_agent_exec: bool,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Clone, Debug)]
struct RunscPortForwardTarget {
    runsc_bin: PathBuf,
    runsc_root: PathBuf,
    network: String,
    container_id: String,
    agent_path: String,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct RunscPoolInner {
    parts: RunscImageParts,
    vm_config: VmConfig,
    min: usize,
    max: usize,
    warm_spares: usize,
    runsc_bin: PathBuf,
    runsc_root: PathBuf,
    network: String,
    build_netns: Option<RunscBuildNetwork>,
    pool_dir: PathBuf,
    base_bundle_dir: PathBuf,
    base_rootfs: PathBuf,
    checkpoint_dir: Option<PathBuf>,
    admission: Admission,
    checked_out: std::sync::atomic::AtomicUsize,
    idle: Mutex<Vec<Vm>>,
    restore_on_release: bool,
    shut_down: std::sync::atomic::AtomicBool,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct KboxlikePoolInner {
    parts: KboxlikeImageParts,
    vm_config: VmConfig,
    build_root: Option<PathBuf>,
    min: usize,
    admission: Admission,
    idle: Mutex<Vec<Vm>>,
    restore_on_release: bool,
    refilling: std::sync::atomic::AtomicBool,
    shut_down: std::sync::atomic::AtomicBool,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Debug)]
struct RunscBuildNetwork {
    name: String,
    host_veth: String,
    subnet: String,
    iface: String,
    old_ip_forward: Option<String>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl RunscRuntime {
    fn cleanup(&self) {
        let mut kill = Command::new(&self.runsc_bin);
        crate::exec::add_runsc_global_flags_with_network(
            &mut kill,
            &self.runsc_root,
            &self.network,
        );
        let _ = kill
            .arg("kill")
            .arg(&self.container_id)
            .arg("KILL")
            .status();

        let mut delete = Command::new(&self.runsc_bin);
        crate::exec::add_runsc_global_flags_with_network(
            &mut delete,
            &self.runsc_root,
            &self.network,
        );
        let _ = delete
            .arg("delete")
            .arg("-force")
            .arg(&self.container_id)
            .status();

        let _ = Command::new("umount").arg("-l").arg(&self.rootfs).status();

        if let Some(dir) = self.bundle_dir.parent() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for RunscRuntime {
    fn drop(&mut self) {
        self.cleanup();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Debug)]
struct KboxlikeRuntime {
    runtime_dir: PathBuf,
    source_root_host_pid: Option<i32>,
    restored_host_pids: Vec<i32>,
    rootfs: PathBuf,
    parts: KboxlikeImageParts,
    mounts: Vec<(PathBuf, String)>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Clone, Debug)]
struct KboxlikePortForwardTarget {
    restored_host_pids: Vec<i32>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl KboxlikeRuntime {
    fn cleanup(&mut self) {
        if let Some(pid) = self.source_root_host_pid.take() {
            crate::kboxlike::kill_and_reap_live_process_group(pid);
        }
        let mut pending: std::collections::BTreeSet<i32> =
            self.restored_host_pids.drain(..).collect();
        for pid in pending.iter().copied() {
            unsafe {
                libc::kill(pid, libc::SIGKILL);
            }
        }
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while !pending.is_empty() && std::time::Instant::now() <= deadline {
            let mut status = 0;
            let waited = unsafe { libc::waitpid(-1, &mut status, libc::__WALL | libc::WNOHANG) };
            if waited > 0 {
                pending.remove(&waited);
            } else if waited == 0 {
                std::thread::sleep(std::time::Duration::from_millis(1));
            } else {
                break;
            }
        }
        let _ = std::fs::remove_dir_all(&self.runtime_dir);
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for KboxlikeRuntime {
    fn drop(&mut self) {
        self.cleanup();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for KboxlikePoolInner {
    fn drop(&mut self) {
        self.shut_down
            .store(true, std::sync::atomic::Ordering::SeqCst);
        self.idle.lock().unwrap_or_else(|e| e.into_inner()).clear();
        if let Some(dir) = self.build_root.take() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_host_exe_path(parts: &KboxlikeImageParts, argv0: Option<&str>) -> String {
    let Some(argv0) = argv0.filter(|value| !value.is_empty()) else {
        return std::env::current_exe()
            .ok()
            .map(|path| path.to_string_lossy().into_owned())
            .unwrap_or_else(|| "supermachine".to_owned());
    };
    if let Some(guest_abs) = argv0.strip_prefix('/') {
        return parts.rootfs.join(guest_abs).to_string_lossy().into_owned();
    }
    argv0.to_owned()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_timing_enabled() -> bool {
    matches!(
        std::env::var("SUPERMACHINE_RUNSC_TIMINGS").as_deref(),
        Ok("1") | Ok("true") | Ok("TRUE") | Ok("yes") | Ok("YES")
    )
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_timing(label: &str, start: Instant) {
    if runsc_timing_enabled() {
        eprintln!(
            "supermachine(runsc timing): {label} {}ms",
            start.elapsed().as_millis()
        );
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_pool_spares(max: usize, restore_on_release: bool) -> usize {
    if !restore_on_release {
        return 0;
    }
    if let Ok(raw) = std::env::var("SUPERMACHINE_RUNSC_POOL_SPARES") {
        if let Ok(n) = raw.parse::<usize>() {
            return n;
        }
    }
    ((max + 1) / 2).clamp(1, 4).min(max.max(1))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl RunscBuildNetwork {
    fn create() -> Result<Self, Error> {
        let iface = runsc_default_host_iface()?;
        let suffix = format!("{:x}", unique_suffix());
        let short = &suffix[..suffix.len().min(8)];
        let name = format!("sm{short}");
        let host_veth = format!("vh{short}");
        let guest_veth = format!("vg{short}");
        let octet = 32 + (std::process::id() % 160);
        let subnet = format!("10.231.{octet}.0/24");
        let host_ip = format!("10.231.{octet}.1");
        let guest_ip = format!("10.231.{octet}.2");
        let old_ip_forward = std::fs::read_to_string("/proc/sys/net/ipv4/ip_forward")
            .ok()
            .map(|s| s.trim().to_owned());

        let net = Self {
            name,
            host_veth,
            subnet,
            iface,
            old_ip_forward,
        };
        if let Err(e) = net.setup(&guest_veth, &host_ip, &guest_ip) {
            net.cleanup();
            return Err(e);
        }
        Ok(net)
    }

    fn path(&self) -> PathBuf {
        PathBuf::from(format!("/run/netns/{}", self.name))
    }

    fn setup(&self, guest_veth: &str, host_ip: &str, guest_ip: &str) -> Result<(), Error> {
        runsc_host_cmd("sysctl", &["-w", "net.ipv4.ip_forward=1"])?;
        runsc_host_cmd("ip", &["netns", "add", &self.name])?;
        runsc_host_cmd(
            "ip",
            &[
                "link",
                "add",
                &self.host_veth,
                "type",
                "veth",
                "peer",
                "name",
                guest_veth,
            ],
        )?;
        runsc_host_cmd("ip", &["link", "set", guest_veth, "netns", &self.name])?;
        let host_cidr = format!("{host_ip}/24");
        runsc_host_cmd("ip", &["addr", "add", &host_cidr, "dev", &self.host_veth])?;
        runsc_host_cmd("ip", &["link", "set", &self.host_veth, "up"])?;
        let guest_cidr = format!("{guest_ip}/24");
        runsc_host_cmd(
            "ip",
            &[
                "netns",
                "exec",
                &self.name,
                "ip",
                "addr",
                "add",
                &guest_cidr,
                "dev",
                guest_veth,
            ],
        )?;
        runsc_host_cmd(
            "ip",
            &["netns", "exec", &self.name, "ip", "link", "set", "lo", "up"],
        )?;
        runsc_host_cmd(
            "ip",
            &[
                "netns", "exec", &self.name, "ip", "link", "set", guest_veth, "up",
            ],
        )?;
        runsc_host_cmd(
            "ip",
            &[
                "netns", "exec", &self.name, "ip", "route", "add", "default", "via", host_ip,
            ],
        )?;
        runsc_host_cmd(
            "iptables",
            &[
                "-t",
                "nat",
                "-A",
                "POSTROUTING",
                "-s",
                &self.subnet,
                "-o",
                &self.iface,
                "-j",
                "MASQUERADE",
            ],
        )
    }

    fn cleanup(&self) {
        let _ = Command::new("iptables")
            .args([
                "-t",
                "nat",
                "-D",
                "POSTROUTING",
                "-s",
                &self.subnet,
                "-o",
                &self.iface,
                "-j",
                "MASQUERADE",
            ])
            .status();
        let _ = Command::new("ip")
            .args(["link", "del", &self.host_veth])
            .status();
        let _ = Command::new("ip")
            .args(["netns", "del", &self.name])
            .status();
        if let Some(old) = &self.old_ip_forward {
            let setting = format!("net.ipv4.ip_forward={old}");
            let _ = Command::new("sysctl").args(["-w", &setting]).status();
        }
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for RunscBuildNetwork {
    fn drop(&mut self) {
        self.cleanup();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_host_cmd(program: &str, args: &[&str]) -> Result<(), Error> {
    let out = Command::new(program)
        .args(args)
        .output()
        .map_err(|e| Error::vm_msg(format!("{program} {}: {e}", args.join(" "))))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "{program} {} failed with status {:?}: {}",
            args.join(" "),
            out.status.code(),
            String::from_utf8_lossy(&out.stderr)
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_default_host_iface() -> Result<String, Error> {
    let routes = std::fs::read_to_string("/proc/net/route").map_err(Error::Io)?;
    for line in routes.lines().skip(1) {
        let fields: Vec<_> = line.split_whitespace().collect();
        if fields.len() > 1 && fields[1] == "00000000" {
            return Ok(fields[0].to_owned());
        }
    }
    Err(Error::vm_msg(
        "runsc build network: host default route not found".to_owned(),
    ))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_network_for_config(config: &VmConfig) -> &'static str {
    if config.for_build {
        crate::exec::RUNSC_NETWORK_SANDBOX
    } else {
        crate::exec::RUNSC_NETWORK_NONE
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl RunscPoolInner {
    fn build(
        image: &Image,
        config: &VmConfig,
        min: usize,
        max: usize,
        acquire_timeout: Option<Duration>,
        restore_on_release: bool,
    ) -> Result<Arc<Self>, Error> {
        let parts = image
            .runsc
            .as_ref()
            .ok_or_else(|| Error::vm_msg("RunscPoolInner::build on a non-runsc image"))?
            .clone();
        let runsc_bin = runsc_bin_path();
        let network = runsc_network_for_config(config).to_owned();
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        std::fs::create_dir_all(&dir).map_err(Error::Io)?;
        let pool_dir = dir.join(format!(
            "supermachine-runsc-pool-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        let base_bundle_dir = pool_dir.join("base-bundle");
        let base_rootfs = base_bundle_dir.join("rootfs");
        let runsc_root = pool_dir.join("runsc-root");
        std::fs::create_dir_all(&runsc_root).map_err(Error::Io)?;
        let build_netns = if network == crate::exec::RUNSC_NETWORK_SANDBOX {
            Some(RunscBuildNetwork::create()?)
        } else {
            None
        };
        let netns_path = build_netns.as_ref().map(|net| net.path());
        prepare_runsc_bundle(
            &runsc_bin,
            &parts,
            &base_bundle_dir,
            &base_rootfs,
            &network,
            netns_path.as_deref(),
        )?;

        let checkpoint_dir = if network == crate::exec::RUNSC_NETWORK_SANDBOX {
            None
        } else {
            let checkpoint_dir = pool_dir.join("checkpoint");
            std::fs::create_dir_all(&checkpoint_dir).map_err(Error::Io)?;
            Some(checkpoint_dir)
        };

        if let (Some(source_checkpoint), Some(checkpoint_dir)) =
            (&parts.checkpoint, checkpoint_dir.as_ref())
        {
            if let Err(e) = copy_dir_recursive(source_checkpoint, &checkpoint_dir) {
                let _ = std::fs::remove_dir_all(&pool_dir);
                return Err(Error::vm_msg(format!(
                    "runsc checkpoint clone {} -> {}: {e}",
                    source_checkpoint.display(),
                    checkpoint_dir.display()
                )));
            }
        } else if let Some(checkpoint_dir) = checkpoint_dir.as_ref() {
            let warm_id = format!("sm-runsc-warm-{}-{}", std::process::id(), unique_suffix());
            let pid_file = pool_dir.join("warm.pid");
            if let Err(e) = runsc_run_detached(
                &runsc_bin,
                &runsc_root,
                &network,
                &base_bundle_dir,
                &pid_file,
                &warm_id,
            ) {
                let _ = std::fs::remove_dir_all(&pool_dir);
                return Err(e);
            }
            let checkpoint =
                runsc_checkpoint(&runsc_bin, &runsc_root, &network, &checkpoint_dir, &warm_id);
            let _ = runsc_delete_force(&runsc_bin, &runsc_root, &network, &warm_id);
            if let Err(e) = checkpoint {
                let _ = std::fs::remove_dir_all(&pool_dir);
                return Err(e);
            }
        }

        let max = max.max(1);
        let min = min.min(max);
        let warm_spares = if min > 0 {
            runsc_pool_spares(max, restore_on_release)
        } else {
            0
        };
        let inner = Arc::new(Self {
            parts,
            vm_config: config.clone(),
            min,
            max,
            warm_spares,
            runsc_bin,
            runsc_root,
            network,
            build_netns,
            pool_dir,
            base_bundle_dir,
            base_rootfs,
            checkpoint_dir,
            admission: Admission::new(max.saturating_add(warm_spares), acquire_timeout),
            checked_out: std::sync::atomic::AtomicUsize::new(0),
            idle: Mutex::new(Vec::new()),
            restore_on_release,
            shut_down: std::sync::atomic::AtomicBool::new(false),
        });
        inner.prewarm_to_min();
        Ok(inner)
    }

    fn warm_target(&self) -> usize {
        self.min.saturating_add(self.warm_spares)
    }

    fn try_checkout(&self) -> bool {
        use std::sync::atomic::Ordering::SeqCst;
        loop {
            let cur = self.checked_out.load(SeqCst);
            if cur >= self.max {
                return false;
            }
            if self
                .checked_out
                .compare_exchange(cur, cur + 1, SeqCst, SeqCst)
                .is_ok()
            {
                return true;
            }
        }
    }

    fn release_checkout(&self) {
        self.checked_out
            .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        self.admission.notify();
    }

    fn acquire_vm(&self) -> Result<Vm, Error> {
        let deadline = self
            .admission
            .acquire_timeout
            .map(|d| std::time::Instant::now() + d);
        loop {
            if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
                return Err(Error::pool_exhausted("pool is shut down"));
            }
            if self.checked_out.load(std::sync::atomic::Ordering::SeqCst) < self.max {
                let mut idle = self.idle.lock().unwrap_or_else(|e| e.into_inner());
                if !idle.is_empty() && self.try_checkout() {
                    return Ok(idle.pop().expect("idle checked above"));
                }
            }
            if self.try_checkout() {
                if self.admission.try_reserve() {
                    return self.restore_one().inspect_err(|_| {
                        self.release_checkout();
                        self.admission.release();
                    });
                }
                self.release_checkout();
            }
            if !self.admission.wait_for_change(deadline)? {
                return Err(Error::pool_exhausted(format!(
                    "runsc pool saturated: all {} checkout slots in use and none freed within \
                     acquire_timeout",
                    self.max
                )));
            }
        }
    }

    fn restore_one(&self) -> Result<Vm, Error> {
        let restore_total = Instant::now();
        let runtime_dir = self.pool_dir.join(format!(
            "restore-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        let bundle_dir = runtime_dir.join("bundle");
        let rootfs = bundle_dir.join("rootfs");
        let phase = Instant::now();
        std::fs::create_dir_all(&bundle_dir).map_err(Error::Io)?;
        prepare_runsc_restore_rootfs(&self.base_rootfs, &runtime_dir, &rootfs)?;
        runsc_timing("restore.prepare_rootfs", phase);
        let netns_path = self.build_netns.as_ref().map(|net| net.path());
        let phase = Instant::now();
        copy_runsc_bundle_config(
            &self.base_bundle_dir,
            &bundle_dir,
            &self.parts,
            &rootfs,
            &self.network,
            netns_path.as_deref(),
        )?;
        runsc_timing("restore.bundle_config", phase);

        let container_id = format!(
            "sm-runsc-restored-{}-{}",
            std::process::id(),
            unique_suffix()
        );
        let pid_file = runtime_dir.join("container.pid");
        if let Some(checkpoint_dir) = &self.checkpoint_dir {
            let phase = Instant::now();
            if let Err(e) = runsc_restore_detached(
                &self.runsc_bin,
                &self.runsc_root,
                &self.network,
                &bundle_dir,
                checkpoint_dir,
                &pid_file,
                &container_id,
            ) {
                let _ = std::fs::remove_dir_all(&runtime_dir);
                return Err(e);
            }
            runsc_timing("restore.runsc_restore", phase);
        } else {
            let phase = Instant::now();
            if let Err(e) = runsc_run_detached(
                &self.runsc_bin,
                &self.runsc_root,
                &self.network,
                &bundle_dir,
                &pid_file,
                &container_id,
            ) {
                let _ = std::fs::remove_dir_all(&runtime_dir);
                return Err(e);
            }
            runsc_timing("restore.runsc_run", phase);
        }
        runsc_timing("restore.total", restore_total);

        Ok(Vm {
            running: None,
            sentry_exec: None,
            sentry_src_rootfs: None,
            vsock_mux_path: runtime_dir.join("runsc-unwired.sock"),
            vsock_exec_path: runtime_dir.join("runsc-exec-unwired.sock"),
            own_vsock_mux_dir: None,
            skip_cleanup: false,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            _sentry_mem_admission: None,
            sentry_warm_pool: None,
            sentry_unified_pool: None,
            runsc: Some(RunscRuntime {
                runsc_bin: self.runsc_bin.clone(),
                runsc_root: self.runsc_root.clone(),
                network: self.network.clone(),
                build_netns: None,
                container_id,
                bundle_dir,
                rootfs,
                parts: self.parts.clone(),
                file_agent_exec: false,
            }),
            kboxlike: None,
        })
    }

    fn prewarm_to_min(&self) {
        loop {
            let idle_len = self.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
            if idle_len >= self.warm_target() || !self.admission.try_reserve() {
                break;
            }
            match self.restore_one() {
                Ok(vm) => {
                    self.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
                    self.admission.notify();
                }
                Err(e) => {
                    eprintln!("supermachine(runsc): prewarm restore failed: {e}");
                    self.admission.release();
                    break;
                }
            }
        }
    }

    fn release_vm(self: &Arc<Self>, vm: Vm) {
        if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
            self.release_checkout();
            drop(vm);
            self.admission.release();
            return;
        }
        if !self.restore_on_release {
            self.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
            self.release_checkout();
            self.admission.notify();
            return;
        }

        self.release_checkout();
        let inner = Arc::clone(self);
        if let Err(e) = std::thread::Builder::new()
            .name("supermachine-runsc-refill".into())
            .spawn(move || inner.recycle_released_vm(vm))
        {
            eprintln!("supermachine(runsc): spawn refill thread failed: {e}");
            self.admission.release();
        }
    }

    fn recycle_released_vm(self: Arc<Self>, vm: Vm) {
        let total = Instant::now();
        drop(vm);
        runsc_timing("release.drop_dirty", total);
        if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
            self.admission.release();
            return;
        }
        let keep_warm =
            self.idle.lock().unwrap_or_else(|e| e.into_inner()).len() < self.warm_target();
        if keep_warm {
            match self.restore_one() {
                Ok(fresh) => {
                    self.idle
                        .lock()
                        .unwrap_or_else(|e| e.into_inner())
                        .push(fresh);
                    self.admission.notify();
                }
                Err(e) => {
                    eprintln!("supermachine(runsc): restore_on_release refill failed: {e}");
                    self.admission.release();
                }
            }
        } else {
            self.admission.release();
        }
        runsc_timing("release.total", total);
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for RunscPoolInner {
    fn drop(&mut self) {
        self.shut_down
            .store(true, std::sync::atomic::Ordering::SeqCst);
        self.admission.notify();
        let drained: Vec<Vm> =
            std::mem::take(&mut *self.idle.lock().unwrap_or_else(|e| e.into_inner()));
        for vm in drained {
            drop(vm);
        }
        let _ = std::fs::remove_dir_all(&self.pool_dir);
    }
}

/// Run-config for a sentry bake (Linux/x86_64): the [`OciImageBuilder`] fields
/// that the no-virt backend honors. The KVM/HVF backends carry these through
/// their own bake pipelines; the sentry path applies them in
/// [`Image::bake_sentry_with_config`].
///
/// Construct via [`SentryBakeConfig::default`] (the base image's own config) and
/// fill the fields the builder set. Not `Clone`/`Debug` because `warmup` is a
/// boxed `FnOnce`.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[derive(Default)]
pub struct SentryBakeConfig {
    /// Default memory recorded in image metadata; VmConfig can still override it.
    pub memory_mib: Option<u32>,
    /// Default vCPU count recorded in image metadata; VmConfig can still override it.
    pub vcpus: Option<u32>,
    /// Override the workload argv (`Entrypoint`/`Cmd`). `None` → the image's own.
    pub cmd: Option<Vec<String>>,
    /// Extra env merged OVER the image `Env` (builder wins on key collision).
    pub env: Vec<(String, String)>,
    /// Override the workload's working directory. `None` → the image's.
    pub working_dir: Option<String>,
    /// Override the recorded `user`. `None` → the image's.
    pub user: Option<String>,
    /// Files staged into the rootfs at bake time: `(host_path, guest_path)`.
    pub extra_files: Vec<(PathBuf, String)>,
    /// Mounts persisted in metadata: `(host_path, guest_tag, policy, guest_path)`.
    pub mounts: Vec<(
        PathBuf,
        String,
        crate::vmm::resources::SymlinkPolicy,
        String,
    )>,
    /// Writable volumes persisted in metadata: `(host_file, guest_path, size)`.
    pub volumes: Vec<(PathBuf, String, u64)>,
    /// Post-bake warmup run against a transient sentry [`Vm`]; its rootfs writes
    /// land in-place in the baked artifact.
    pub warmup: Option<Box<dyn FnOnce(&Vm) -> Result<(), Error> + Send>>,
    /// Bake the image for the warm-daemon pool backend (a persistent parked cell).
    /// Persisted to `metadata.json["warm_daemon"]` and read back into
    /// [`SentryImageParts::warm_daemon`].
    pub warm_daemon: bool,
    /// Stable warmup tag, persisted to `metadata.json["warmup_tag"]` for round-trip
    /// parity with the KVM/HVF bakes (the sentry path previously DROPPED it).
    pub warmup_tag: Option<String>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_sha256_bytes(bytes: &[u8]) -> String {
    let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
    let mut out = String::with_capacity(64);
    for b in digest.as_ref() {
        use std::fmt::Write as _;
        let _ = write!(out, "{b:02x}");
    }
    out
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_sha256_file(path: &Path) -> Result<String, Error> {
    let mut f = std::fs::File::open(path).map_err(|e| {
        Error::bake_msg(format!(
            "hash sentry bake input file {}: {e}",
            path.display()
        ))
    })?;
    let mut ctx = ring::digest::Context::new(&ring::digest::SHA256);
    let mut buf = [0u8; 64 * 1024];
    loop {
        let n = f.read(&mut buf).map_err(|e| {
            Error::bake_msg(format!(
                "read sentry bake input file {}: {e}",
                path.display()
            ))
        })?;
        if n == 0 {
            break;
        }
        ctx.update(&buf[..n]);
    }
    let digest = ctx.finish();
    let mut out = String::with_capacity(64);
    for b in digest.as_ref() {
        use std::fmt::Write as _;
        let _ = write!(out, "{b:02x}");
    }
    Ok(out)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_file_mode(path: &Path) -> Result<u32, Error> {
    use std::os::unix::fs::PermissionsExt as _;
    Ok(std::fs::metadata(path)
        .map_err(|e| Error::bake_msg(format!("stat sentry bake input {}: {e}", path.display())))?
        .permissions()
        .mode()
        & 0o7777)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_bake_cache_key(image_ref: &str, config: &SentryBakeConfig) -> Result<String, Error> {
    let mut extra_files = Vec::with_capacity(config.extra_files.len());
    for (host, guest) in &config.extra_files {
        extra_files.push(serde_json::json!({
            "guest": guest,
            "mode": sentry_file_mode(host)?,
            "sha256": sentry_sha256_file(host)?,
        }));
    }
    let mounts: Vec<_> = config
        .mounts
        .iter()
        .map(|(host, tag, policy, guest)| {
            serde_json::json!({
                "host": host.to_string_lossy(),
                "tag": tag,
                "policy": format!("{policy:?}"),
                "guest": guest,
            })
        })
        .collect();
    let volumes: Vec<_> = config
        .volumes
        .iter()
        .map(|(host, guest, size)| {
            serde_json::json!({
                "host": host.to_string_lossy(),
                "guest": guest,
                "size": size,
            })
        })
        .collect();
    let input = serde_json::json!({
        "schema": 1,
        "image": image_ref,
        "memory_mib": config.memory_mib,
        "vcpus": config.vcpus,
        "cmd": &config.cmd,
        "env": &config.env,
        "working_dir": &config.working_dir,
        "user": &config.user,
        "extra_files": extra_files,
        "mounts": mounts,
        "volumes": volumes,
        "has_warmup": config.warmup.is_some(),
        "warmup_tag": &config.warmup_tag,
        "warm_daemon": config.warm_daemon,
    });
    let bytes = serde_json::to_vec(&input)
        .map_err(|e| Error::bake_msg(format!("encode sentry bake cache key: {e}")))?;
    Ok(sentry_sha256_bytes(&bytes))
}

#[derive(Debug, Clone)]
pub struct Image {
    snapshot_path: PathBuf,
    /// Default memory; can be overridden via [`VmConfig::with_memory_mib`].
    pub(crate) memory_mib: u32,
    /// Default vCPUs; can be overridden via [`VmConfig::with_vcpus`].
    pub(crate) vcpus: u32,
    /// 16-hex-prefix of the supermachine-worker SHA256 that baked
    /// this snapshot, parsed from `metadata.json["runtime_sha16"]`.
    /// Used to skip the agent-protocol probe when a fresh-bake
    /// invariant holds (snapshot baked by the same lib version
    /// the host is now running). `None` means metadata didn't
    /// record one — older snapshots, third-party bakes, etc; the
    /// probe runs unconditionally in that case.
    pub(crate) baker_runtime_sha16: Option<String>,
    /// `metadata.json["balloon_target_pages"]` — bake-time
    /// recommended balloon inflation target for idle workers.
    /// Plumbed through SpawnConfig → worker CLI → runner so each
    /// pool worker requests inflate after restore. None disables
    /// ballooning. Defaults to 75% of `memory_mib` in 4 KiB
    /// pages (set by bake.rs).
    pub(crate) balloon_target_pages: Option<u32>,
    /// TSI control-channel auth token (64-char lowercase hex).
    /// Generated at fresh bake, persisted in metadata.json,
    /// re-injected on every restore via the worker's
    /// `--tsi-token` flag. `None` on legacy snapshots (pre-0.6.0)
    /// — the muxer accepts all control DGRAMs in that case.
    /// See `kernel-build/patches/af-tsi/0014-*.patch` for the
    /// threat model.
    pub(crate) tsi_token: Option<String>,
    /// 0.7.65+ per-snapshot egress policy from
    /// `metadata.json["egress_policy"]` (e.g. `deny_private`,
    /// `allowlist:<cidrs>`, `denylist:<cidrs>`). Re-injected on the
    /// worker via `--egress-policy` so the muxer enforces it at TSI
    /// connect time. `None` (the common case) → `allow_all`. Previously
    /// only the router/worker CLI honored this; threading it here makes
    /// the high-level `Image::acquire` / `Pool` path enforce a baked
    /// snapshot's network policy too.
    pub(crate) egress_policy: Option<String>,
    /// 0.7.44+ pre-exec sync flag. `true` → init-oci is paused
    /// inside `read(0)` in the saved snapshot at the pre-exec
    /// pause point. spawn_one sets
    /// SUPERMACHINE_PRE_EXEC_SYNC_RESUME=1 on the worker so the
    /// `supermachine-pre-exec-resume` thread pushes the unblock
    /// byte after restore. `false` (legacy / pre-0.7.44) → init-oci
    /// used the 250 ms nanosleep at that point; no push needed.
    pub(crate) pre_exec_sync: bool,
    /// virtio-blk layer file paths in the order the bake step
    /// produced them. The microVM needs all of them attached at
    /// restore time (the OverlayFS in the guest is mounted on top).
    pub(crate) layers: Vec<PathBuf>,
    /// Optional per-image delta layer applied after `layers`.
    pub(crate) delta_squashfs: Option<PathBuf>,
    /// virtio-fs DAX mounts persisted in metadata.json. The bake
    /// captures the snapshot with these mounts wired into the FDT,
    /// so restore must re-create the same VirtioFs devices at the
    /// same MMIO addresses for the guest kernel to find them.
    pub(crate) mounts: Vec<crate::vmm::resources::MountSpec>,
    /// Writable virtio-blk volumes persisted in metadata.json as
    /// `[{host_file, guest_path, size_bytes, pristine?}, ...]`.
    /// The bake snapshots the guest BEFORE `mount_volumes()` runs
    /// (init-oci's `[SUPERMACHINE-INIT] heartbeat counter=1` marker
    /// fires pre-mount), so the snapshot itself doesn't carry the
    /// volume mount — init-oci re-runs `mount_volumes()` on each
    /// restore. For that re-mount to find a `/dev/vd<N>` device,
    /// the warm-restore worker MUST re-attach the volume via
    /// `--volume HOST:GUEST:SIZE`. Without this, the guest hangs
    /// on any ext4 read after restore. (Field-report bug fixed
    /// 0.7.30.)
    ///
    /// Tuple shape: (host_file, guest_path, size_bytes, pristine).
    /// `pristine` is `Some(path)` for 0.7.49+ snapshots and points
    /// at an immutable byte-identical copy of `host_file` captured
    /// at snapshot save time. Pools running with
    /// `restoreOnRelease=true` clone the pristine to a per-worker
    /// temp file on each spawn so the worker's writes never leak
    /// between acquires — keeps virtio-blk bytes in lock-step with
    /// the snapshot's captured ext4 RAM state. Pre-0.7.49 snapshots
    /// have `None`; the pool logs a one-line warning and falls
    /// through to the legacy behavior (worker uses `host_file`
    /// directly, writes persist).
    pub(crate) volumes: Vec<(PathBuf, String, u64, Option<PathBuf>)>,
    /// Bundled kernel path, if the snapshot dir ships one alongside.
    /// Lets a self-contained bundle (e.g. `MyApp.app/Contents/
    /// Resources/<image>/kernel`) start a VM without requiring the
    /// embedder's host to have supermachine assets installed
    /// system-wide. `None` means [`Vm::start`] falls back to
    /// [`AssetPaths::discover`].
    pub(crate) bundled_kernel: Option<PathBuf>,
    /// Linux/KVM artifacts parsed from `metadata.json` when
    /// `"backend": "kvm"`: the bzImage, the PID-1 agent initramfs, and an
    /// optional rootfs disk (attached as `/dev/vda`). `None` for HVF
    /// snapshots. Consumed by the Linux [`Vm::start`].
    pub(crate) kvm: Option<KvmImageParts>,
    /// `"backend":"sentry"`: the extracted rootfs dir served by the no-virt
    /// process-isolation backend (see [`crate::sentry`]). `None` for HVF/KVM
    /// images. Run with [`Image::run_sentry`].
    pub(crate) sentry: Option<SentryImageParts>,
    /// `"backend":"runsc"`: the extracted rootfs dir served by the external
    /// gVisor/runsc no-KVM backend. `None` for HVF/KVM/sentry images.
    pub(crate) runsc: Option<RunscImageParts>,
    /// `"backend":"kboxlike"`: the extracted rootfs dir for the native Rust
    /// kbox/LKL-inspired no-KVM backend under construction.
    pub(crate) kboxlike: Option<KboxlikeImageParts>,
    /// Hidden warm pool, lazy-initialized on first
    /// [`Image::acquire`]. The pool holds a single long-lived
    /// `WarmPool` (in-process worker + the snapshot mmap'd in)
    /// behind a mutex; each `acquire` calls `restore` to reset
    /// the worker to clean snapshot state, returns a [`PooledVm`]
    /// that holds the lock, and re-enters the pool on `Drop`.
    /// Per-acquire cost is just the snapshot restore (~5 ms),
    /// not the full VM spawn (~50–100 ms).
    ///
    /// Wrapped in `Arc` so cloning an `Image` shares the same
    /// pool instance — useful when multiple parts of an app hold
    /// `Image` references but should share a single warm worker.
    pub(crate) hidden_pool: std::sync::OnceLock<Arc<HiddenPool>>,
    /// Warm handoff: the bake-time worker, kept alive after the
    /// pipelined bake completes (`Image::builder().with_warmup(…)`)
    /// so the FIRST `Pool::acquire()` can use it directly instead
    /// of paying ~50 ms spawn + ~5 ms restore for a fresh worker.
    /// Subsequent acquires fall through to the normal spawn-from-
    /// disk path.
    ///
    /// Atomic claim semantics: the consumer (`PoolBuilder::build` or
    /// `HiddenPool::ensure_min_workers`) calls
    /// `warm_baked_worker.lock().take()`. Only one party gets
    /// `Some`; everyone else gets `None` and falls through cleanly.
    /// This also guards against multi-pool-from-same-Image: only
    /// the first pool gets the warm worker.
    ///
    /// Drop semantics: if the Image is dropped without anyone
    /// claiming, `Drop for Image` (below) takes the value and
    /// shuts down the worker via QUIT (drains in-flight saves)
    /// + `child.wait()` + socks_dir cleanup. The bake driver
    /// already drained the bg base save before returning the
    /// BakedWorker, so QUIT is a fast (~10 ms) drain-noop in this
    /// case — no `.partial` leaks.
    pub(crate) warm_baked_worker: Arc<crate::bake::WarmStash>,
    /// Linux/KVM ambient warm pool, built lazily on the first `acquire`/
    /// `acquire_with` and shared across clones (Arc). Makes `image.acquire()`
    /// a CoW restore (~ms) instead of a cold boot (~1s) — the macOS
    /// `hidden_pool` equivalent for KVM. `Arc<Pool>` breaks the Image↔Pool cycle.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub(crate) kvm_pool: std::sync::OnceLock<Arc<Pool>>,
}

impl Image {
    /// Test-only introspection: is a warm-handoff worker currently
    /// stashed? Used by the warm-handoff integration tests to
    /// verify the bake actually populated the stash, and that the
    /// first `Pool::build()` consumed it. Not part of the public
    /// API contract — the field itself is `pub(crate)` and may
    /// move; this accessor is doc-hidden because it's a peephole
    /// for tests, not a feature.
    /// Test-only introspection: is this a Linux/KVM cold-boot image (kernel +
    /// initrd, no warm snapshot)? Cold-boot images go through
    /// `warm_snapshot_for_pool`'s persist+dedup path; snapshot-backed ones
    /// early-return. Used by the warm-persist test to skip cross-family
    /// assertions when the second image is already snapshot-backed. Not stable.
    #[doc(hidden)]
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn is_kvm_cold_boot(&self) -> bool {
        self.kvm
            .as_ref()
            .map(|k| k.snapshot.is_none())
            .unwrap_or(false)
    }
    /// True iff this image is backed by the no-virt sentry backend (vs KVM/HVF).
    /// Lets a caller (e.g. the CLI's snapshot cache) tell which backend a loaded
    /// snapshot was baked for, so a cache hit can be matched to the requested backend.
    pub fn is_sentry(&self) -> bool {
        self.sentry.is_some()
    }
    /// True iff this image is backed by the experimental runsc no-KVM backend.
    pub fn is_runsc(&self) -> bool {
        self.runsc.is_some()
    }
    /// True iff this image is backed by the experimental native kboxlike backend.
    #[doc(hidden)]
    pub fn is_kboxlike(&self) -> bool {
        self.kboxlike.is_some()
    }
    #[doc(hidden)]
    pub fn _warm_handoff_present(&self) -> bool {
        self.warm_baked_worker
            .inner
            .lock()
            .map(|g| g.is_some())
            .unwrap_or(false)
    }
    /// Test-only: PID of the stashed warm worker, or None. Used by
    /// the R1 integration test (Image-dropped-without-claim) to
    /// `kill -0` the pid after dropping the Image and confirm
    /// reaping. Not stable.
    #[doc(hidden)]
    pub fn _warm_handoff_pid(&self) -> Option<u32> {
        self.warm_baked_worker
            .inner
            .lock()
            .ok()
            .and_then(|g| g.as_ref().map(|bw| bw.child.id()))
    }
}

/// Internal state for the hidden subprocess pool an [`Image`]
/// manages for [`Image::acquire`] users. Spawns N
/// `supermachine-worker` subprocesses up front, each pre-restored
/// from the snapshot — so `acquire` is just "pop an idle worker
/// off the queue" (~1 ms) and N concurrent acquires really run N
/// VMs in parallel (each in its own subprocess, each its own
/// `hv_vm_create` singleton).
///
/// On `Drop`, kills every worker and unlinks every socket.
#[doc(hidden)]
pub struct HiddenPool {
    /// Per-worker state: idle queue + counts. Arc'd separately
    /// from the pool so housekeeping threads can hold it across
    /// condvar waits without keeping `HiddenPool` itself alive
    /// (otherwise the user-side drop never fires).
    state: Arc<Mutex<PoolState>>,
    /// Wakes `acquire()` callers blocked on an empty idle queue
    /// AND wakes housekeeping threads on shutdown. Signalled when
    /// a worker re-enters idle, when the pool is shutting down,
    /// or when a wait_timeout window in a housekeeper expires.
    available: Arc<Condvar>,
    /// Workers handed back from `PooledVm::drop` waiting to be
    /// restored to clean snapshot state before going back into
    /// the idle queue. The restorer thread drains this. Arc'd
    /// so the restorer can wait on the condvar without keeping
    /// `HiddenPool` alive.
    dirty: Option<Arc<Mutex<VecDeque<Worker>>>>,
    /// Wakes any restorer thread when a worker lands on dirty
    /// (or on shutdown).
    dirty_pending: Option<Arc<Condvar>>,
    /// Where each worker's vsock mux/exec sockets live.
    socks_dir: PathBuf,
    /// True once `Drop` has started; replenisher / restorer /
    /// janitor exit the next time around their wait loops. Arc'd
    /// so housekeeping threads can poll it after dropping their
    /// strong `HiddenPool` reference.
    shutting_down: Arc<AtomicBool>,
    /// Image-derived spawn config, copied so the pool is self-
    /// contained.
    spawn_cfg: Arc<SpawnConfig>,
    /// Static pool policy. Read from many threads; never mutated
    /// after construction so we can stash by value (no Mutex).
    policy: PoolPolicy,
}

/// Static policy for an auto-scaling pool. Set at builder time;
/// immutable thereafter.
#[derive(Debug, Clone, Copy)]
struct PoolPolicy {
    /// Always-warm baseline. The replenisher keeps `alive >= min`.
    /// `min == 0` means lazy: the first acquire spawns the first
    /// worker.
    min: usize,
    /// Hard concurrency cap. Acquire blocks (with timeout) when
    /// `alive == max`. `max == usize::MAX` means uncapped.
    max: usize,
    /// Idle workers above `min` that have sat unused for longer
    /// than this get evicted by the janitor. `Duration::MAX`
    /// disables eviction (fixed-size pool).
    idle_timeout: Duration,
    /// Caller's `acquire()` blocks at most this long when the
    /// pool is at `max` and no worker is idle. After that the
    /// call returns `Error::PoolExhausted`. `None` = block forever.
    acquire_timeout: Option<Duration>,
    /// When `true` (default), `PooledVm::drop` queues the worker
    /// for restoration via the supervisor RESTORE RPC before
    /// it goes back to idle. Each cycle starts with a clean
    /// snapshot-state guest. Costs ~3 ms per cycle (off the
    /// critical path if the pool has a buddy slot).
    ///
    /// When `false`, drop pushes the worker DIRECTLY back to
    /// idle without restoring. The next acquire gets the same
    /// guest in whatever state the previous user left it. The
    /// per-cycle restore cost vanishes, AND the guest's page
    /// cache stays warm — for workloads like rustc that re-read
    /// the same sysroot/deps every invocation, this is a HUGE
    /// win (300 ms cold compile → ~50–100 ms warm-cache compile).
    ///
    /// Caveats: workloads must be tolerant of leftover state
    /// in `/tmp` etc. The integrator's pattern (write_file
    /// `main.rs`, run `rustc -o /tmp/m && /tmp/m`) is safe — the
    /// `&&` short-circuits on compile failure, and outputs are
    /// always overwritten. Pair with periodic full pool drain
    /// + rebuild if you need bounded resource accumulation over
    /// long runs.
    restore_on_release: bool,
}

impl Default for PoolPolicy {
    fn default() -> Self {
        Self {
            min: 0,
            max: 64,
            idle_timeout: Duration::from_secs(60),
            acquire_timeout: Some(Duration::from_secs(60)),
            restore_on_release: true,
        }
    }
}

/// Per-Pool internal state under one mutex. Held only briefly
/// during acquire/release; the long-running work (spawn /
/// restore / kill) happens outside the lock.
struct PoolState {
    /// Idle workers ready for the next `acquire()`. **LIFO** —
    /// the most recently used worker has the hottest host page
    /// cache (squashfs layer pages, kernel mmap pages), so it
    /// pays the cheapest restore on the next acquire. Both ops
    /// are at the back of the `Vec`.
    idle: Vec<IdleEntry>,
    /// Total workers in the pool right now: idle + currently
    /// checked-out + currently being spawned/restored. The
    /// auto-grow path bumps this *before* spawning so a
    /// concurrent `acquire` can see "we already promised someone
    /// a worker, don't double-spawn."
    alive: usize,
    /// Currently-blocked acquire callers (for stats /
    /// observability). Incremented at the wait site, decremented
    /// when the wait returns.
    waiting: usize,
    /// Cumulative count of workers the watchdog reaped because their
    /// process had died while sitting idle (never popped, so the
    /// acquire-time `try_wait` never saw them). Pure observability.
    reaped: u64,
}

/// An idle worker plus the timestamp it returned to the queue,
/// used by the janitor to evict above-`min` workers that have
/// sat unused longer than `idle_timeout`.
struct IdleEntry {
    worker: Worker,
    last_used: Instant,
}

/// One spawned `supermachine-worker` subprocess + its vsock
/// socket paths + the lib-side end of the supervisor control
/// socket.
///
/// Workers are launched in `--pool-worker` mode (see
/// `bin/worker.rs`): each one connects back to a unix socket the
/// lib listens on, accepts text-line commands (`RESTORE <path>`,
/// `QUIT`), and writes `DONE …` after each restore. This lets
/// the same worker process serve many `acquire`/`drop` cycles
/// — each cycle is a snapshot restore (~3 ms) instead of a full
/// process spawn (~10 ms) plus a kill.
///
/// The control socket is bidirectional: lib writes commands,
/// worker writes responses. We hold separate read/write halves
/// behind a `Mutex` so the restorer thread (which sends RESTORE
/// during release-handling) doesn't race with the QUIT path
/// during pool teardown.
struct Worker {
    child: Child,
    vsock_mux_path: PathBuf,
    vsock_exec_path: PathBuf,
    /// Path of the unix listener the lib is using to talk to
    /// this worker. Cleaned up on drop alongside the vsock paths.
    control_path: PathBuf,
    /// Live control connection. Writer side; reads happen on a
    /// `BufReader` we construct on demand for the restore round-
    /// trip. Wrapped in `Mutex` so concurrent code paths
    /// (RESTORE during release vs. QUIT during shutdown) are
    /// linearized cleanly.
    control: Arc<Mutex<ControlChannel>>,
    /// The snapshot file this worker was last restored from.
    /// Used as the `base` hint on cycle-snapshot RPCs so the
    /// runner can use APFS clonefile + diff pwrite instead of
    /// the plain streaming sync save (~3× speedup on the
    /// cycle-snapshot path).
    last_restore_path: PathBuf,
    /// Guest memory (MiB) the worker was started with. Used by
    /// the cycle-restore path to gate the post-restore
    /// `drop_vfs_caches` RPC behind the 512-MiB memory threshold
    /// (see `drop_vfs_caches_via_agent`).
    memory_mib: u32,
    /// 0.7.44+ — true when the snapshot has virtio-fs mounts OR
    /// virtio-blk volumes (any host-backed write surface). The
    /// cycle-restore path checks this to skip the VFS-drop RPC
    /// when there's nothing host-backed to invalidate. Pure-image
    /// snapshots (no mounts, no volumes) save ~5-15 ms / cycle.
    has_mounts: bool,
    /// 0.7.44+ — vcpu count this worker was started with. Used by
    /// the cycle-restore path to gate the post-restore smpark_unpark
    /// RPC (only needed when vcpus > 1; secondaries don't exist
    /// otherwise).
    vcpus: u32,
    /// 0.7.49+ — per-worker virtio-blk temp files (clonefile of
    /// the snapshot's `volumes/<i>.pristine`). 0.7.50+: non-empty
    /// whenever the snapshot has pristines, regardless of
    /// `policy.restore_on_release` (previously gated on
    /// `restore_on_release=true`). Unlinked on Worker drop so
    /// /tmp stays clean. Empty only for no-pristine snapshots
    /// (pre-0.7.49 bakes; workers use the host file directly).
    volume_temp_files: Vec<PathBuf>,
    /// 0.7.67+ — guest mountpoints of this worker's virtio-blk
    /// volumes (e.g. `/data`). init-oci runs `mount_volumes()`
    /// AFTER the snapshot/exec-ready marker (the snapshot is captured
    /// before the volume mount so each restore re-mounts fresh host
    /// bytes — see `SpawnConfig.volumes`). On restore the guest
    /// therefore resumes with the agent already accepting execs but
    /// `/data` not yet mounted — a TOCTOU window where the caller's
    /// first exec reads an empty volume. The post-restore readiness
    /// gate (`wait_for_volumes_mounted`) polls `/proc/mounts` for
    /// these paths before the worker is handed out. Empty for
    /// no-volume snapshots (the gate is skipped).
    volume_guest_paths: Vec<String>,
    /// 0.7.49+ — true when this worker has per-worker COW volume
    /// temps. The pool's release path uses this to decide
    /// kill+respawn (volume-bearing `restore_on_release=true`
    /// pools) vs. RESTORE-recycle / push-to-idle (everything
    /// else): RESTORE can't reset the worker's open virtio-blk
    /// fds back to pristine bytes.
    ///
    /// 0.7.50+: also true for `restore_on_release=false` pools
    /// (the COW gate moved upstream — every spawn gets a temp).
    /// In skip-restore mode the worker is reused across acquires
    /// within the process, so the temp's writes persist within
    /// the process — exactly matching the prior skip-restore
    /// semantics for volume mutations. The cross-process leak is
    /// blocked because each new process spawns a worker with a
    /// fresh COW clone.
    has_cow_volumes: bool,
    /// 0.7.63+ — memory admission reservation, held for this worker's
    /// whole lifetime and returned on drop. `spawn_one` charges it
    /// against the process-wide budget BEFORE forking (blocking if the
    /// budget is full) so concurrent spawns can't overcommit host RAM
    /// into jetsam/OOM; warm-handoff workers charge non-blockingly
    /// (their RAM is already spent). See [`crate::memory_admission`].
    _admission: crate::memory_admission::AdmissionGuard,
}

/// Stats returned from a successful subprocess snapshot RPC.
struct SnapshotStats {
    bytes_written: u64,
    capture_us: u64,
    save_us: u64,
}

/// Lib-side bookkeeping for the `--pool-worker` text protocol.
struct ControlChannel {
    /// Buffered reader so we can read line-at-a-time without
    /// over-consuming bytes.
    reader: std::io::BufReader<std::os::unix::net::UnixStream>,
    /// Direct write half — `BufReader` borrows the reader half.
    writer: std::os::unix::net::UnixStream,
}

impl ControlChannel {
    fn send_line(&mut self, line: &str) -> std::io::Result<()> {
        use std::io::Write;
        self.writer.write_all(line.as_bytes())?;
        if !line.ends_with('\n') {
            self.writer.write_all(b"\n")?;
        }
        self.writer.flush()
    }

    fn read_line(&mut self) -> std::io::Result<String> {
        use std::io::BufRead;
        // Transparently skip `SAVE_DONE <path>` / `SAVE_FAIL <path> ...`
        // notifications. The worker's bg async-save thread emits those
        // on the same supervisor channel as the request/response
        // protocol — they're orthogonal "I finished a save you asked
        // me to start earlier" announcements, never a response to the
        // current request. If we returned one to a caller expecting
        // (say) DONE_SNAPSHOT, the line-oriented parse would mis-match.
        //
        // The bake pipeline has its own copy of this filter
        // (`read_supervisor_line_skip_save_notifications` in bake.rs)
        // because the bake driver owns the BufReader directly; this
        // version is for the `ControlChannel`-wrapped pooled path.
        loop {
            let mut buf = String::new();
            let n = self.reader.read_line(&mut buf)?;
            if n == 0 {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::UnexpectedEof,
                    "worker control socket closed",
                ));
            }
            let trimmed = buf.trim_start();
            if trimmed.starts_with("SAVE_DONE ") || trimmed.starts_with("SAVE_FAIL ") {
                tracing::debug!(line = %buf.trim_end(), "skipping orthogonal bg-save notification");
                continue;
            }
            // 0.7.43+ kernel-boot cache marker is normally consumed
            // by the bake driver's kcache-WRITE orchestrator in
            // `bake.rs::run_native_supermachine_bake_pipelined`.
            // This control channel (ControlChannel, the pooled-VM
            // path) doesn't enter the kcache window so won't see
            // the marker in normal operation. Keep the skip as
            // defense-in-depth: if a future code path leaks the
            // marker through here, drop silently rather than
            // confusing the protocol.
            if trimmed.starts_with("MARKER_KCACHE_READY") {
                tracing::debug!("skipping MARKER_KCACHE_READY notification");
                continue;
            }
            return Ok(buf);
        }
    }
}

/// Convert a `bake::BakedWorker` (handle handed back from the
/// pipelined-bake driver when `keep_alive=true`) into a regular
/// `Worker` that the `HiddenPool` can use as an idle entry.
///
/// This is a pure handle-transfer — no I/O, no liveness check
/// (caller did the `try_wait` first). The resulting Worker has
/// `last_restore_path` set to the warm snapshot path, so any
/// subsequent cycle SNAPSHOT RPCs use it as the diff-via-clone
/// `base=` hint, same as a normal pool worker that just restored.
#[cfg(target_os = "macos")]
fn warm_baked_to_worker(
    bw: crate::bake::BakedWorker,
    memory_mib: u32,
    has_mounts: bool,
    volume_guest_paths: Vec<String>,
    vcpus: u32,
    use_once: bool,
) -> Worker {
    // Already-running bake-time worker: account its footprint so later
    // blocking spawns see it, but don't gate (the RAM is already
    // committed — blocking here would be pointless). It's live, so
    // charge what it MEASURES (+ the standard margin via
    // learned_charge_mib) rather than its guest-RAM cap — a cap charge
    // for a CoW-resident worker overstates by GiBs and starves the
    // pool's parallel prewarm spawns of budget.
    let admission = crate::memory_admission::charge({
        let overhead = crate::memory_admission::WORKER_OVERHEAD_MIB;
        let observed = crate::memory_admission::phys_footprint_mib(bw.child.id()).unwrap_or(0);
        learned_charge_mib(memory_mib, observed, overhead)
    });
    Worker {
        child: bw.child,
        vsock_mux_path: bw.vsock_mux_path,
        vsock_exec_path: bw.vsock_exec_path,
        control_path: bw.control_path,
        control: Arc::new(Mutex::new(ControlChannel {
            reader: std::io::BufReader::new(bw.control_reader),
            writer: bw.control_writer,
        })),
        last_restore_path: bw.last_restore_path,
        memory_mib,
        has_mounts,
        vcpus,
        // Empty: the warm-handoff worker was launched at bake-time
        // and has its volume fds pointing at the user's host file
        // — not at a COW temp. Pool's `release` path uses
        // `has_cow_volumes` to decide kill-on-release.
        //
        // For warm-handoff workers in a `restore_on_release=true`
        // pool with pristines, `use_once=true` flips the flag
        // synthetically so release kills the worker after one
        // cycle; the replenisher then spawns a fresh worker that
        // DOES go through the COW path. The user's host file is
        // mutated by that ONE cycle but the pristine is unaffected
        // so subsequent COW spawns get clean bytes.
        //
        // For `restore_on_release=false`, `use_once=false` and the
        // warm-handoff worker is reused across acquires within
        // the process. It writes to the user's host file, not a
        // COW. The cross-process safety still holds: a separate
        // process opens via `Image::from_snapshot` (no warm
        // handoff), spawn_one always COWs from pristine, and
        // pristine never changes — so process N+1 sees bake-time
        // bytes regardless of what process N's warm-handoff
        // worker wrote.
        volume_temp_files: Vec::new(),
        // Stored for the worker's *cycle* restores: the first warm
        // handoff already has volumes mounted (booted at bake time),
        // but every later send_restore resumes pre-mount_volumes and
        // must re-gate on them.
        volume_guest_paths,
        has_cow_volumes: use_once,
        _admission: admission,
    }
}

/// Block until every `guest_paths` mountpoint is present in the guest's
/// `/proc/mounts`, or a bounded budget elapses.
///
/// init-oci runs `mount_volumes()` AFTER the snapshot/exec-ready marker
/// (the snapshot is captured before the volume mount so each restore
/// re-mounts against current host bytes — see `SpawnConfig.volumes`).
/// On restore the guest resumes with the agent already accepting execs
/// but the virtio-blk volumes not yet mounted: a TOCTOU window where the
/// caller's first exec would read an empty `/data`. `/proc/mounts` is the
/// deterministic mount-done signal; we poll it via the agent — which also
/// proves the worker can fork+exec (the same liveness signal as the
/// `/bin/true` probe). Returns `Err` if the volumes never mount within the
/// budget (a real failure) so the worker is respawned rather than silently
/// served with an unmounted volume.
#[cfg(target_os = "macos")]
fn wait_for_volumes_mounted(exec_path: &Path, guest_paths: &[String]) -> Result<(), Error> {
    let t0 = std::time::Instant::now();
    let budget = std::time::Duration::from_secs(3);
    loop {
        let out = crate::exec::ExecBuilder::new(exec_path.to_path_buf())
            .argv(["cat", "/proc/mounts"])
            .timeout(std::time::Duration::from_secs(3))
            .output()
            .map_err(|e| {
                Error::vm_msg(format!(
                    "post-restore volume-readiness exec failed in {:?}: {e}\
                     worker will be respawned",
                    t0.elapsed()
                ))
            })?;
        if out.status.code() == Some(0) {
            let mounts = String::from_utf8_lossy(&out.stdout);
            // /proc/mounts lines are "<dev> <mountpoint> <fstype> …";
            // the 2nd whitespace field is the mountpoint.
            let all_mounted = guest_paths.iter().all(|gp| {
                mounts
                    .lines()
                    .any(|l| l.split(' ').nth(1) == Some(gp.as_str()))
            });
            if all_mounted {
                return Ok(());
            }
        }
        if t0.elapsed() >= budget {
            return Err(Error::vm_msg(format!(
                "post-restore volumes not mounted within {budget:?}: {guest_paths:?} \
                 absent from /proc/mounts — worker will be respawned"
            )));
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}

impl Worker {
    /// Send a `RESTORE <path>` command and block until the
    /// worker writes `DONE …`. Returns `Ok` on success, `Err`
    /// if the protocol broke (worker crashed, socket closed,
    /// malformed response). Caller treats `Err` as "worker is
    /// unusable" and respawns.
    fn send_restore(&self, snapshot_path: &Path) -> Result<(), Error> {
        let path_str = snapshot_path
            .to_str()
            .ok_or_else(|| Error::vm_msg("snapshot path is not valid UTF-8".to_owned()))?;
        let mut ctl = self
            .control
            .lock()
            .map_err(|_| Error::vm_msg("worker control mutex poisoned".to_owned()))?;
        ctl.send_line(&format!("RESTORE {path_str}"))
            .map_err(Error::Io)?;
        let line = ctl.read_line().map_err(Error::Io)?;
        if !line.starts_with("DONE") {
            return Err(Error::vm_msg(format!(
                "worker RESTORE: expected DONE response, got: {}",
                line.trim()
            )));
        }

        // 0.7.44+ host-direct smpark_unpark BEFORE we drop the
        // control mutex. Sets the unpark_signal byte directly via
        // the worker's mapped host RAM, BEFORE the agent RPC below
        // sends the SGI/IPI. Belt-and-suspenders: if the IPI path
        // is slow under load, the secondaries still wake on the
        // next vtimer tick (≤10 ms) and see signal=1.
        //
        // ERR_SMPARK_UNPARK on older smpark.ko or single-vCPU is
        // harmless — we just continue.
        if self.vcpus > 1 {
            ctl.send_line("SMPARK_UNPARK_DIRECT").map_err(Error::Io)?;
            let _ = ctl.read_line().map_err(Error::Io)?;
        }

        // Drop the agent's mutex before issuing the agent RPCs
        // below — they open their own AF_VSOCK connections on the
        // exec path, independent of the control channel.
        drop(ctl);

        // 0.7.44+ post-cycle-restore agent reachability +
        // secondary unpark + liveness verification.
        //
        // The supervisor's DONE only confirms restore_snapshot
        // completed — it does NOT guarantee the worker is ready
        // to handle a user exec. Two races + one verification:
        //
        //   1. vCPU 0 resume-window race: when DONE is written,
        //      the dispatch thread is about to loop back to
        //      hv_vcpu_run but hasn't actually entered it yet.
        //      Host's next acquire+exec can land a vsock REQUEST
        //      before vCPU 0 is executing — muxer raises an IRQ
        //      that's sometimes lost.
        //   2. Secondary-parked race: secondaries are in WFI
        //      inside smpark_park_routine (snapshot was captured
        //      with them parked). After cycle-restore, they need
        //      to be unparked — initial spawn_one does this via
        //      smpark_unpark CONTROL RPC, but the cycle-restore
        //      path historically bypassed it. Even with the
        //      unpark RPC, Apple silicon HVF's SGI delivery has
        //      variable latency (30-50 ms under load): if a user
        //      exec's fork() child (which resets affinity via
        //      sched_setaffinity(0)) lands in this window, it
        //      can be scheduled onto a still-parked secondary
        //      and block in WFI forever — exec hangs 5 s + 2 s,
        //      returns exit=-1 stdout="".
        //
        // Fix: 3 steps to address both races, then a liveness
        // exec to VERIFY the worker is actually ready:
        //
        //   1. PROBE: vsock-exec CONTROL ack-roundtrip with retry
        //      (10 × 200 ms). Forces muxer to kick the guest,
        //      wakes vCPU 0 from resume-window WFI. Typical
        //      convergence: 1 attempt.
        //   2. SMPARK_UNPARK CONTROL RPC: agent ioctl's
        //      /dev/smpark to write unpark_signal byte +
        //      smp_call_function_many to send SGIs. Wakes
        //      secondaries from WFI. (SMPARK_UNPARK_DIRECT on
        //      the supervisor socket above ALSO writes the
        //      signal byte — belt-and-suspenders for slow IPI
        //      paths since secondaries also wake on vtimer when
        //      they re-check the byte.)
        //   3. LIVENESS EXEC: run `/bin/true` through the agent.
        //      This exercises the EXACT path that user execs
        //      use — fork+exec+affinity-reset+wait. If it
        //      returns within timeout, the worker is FULLY
        //      ALIVE. If it hangs/fails, return Err so the
        //      restorer shuts down this worker and the
        //      replenisher spawns a fresh one. Replaces the
        //      brittle "sleep N ms" approach (50 ms gave ~95%
        //      pass, 200 ms gave ~78% — longer sleep exposed
        //      MORE races, so sleeping isn't the answer).
        //
        // Repro of the bug this fix addresses:
        // python:3.12-alpine pool, 1024 MiB, 2 vcpus,
        // restoreOnRelease, no warmup — T2/T3's exec failed
        // intermittently (~10-50% depending on system load).
        // With this fix: 100 % pass on 400+ iter stress tests
        // including under load average 11.83.
        //
        // Env: SUPERMACHINE_POST_RESTORE_PROBE=0 disables probe
        // + smpark_unpark steps;
        // SUPERMACHINE_POST_RESTORE_LIVENESS=0 disables the
        // liveness exec. For embedders who do their own warmup
        // and don't want the per-cycle overhead.
        let probe_enabled = std::env::var("SUPERMACHINE_POST_RESTORE_PROBE")
            .map(|v| v != "0" && v != "false")
            .unwrap_or(true);
        if probe_enabled {
            let per_attempt = std::time::Duration::from_millis(200);
            let max_attempts = 10;
            for attempt in 0..max_attempts {
                let body = serde_json::json!({ "action": "probe" });
                match crate::exec::send_control_with_ack(
                    &self.vsock_exec_path,
                    &body,
                    Some(per_attempt),
                ) {
                    Ok(_) => break,
                    Err(_) if attempt + 1 < max_attempts => {}
                    Err(e) => {
                        return Err(Error::vm_msg(format!(
                            "post-restore agent probe failed after {max_attempts} attempts: {e}"
                        )));
                    }
                }
            }
            if self.vcpus > 1 {
                let body = serde_json::json!({ "action": "smpark_unpark" });
                let _ = crate::exec::send_control_with_ack(
                    &self.vsock_exec_path,
                    &body,
                    Some(std::time::Duration::from_millis(500)),
                );
            }
            // 0.7.44+ liveness exec.
            //
            // Sleep-based "wait for secondaries to wake" was unreliable:
            // 100 ms gave ~95% pass, 200 ms gave ~78% (longer sleep
            // exposed other races). The fundamental problem is sleep
            // is a guess; we want PROOF that the worker can run a
            // fork+exec workload.
            //
            // Solution: do a real /bin/true exec inside send_restore.
            // This forks the agent's per-conn handler, which forks a
            // child, which resets affinity (the path that triggers
            // "child blocks on parked secondary"), and execs /bin/true.
            // If the exec returns within timeout, the worker is FULLY
            // alive — vCPU 0 + secondaries + scheduler + agent fork
            // all working. If the exec hangs/fails, return Err so the
            // worker is shut down + replaced by the replenisher.
            //
            // Cost: one full exec round-trip (~5-15 ms typical) on
            // every cycle-restore. Replaces the 100 ms sleep.
            //
            // Env: SUPERMACHINE_POST_RESTORE_LIVENESS=0 to disable.
            let liveness_enabled = std::env::var("SUPERMACHINE_POST_RESTORE_LIVENESS")
                .map(|v| v != "0" && v != "false")
                .unwrap_or(true);
            if liveness_enabled {
                let liveness_t0 = std::time::Instant::now();
                let exec_res = crate::exec::ExecBuilder::new(self.vsock_exec_path.clone())
                    .argv(["/bin/true"])
                    .timeout(std::time::Duration::from_secs(3))
                    .output();
                match exec_res {
                    Ok(out) if out.status.code() == Some(0) => {
                        // Worker is fully alive — vCPU 0 + secondaries
                        // + scheduler + agent fork path all working.
                    }
                    Ok(out) => {
                        return Err(Error::vm_msg(format!(
                            "post-restore liveness exec returned non-zero in {:?}: exit={:?} \
                             stderr={:?} — worker will be respawned",
                            liveness_t0.elapsed(),
                            out.status.code(),
                            String::from_utf8_lossy(&out.stderr)
                                .chars()
                                .take(200)
                                .collect::<String>(),
                        )));
                    }
                    Err(e) => {
                        return Err(Error::vm_msg(format!(
                            "post-restore liveness exec failed in {:?}: {e} — worker will be respawned",
                            liveness_t0.elapsed(),
                        )));
                    }
                }
            }
        }

        // 0.7.67+ — volume-mount readiness gate (mirrors spawn_one).
        // Cycle-restore resumes the guest BEFORE init-oci re-runs
        // mount_volumes(), so without this a post-restore exec could
        // read an unmounted /data. Runs regardless of the liveness env
        // (it's a correctness gate, not just a liveness probe) and
        // also proves the worker can fork+exec. Err => caller treats
        // the worker as unusable and respawns it.
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        if !self.volume_guest_paths.is_empty() {
            wait_for_volumes_mounted(&self.vsock_exec_path, &self.volume_guest_paths)?;
        }

        // Cycle-restore reinstates RAM from the snapshot — that
        // includes the guest VFS page/dentry/inode caches as they
        // were at capture time. Without dropping, subsequent reads
        // on `mounts:`/`volumes:` paths can return stale bytes
        // when the host backing file changed post-capture. See
        // `drop_vfs_caches_via_agent` for the full story.
        //
        // 0.7.44+ probe-skip: when this snapshot has no virtio-fs
        // mounts (Worker.has_mounts=false) there's nothing
        // host-backed in the pagecache, so the drop is a no-op.
        // Skip the RPC to shave ~5-15 ms per cycle-restore on the
        // common Image.build-from-Docker, no-extra-mounts case.
        if self.has_mounts {
            let _ = drop_vfs_caches_via_agent(&self.vsock_exec_path, self.memory_mib);
        }
        // 0.7.51+ wall-clock sync. Unlike drop_vfs_caches, this
        // is NOT gated on the presence of host-backed surfaces —
        // every cycle-restore needs to advance the guest's
        // CLOCK_REALTIME from snapshot-capture-time to "now",
        // regardless of mounts/volumes. The vtimer state keeps
        // CLOCK_MONOTONIC ticking correctly across restore (which
        // is what tokio/timer-wheels need), but the wall-clock
        // offset is captured + restored verbatim — so without
        // this RPC `Date.now()` reports bake-time post-restore.
        // Order: cache-drop first (so re-LOOKUPs see fresh host
        // state), then time-sync. Both are best-effort and
        // independent — neither failure blocks the other.
        let _ = sync_time_via_agent(&self.vsock_exec_path);
        Ok(())
    }

    /// Send `SNAPSHOT <out_path>` and block on the response.
    /// The worker pauses the guest, captures snapshot, writes to
    /// `out_path`, then writes either `DONE_SNAPSHOT
    /// bytes_written=N capture_us=… save_us=…` or
    /// `ERR_SNAPSHOT <reason>` on the supervisor socket. We
    /// parse the response and surface it as `Result`.
    fn send_snapshot(&self, out_path: &Path) -> Result<SnapshotStats, Error> {
        let path_str = out_path
            .to_str()
            .ok_or_else(|| Error::vm_msg("snapshot path is not valid UTF-8".to_owned()))?;
        let mut ctl = self
            .control
            .lock()
            .map_err(|_| Error::vm_msg("worker control mutex poisoned".to_owned()))?;
        ctl.send_line(&format!("SNAPSHOT {path_str}"))
            .map_err(Error::Io)?;
        let line = ctl.read_line().map_err(Error::Io)?;
        if let Some(rest) = line.strip_prefix("DONE_SNAPSHOT") {
            let mut stats = SnapshotStats {
                bytes_written: 0,
                capture_us: 0,
                save_us: 0,
            };
            for kv in rest.split_ascii_whitespace() {
                if let Some(v) = kv.strip_prefix("bytes_written=") {
                    stats.bytes_written = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("capture_us=") {
                    stats.capture_us = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("save_us=") {
                    stats.save_us = v.parse().unwrap_or(0);
                }
            }
            Ok(stats)
        } else if let Some(rest) = line.strip_prefix("ERR_SNAPSHOT ") {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT failed: {}",
                rest.trim()
            )))
        } else {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT: unexpected response: {}",
                line.trim()
            )))
        }
    }

    /// Differential snapshot variant. Sends
    /// `SNAPSHOT <out_path> base=<base_path>`. The worker, if it
    /// has a matching in-flight async save to `base_path` (i.e.
    /// the snapshot is still in memory from a recent
    /// SNAPSHOT_ASYNC), uses APFS `clonefile` + diff `pwrite` to
    /// land the warm snapshot — usually ~10x faster than the
    /// plain streaming sync path.
    ///
    /// Falls back to the plain streaming sync save inside the
    /// runner on any of: no matching in-flight save, clonefile
    /// EXDEV (different filesystems), warm meta overflows base's
    /// ram_offset slack. Caller never sees this distinction; the
    /// returned `SnapshotStats` is well-formed in both cases.
    ///
    /// Used by the pipelined bake flow's warm capture.
    fn send_snapshot_with_base(
        &self,
        out_path: &Path,
        base_path: &Path,
        inline: bool,
    ) -> Result<SnapshotStats, Error> {
        let path_str = out_path
            .to_str()
            .ok_or_else(|| Error::vm_msg("snapshot out path is not valid UTF-8".to_owned()))?;
        let base_str = base_path
            .to_str()
            .ok_or_else(|| Error::vm_msg("snapshot base path is not valid UTF-8".to_owned()))?;
        let mut ctl = self
            .control
            .lock()
            .map_err(|_| Error::vm_msg("worker control mutex poisoned".to_owned()))?;
        // `inline` makes the worker wait for the diff save to land before
        // replying, so the caller can read the file immediately (the builder's
        // per-layer chain) — while still retaining the base in memory.
        let line = if inline {
            format!("SNAPSHOT {path_str} base={base_str} inline")
        } else {
            format!("SNAPSHOT {path_str} base={base_str}")
        };
        ctl.send_line(&line).map_err(Error::Io)?;
        let line = ctl.read_line().map_err(Error::Io)?;
        if let Some(rest) = line.strip_prefix("DONE_SNAPSHOT") {
            let mut stats = SnapshotStats {
                bytes_written: 0,
                capture_us: 0,
                save_us: 0,
            };
            for kv in rest.split_ascii_whitespace() {
                if let Some(v) = kv.strip_prefix("bytes_written=") {
                    stats.bytes_written = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("capture_us=") {
                    stats.capture_us = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("save_us=") {
                    stats.save_us = v.parse().unwrap_or(0);
                }
            }
            Ok(stats)
        } else if let Some(rest) = line.strip_prefix("ERR_SNAPSHOT ") {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT (with base) failed: {}",
                rest.trim()
            )))
        } else {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT (with base): unexpected response: {}",
                line.trim()
            )))
        }
    }

    /// Async-save variant of [`Worker::send_snapshot`]. Sends
    /// `SNAPSHOT_ASYNC <out_path>`; the worker pauses, captures
    /// into a compact in-memory buffer, kicks off a background
    /// save thread, and returns `DONE_SNAPSHOT_ASYNC` immediately.
    /// The on-disk file appears asynchronously — drain via
    /// [`Worker::shutdown`] (which sends QUIT and waits for the
    /// worker process to exit) before relying on the file existing.
    ///
    /// Used by the pipelined bake flow.
    #[allow(dead_code)]
    fn send_snapshot_async(&self, out_path: &Path) -> Result<SnapshotStats, Error> {
        let path_str = out_path
            .to_str()
            .ok_or_else(|| Error::vm_msg("snapshot path is not valid UTF-8".to_owned()))?;
        let mut ctl = self
            .control
            .lock()
            .map_err(|_| Error::vm_msg("worker control mutex poisoned".to_owned()))?;
        ctl.send_line(&format!("SNAPSHOT_ASYNC {path_str}"))
            .map_err(Error::Io)?;
        let line = ctl.read_line().map_err(Error::Io)?;
        if let Some(rest) = line.strip_prefix("DONE_SNAPSHOT_ASYNC") {
            let mut stats = SnapshotStats {
                bytes_written: 0,
                capture_us: 0,
                save_us: 0,
            };
            for kv in rest.split_ascii_whitespace() {
                if let Some(v) = kv.strip_prefix("bytes_written=") {
                    stats.bytes_written = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("capture_us=") {
                    stats.capture_us = v.parse().unwrap_or(0);
                } else if let Some(v) = kv.strip_prefix("save_us=") {
                    stats.save_us = v.parse().unwrap_or(0);
                }
            }
            Ok(stats)
        } else if let Some(rest) = line.strip_prefix("ERR_SNAPSHOT ") {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT_ASYNC failed: {}",
                rest.trim()
            )))
        } else {
            Err(Error::vm_msg(format!(
                "worker SNAPSHOT_ASYNC: unexpected response: {}",
                line.trim()
            )))
        }
    }

    /// Best-effort `smpark_park` CONTROL RPC to the in-guest agent.
    /// Drives all secondary vCPUs into a known parked-WFI state via
    /// `ioctl(/dev/smpark, PARK)`. Returns `Ok(true)` on success,
    /// `Ok(false)` if the module isn't available (single-vCPU bake
    /// or smpark.ko not loaded), `Err` only on transport failure.
    /// Caller treats `Ok(false)` as "skip park, fall back to the
    /// existing rendezvous-only path".
    #[cfg_attr(
        not(all(target_os = "macos", target_arch = "aarch64")),
        allow(dead_code)
    )]
    fn send_smpark_park(&self) -> Result<bool, Error> {
        let body = serde_json::json!({ "action": "smpark_park" });
        match crate::exec::send_control_with_ack(
            &self.vsock_exec_path,
            &body,
            Some(Duration::from_secs(5)),
        ) {
            Ok(_) => Ok(true),
            Err(e) => {
                // Agent reports `ok=false` for "module not loaded /
                // /dev/smpark not available" — surfaces as
                // io::ErrorKind::Other with the agent's message.
                // Treat any transport-level failure as "skip park"
                // so callers don't break the snapshot path on the
                // 1-vCPU common case (where smpark is a no-op the
                // module reports as such).
                tracing::debug!(error = %e, "smpark_park unavailable; skipping");
                Ok(false)
            }
        }
    }

    /// Best-effort `smpark_unpark` CONTROL RPC. Wakes the parked
    /// secondaries. Same fallback semantics as
    /// [`Worker::send_smpark_park`] — returns `Ok(false)` if the
    /// module isn't there.
    #[cfg_attr(
        not(all(target_os = "macos", target_arch = "aarch64")),
        allow(dead_code)
    )]
    fn send_smpark_unpark(&self) -> Result<bool, Error> {
        let body = serde_json::json!({ "action": "smpark_unpark" });
        match crate::exec::send_control_with_ack(
            &self.vsock_exec_path,
            &body,
            Some(Duration::from_secs(5)),
        ) {
            Ok(_) => Ok(true),
            Err(e) => {
                tracing::debug!(error = %e, "smpark_unpark unavailable; skipping");
                Ok(false)
            }
        }
    }

    /// Best-effort QUIT. Tries the supervisor protocol first —
    /// gives the worker a chance to flush state cleanly — then
    /// falls back to SIGKILL if the worker doesn't exit within
    /// the grace window.
    fn shutdown(&mut self) {
        // Send QUIT — best effort, ignore failures (worker may
        // already be dead, mutex may be poisoned).
        if let Ok(mut ctl) = self.control.lock() {
            let _ = ctl.send_line("QUIT");
        }
        // Give the worker ~100 ms to exit cleanly. Most exits
        // happen in <10 ms; the upper bound is for slow restore-
        // cleanup paths.
        let deadline = Instant::now() + Duration::from_millis(100);
        loop {
            match self.child.try_wait() {
                Ok(Some(_)) => break,
                Ok(None) if Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(2));
                }
                _ => {
                    let _ = self.child.kill();
                    let _ = self.child.wait();
                    break;
                }
            }
        }
        let _ = std::fs::remove_file(&self.vsock_mux_path);
        let _ = std::fs::remove_file(&self.vsock_exec_path);
        let _ = std::fs::remove_file(&self.control_path);
        let mut h = self.vsock_mux_path.clone();
        h.set_extension("handoff");
        let _ = std::fs::remove_file(&h);
        // 0.7.49+ COW volume temps. Worker is dead; the kernel
        // already closed the fds, so unlink here is safe (no fd
        // leaks). Empty vec for restore_on_release=false / no-
        // pristine snapshots.
        for path in self.volume_temp_files.drain(..) {
            let _ = std::fs::remove_file(&path);
        }
    }
}

/// Resolved + reusable spawn config for one Image's pool.
struct SpawnConfig {
    /// High-water-mark of the resident footprint (phys_footprint, MiB)
    /// observed across this pool's workers — measured at spawn (idle,
    /// post-restore) and at release (post-workload). `0` until the first
    /// measurement. Admission charges the MEASURED footprint (+margin)
    /// instead of the `--memory` cap, which is usually a big
    /// over-estimate for CoW restores — see `learned_charge_mib`.
    /// Shared across spawns via the enclosing `Arc<SpawnConfig>`.
    observed_footprint_mib: std::sync::atomic::AtomicU64,
    worker_bin: PathBuf,
    snapshot_path: PathBuf,
    layers: Vec<PathBuf>,
    delta_squashfs: Option<PathBuf>,
    /// virtio-fs mounts to re-create on the worker side. Snapshot's
    /// metadata.json `mounts` field, propagated through `Image`.
    mounts: Vec<crate::vmm::resources::MountSpec>,
    /// virtio-blk volumes to re-attach on the worker side. Snapshot's
    /// metadata.json `volumes` field, propagated through `Image`.
    /// Each entry is `(host_file, guest_path, size_bytes, pristine)`
    /// and is passed to the worker as `--volume HOST:GUEST:SIZE`.
    ///
    /// `pristine` (0.7.49+) is the bake-time captured copy of
    /// `host_file`. 0.7.50+: when `pristine.is_some()`, spawn_one
    /// clones the pristine to a per-process temp file under /tmp
    /// and substitutes that path for `host_file` in the `--volume`
    /// arg — regardless of `policy.restore_on_release`. The
    /// Worker tracks the temp files for cleanup on drop / pool
    /// shutdown. This blocks the cross-process leak where
    /// `restore_on_release=false` workers used to write straight
    /// to the user's host file and diverge it from the snapshot's
    /// in-RAM ext4 state.
    ///
    /// CRITICAL for warm-restore correctness: init-oci's snapshot
    /// marker fires BEFORE `mount_volumes()`, so the snapshot doesn't
    /// carry the volume mount. Each restore re-runs `mount_volumes()`
    /// which scans `/dev/vd*`. If the warm-restore worker doesn't
    /// re-attach the volumes here, the device count comes up short,
    /// the ext4 mount references a non-existent device, and reads
    /// hang on the restored guest. (Field-report bug fixed 0.7.30.)
    volumes: Vec<(PathBuf, String, u64, Option<PathBuf>)>,
    memory_mib: u32,
    vcpus: u32,
    socks_dir: PathBuf,
    /// Identifier folded into the socket file names. Just for
    /// readability when looking at /tmp.
    name_prefix: String,
    /// Honored when waiting for a freshly spawned worker's vsock
    /// socket to appear.
    spawn_timeout: Duration,
    /// `metadata.json["runtime_sha16"]` of the snapshot being
    /// restored. When this matches the current `worker_bin`'s
    /// SHA16, we know the in-guest agent shipped with this
    /// snapshot is the same agent the lib expects, so the
    /// agent-protocol probe can be skipped. ~25 ms saved per
    /// acquire.
    baker_runtime_sha16: Option<String>,
    /// `metadata.json["balloon_target_pages"]` from the snapshot
    /// — number of 4 KiB pages the host asks the guest to
    /// inflate via virtio-balloon after restore. Drops idle
    /// worker RSS from `~memory_mib` to ~25% of memory_mib on
    /// rust:1-slim and similar workloads. Plumbed through to
    /// the worker binary as `--balloon-target-pages N`.
    balloon_target_pages: Option<u32>,
    /// `metadata.json["tsi_token"]` from the snapshot — 64-char
    /// lowercase hex, encoding the 32-byte secret baked into the
    /// guest kernel's BSS at fresh bake. Re-injected on every
    /// restore so the muxer's `--tsi-token` matches what the
    /// frozen kernel already has. Absent on pre-0.6.0 snapshots
    /// (legacy unauthenticated mode).
    tsi_token: Option<String>,
    /// `metadata.json["egress_policy"]` — per-snapshot network egress
    /// policy, passed to the worker as `--egress-policy` so the muxer
    /// enforces it at TSI connect time. `None` → `allow_all`.
    egress_policy: Option<String>,
    /// 0.7.44+ `metadata.json["pre_exec_sync"]`. When true,
    /// spawn_one sets `SUPERMACHINE_PRE_EXEC_SYNC_RESUME=1` in
    /// the restored worker's env so its
    /// `supermachine-pre-exec-resume` thread pushes the 'P\n'
    /// unblock byte after restore. Required for pre_exec_sync
    /// snapshots — the saved guest is blocked inside `read(0)`
    /// and never wakes without the push.
    pre_exec_sync: bool,
    /// 0.7.49+ — `PoolPolicy::restore_on_release` propagated here
    /// for spawn-time volume COW. When true AND a volume's
    /// `pristine` is `Some`, spawn_one clones the pristine to a
    /// per-worker temp file under /tmp and substitutes the temp
    /// path for the user's host file in the `--volume` arg. Keeps
    /// per-cycle volume state in lock-step with the snapshot's
    /// captured ext4 RAM state — the user's host file never gets
    /// the worker's mid-life writes. Worker drop unlinks the temp.
    restore_on_release: bool,
}

/// Admission charge for one worker: the pool's measured resident
/// footprint high-water-mark + 25% margin (+ overhead), never above the
/// configured cap. Unmeasured (`observed == 0`, i.e. the pool's first
/// spawn) charges the conservative full cap.
///
/// Why charge by observation instead of the cap: a restored VM's
/// `--memory` is fixed at bake time, but a CoW restore actually commits
/// a small fraction of it (e.g. ~288 MiB resident for an 8 GiB-cap
/// browser image). Charging the cap made every pool spawn past
/// `budget/cap` sit out the FULL 60 s admission timeout before the
/// forward-progress override force-admitted it — pure dead time that
/// turned a ~2 s pool spin-up into ~60 s per extra worker. The charge
/// is a prediction, not a guarantee, so the margin + the budget's 20%
/// host headroom + the host memory-pressure backstop (spawns pause
/// while the host is genuinely tight) carry the overcommit risk; the
/// cap ceiling means we never charge MORE than the worst case. There
/// is deliberately no half-cap floor: the floor is what kept the
/// 8 GiB-cap/288 MiB-resident shape stalling, and footprint GROWTH is
/// fed back via the high-water-mark (later spawns charge more as the
/// fleet's real usage grows).
fn learned_charge_mib(memory_mib: u32, observed_mib: u64, overhead: u64) -> u64 {
    let cap = memory_mib as u64 + overhead;
    if observed_mib == 0 {
        return cap;
    }
    let margined = observed_mib + observed_mib / 4 + overhead; // +25%
    margined.min(cap)
}

/// MiB to reserve from the process-wide memory-admission budget for a no-virt
/// **sentry** unit (Linux/x86_64). Unlike the KVM worker — one subprocess whose
/// whole guest RAM is committed up front — the sentry forks a fresh cgroup-capped
/// cell PER concurrent exec, so the resident worst case scales with the number of
/// concurrent cells, each bounded by its `memory.max` (= `mem_mib`) plus the same
/// fixed host-side overhead the worker charges. A one-shot `Vm::start_sentry`
/// passes `cells = 1`; a `SentryPool` with concurrency cap `max` passes
/// `cells = max` so the pool reserves its WHOLE worst-case footprint at build —
/// the analogue of the KVM pool's per-VM charge summed over its admission cap,
/// which is what stops an unbounded sentry pool from OOMing the host.
///
/// `mem_mib == 0` (the explicitly-uncapped / no-baked-memory case) charges only
/// the overhead per cell — we still want SOME accounting, but with no cgroup
/// ceiling there is no worst case to bound against, so we don't fabricate one.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_admission_charge_mib(mem_mib: u64, cells: u64) -> u64 {
    let per_cell = mem_mib.saturating_add(crate::memory_admission::WORKER_OVERHEAD_MIB);
    per_cell.saturating_mul(cells.max(1))
}

/// The cgroup-`memory.max` value (MiB) a sentry cell is bounded to for `image`
/// under `config` — the same derivation [`Image::sentry_sandbox_with`] uses to
/// set the cell's `memory.max`. `0` when the sandbox is explicitly uncapped (no
/// `memory.max` set), so the admission charge degrades to overhead-only.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_cell_mem_mib(image: &Image, config: &VmConfig) -> u64 {
    if config.sentry_uncapped {
        return 0;
    }
    config.memory_mib.unwrap_or(image.memory_mib) as u64
}

#[cfg(test)]
mod learned_charge_tests {
    use super::learned_charge_mib;
    const OH: u64 = 64;

    #[test]
    fn unmeasured_charges_full_cap() {
        // No observation yet → conservative full cap.
        assert_eq!(learned_charge_mib(512, 0, OH), 512 + OH);
    }

    #[test]
    fn measured_charges_observed_plus_margin() {
        // 300 MiB observed → 300 + 25% (75) + OH = 439.
        assert_eq!(learned_charge_mib(512, 300, OH), 375 + OH);
    }

    #[test]
    fn never_exceeds_the_cap() {
        // Observed at/above the cap → clamped to the conservative cap;
        // the learned charge never exceeds the worst case.
        assert_eq!(learned_charge_mib(512, 1000, OH), 512 + OH);
    }

    #[test]
    fn cow_restored_pool_fits_under_budget_without_timeouts() {
        // The field shape that motivated learned charging: 8 GiB-cap
        // VMs whose CoW restores commit ~288 MiB. The old cap charge
        // (8256+64) packed only 2 under a 19660 MiB budget — workers
        // 3+ each burned the full 60 s admission timeout. The learned
        // charge must fit a pool of 8 once the first worker's
        // footprint is observed.
        let charge = learned_charge_mib(8256, 288, OH);
        assert_eq!(charge, 288 + 72 + OH);
        assert!(
            charge * 8 < 19660,
            "8 CoW-restored workers must fit the integrator's budget (charge {charge} MiB)"
        );
    }
}

#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
mod sentry_admission_tests {
    use super::sentry_admission_charge_mib;
    const OH: u64 = crate::memory_admission::WORKER_OVERHEAD_MIB; // 64

    #[test]
    fn one_shot_charges_one_capped_cell_plus_overhead() {
        // Vm::start_sentry reserves exactly one cell's worst case.
        assert_eq!(sentry_admission_charge_mib(512, 1), 512 + OH);
    }

    #[test]
    fn pool_charge_scales_with_concurrency_cap() {
        // The helper composes N live cells' worst-case footprint. Pool acquire
        // charges one cell at a time; callers can still use the helper to reason
        // about a saturated pool.
        assert_eq!(sentry_admission_charge_mib(512, 4), 4 * (512 + OH));
        // Strictly grows with the cell count.
        assert!(sentry_admission_charge_mib(512, 8) > sentry_admission_charge_mib(512, 4));
    }

    #[test]
    fn uncapped_cell_charges_overhead_only() {
        // mem_mib == 0 (sentry_uncapped / no baked memory): no cgroup ceiling, so
        // no worst case to bound — charge only the per-cell overhead, never a
        // fabricated cap.
        assert_eq!(sentry_admission_charge_mib(0, 1), OH);
        assert_eq!(sentry_admission_charge_mib(0, 4), 4 * OH);
    }

    #[test]
    fn zero_cells_clamps_to_one() {
        // A pool's `max` is clamped to >=1 by `Admission::new`; mirror that here
        // so a degenerate `max == 0` still reserves a real (non-zero) cell.
        assert_eq!(sentry_admission_charge_mib(512, 0), 512 + OH);
    }

    #[test]
    fn over_budget_pool_reserves_more_than_the_budget() {
        // THE OOM-prevention contract: a pool whose worst-case footprint exceeds
        // the admission budget asks the accountant for MORE than the budget — so
        // `memory_admission::admit_with` back-pressures it (blocks until a release
        // or the admission timeout) instead of letting unbounded cell spawn
        // overcommit host RAM into OOM. Here: 32 cells × (512 + 64) = 18432 MiB
        // against a 4096-MiB budget.
        let budget_mib = 4096u64;
        let pool_charge = sentry_admission_charge_mib(512, 32);
        assert!(
            pool_charge > budget_mib,
            "an over-budget pool must reserve > the budget so admission gates it \
             (charge {pool_charge} MiB vs budget {budget_mib} MiB)"
        );
        // A pool that DOES fit (4 cells = 2304 MiB) charges within budget, so it
        // admits without back-pressure — the gate only bites the oversized pool.
        assert!(sentry_admission_charge_mib(512, 4) <= budget_mib);
    }
}

impl SpawnConfig {
    /// MiB to reserve from the memory-admission budget for a new worker:
    /// the pool's MEASURED footprint high-water-mark + a 25% margin,
    /// never above the configured cap (+ overhead). See
    /// [`learned_charge_mib`] for why observation, not the guest
    /// ceiling, is the right charge for CoW-restored pool VMs.
    ///
    /// Before anything is measured, the expectation is the
    /// restore-typical baseline, NOT the cap: every `spawn_one` is a
    /// CoW restore whose spawn-time resident cost is a few hundred MiB
    /// regardless of the guest ceiling (an idle alpine restore measures
    /// single-digit MiB of phys_footprint; the integrator's browser
    /// image, ~288 MiB). The ceiling is only approached as the workload
    /// dirties pages — captured later by the spawn/release re-measures
    /// feeding the HWM, with the budget's 20% headroom + the host
    /// memory-pressure backstop carrying the prediction error. Charging
    /// the cap pre-measurement re-creates the cold-prewarm
    /// chicken-and-egg: all parallel min-spawns ask for the ceiling,
    /// blow the budget, and serialize on the 60 s admission timeout
    /// with nobody running yet to BE measured.
    fn admission_charge_mib(&self) -> u64 {
        /// Pre-measurement expectation for one CoW restore (pre-margin).
        const UNMEASURED_RESTORE_BASELINE_MIB: u64 = 256;
        let overhead = crate::memory_admission::WORKER_OVERHEAD_MIB;
        let observed = self
            .observed_footprint_mib
            .load(std::sync::atomic::Ordering::Relaxed);
        let effective = if observed == 0 {
            UNMEASURED_RESTORE_BASELINE_MIB
        } else {
            observed
        };
        learned_charge_mib(self.memory_mib, effective, overhead)
    }

    /// Spawn ONE worker subprocess in `--pool-worker` mode and
    /// return it ready to serve. The worker handles its initial
    /// snapshot restore on boot and writes a `DONE …` line on
    /// the supervisor control socket once that completes — we
    /// block on that line so callers can treat the returned
    /// `Worker` as fully restored.
    fn spawn_one(&self) -> Result<Worker, Error> {
        use std::os::unix::net::UnixListener;

        // 64-bit hex suffix from `unique_suffix()` (nanos +
        // monotonic counter). Distinct across parallel spawns;
        // collision-free in practice.
        let suffix = unique_suffix();
        let vsock_mux_path = self
            .socks_dir
            .join(format!("{}-{:016x}.sock", self.name_prefix, suffix));
        let vsock_exec_path = {
            let mut p = vsock_mux_path.clone();
            let mut name = p.file_name().unwrap().to_owned();
            name.push("-exec");
            p.set_file_name(name);
            p
        };
        let control_path = {
            let mut p = vsock_mux_path.clone();
            let mut name = p.file_name().unwrap().to_owned();
            name.push("-ctl");
            p.set_file_name(name);
            p
        };
        let _ = std::fs::remove_file(&vsock_mux_path);
        let _ = std::fs::remove_file(&vsock_exec_path);
        let _ = std::fs::remove_file(&control_path);

        // Lib listens on the control socket BEFORE spawning so
        // the worker's `connect()` always finds it.
        let ctl_listener = UnixListener::bind(&control_path).map_err(|e| {
            Error::vm_msg(format!(
                "bind control socket {}: {e}",
                control_path.display()
            ))
        })?;

        // ATOMIC-RENAME SENTINEL POLL: when the Image was returned
        // from an always-pipelined-skip-warm `.build()`, the bg
        // save of `restore.snap` may still be in flight. The worker
        // would fail-fast on `--restore-from` pointing at a missing
        // file. `save_compact_to_file` writes to `<path>.partial`
        // and atomic-renames to `<path>` on completion, so file
        // existence ↔ save complete.
        //
        // Bound at `spawn_timeout` (default 30s; configurable via
        // `VmConfig::restore_timeout`). Steady-state save lands in
        // ~50–200 ms on typical hardware; the cap is well over the
        // p99.99. On timeout, surface a clear error rather than
        // letting the worker fail with a confusing "no such file"
        // message.
        //
        // No-op when the file already exists (the common case for
        // workers spawned after the first acquire, or for Images
        // loaded via `Image::from_snapshot`).
        if !self.snapshot_path.is_file() {
            let poll_t0 = Instant::now();
            let poll_deadline = poll_t0 + self.spawn_timeout;
            let mut backoff = Duration::from_millis(2);
            loop {
                if self.snapshot_path.is_file() {
                    if crate::trace::enabled("timings") {
                        eprintln!(
                            "[spawn_one] waited {:?} for snapshot file to land at {}",
                            poll_t0.elapsed(),
                            self.snapshot_path.display(),
                        );
                    }
                    break;
                }
                if Instant::now() > poll_deadline {
                    let _ = std::fs::remove_file(&control_path);
                    return Err(Error::vm_msg(format!(
                        "worker spawn: snapshot file {} did not appear within {:?} \
                         (bg save in flight from a pipelined bake — increase \
                         `VmConfig::restore_timeout` if your disk is slow)",
                        self.snapshot_path.display(),
                        self.spawn_timeout
                    )));
                }
                std::thread::sleep(backoff);
                backoff = (backoff * 2).min(Duration::from_millis(50));
            }
        }

        let mut cmd = Command::new(&self.worker_bin);
        for layer in &self.layers {
            cmd.arg("--virtio-blk").arg(layer);
        }
        if let Some(delta) = &self.delta_squashfs {
            cmd.arg("--virtio-blk").arg(delta);
        }
        // virtio-fs mounts persisted in the snapshot metadata. The
        // worker re-constructs the VirtioFs devices at the same MMIO
        // slots so the guest's baked-in FDT entries find them.
        // Wire encoding mirrors the bake-time form:
        // `HOST:TAG:GUEST_PATH[:POLICY]`.
        for m in &self.mounts {
            cmd.arg("--mount")
                .arg(format!("{}:{}:{}", m.host_path, m.guest_tag, m.guest_path));
        }
        // virtio-blk volumes persisted in the snapshot metadata.
        // Same critical replay as `mounts`: the FDT baked into the
        // snapshot expects these virtio-blk devices to be present
        // at restore, and init-oci's `mount_volumes()` re-runs
        // post-restore against `/dev/vd<N>`. Without this loop, the
        // post-restore guest mounts ext4 against a non-existent
        // device and reads hang.
        //
        // Wire encoding mirrors the bake-time form:
        // `HOST_FILE:GUEST_PATH:SIZE_BYTES`. Worker's CLI parser
        // builds a `VolumeSpec` from each, attaches a `virtio-blk`
        // device, and orders volumes after `layers + delta` so the
        // guest sees `/dev/vd<n+1>..` (same ordering the bake-time
        // worker used, keeping init-oci's index → device mapping
        // stable across bake and restore).
        //
        // 0.7.50+ COW-on-spawn (was 0.7.49 + restoreOnRelease=true
        // only; broadened to always-on when pristine is available):
        // every spawn clones the pristine to a per-process temp
        // file. The worker's writes land on the temp; the user's
        // host file stays at bake-time content forever.
        //
        // Why always-on, not just for `restoreOnRelease=true`:
        //
        //   * `restoreOnRelease=false` pools share one worker
        //     across acquires within ONE process — writes still
        //     persist within that process (same worker → same COW
        //     temp). The skip-restore semantics are unchanged.
        //   * Across PROCESSES, each new pool gets a fresh COW
        //     clone from the bake-time pristine. Process N's
        //     writes never leak into process N+1's view.
        //
        // Pre-0.7.50 with `restoreOnRelease=false`, the worker
        // wrote directly to the user's host file. The on-disk
        // bytes drifted from the snapshot's in-RAM ext4 state on
        // every cycle. The next process re-opened the same host
        // file with the same in-RAM snapshot and got divergence:
        // EUCLEAN on lstat for files the prior process touched
        // (vite's `.vite/deps`), or silent leakage of bake-foreign
        // files visible only via disk-bypassing probes (the
        // shape this test asserts).
        //
        // On release of a worker with a COW temp:
        //   * `restoreOnRelease=true`: release path at 2503 kills
        //     the worker (RESTORE can't reset open virtio-blk
        //     fds), replenisher spawns a fresh COW-backed worker.
        //   * `restoreOnRelease=false`: release path returns
        //     early at 2481 (push to idle), worker is reused
        //     within the process. The COW temp lives until the
        //     worker dies (Pool drop / shutdown). See
        //     `cow_volume_for_spawn` for the temp path scheme and
        //     `Worker::shutdown` for unlink.
        let cow_volumes_enabled = self.volumes.iter().any(|(_, _, _, p)| p.is_some());
        let mut volume_temp_files: Vec<PathBuf> = Vec::new();
        for (i, (host_file, guest_path, size_bytes, pristine)) in self.volumes.iter().enumerate() {
            let effective_host = if cow_volumes_enabled {
                match pristine.as_ref() {
                    Some(pristine_path) => {
                        match cow_volume_for_spawn(pristine_path, i, suffix) {
                            Ok(temp) => {
                                volume_temp_files.push(temp.clone());
                                temp
                            }
                            Err(e) => {
                                // Clean up any temps we already
                                // made — never strand them in /tmp.
                                for p in &volume_temp_files {
                                    let _ = std::fs::remove_file(p);
                                }
                                let _ = std::fs::remove_file(&control_path);
                                return Err(Error::vm_msg(format!(
                                    "spawn_one: COW volume {}: {e}",
                                    pristine_path.display()
                                )));
                            }
                        }
                    }
                    None => {
                        // Snapshot pre-dates the pristine fix.
                        // One-line warn (rate-limited globally so
                        // multi-volume pools don't spam) then
                        // fall back to legacy behavior.
                        warn_legacy_volume_without_pristine_once(host_file);
                        host_file.clone()
                    }
                }
            } else {
                host_file.clone()
            };
            cmd.arg("--volume").arg(format!(
                "{}:{}:{}",
                effective_host.display(),
                guest_path,
                size_bytes
            ));
        }
        cmd.arg("--memory").arg(self.memory_mib.to_string());
        cmd.arg("--vcpus").arg(self.vcpus.to_string());
        cmd.arg("--restore-from").arg(&self.snapshot_path);
        cmd.arg("--cow-restore");
        cmd.arg("--vsock-mux").arg(&vsock_mux_path);
        cmd.arg("--vsock-exec").arg(&vsock_exec_path);
        cmd.arg("--pool-worker").arg(&control_path);
        // 0.7.44+ pre-compute host IPv6 routing in the lib (cached
        // process-wide) and pass to the worker as an env var. The
        // worker used to run its own probe at startup — ~1-3 ms
        // bind+connect+getsockname on every spawn_one. Identical
        // semantics; the worker still falls back to its local probe
        // if the env var isn't set (direct worker invocation).
        // `host_ipv6_route` (not `cached_host_ipv6_route`): an explicit
        // SUPERMACHINE_HOST_IPV6 set on THIS process must win over the
        // probe, matching the worker's own precedence — otherwise an
        // operator override would be silently stomped on every spawn.
        cmd.env(
            "SUPERMACHINE_HOST_IPV6",
            if crate::utils::net::host_ipv6_route() {
                "1"
            } else {
                "0"
            },
        );
        if let Some(pages) = self.balloon_target_pages {
            cmd.arg("--balloon-target-pages").arg(pages.to_string());
        }
        // TSI control-channel auth: re-inject the per-snapshot
        // token so the muxer's expected-prefix matches what the
        // frozen kernel will send on every control DGRAM. See
        // `kernel-build/patches/af-tsi/0014-*.patch`.
        if let Some(hex) = self.tsi_token.as_deref() {
            cmd.arg("--tsi-token").arg(hex);
        }
        // Per-snapshot egress policy: the muxer enforces it at TSI
        // connect time (one-time, never per-packet). Set once at spawn;
        // the worker's process-global policy persists across this
        // worker's cycle-restores. `None` → worker default (allow_all).
        if let Some(policy) = self.egress_policy.as_deref() {
            cmd.arg("--egress-policy").arg(policy);
        }
        // 0.7.44+ pre-exec sync resume. Snapshot was taken with
        // init-oci paused inside `read(0)`. Tell the worker to
        // start its supermachine-pre-exec-resume thread, which
        // pushes 'P\n' shortly after restore so init-oci unblocks.
        // Without this, the restored guest hangs in the read for
        // 30 s, then the SIGALRM fires and the bake/exec continues
        // (slowly + with a "timeout" log line that's confusing).
        if self.pre_exec_sync {
            cmd.env("SUPERMACHINE_PRE_EXEC_SYNC_RESUME", "1");
        }
        // Quiet by default — embedders don't want VM kernel logs
        // on their stdout. SUPERMACHINE_WORKER_LOG=1 to opt in.
        let log_to_stdio = std::env::var("SUPERMACHINE_WORKER_LOG")
            .map(|v| v == "1" || v == "true")
            .unwrap_or(false);
        // Pipe stdout+stderr to a file we can inspect later when the
        // user opts in via SUPERMACHINE_WORKER_LOG_FILE=<path>. A `%`
        // in the path is expanded to THIS worker's unique hex suffix
        // (the same id used for its sockets), so a pool of concurrent
        // workers writes separate, correlatable logs — e.g.
        // `/tmp/sm-worker-%.log` → `/tmp/sm-worker-1a2b...f.log`. This
        // makes a post-mortem (e.g. tracing an "agent closed before
        // EXIT" back to one worker's muxer diagnostics) tractable.
        // Without a `%`, all workers append to the one named file
        // (legacy behaviour; lines from different workers interleave).
        let log_file_path = std::env::var("SUPERMACHINE_WORKER_LOG_FILE").ok().map(|p| {
            if p.contains('%') {
                p.replace('%', &format!("{suffix:016x}"))
            } else {
                p
            }
        });
        if let Some(path) = log_file_path.as_deref() {
            let f = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .ok();
            if let Some(f) = f {
                let f2 = f.try_clone().ok();
                cmd.stdout(Stdio::from(f));
                if let Some(f2) = f2 {
                    cmd.stderr(Stdio::from(f2));
                } else {
                    cmd.stderr(Stdio::null());
                }
            }
        } else if !log_to_stdio {
            cmd.stdout(Stdio::null()).stderr(Stdio::null());
        }

        // Memory admission: reserve this worker's footprint against the
        // process-wide budget BEFORE forking. If too many workers are
        // already live this BLOCKS until one is released, rather than
        // overcommitting host RAM into macOS jetsam/OOM. The reservation
        // rides in the returned `Worker` and is released on drop. Declared
        // before `SpawnCleanup` so an early return kills the child first,
        // then releases the budget. Disabled with
        // SUPERMACHINE_MEMORY_BUDGET_MIB=0.
        //
        // The charge is the pool's MEASURED footprint high-water-mark +
        // margin (capped at the configured guest RAM + overhead; the
        // first spawn charges the cap) — see admission_charge_mib. The
        // host memory-pressure backstop pauses spawns while the host is
        // actually tight, so the learned-charge overcommit can't drive
        // jetsam; it's a no-op sysctl when pressure is normal.
        crate::memory_admission::await_pressure_relief();
        // admit_with: the charge is re-computed while blocked, so a cold
        // pool's parallel prewarm doesn't serialize on the timeout — the
        // first sibling to finish restoring records the real footprint
        // (notify_waiters below) and the blocked spawns re-ask with the
        // learned charge instead of their original cap-sized request.
        let admission_guard = crate::memory_admission::admit_with(|| self.admission_charge_mib());

        // Boot-rate gate: cap how many spawns BOOT concurrently (vCPU
        // threads + restore are thread/CPU-heavy; a storm can hit EAGAIN).
        // Acquired AFTER the memory admit (consistent global lock order, no
        // AB-BA) and held only as a local for the duration of this boot —
        // it is NOT moved into `Worker`, so it releases when `spawn_one`
        // returns. That caps concurrent boots, never running VMs, so VM
        // density and the acquire/exec hot paths are untouched. On an early
        // return it drops here (frees the slot). Disabled with
        // SUPERMACHINE_MAX_CONCURRENT_SPAWNS=0.
        let _spawn_permit = crate::spawn_concurrency::acquire();

        let __t0 = Instant::now();
        let child = cmd.spawn().map_err(|e| {
            Error::vm_msg(format!("spawn worker {}: {e}", self.worker_bin.display()))
        })?;
        let __t_spawned = __t0.elapsed();

        // RAII cleanup for a partially-spawned worker. Until ownership
        // passes to the returned `Worker` on success, ANY early return
        // (or panic) below must kill the orphaned worker process and
        // unlink its COW volume clones + control socket. Without this a
        // failed handshake (stale agent, restore stall, control-accept
        // timeout) leaks a live `supermachine-worker` process plus up
        // to GiB of `/tmp/supermachine-vol-*.img` per attempt — only
        // swept on the NEXT pool init, not in-run. `child` is otherwise
        // untouched between here and the success `Ok(Worker)`.
        struct SpawnCleanup {
            child: Option<std::process::Child>,
            cleanup_paths: Vec<PathBuf>,
            armed: bool,
        }
        impl Drop for SpawnCleanup {
            fn drop(&mut self) {
                if !self.armed {
                    return;
                }
                if let Some(mut c) = self.child.take() {
                    let _ = c.kill();
                    let _ = c.wait();
                }
                for p in &self.cleanup_paths {
                    let _ = std::fs::remove_file(p);
                }
            }
        }
        let mut spawn_cleanup = {
            let mut cleanup_paths = volume_temp_files.clone();
            cleanup_paths.push(control_path.clone());
            SpawnCleanup {
                child: Some(child),
                cleanup_paths,
                armed: true,
            }
        };

        // Worker connects to ctl_listener once it's far enough
        // through main() to call UnixStream::connect — well
        // before any expensive work. We just accept and read the
        // initial DONE line, which the worker writes after its
        // snapshot restore completes. That means callers get a
        // worker that's truly ready to serve, no further polling.
        ctl_listener
            .set_nonblocking(true)
            .map_err(|e| Error::vm_msg(format!("set control listener nonblocking: {e}")))?;
        let deadline = Instant::now() + self.spawn_timeout;
        let mut backoff = Duration::from_millis(1);
        let stream = loop {
            match ctl_listener.accept() {
                Ok((s, _)) => break s,
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    if Instant::now() > deadline {
                        let _ = std::fs::remove_file(&control_path);
                        return Err(Error::vm_msg(format!(
                            "worker spawn: control connect did not arrive within {:?}",
                            self.spawn_timeout
                        )));
                    }
                    std::thread::sleep(backoff);
                    backoff = (backoff * 2).min(Duration::from_millis(10));
                }
                Err(e) => {
                    let _ = std::fs::remove_file(&control_path);
                    return Err(Error::vm_msg(format!("worker spawn: control accept: {e}")));
                }
            }
        };
        // Switch back to blocking — the rest is line-oriented and
        // synchronous.
        stream
            .set_nonblocking(false)
            .map_err(|e| Error::vm_msg(format!("set control stream blocking: {e}")))?;
        let writer = stream
            .try_clone()
            .map_err(|e| Error::vm_msg(format!("clone control stream: {e}")))?;
        let mut control = ControlChannel {
            reader: std::io::BufReader::new(stream),
            writer,
        };

        // The supervisor protocol opens with a "READY\n" line
        // from the worker (it writes that immediately after
        // connecting, before doing any HVF setup). We then send
        // RESTORE <snap_path>, the worker boots+restores, and
        // writes back DONE us=… host_port=… …
        let ready = match control.read_line() {
            Ok(l) => l,
            Err(e) => {
                let _ = std::fs::remove_file(&control_path);
                return Err(Error::vm_msg(format!("worker spawn: read READY: {e}")));
            }
        };
        if ready.trim() != "READY" {
            let _ = std::fs::remove_file(&control_path);
            return Err(Error::vm_msg(format!(
                "worker spawn: expected READY, got: {}",
                ready.trim()
            )));
        }
        let snap_path_str = self.snapshot_path.to_string_lossy().to_string();
        if let Err(e) = control.send_line(&format!("RESTORE {snap_path_str}")) {
            let _ = std::fs::remove_file(&control_path);
            return Err(Error::vm_msg(format!(
                "worker spawn: send initial RESTORE: {e}"
            )));
        }
        let done = match control.read_line() {
            Ok(l) => l,
            Err(e) => {
                let _ = std::fs::remove_file(&control_path);
                return Err(Error::vm_msg(format!(
                    "worker spawn: read initial DONE: {e}"
                )));
            }
        };
        if !done.starts_with("DONE") {
            let _ = std::fs::remove_file(&control_path);
            return Err(Error::vm_msg(format!(
                "worker spawn: expected initial DONE, got: {}",
                done.trim()
            )));
        }
        if crate::trace::enabled("timings") {
            eprintln!(
                "[spawn_one] spawn={:?} accept_to_done={:?} total={:?}",
                __t_spawned,
                __t0.elapsed() - __t_spawned,
                __t0.elapsed()
            );
        }

        // Probe the in-guest agent's wire-protocol version.
        // Catches the failure mode where a snapshot was baked
        // against a previous supermachine release whose agent
        // doesn't speak the current protocol — without this,
        // unknown JSON fields (stage_files / chain) silently
        // hit serde's `#[serde(default)]` ignore-unknown path
        // and the host sees "exec ran with exit 0" but the
        // staged file was never written.
        //
        // Fast path: skip the probe when the snapshot's recorded
        // `runtime_sha16` matches the current worker binary's
        // SHA16. By construction the in-guest agent shipped at
        // bake time matches what the lib expects — the probe
        // would always succeed, just round-trip for nothing.
        // ~25 ms saved per acquire on the hot path.
        //
        // Multi-vCPU caveat: HVF can't round-trip ICH_LR_EL2
        // (GIC List Registers) cleanly across snapshot/restore,
        // so a multi-vCPU restored guest sometimes RCU-stalls
        // on boot — see docs/design/multi-vcpu-snapshot-
        // intermittency-2026-04-27.md and the deferral note. In
        // that state the agent never responds and the probe
        // times out, masquerading as a stale-agent error.
        // For vcpus > 1 we downgrade probe timeouts to a soft
        // warning instead of failing spawn — the workload's
        // first exec() will surface the real error if the
        // guest is genuinely hung. Definitive stale-agent
        // signals (probe ack with old protocol number) still
        // hard-fail.
        //
        // Post-restore smpark_unpark. The snapshot file was
        // captured with all secondaries parked in WFI inside
        // smpark_park_routine (so HVF's lossy ICH/redistributor
        // round-trip lands on a byte-identical state). On
        // restore, those secondaries come back STILL in the
        // park spin loop with `unpark_signal=0`. Without this
        // RPC, they sit in WFI forever and any task scheduled on
        // them stalls — manifests as `__skb_wait_for_more_packets`
        // hangs on rosettad's UNIX-DGRAM socket when the first
        // amd64 binary tries to start.
        //
        // The agent itself runs on vCPU 0 (the boot vCPU, never
        // parked) so the vsock RPC works pre-unpark. The unpark
        // routine on vCPU 0 sends an IPI to each secondary which
        // wakes them from WFI; they re-check `unpark_signal`,
        // see 1, exit the spin loop, re-enable IRQs, and return
        // from the SGI handler back to whatever the kernel
        // scheduler was doing pre-park (typically the idle loop).
        //
        // Best-effort: agent reports `ok=false` when the kernel
        // module isn't loaded (single-vCPU bake or pre-smpark
        // snapshot) — that surfaces as transport `Ok(_)` here
        // since the agent did ack the request, just with
        // `ok=false`. Either way we ignore the result and let
        // probe_agent_protocol below tell us if the guest is
        // genuinely alive.
        //
        // Skip entirely for single-vCPU — no secondaries to
        // unpark, the RPC is pure overhead (~1-3 ms vsock
        // round-trip). The integrator's `vm.exec()` hot path
        // doesn't need this.
        if self.vcpus > 1 {
            let body = serde_json::json!({ "action": "smpark_unpark" });
            match crate::exec::send_control_with_ack(
                &vsock_exec_path,
                &body,
                Some(Duration::from_secs(2)),
            ) {
                Ok(_) => {}
                Err(e) => {
                    tracing::debug!(
                        error = %e,
                        "post-restore smpark_unpark RPC error (continuing)"
                    );
                }
            }
        }

        // Drop the guest's VFS caches so the first
        // virtio-fs/virtio-blk access after this cold restore
        // re-LOOKUPs through the daemon / re-reads from disk
        // instead of returning stale bytes the snapshot captured
        // alongside RAM. Single-vCPU and multi-vCPU both need
        // this — orthogonal to smpark.
        //
        // 0.7.44+ probe-skip: only safe to skip when there are NO
        // virtio-fs mounts AND no virtio-blk volumes. Both surfaces
        // can have host-side state that drifts between bake and
        // restore (host file changes for mounts; out-of-band volume
        // writes via Vm::stage_files or external dd for volumes).
        // Layers stay read-only and content-addressable, so they
        // don't need invalidation.
        //
        // Saves ~5-15 ms vsock RPC on the dominant
        // Image.build-from-Docker no-mounts no-volumes case.
        if !self.mounts.is_empty() || !self.volumes.is_empty() {
            let _ = drop_vfs_caches_via_agent(&vsock_exec_path, self.memory_mib);
        }
        // 0.7.51+ wall-clock sync. See the matching call in
        // `Worker::send_restore` for the rationale: even pure-image
        // snapshots with no mounts need this — Date.now() in the
        // guest reads CLOCK_REALTIME, which was frozen at snapshot
        // capture and stays frozen across restore (the vtimer
        // state covers CLOCK_MONOTONIC but not the wall-clock
        // offset). Fixes JWT iat/exp, OAuth, TLS cert validation,
        // etc. against external authorities.
        let _ = sync_time_via_agent(&vsock_exec_path);

        let probe_skip = self
            .baker_runtime_sha16
            .as_deref()
            .and_then(|stored| {
                current_worker_sha16(&self.worker_bin).map(|current| stored == current.as_str())
            })
            .unwrap_or(false);
        if !probe_skip {
            if let Err(e) = probe_agent_protocol(&vsock_exec_path, self.vcpus) {
                if self.vcpus > 1 && e.is_likely_multi_vcpu_restore_stall() {
                    eprintln!(
                        "supermachine: WARNING multi-vCPU ({}vCPU) snapshot agent probe \
                         timed out — guest may be RCU-stalled after restore. \
                         Continuing (multi-vCPU is unsupported per design); \
                         workload exec will surface a real error if the guest is hung.",
                        self.vcpus
                    );
                } else {
                    let _ = std::fs::remove_file(&control_path);
                    return Err(e);
                }
            }
        }

        // 0.7.67+ — volume-mount readiness gate. init-oci runs
        // mount_volumes() AFTER the snapshot/exec-ready marker, so a
        // freshly-restored guest can accept execs before /data is
        // mounted. Block until every volume appears in /proc/mounts so
        // the caller's first exec can't read an unmounted volume (the
        // snapshot_combinations "T2" empty-/data race). On failure we
        // return before disarming `spawn_cleanup`, so its armed guard
        // tears down the child — exactly like the probe failure above.
        if !self.volumes.is_empty() {
            #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
            let gps: Vec<String> = self
                .volumes
                .iter()
                .map(|(_, gp, _, _)| gp.clone())
                .collect();
            #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
            if let Err(e) = wait_for_volumes_mounted(&vsock_exec_path, &gps) {
                let _ = std::fs::remove_file(&control_path);
                return Err(e);
            }
        }

        // Spawn succeeded end-to-end: take the child back from the
        // cleanup guard and disarm it (the COW temps + control socket
        // now live for the Worker's lifetime).
        spawn_cleanup.armed = false;
        let child = spawn_cleanup
            .child
            .take()
            .expect("spawn_cleanup holds the child until success");
        // Fold this freshly-restored worker's resident footprint into
        // the pool's high-water-mark. Per-spawn (off the hot path).
        // This is the feedback that lets every LATER spawn charge the
        // measured footprint instead of the guest ceiling — see
        // admission_charge_mib.
        if let Some(fp) = crate::memory_admission::phys_footprint_mib(child.id()) {
            let prev = self
                .observed_footprint_mib
                .fetch_max(fp, std::sync::atomic::Ordering::Relaxed);
            if fp > prev {
                eprintln!(
                    "[admission] observed worker footprint {fp} MiB (cap {} MiB) — \
                     new high-water-mark",
                    self.memory_mib
                );
            }
            if prev == 0 {
                // First measurement for this pool: spawns blocked on the
                // conservative cap charge can now re-ask with the learned
                // one — wake them instead of letting them sit out the
                // 60 s admission timeout.
                crate::memory_admission::notify_waiters();
            }
        }
        Ok(Worker {
            child,
            vsock_mux_path,
            vsock_exec_path,
            control_path,
            control: Arc::new(Mutex::new(control)),
            last_restore_path: self.snapshot_path.clone(),
            memory_mib: self.memory_mib,
            has_mounts: !self.mounts.is_empty() || !self.volumes.is_empty(),
            volume_guest_paths: self
                .volumes
                .iter()
                .map(|(_, gp, _, _)| gp.clone())
                .collect(),
            vcpus: self.vcpus,
            has_cow_volumes: !volume_temp_files.is_empty(),
            volume_temp_files,
            _admission: admission_guard,
        })
    }
}

/// Clone the pristine to a per-worker
/// `/tmp/supermachine-vol-<pid>-<suffix>-<index>.img`.
///
/// `pid` ties the file back to the process that owns it (used by
/// crash-recovery sweep to safely unlink only files belonging to
/// dead processes). `suffix` is the same `unique_suffix()` used
/// for the worker's socket paths — gives us per-spawn uniqueness
/// without a separate counter.
///
/// Uses the bake crate's `cow_or_copy` helper: APFS clonefile is
/// metadata-only (~µs), so per-spawn cost is negligible on the
/// dominant macOS-APFS path. Falls back to a full `std::fs::copy`
/// on non-APFS filesystems.
///
/// Caller MUST track the returned path on the spawned Worker so
/// the temp gets unlinked when the worker exits.
fn cow_volume_for_spawn(pristine: &Path, index: usize, suffix: u64) -> std::io::Result<PathBuf> {
    let pid = std::process::id();
    let dst =
        std::env::temp_dir().join(format!("supermachine-vol-{pid}-{suffix:016x}-{index}.img"));
    crate::bake::cow_or_copy(pristine, &dst)?;
    Ok(dst)
}

/// Process-wide once-per-process latch around `sweep_stranded_volume_temps`.
/// Pool builds can fire concurrently; only the first one pays the
/// /tmp readdir cost.
fn sweep_volume_temps_once() {
    static SWEPT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
    if SWEPT.get().is_some() {
        return;
    }
    sweep_stranded_volume_temps();
    let _ = SWEPT.set(());
}

/// Best-effort sweep of stranded COW volume temp files in /tmp.
/// Identifies files matching `supermachine-vol-<pid>-*.img` and
/// unlinks them if the owning pid no longer exists. Used by pool
/// construction (one shot per Image-pool init) so a crash in a
/// previous process doesn't leave 4 GiB+ files lying around.
///
/// Live processes are detected via `kill(pid, 0)` — same probe
/// used elsewhere in the codebase for liveness checks. ESRCH ⇒
/// dead, unlink. EPERM ⇒ alive but owned by someone else, skip.
/// On macOS POSIX semantics this is safe even for a pid that has
/// been recycled to a different process (worst case we keep the
/// file; we never unlink a live process's file by mistake).
fn sweep_stranded_volume_temps() {
    let tmp = std::env::temp_dir();
    let entries = match std::fs::read_dir(&tmp) {
        Ok(e) => e,
        Err(_) => return,
    };
    let me = std::process::id();
    for entry in entries.flatten() {
        let fname = entry.file_name();
        let Some(name) = fname.to_str() else {
            continue;
        };
        // Match supermachine-vol-<pid>-...img
        let Some(rest) = name.strip_prefix("supermachine-vol-") else {
            continue;
        };
        if !name.ends_with(".img") {
            continue;
        }
        let Some(dash) = rest.find('-') else {
            continue;
        };
        let pid_str = &rest[..dash];
        let Ok(pid) = pid_str.parse::<i32>() else {
            continue;
        };
        // Never sweep our own files — they belong to live workers
        // that haven't released yet.
        if pid as u32 == me {
            continue;
        }
        // Liveness probe. kill(pid, 0) returns 0 if pid is alive
        // and we have permission to signal it, -1 with errno set
        // otherwise.
        let alive = unsafe { libc::kill(pid, 0) };
        if alive == 0 {
            // Still live, leave it.
            continue;
        }
        let err = std::io::Error::last_os_error();
        // ESRCH: no such pid → safe to unlink. EPERM: pid exists
        // but not signalable by us → conservative skip.
        if err.raw_os_error() != Some(libc::ESRCH) {
            continue;
        }
        let _ = std::fs::remove_file(entry.path());
    }
}

/// Best-effort one-shot warning when a snapshot lacks `pristine`
/// files. Pre-0.7.49 snapshots — fix requires a re-bake. Globally
/// rate-limited so a multi-volume snapshot only logs once total.
fn warn_legacy_volume_without_pristine_once(host_file: &Path) {
    static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
    if WARNED.get().is_some() {
        return;
    }
    let _ = WARNED.set(());
    eprintln!(
        "supermachine: WARNING snapshot lacks pristine volume bytes (host_file={}); \
         workers will write directly to the host file, leaking state across \
         processes and across `restore_on_release=true` acquires — re-bake \
         under 0.7.49+ for per-spawn COW reset semantics",
        host_file.display()
    );
}

/// Minimum agent wire-protocol version this lib understands.
/// MUST match `AGENT_PROTOCOL` in
/// `crates/supermachine-guest-agent/src/main.rs`. Bump in
/// lockstep when the protocol gains a feature the lib expects
/// the agent to support (e.g. stage_files, chain).
///
/// Version log:
///   1: pre-stage_file. ExecRequest = {argv, env, cwd, tty,
///      cols, rows}. CONTROL actions: signal, write_file,
///      read_file.
///   2: + stage_files + chain on ExecRequest. + probe CONTROL.
///   3: + sync_time CONTROL. The host pushes wall-clock on every
///      restore so the guest's CLOCK_REALTIME doesn't stay frozen
///      at bake-time (which breaks JWT iat/exp, OAuth, TLS cert
///      date validation, etc.). Old snapshots warn via the
///      `probe_agent_protocol` mismatch message — rebake to pick
///      up the new agent.
const HOST_AGENT_PROTOCOL_MIN: u32 = 3;

/// Returns a 16-hex prefix of the SHA-256 of the worker binary at
/// `worker_bin`, cached per-binary-path. Used by the spawn-time
/// probe-skip fast path to compare against the snapshot's stored
/// `runtime_sha16`. Caching is keyed on `(path, file_size,
/// mtime_ns)` so a re-installed worker (same path, new contents)
/// invalidates correctly.
fn current_worker_sha16(worker_bin: &Path) -> Option<String> {
    use std::sync::Mutex;
    static CACHE: Mutex<Option<(PathBuf, u64, u128, String)>> = Mutex::new(None);

    let meta = std::fs::metadata(worker_bin).ok()?;
    let len = meta.len();
    let mtime_ns = meta
        .modified()
        .ok()?
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_nanos();

    if let Ok(g) = CACHE.lock() {
        if let Some((p, l, m, sha)) = g.as_ref() {
            if p == worker_bin && *l == len && *m == mtime_ns {
                return Some(sha.clone());
            }
        }
    }

    // 0.7.44+ in-process SHA-256 via ring (same algorithm + same
    // digest format as `bake::sha256_file`, so the comparison still
    // matches metadata.json's `runtime_sha16` written by the bake).
    // ~10× faster than the pre-0.7.44 `shasum` fork (~15 ms of
    // fork+execve overhead saved on first call; subsequent calls
    // hit this function's pre-existing per-binary-path cache and
    // pay nothing).
    use ring::digest::{Context, SHA256};
    use std::io::Read;
    let mut f = std::fs::File::open(worker_bin).ok()?;
    let mut ctx = Context::new(&SHA256);
    let mut buf = [0u8; 64 * 1024];
    loop {
        let n = f.read(&mut buf).ok()?;
        if n == 0 {
            break;
        }
        ctx.update(&buf[..n]);
    }
    let d = ctx.finish();
    let mut digest = String::with_capacity(64);
    for b in d.as_ref() {
        use std::fmt::Write;
        let _ = write!(digest, "{:02x}", b);
    }
    let sha16 = digest[..digest.len().min(16)].to_owned();

    if let Ok(mut g) = CACHE.lock() {
        *g = Some((worker_bin.to_path_buf(), len, mtime_ns, sha16.clone()));
    }
    Some(sha16)
}

/// Tell the in-guest agent to drop the kernel's VFS caches
/// (page + dentry + inode) via `echo 3 > /proc/sys/vm/drop_caches`.
///
/// Why we do this on every restore: a snapshot captures the
/// guest kernel's RAM verbatim — including the VFS caches. After
/// a restore the guest's view of `mounts:` (virtio-fs) and
/// `volumes:` (virtio-blk + ext4) is whatever the kernel cached
/// at capture time. If the host bind file or volume backing file
/// changed between capture and restore (typical: developer
/// edits a `dist/` file in their workspace mount; or
/// `restoreOnRelease: true` cycled and a different exec wrote to
/// the volume between snapshots), the post-restore first read
/// returns the OLD bytes. The FUSE entry/attr validity windows
/// (60 s) are measured in guest jiffies, which are also frozen
/// at snapshot, so the cache stays "fresh" by guest reckoning
/// long after it's actually stale.
///
/// Dropping the caches forces the guest to re-LOOKUP via the
/// virtio-fs daemon (which reports current host attrs) and to
/// re-read ext4 inode/page state from the underlying block
/// device — both of which see post-snapshot host changes
/// correctly.
///
/// Best-effort and silent: the RPC failing (agent missing,
/// vsock wedged, mode-0 opt-out) does NOT abort the restore;
/// the workload may still execute correctly against the stale
/// caches in many cases, and a hard-fail here would be more
/// disruptive than the staleness it prevents.
///
/// Opt-out: `SUPERMACHINE_VFS_AUTO_INVALIDATE=0` skips the RPC.
/// Useful for throughput-sensitive workloads that read mostly
/// from snapshot-stable paths and don't want to pay the
/// ~few-ms drop on every restore.
///
/// Memory note: `drop_caches=3` drops pagecache too, which
/// forces re-reads of the agent's own executable pages and any
/// virtio-blk/ext4 metadata blocks. On a memory-tight guest
/// (alpine 256 MiB after balloon inflate ~ 96 MiB usable), those
/// re-reads can OOM the agent. Production guests using
/// `mounts:`/`volumes:` are typically ≥512 MiB; the OOM is
/// observable only on the smallest test shapes. If you see
/// guest stderr with `Out of memory: Killed process … (supermachine-ag)`
/// after a restore, bump `memoryMib` to ≥512 or set
/// `SUPERMACHINE_VFS_AUTO_INVALIDATE=0`.
///
/// Diagnostic: set `SUPERMACHINE_VFS_TRACE=1` to print each
/// RPC's outcome + latency to host stderr.
fn drop_vfs_caches_via_agent(vsock_exec_path: &Path, memory_mib: u32) -> bool {
    // `SUPERMACHINE_VFS_AUTO_INVALIDATE` accepts:
    //   "0"     — skip the drop (kill-switch for stale-but-fast reads)
    //   "force" — drop even on memoryMib < 512 (accept OOM risk)
    //   anything else / unset — default (drop when memoryMib >= 512)
    //
    // 0.7.36's separate `SUPERMACHINE_VFS_AUTO_INVALIDATE_FORCE=1`
    // was redundant — collapsed here.
    let setting = std::env::var("SUPERMACHINE_VFS_AUTO_INVALIDATE").ok();
    let s = setting.as_deref();
    if s == Some("0") {
        return false;
    }
    let force = s == Some("force") || s == Some("FORCE");
    // Memory gate. `echo 3 > /proc/sys/vm/drop_caches` forces
    // re-reads of the agent's executable pages + virtio-blk/ext4
    // metadata blocks. The agent's pages are mlock'd (in
    // `crates/supermachine-guest-agent/src/main.rs::main`), but the
    // re-read still allocates pagecache for the metadata blocks.
    // On tight-memory guests (≤256 MiB), the post-restore balloon
    // inflate (≈62.5% reclaim per resources.rs) leaves the agent
    // with ≈96 MiB headroom, and the drop's re-reads push the
    // guest into either an OOM-kill of the agent OR (if the agent
    // is OOM-immune) an unrecoverable kernel panic
    // ("System is deadlocked on memory"). Neither is recoverable
    // from the host.
    //
    // 512 MiB threshold: empirically the floor where the agent's
    // exec path doesn't tip over after drop_caches=3.  Smaller
    // guests trade the cache-staleness fix for not crashing — the
    // operator can either bump memoryMib, or explicitly opt in via
    // `SUPERMACHINE_VFS_AUTO_INVALIDATE=force`.
    if memory_mib < 512 && !force {
        if crate::trace::enabled("vfs") {
            eprintln!(
                "[drop_vfs_caches] SKIP memory_mib={memory_mib} < 512 (set \
                 SUPERMACHINE_VFS_AUTO_INVALIDATE=force to override)"
            );
        }
        return false;
    }
    let body = serde_json::json!({ "action": "drop_vfs_caches" });
    let t0 = Instant::now();
    let trace = crate::trace::enabled("vfs");
    match crate::exec::send_control_with_ack(vsock_exec_path, &body, Some(Duration::from_secs(5))) {
        Ok(ack) => {
            if trace {
                eprintln!(
                    "[drop_vfs_caches] OK in {} ms ack={ack:?}",
                    t0.elapsed().as_millis()
                );
            }
            true
        }
        Err(e) => {
            if trace {
                eprintln!(
                    "[drop_vfs_caches] FAIL in {} ms ({e})",
                    t0.elapsed().as_millis()
                );
            }
            tracing::debug!(
                error = %e,
                "drop_vfs_caches RPC error (continuing with stale caches)"
            );
            false
        }
    }
}

/// Push the host's current wall-clock to the guest so its
/// CLOCK_REALTIME advances with host time across restores.
/// See the agent's `SyncTime` doc-comment for the full
/// rationale: the snapshot captures Linux's `xtime` verbatim,
/// so without this RPC `Date.now()` in the guest reports
/// bake-time hours after the host has moved on — breaking JWT
/// iat/exp, OAuth token freshness, TLS NotBefore/NotAfter,
/// etc. CLOCK_MONOTONIC is deliberately untouched (the
/// captured vtimer state preserves it correctly across
/// restore, which is what tokio's timer wheel, in-flight
/// futures, and TCP retransmit timers need).
///
/// Best-effort: if the RPC fails (agent missing, snapshot
/// baked against pre-v3 agent that doesn't understand the
/// action, CAP_SYS_TIME denied) we log via the existing
/// trace channel and continue. Workloads that don't validate
/// timestamps against external authorities are unaffected;
/// ones that do (JWT, TLS) will hit auth failures, which is
/// exactly what they'd see today.
///
/// Opt-out: `SUPERMACHINE_TIME_AUTO_SYNC=0` skips the call.
/// Useful for tests that intentionally exercise frozen-time
/// scenarios.
///
/// Diagnostic: set `SUPERMACHINE_TRACE=time` (or `all`) to
/// print each RPC's outcome + latency to host stderr.
fn sync_time_via_agent(vsock_exec_path: &Path) -> bool {
    if std::env::var("SUPERMACHINE_TIME_AUTO_SYNC").as_deref() == Ok("0") {
        return false;
    }
    let now = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
        Ok(d) => d.as_nanos(),
        Err(_) => return false,
    };
    let host_unix_ns = u64::try_from(now).unwrap_or(u64::MAX);
    let body = serde_json::json!({
        "action": "sync_time",
        "host_unix_ns": host_unix_ns,
    });
    let t0 = Instant::now();
    let trace = crate::trace::enabled("time");
    match crate::exec::send_control_with_ack(vsock_exec_path, &body, Some(Duration::from_secs(5))) {
        Ok(ack) => {
            if trace {
                eprintln!(
                    "[sync_time] OK in {} ms ack={ack:?}",
                    t0.elapsed().as_millis()
                );
            }
            true
        }
        Err(e) => {
            if trace {
                eprintln!("[sync_time] FAIL in {} ms ({e})", t0.elapsed().as_millis());
            }
            tracing::debug!(
                error = %e,
                "sync_time RPC error (continuing with frozen wall-clock)"
            );
            false
        }
    }
}

/// Best-effort guest-wide writeback flush (`sync(2)` in the guest)
/// via the agent's `sync` CONTROL action. Returns `true` when the
/// agent ack'd the flush.
///
/// Sent before EVERY snapshot capture. The capture freezes guest
/// RAM atomically, but host-persistent writable backing — virtio-blk
/// volume files, writeback-cached virtio-fs host files — only has
/// the writes the guest already flushed; anything still dirty in the
/// guest page cache is missing from the host file. The captured
/// guest itself would flush those pages after a restore, but the
/// backing file outlives this VM: a rebake or a fresh VM attaching
/// the same volume reads the torn host file directly. Field case:
/// a warmup's `npm install` left a package's source map empty in
/// the volume backing file; the next bake saw the package dir
/// present, skipped the reinstall, and the torn file persisted
/// through every subsequent run.
///
/// Must be sent while vCPUs still run normally — in particular
/// BEFORE `smpark_park` (writeback kworkers may be scheduled on
/// secondaries, which park freezes in WFI).
///
/// Timeout is generous (60 s): the flush is bounded by dirty-data
/// volume, and a post-warmup capture is exactly when there can be
/// hundreds of MiB of it. Failure (old agent without the action,
/// transport error) is logged and the capture proceeds — same
/// semantics those callers already use for park/drop-caches.
pub(crate) fn guest_sync_via_agent(vsock_exec_path: &Path) -> bool {
    let body = serde_json::json!({ "action": "sync" });
    let t0 = Instant::now();
    match crate::exec::send_control_with_ack(vsock_exec_path, &body, Some(Duration::from_secs(60)))
    {
        Ok(_) => {
            if crate::trace::enabled("phases") {
                eprintln!("[guest_sync] OK in {} ms", t0.elapsed().as_millis());
            }
            true
        }
        Err(e) => {
            eprintln!(
                "supermachine: guest sync before snapshot capture unavailable \
                 ({e}); volume writes still dirty in the guest may be missing \
                 from the host backing file (rebake to refresh the in-guest agent)"
            );
            false
        }
    }
}

/// First-contact handshake with an in-guest agent. Sends a
/// `probe` CONTROL action; verifies the returned protocol
/// version is at least `HOST_AGENT_PROTOCOL_MIN`. Mismatch →
/// surface a typed `Error` that tells the caller exactly what
/// to do (rebake the snapshot).
///
/// `vcpus` is the snapshot's vCPU count. For vcpus > 1 we use a
/// short timeout (1 s) — a multi-vCPU restored guest either
/// answers within milliseconds or has RCU-stalled and is never
/// going to answer; waiting the full 10 s only delays the
/// downgrade-to-warning path in the spawn caller.
fn probe_agent_protocol(vsock_exec_path: &Path, vcpus: u32) -> Result<(), Error> {
    let timeout = if vcpus > 1 {
        Duration::from_secs(1)
    } else {
        Duration::from_secs(10)
    };
    let body = serde_json::json!({ "action": "probe" });
    let ack = match crate::exec::send_control_with_ack(vsock_exec_path, &body, Some(timeout)) {
        Ok(a) => a,
        Err(e) => {
            // Old agents (pre-protocol-2) don't know "probe"
            // and return ack with ok=false; send_control_with_ack
            // surfaces that as an io::Error with the agent's
            // error message. Any error here = stale agent.
            return Err(Error::vm_msg(format!(
                "agent in this snapshot is from an older supermachine release \
                 (probe failed: {e}). Rebake the snapshot to pick up the new \
                 agent: rm -rf the snapshot dir and re-run your bake (e.g. \
                 `supermachine pull <image> --name <name>`)."
            )));
        }
    };
    let proto = ack.get("protocol").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
    if proto < HOST_AGENT_PROTOCOL_MIN {
        return Err(Error::vm_msg(format!(
            "agent in this snapshot speaks protocol v{proto} but this \
             supermachine library expects v{HOST_AGENT_PROTOCOL_MIN}+. The \
             snapshot was baked against a previous release; rebake to pick up \
             the new agent (rm -rf the snapshot dir and re-run your bake)."
        )));
    }
    Ok(())
}

impl std::fmt::Debug for HiddenPool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = self.state.lock().ok();
        f.debug_struct("HiddenPool")
            .field("socks_dir", &self.socks_dir)
            .field("alive", &s.as_ref().map(|s| s.alive).unwrap_or(usize::MAX))
            .field(
                "idle",
                &s.as_ref().map(|s| s.idle.len()).unwrap_or(usize::MAX),
            )
            .finish()
    }
}

impl HiddenPool {
    /// Explicit shutdown — same effect as dropping the pool, but
    /// callable by name from the high-level API. Sets the
    /// `shutting_down` flag, wakes every `acquire()` caller blocked
    /// on the condvar (they observe the flag and return
    /// `Error::vm_msg("pool is shutting down")`), drains the idle
    /// + dirty queues, and shuts each worker down (QUIT → SIGKILL).
    ///
    /// Idempotent. Subsequent calls are no-ops once the queues are
    /// drained and the flag is set.
    fn shutdown_pool(&self) {
        self.shutting_down.store(true, Ordering::SeqCst);
        self.available.notify_all();
        if let Some(c) = self.dirty_pending.as_ref() {
            c.notify_all();
        }
        if let Ok(mut s) = self.state.lock() {
            while let Some(mut e) = s.idle.pop() {
                e.worker.shutdown();
                s.alive = s.alive.saturating_sub(1);
            }
            if let Some(d) = self.dirty.as_ref() {
                if let Ok(mut q) = d.lock() {
                    while let Some(mut w) = q.pop_front() {
                        w.shutdown();
                        s.alive = s.alive.saturating_sub(1);
                    }
                }
            }
        }
    }
}

impl Drop for HiddenPool {
    fn drop(&mut self) {
        // Signal housekeeping threads to exit. They hold their
        // own clones of the wait-state Arcs (`PoolWaitHandles`),
        // not `Arc<HiddenPool>`, so they don't keep us alive
        // and this drop is allowed to fire as soon as the user-
        // side `Pool` + `Image` references go away. Each thread
        // re-checks `shutting_down` within ~100 ms of its next
        // condvar wait timeout.
        self.shutdown_pool();
        // Best-effort cleanup of the per-pool socks dir.
        let _ = std::fs::remove_dir_all(&self.socks_dir);
    }
}

impl HiddenPool {
    /// Acquire a worker. Three paths:
    ///
    /// 1. **Idle hit (hot path).** A worker is in the idle queue
    ///    — pop and return. ~µs.
    /// 2. **Auto-grow.** No idle worker, but `alive < max`. Bump
    ///    the alive count (reserves a slot before we drop the
    ///    lock), spawn a fresh worker outside the lock, return
    ///    it. ~10-15 ms cold spawn cost.
    /// 3. **Wait.** No idle worker, `alive == max`. Block on the
    ///    `available` condvar with `acquire_timeout`. On timeout
    ///    return `Error::PoolExhausted`.
    fn acquire(&self) -> Result<Worker, Error> {
        let acquire_t0 = Instant::now();
        let acquire_timeout = self.policy.acquire_timeout;
        let mut state = self
            .state
            .lock()
            .map_err(|_| Error::vm_msg("pool mutex poisoned".to_owned()))?;
        loop {
            // Liveness check at pop time. Dead workers are a real
            // failure mode with `restore_on_release(false)`: the
            // worker is returned to idle on Vm drop WITHOUT a cycle
            // restore, so if its process died (HVF crash, SIGKILL,
            // jetsam, etc.) we'd hand the caller a doomed handle
            // whose first `vm.exec` fails with "Connection refused"
            // on the closed vsock socket. Try_wait is non-blocking
            // and cheap; discarding the dead entry + decrementing
            // alive lets the auto-grow path below spawn a fresh
            // worker on the same acquire call.
            //
            // `restore_on_release(true)` workers normally can't
            // reach this branch alive-but-dead because the
            // restorer thread already RESTOREs them on drop (a
            // failed restore would have removed them from the
            // pool). Belt-and-suspenders: same check applies.
            while let Some(mut entry) = state.idle.pop() {
                match entry.worker.child.try_wait() {
                    Ok(None) => {
                        // 0.7.51+ skip-restore wall-clock refresh.
                        // restore_on_release=true workers come off
                        // the dirty queue via send_restore, which
                        // already calls sync_time. restore_on_release
                        // =false workers go straight back to idle on
                        // release without a RESTORE round-trip — so
                        // their CLOCK_REALTIME keeps drifting from
                        // the host's. If the worker has sat idle
                        // for more than a second, push the host's
                        // wall-clock in.
                        //
                        // 1 s threshold: avoids per-acquire RPC
                        // overhead in tight-loop throughput
                        // workloads (where idle time between
                        // acquires is sub-ms and drift is
                        // negligible), while still keeping a
                        // worker-reused-after-an-hour case accurate.
                        // The first-acquire-after-spawn case is
                        // already covered by spawn_one's
                        // sync_time_via_agent call.
                        if !self.policy.restore_on_release {
                            let idle_for = entry.last_used.elapsed();
                            if idle_for > Duration::from_secs(1) {
                                // Drop the lock before the vsock RPC
                                // so we don't block other acquirers
                                // (per-pool global mutex).
                                let exec_path = entry.worker.vsock_exec_path.clone();
                                drop(state);
                                let _ = sync_time_via_agent(&exec_path);
                                return Ok(entry.worker);
                            }
                        }
                        return Ok(entry.worker); // alive
                    }
                    Ok(Some(_status)) => {
                        // Already exited. Decrement alive so the
                        // auto-grow branch (or replenisher) replaces
                        // it. The worker handle's Drop will tidy
                        // sockets without trying to send QUIT to a
                        // dead process.
                        state.alive = state.alive.saturating_sub(1);
                        continue; // try next idle entry
                    }
                    Err(_) => {
                        // Stat failed (e.g. permission, OS weirdness).
                        // Treat as dead — same handling.
                        state.alive = state.alive.saturating_sub(1);
                        continue;
                    }
                }
            }
            if self.shutting_down.load(Ordering::SeqCst) {
                return Err(Error::vm_msg("pool is shutting down".to_owned()));
            }
            // Auto-grow: spawn a worker if we're under the cap.
            // Reserve the alive slot inside the lock so concurrent
            // acquires don't both spawn past max.
            if state.alive < self.policy.max {
                state.alive += 1;
                drop(state);
                let spawned = self.spawn_cfg.spawn_one();
                match spawned {
                    Ok(w) => return Ok(w),
                    Err(e) => {
                        // Roll back the reservation so the pool
                        // doesn't permanently lose the slot.
                        if let Ok(mut s) = self.state.lock() {
                            s.alive = s.alive.saturating_sub(1);
                        }
                        // Wake any other waiters so they can retry
                        // (they may not need to spawn — restorer
                        // could push to idle in the meantime).
                        self.available.notify_all();
                        return Err(e);
                    }
                }
            }
            // At max: wait on condvar with timeout (or forever).
            // If we've already exceeded the budget, return now —
            // don't bother re-entering wait.
            if let Some(total) = acquire_timeout {
                if acquire_t0.elapsed() >= total {
                    return Err(Error::pool_exhausted(format!(
                        "acquire timed out after {total:?}; pool at max ({})",
                        self.policy.max
                    )));
                }
            }
            state.waiting += 1;
            let (new_state, timed_out) = match acquire_timeout {
                None => match self.available.wait(state) {
                    Ok(s) => (s, false),
                    Err(_) => return Err(Error::vm_msg("pool condvar poisoned".to_owned())),
                },
                Some(total) => {
                    let remaining = total.saturating_sub(acquire_t0.elapsed());
                    match self.available.wait_timeout(state, remaining) {
                        Ok((s, r)) => (s, r.timed_out()),
                        Err(_) => return Err(Error::vm_msg("pool condvar poisoned".to_owned())),
                    }
                }
            };
            state = new_state;
            state.waiting = state.waiting.saturating_sub(1);
            if timed_out {
                return Err(Error::pool_exhausted(format!(
                    "acquire timed out after {:?}; pool at max ({})",
                    acquire_timeout.unwrap_or_default(),
                    self.policy.max
                )));
            }
        }
    }

    /// `PooledVm::drop` calls this with the now-dirty worker.
    /// Pushes onto the dirty queue and signals the restorer
    /// thread, which sends a RESTORE command to reset the
    /// worker's guest state and then returns it to the idle
    /// queue. Drop returns to the user immediately — the ~3 ms
    /// restore happens off the user's thread.
    ///
    /// Returns the worker to the dirty queue rather than
    /// killing it. The same supervisor-mode worker process
    /// serves many cycles; we only kill on shutdown or on a
    /// genuine RESTORE protocol failure (then the replenisher
    /// spawns a fresh worker to keep the pool at target size).
    fn release(&self, worker: Worker) {
        // Post-workload footprint re-measure: the spawn-time measurement
        // sees only the idle CoW-restore footprint (single-digit MiB —
        // clean file-backed mmap pages don't count toward
        // phys_footprint). The workload's dirty set shows up HERE, at
        // hand-back, and folding it into the pool's high-water-mark is
        // what makes the learned admission charge GROW with real usage
        // instead of admitting forever at the idle-restore size. One
        // proc_pid_rusage on the (already lock-taking) release path.
        if let Some(fp) = crate::memory_admission::phys_footprint_mib(worker.child.id()) {
            let prev = self
                .spawn_cfg
                .observed_footprint_mib
                .fetch_max(fp, std::sync::atomic::Ordering::Relaxed);
            if fp > prev {
                eprintln!(
                    "[admission] observed worker footprint {fp} MiB at release \
                     (cap {} MiB) — new high-water-mark",
                    self.spawn_cfg.memory_mib
                );
            }
        }
        // Skip-restore mode: push directly to idle without
        // queueing for the restorer. Per-cycle cost vanishes
        // and the guest's page cache stays warm across uses.
        // Caller opted in via `PoolBuilder::restore_on_release(false)`.
        if !self.policy.restore_on_release {
            if let Ok(mut s) = self.state.lock() {
                s.idle.push(IdleEntry {
                    worker,
                    last_used: Instant::now(),
                });
                self.available.notify_all();
            }
            return;
        }
        // 0.7.49+ COW-volume cycle: kill + respawn instead of
        // RESTORE. RESTORE only rewinds RAM; the worker's open
        // virtio-blk fds keep pointing at temp files that contain
        // the just-finished cycle's writes. Killing the worker
        // unlinks the temp (via shutdown() → drain
        // volume_temp_files), the replenisher spawns a fresh
        // worker which clones a new pristine → temp pair, and the
        // next acquire sees clean ext4 bytes that match the
        // snapshot's captured ext4 RAM state. ~50 ms spawn cost
        // happens off the user's thread (release returns
        // immediately); the next acquire blocks only if
        // replenisher hasn't finished by then.
        //
        // Note: this branch is reachable ONLY under
        // `restore_on_release=true` — the skip-restore early
        // return above (line 2530) covers `=false`, so a worker
        // with `has_cow_volumes=true` and `restore_on_release=false`
        // is reused within the process (same worker → same COW
        // temp → writes persist for that process). The
        // cross-process safety lives in `spawn_one` (every spawn
        // gets a fresh COW from pristine), not here.
        if worker.has_cow_volumes {
            let mut w = worker;
            w.shutdown();
            if let Ok(mut s) = self.state.lock() {
                s.alive = s.alive.saturating_sub(1);
            }
            self.available.notify_all();
            return;
        }
        if let Some(d) = self.dirty.as_ref() {
            if let Ok(mut q) = d.lock() {
                q.push_back(worker);
            }
            if let Some(c) = self.dirty_pending.as_ref() {
                c.notify_all();
            }
        } else {
            // Defensive fallback: if for some reason the dirty
            // queue isn't wired up (shouldn't happen with the
            // current init path), fall back to the old "kill +
            // ask replenisher" behaviour so we never strand a
            // worker.
            let mut w = worker;
            w.shutdown();
            if let Ok(mut s) = self.state.lock() {
                s.alive = s.alive.saturating_sub(1);
            }
            self.available.notify_all();
        }
    }
}

impl Image {
    /// Load an image from the on-disk artifacts produced by
    /// `supermachine run IMAGE`. The argument can be either:
    ///
    /// - The directory containing `metadata.json` and `restore.snap`
    ///   (typical: `~/.local/supermachine-snapshots/<name>/`).
    /// - The `restore.snap` file itself; we read `metadata.json`
    ///   from its parent dir.
    ///
    /// ```sh
    /// supermachine run nginx:1.27-alpine --detach && supermachine run --stop
    /// # snapshot dir: ~/.local/supermachine-snapshots/nginx_1_27-alpine/
    /// ```
    ///
    /// On disk, that directory contains:
    ///
    /// ```text
    /// metadata.json    # layers, memory, vcpus, etc.
    /// restore.snap     # captured VM state (CoW-mappable)
    /// delta.squashfs   # writable overlay layer (optional)
    /// ```
    pub fn from_snapshot(path: impl Into<PathBuf>) -> Result<Self, Error> {
        Self::from_snapshot_inner(path.into(), false)
    }

    /// Like [`Self::from_snapshot`] but tolerates the snapshot
    /// `restore.snap` file being absent — used by the
    /// always-pipelined plain-`build()` path where the bg
    /// `save_compact_to_file` may still be in flight when
    /// `build()` returns. The Image is constructed from
    /// `metadata.json` (which IS written synchronously) and the
    /// stashed warm `BakedWorker` covers the first acquire from
    /// in-memory state. Subsequent `Pool::spawn_one` calls poll
    /// for `snapshot_path.is_file()` before invoking the worker —
    /// `save_compact_to_file` writes to `<path>.partial` and
    /// atomic-renames, so file existence ↔ save complete.
    pub(crate) fn from_snapshot_pending(path: impl Into<PathBuf>) -> Result<Self, Error> {
        Self::from_snapshot_inner(path.into(), true)
    }

    fn from_snapshot_inner(path: PathBuf, allow_pending: bool) -> Result<Self, Error> {
        // Resolve to a (snapshot_path, metadata_path) pair. Under
        // `allow_pending`, the path may be a directory whose
        // `restore.snap` doesn't exist yet — accept that and let
        // spawn_one poll for the file later.
        let (snapshot_path, metadata_path) = if path.is_dir() {
            (path.join("restore.snap"), path.join("metadata.json"))
        } else if path.is_file() {
            let parent = path.parent().ok_or_else(|| {
                Error::image_msg(format!(
                    "snapshot path has no parent dir: {}",
                    path.display()
                ))
            })?;
            (path.clone(), parent.join("metadata.json"))
        } else if path
            .file_name()
            .map(|n| n == "restore.snap")
            .unwrap_or(false)
            && path
                .parent()
                .map(|p| p.join("metadata.json").is_file())
                .unwrap_or(false)
        {
            // A `<dir>/restore.snap` whose file is LEGITIMATELY ABSENT — a sentry
            // layer (FS-backed, no RAM dump) or a KVM cold-boot image. `snapshot_path()`
            // returns this conventional `restore.snap` path for EVERY backend, so the
            // round-trip `from_snapshot(img.snapshot_path())` (used across the builder,
            // e.g. executor `build_stage`) must reconstruct the image even when no
            // restore.snap exists. Resolve metadata from the sibling and let the backend
            // gate below decide whether the file is actually required (HVF: yes).
            let parent = path.parent().expect("checked parent has metadata.json");
            (path.clone(), parent.join("metadata.json"))
        } else if allow_pending {
            // Path doesn't exist as either dir or file. With
            // pending we still expect the directory at minimum
            // (metadata.json must live there).
            return Err(Error::image_msg(format!(
                "snapshot path not found: {}",
                path.display()
            )));
        } else {
            return Err(Error::image_msg(format!(
                "snapshot path not found: {}",
                path.display()
            )));
        };

        // metadata.json is required for every backend; read it first so we know
        // the backend before deciding whether a `restore.snap` is mandatory.
        if !metadata_path.is_file() {
            return Err(Error::image_msg(format!(
                "metadata.json not found alongside snapshot at {}",
                metadata_path.display()
            )));
        }

        let meta_text = std::fs::read_to_string(&metadata_path)
            .map_err(|e| Error::image_msg(format!("read {}: {e}", metadata_path.display())))?;
        let meta: serde_json::Value = serde_json::from_str(&meta_text)
            .map_err(|e| Error::image_msg(format!("parse {}: {e}", metadata_path.display())))?;

        // Backend selects the runtime artifact model. HVF restores from a
        // `restore.snap`; KVM ("backend":"kvm") boots COLD from a kernel +
        // agent initramfs (+ optional rootfs disk), so it has no snapshot file.
        let backend = meta
            .get("backend")
            .and_then(|v| v.as_str())
            .unwrap_or("hvf")
            .to_string();
        // HVF restores from `restore.snap`; KVM cold-boots from kernel+initrd,
        // while sentry/runsc/kboxlike serve from an extracted rootfs dir — none
        // of those require an HVF-style snapshot file here.
        if !allow_pending
            && backend != "kvm"
            && backend != "sentry"
            && backend != "runsc"
            && backend != "kboxlike"
            && !snapshot_path.is_file()
        {
            return Err(Error::image_msg(format!(
                "snapshot file not found: {}",
                snapshot_path.display()
            )));
        }

        // Snapshots baked under a previous binary version are REFUSED, not
        // warned about: the pinned init/kernel/agent inside the snapshot can
        // be arbitrarily incompatible with current binaries, and the failure
        // shape is vicious — a field report had a 0.7.74 dockerfile-layer
        // snapshot restore fine under 0.7.80 binaries and run with ZERO
        // egress (DNS + direct-IP silently dead). A hard error here turns
        // that into an actionable message, and every cache-or-bake caller
        // (`build_hvf`, `from_oci_to_dir`, `warm_snapshot_for_pool`, the
        // dockerfile short-circuit, the builder's layer-cache prefix scan)
        // treats a from_snapshot error as a cache MISS and rebakes
        // automatically. Indeterminate version info (bundles, custom kernel
        // paths) stays permissive — we can't reason about skew there.
        if let Some(baked) = snapshot_baked_under_other_version(&meta) {
            let current = env!("CARGO_PKG_VERSION");
            return Err(Error::cache_invalid(format!(
                "snapshot at {} was baked under v{baked}; current binaries are \
                 v{current}. Restoring across versions can produce a silently \
                 broken VM (e.g. no egress). Re-bake: delete the snapshot dir \
                 and re-run the build/pull that produced it.",
                snapshot_path.display()
            )));
        }

        let memory_mib = meta
            .get("memory_mib")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32)
            .unwrap_or(256);
        let vcpus = meta
            .get("vcpus")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32)
            .unwrap_or(1);

        // metadata.json paths may be absolute (default for native
        // bakes that store paths under ~/.local/...) or relative
        // (used by `supermachine bundle --image NAME`, which writes
        // a self-contained dir with `./layers/<sha>.squashfs` style
        // entries). Resolve relative paths against the metadata
        // dir so a bundle works after `cp -r` to a different host.
        let metadata_dir = metadata_path
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        let resolve_path = |s: &str| -> PathBuf {
            let p = PathBuf::from(s);
            if p.is_absolute() {
                p
            } else {
                metadata_dir.join(p)
            }
        };

        let layers: Vec<PathBuf> = meta
            .get("layers")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|x| x.as_str().map(resolve_path))
                    .collect()
            })
            .unwrap_or_default();
        let delta_squashfs = meta
            .get("delta_squashfs")
            .and_then(|v| v.as_str())
            .map(resolve_path);

        // Validate that referenced layer files actually exist on disk
        // BEFORE returning `Ok(Self)`. Without this, a warm-tag snapshot
        // whose metadata points at layer files in a *sibling* base
        // snapshot dir (`<base>` vs `<base>__warm__<tag>`) survives a
        // user `rm -rf <base>` and looks loadable to the cache-hit
        // check upstream — but the actual restore fails partway
        // through with `open block device …: No such file or
        // directory` and the worker control socket closes mid-protocol
        // ("read initial DONE: worker control socket closed"). The
        // confusing error mode reproduces exactly when
        // `bake_timing.test.ts` deletes the base dir while a sibling
        // `__warm__<tag>` dir still references it.
        //
        // Returning Err here makes the upstream `PullPolicy::Missing`
        // arm fall through to re-bake instead of trying to restore an
        // inconsistent snapshot. `allow_pending` callers (where
        // restore.snap doesn't exist yet) skip this check because the
        // bake is still in flight and the layer files may not have
        // been materialized yet.
        if !allow_pending {
            for layer in &layers {
                if !layer.is_file() {
                    return Err(Error::image_msg(format!(
                        "snapshot at {} references missing layer file {}: a sibling \
                         snapshot dir was likely deleted (e.g. the base dir of a \
                         `__warm__<tag>` variant). Delete this dir too and re-bake.",
                        snapshot_path.display(),
                        layer.display()
                    )));
                }
            }
            if let Some(delta) = &delta_squashfs {
                if !delta.is_file() {
                    return Err(Error::image_msg(format!(
                        "snapshot at {} references missing delta squashfs {}: a \
                         sibling snapshot dir was likely deleted (e.g. the base dir \
                         of a `__warm__<tag>` variant). Delete this dir too and re-bake.",
                        snapshot_path.display(),
                        delta.display()
                    )));
                }
            }
        }

        // virtio-fs mounts: persisted by the bake driver as
        // `metadata.mounts = [{host_path, guest_tag, guest_path[,
        // symlinks]}, ...]`. `guest_path` is required — snapshots
        // baked by 0.7.27 or earlier (no auto-mount API) are
        // rejected with an actionable error here rather than
        // silently restoring a broken mount tree.
        let mounts: Vec<crate::vmm::resources::MountSpec> = meta
            .get("mounts")
            .and_then(|v| v.as_array())
            .map(|arr| -> Result<Vec<_>, Error> {
                arr.iter()
                    .filter_map(|x| {
                        let host = x.get("host_path")?.as_str()?;
                        let tag = x.get("guest_tag")?.as_str()?;
                        let guest_path = match x.get("guest_path").and_then(|v| v.as_str()) {
                            Some(p) => p,
                            None => {
                                return Some(Err(Error::bake_msg(format!(
                                    "snapshot mount entry for tag `{tag}` has no \
                                     `guest_path` — this snapshot was baked by \
                                     supermachine 0.7.27 or earlier, which used a \
                                     legacy non-auto-mount API. Re-bake with \
                                     `MountSpec::new(host, tag, guest_path)` to \
                                     pin a guest mount point."
                                ))));
                            }
                        };
                        let policy = x
                            .get("symlinks")
                            .and_then(|v| v.as_str())
                            .and_then(parse_symlink_policy)
                            .unwrap_or_default();
                        let m = crate::vmm::resources::MountSpec::new(host, tag, guest_path)
                            .with_symlinks(policy);
                        Some(Ok(m))
                    })
                    .collect()
            })
            .transpose()?
            .unwrap_or_default();

        // Validate that each recorded mount's host directory still exists,
        // same contract as the layer/delta checks above. Without this, a
        // cached snapshot whose mount dir was deleted (typical for a
        // tmpdir-mounting test or a moved project) looks loadable to the
        // warm cache-hit probe upstream, but the spawned worker dies
        // during restore with `open virtio-fs mount …: No such file or
        // directory` on ITS stderr and the embedder only sees the opaque
        // "read initial DONE: worker control socket closed". Erroring
        // here instead (a) gives the actionable cause, and (b) turns the
        // `.build()` cache-hit probe into a cache MISS so the image is
        // re-baked against the caller's current mount config.
        if !allow_pending {
            for m in &mounts {
                if !Path::new(&m.host_path).is_dir() {
                    return Err(Error::image_msg(format!(
                        "snapshot at {} records virtio-fs mount tag `{}` from host \
                         dir {} which no longer exists. Restore the directory, or \
                         delete the snapshot dir to re-bake with the current mounts.",
                        snapshot_path.display(),
                        m.guest_tag,
                        m.host_path,
                    )));
                }
            }
        }

        // virtio-blk volumes: persisted by the bake driver as
        // `metadata.volumes = [{host_file, guest_path, size_bytes,
        // pristine?}, ...]`. host_file/guest_path/size_bytes are
        // required for the warm-restore worker to replay
        // `--volume HOST:GUEST:SIZE`. Pre-0.7.30 snapshots may be
        // missing `size_bytes`; fall back to the default cap then
        // so older snapshots still warm-restore (with a slightly
        // inflated sparse-size hint, which is harmless because the
        // host file already exists with its actual size on disk).
        //
        // 0.7.49+ snapshots also carry a `pristine` path pointing at
        // a captured-at-bake-time copy of `host_file`. 0.7.50+: when
        // present, the pool clones the pristine to a per-process
        // temp file on each spawn regardless of
        // `restoreOnRelease` — every worker writes to its own COW
        // and the user's host file is never mutated by the pool
        // (only by the baker). Missing field (pre-0.7.49) → None;
        // pool falls back to legacy behavior (workers share the
        // user's host file) and logs a one-line warning the first
        // time it's used.
        let volumes: Vec<(PathBuf, String, u64, Option<PathBuf>)> = meta
            .get("volumes")
            .and_then(|v| v.as_array())
            .map(|arr| -> Vec<(PathBuf, String, u64, Option<PathBuf>)> {
                arr.iter()
                    .filter_map(|x| {
                        let host_file = x.get("host_file")?.as_str()?;
                        let guest_path = x.get("guest_path")?.as_str()?;
                        let size_bytes = x
                            .get("size_bytes")
                            .and_then(|v| v.as_u64())
                            .unwrap_or(crate::vmm::resources::VolumeSpec::DEFAULT_SIZE_BYTES);
                        let pristine = x
                            .get("pristine")
                            .and_then(|v| v.as_str())
                            .map(PathBuf::from)
                            .filter(|p| p.is_file());
                        Some((
                            PathBuf::from(host_file),
                            guest_path.to_owned(),
                            size_bytes,
                            pristine,
                        ))
                    })
                    .collect()
            })
            .unwrap_or_default();

        // Bundled kernel discovery: a self-contained bundle puts
        // the kernel image next to the snapshot. Prefer that over
        // host-wide AssetPaths so a shipped `.app` doesn't depend
        // on the user having supermachine installed.
        let bundled_kernel = {
            let cand = metadata_dir.join("kernel");
            if cand.is_file() {
                Some(cand)
            } else {
                None
            }
        };

        let baker_runtime_sha16 = meta
            .get("runtime_sha16")
            .and_then(|v| v.as_str())
            .map(|s| s.to_owned());

        let balloon_target_pages = meta
            .get("balloon_target_pages")
            .and_then(|v| v.as_u64())
            .and_then(|n| u32::try_from(n).ok())
            .filter(|n| *n > 0);

        // metadata.json["tsi_token"]: 64 lowercase hex chars iff
        // present. Pre-0.6.0 snapshots don't have this field;
        // restore in legacy unauthenticated mode (the kernel
        // baked at the same version also lacks the cmdline arg).
        let tsi_token = meta
            .get("tsi_token")
            .and_then(|v| v.as_str())
            .filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()))
            .map(|s| s.to_ascii_lowercase());

        // metadata.json["egress_policy"]: optional per-snapshot network
        // policy string (allow_all / deny_private / allowlist:<cidrs> /
        // denylist:<cidrs>). Threaded to the worker so the muxer enforces
        // it at TSI connect time. Absent → allow_all (worker default).
        let egress_policy = meta
            .get("egress_policy")
            .and_then(|v| v.as_str())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());

        // 0.7.44+ pre-exec sync. true → snapshot was captured with
        // init-oci paused inside `read(0)` at the pre-exec pause
        // point. spawn_one() will set
        // SUPERMACHINE_PRE_EXEC_SYNC_RESUME=1 in the worker env so
        // the resume thread pushes the unblock byte after restore.
        // Absent / false / pre-0.7.44 snapshots use the legacy
        // nanosleep path which doesn't need a host push.
        let pre_exec_sync = meta
            .get("pre_exec_sync")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // Linux/KVM artifacts (only when "backend":"kvm"). kernel + agent
        // initramfs are required; disk (rootfs as /dev/vda) is optional.
        let kvm = if backend == "kvm" {
            let kernel = meta
                .get("kvm_kernel")
                .and_then(|v| v.as_str())
                .map(resolve_path);
            let initrd = meta
                .get("kvm_initrd")
                .and_then(|v| v.as_str())
                .map(resolve_path);
            let disk = meta
                .get("kvm_disk")
                .and_then(|v| v.as_str())
                .map(resolve_path);
            let snapshot = meta
                .get("kvm_snapshot")
                .and_then(|v| v.as_str())
                .map(resolve_path);
            // A KVM image either cold-boots (kernel + initrd) or restores from a
            // snapshot — require one of those shapes.
            if snapshot.is_none() && (kernel.is_none() || initrd.is_none()) {
                return Err(Error::image_msg(
                    "metadata.json \"backend\":\"kvm\" needs either \"kvm_snapshot\", \
                     or both \"kvm_kernel\" and \"kvm_initrd\""
                        .to_owned(),
                ));
            }
            Some(KvmImageParts {
                kernel,
                initrd,
                disk,
                snapshot,
            })
        } else {
            None
        };

        // Sentry artifacts (only when "backend":"sentry"): the extracted rootfs
        // dir + a workload flag. No kernel/disk/snapshot — the sentry serves
        // files from the dir directly.
        let sentry = if backend == "sentry" {
            let rootfs = meta
                .get("sentry_rootfs")
                .and_then(|v| v.as_str())
                .map(resolve_path)
                .ok_or_else(|| {
                    Error::image_msg(
                        "metadata.json \"backend\":\"sentry\" needs \"sentry_rootfs\"".to_owned(),
                    )
                })?;
            if !allow_pending && !rootfs.is_dir() {
                return Err(Error::image_msg(format!(
                    "sentry rootfs dir not found: {}. Delete the snapshot dir and re-bake.",
                    rootfs.display()
                )));
            }
            let has_workload = meta
                .get("sentry_has_workload")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            // metadata.json["user"]: the OCI config `User` (recorded at bake by
            // `bake_sentry_from_ref`). Parse only the numeric `uid` / `uid:gid`
            // forms — a username (no passwd lookup in the sentry) or `root`/`0` /
            // empty leaves the guest at the sentry's own uid (no drop).
            let user = meta
                .get("user")
                .and_then(|v| v.as_str())
                .and_then(parse_numeric_user);
            // metadata.json["image_env"]: the OCI config `Env` (KEY→VALUE object)
            // recorded at bake. Becomes the exec env base (see SentryImageParts).
            let image_env = meta
                .get("image_env")
                .and_then(|v| v.as_object())
                .map(|o| {
                    o.iter()
                        .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                })
                .unwrap_or_default();
            // metadata.json["cmd"]: the effective workload argv recorded at bake
            // (bake_sentry_with_config). Fall back to ["entrypoint"] when only an
            // Entrypoint was declared (a warm-daemon image relying on the base
            // image's Entrypoint must still surface its argv to Pool::warm).
            // Absent on legacy/base bakes -> empty (the warm-daemon backend gates
            // on `warm_daemon && !cmd.is_empty()`).
            let str_array = |v: &serde_json::Value| -> Vec<String> {
                v.as_array()
                    .map(|a| {
                        a.iter()
                            .filter_map(|s| s.as_str().map(str::to_owned))
                            .collect()
                    })
                    .unwrap_or_default()
            };
            let cmd = meta
                .get("cmd")
                .map(str_array)
                .filter(|c| !c.is_empty())
                .or_else(|| meta.get("entrypoint").map(str_array))
                .unwrap_or_default();
            // metadata.json["warm_daemon"]: default false so legacy/base/KVM/HVF
            // metadata without the key still loads.
            let warm_daemon = meta
                .get("warm_daemon")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            Some(SentryImageParts {
                rootfs,
                has_workload,
                user,
                image_env,
                cmd,
                warm_daemon,
            })
        } else {
            None
        };

        let runsc = if backend == "runsc" {
            let rootfs = meta
                .get("runsc_rootfs")
                .or_else(|| meta.get("sentry_rootfs"))
                .and_then(|v| v.as_str())
                .map(resolve_path)
                .ok_or_else(|| {
                    Error::image_msg(
                        "metadata.json \"backend\":\"runsc\" needs \"runsc_rootfs\"".to_owned(),
                    )
                })?;
            if !allow_pending && !rootfs.is_dir() {
                return Err(Error::image_msg(format!(
                    "runsc rootfs dir not found: {}. Delete the snapshot dir and re-bake.",
                    rootfs.display()
                )));
            }
            let has_workload = meta
                .get("runsc_has_workload")
                .or_else(|| meta.get("sentry_has_workload"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let user = meta
                .get("user")
                .and_then(|v| v.as_str())
                .and_then(parse_numeric_user);
            let image_env = meta
                .get("image_env")
                .and_then(|v| v.as_object())
                .map(|o| {
                    o.iter()
                        .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                })
                .unwrap_or_default();
            let str_array = |v: &serde_json::Value| -> Vec<String> {
                v.as_array()
                    .map(|a| {
                        a.iter()
                            .filter_map(|s| s.as_str().map(str::to_owned))
                            .collect()
                    })
                    .unwrap_or_default()
            };
            let cmd = meta
                .get("cmd")
                .map(str_array)
                .filter(|c| !c.is_empty())
                .or_else(|| meta.get("entrypoint").map(str_array))
                .unwrap_or_default();
            let warm_daemon = meta
                .get("warm_daemon")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let checkpoint = meta
                .get("runsc_checkpoint")
                .and_then(|v| v.as_str())
                .map(resolve_path);
            let agent_path = meta
                .get("runsc_agent_path")
                .and_then(|v| v.as_str())
                .unwrap_or("/.supermachine/supermachine-agent")
                .to_owned();
            let agent_unix_env = meta
                .get("runsc_agent_unix_env")
                .and_then(|v| v.as_str())
                .unwrap_or("SUPERMACHINE_AGENT_UNIX_SOCKET")
                .to_owned();
            Some(RunscImageParts {
                rootfs,
                memory_mib,
                vcpus,
                has_workload,
                user,
                image_env,
                cmd,
                warm_daemon,
                checkpoint,
                mounts: mounts.clone(),
                agent_path,
                agent_unix_env,
            })
        } else {
            None
        };

        let kboxlike = if backend == "kboxlike" {
            let rootfs = meta
                .get("kboxlike_rootfs")
                .or_else(|| meta.get("sentry_rootfs"))
                .and_then(|v| v.as_str())
                .map(resolve_path)
                .ok_or_else(|| {
                    Error::image_msg(
                        "metadata.json \"backend\":\"kboxlike\" needs \"kboxlike_rootfs\""
                            .to_owned(),
                    )
                })?;
            if !allow_pending && !rootfs.is_dir() {
                return Err(Error::image_msg(format!(
                    "kboxlike rootfs dir not found: {}. Delete the snapshot dir and re-bake.",
                    rootfs.display()
                )));
            }
            let has_workload = meta
                .get("kboxlike_has_workload")
                .or_else(|| meta.get("sentry_has_workload"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let user = meta
                .get("user")
                .and_then(|v| v.as_str())
                .and_then(parse_numeric_user);
            let image_env = meta
                .get("image_env")
                .and_then(|v| v.as_object())
                .map(|o| {
                    o.iter()
                        .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                })
                .unwrap_or_default();
            let str_array = |v: &serde_json::Value| -> Vec<String> {
                v.as_array()
                    .map(|a| {
                        a.iter()
                            .filter_map(|s| s.as_str().map(str::to_owned))
                            .collect()
                    })
                    .unwrap_or_default()
            };
            let cmd = meta
                .get("cmd")
                .map(str_array)
                .filter(|c| !c.is_empty())
                .or_else(|| meta.get("entrypoint").map(str_array))
                .unwrap_or_default();
            let warm_daemon = meta
                .get("warm_daemon")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            Some(KboxlikeImageParts {
                rootfs,
                memory_mib,
                vcpus,
                has_workload,
                user,
                image_env,
                cmd,
                warm_daemon,
                mounts: mounts.clone(),
                volumes: volumes.clone(),
            })
        } else {
            None
        };

        Ok(Self {
            snapshot_path,
            memory_mib,
            vcpus,
            baker_runtime_sha16,
            balloon_target_pages,
            tsi_token,
            egress_policy,
            pre_exec_sync,
            layers,
            delta_squashfs,
            mounts,
            volumes,
            bundled_kernel,
            kvm,
            sentry,
            runsc,
            kboxlike,
            hidden_pool: std::sync::OnceLock::new(),
            warm_baked_worker: Arc::new(crate::bake::WarmStash::new(None)),
            #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
            kvm_pool: std::sync::OnceLock::new(),
        })
    }

    /// Pull and bake an image from a registry reference, returning
    /// the loadable [`Image`]. Equivalent to running
    /// `supermachine run <image_ref> --no-detach` from a Rust app,
    /// minus the daemon — you get the [`Image`] back, then call
    /// [`Vm::start`] yourself.
    ///
    /// Uses [`PullPolicy::Missing`] (cache-first) by default. For
    /// other policies, see [`Image::from_oci_with_policy`].
    ///
    /// ```no_run
    /// # use supermachine::{Image, Vm, VmConfig};
    /// let image = Image::from_oci("nginx:1.27-alpine")?;
    /// let vm = Vm::start(&image, &VmConfig::new())?;
    /// # let _ = vm; Ok::<(), supermachine::Error>(())
    /// ```
    pub fn from_oci(image_ref: &str) -> Result<Self, Error> {
        Self::from_oci_with_policy(image_ref, PullPolicy::default())
    }

    /// As [`Image::from_oci`] but with an explicit [`PullPolicy`].
    /// See [`PullPolicy`] for the cache + registry interaction
    /// table.
    pub fn from_oci_with_policy(image_ref: &str, policy: PullPolicy) -> Result<Self, Error> {
        let snapshots_dir = default_snapshots_dir();
        Self::from_oci_to_dir(image_ref, policy, &snapshots_dir, None)
    }

    /// Most explicit constructor: pull/bake into a specific
    /// snapshots directory, with an optional explicit name.
    /// Lets you keep multiple "supermachine snapshot stores"
    /// (e.g. per-project), or pin a snapshot under a name that
    /// differs from the image-derived default.
    pub fn from_oci_to_dir(
        image_ref: &str,
        policy: PullPolicy,
        snapshots_dir: &Path,
        name: Option<&str>,
    ) -> Result<Self, Error> {
        // 1. Compute where the cached snapshot would live and
        //    short-circuit on hit (Missing) or miss (Never).
        let derived = name
            .map(|s| s.to_owned())
            .unwrap_or_else(|| crate::bake::snapshot_name_for_image(image_ref));
        let snap_dir = snapshots_dir.join(&derived);
        let cache_loadable = Self::from_snapshot(&snap_dir).is_ok();
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        let cache_loadable = {
            let mut cache_loadable = cache_loadable;
            if cache_loadable {
                let expected = linux_default_backend();
                let cached = snap_dir_backend(&snap_dir);
                if cached.as_deref() != Some(expected) {
                    if matches!(policy, PullPolicy::Never) {
                        return Err(Error::cache_invalid(format!(
                            "cached snapshot at {} was baked for backend {:?}, but this Linux \
                             build resolves to backend {expected:?} (PullPolicy::Never won't \
                             auto-rebake)",
                            snap_dir.display(),
                            cached
                        )));
                    }
                    eprintln!(
                        "supermachine: snapshot at {} was baked for backend {:?}; current Linux \
                         backend is {expected:?}. Auto-rebaking.",
                        snap_dir.display(),
                        cached
                    );
                    invalidate_stale_snapshot_tree(&snap_dir);
                    cache_loadable = false;
                }
            }
            cache_loadable
        };
        // Version-skew check for Missing/Always: if the cached
        // snapshot was baked under a different binary version,
        // treat as cache-miss and invalidate so the bake below
        // produces a clean tree. Never auto-rebakes on
        // PullPolicy::Never — the operator opted into "fail
        // rather than re-bake."
        let cache_loadable = if cache_loadable && !matches!(policy, PullPolicy::Never) {
            if let Some(baked) = snap_dir_baked_under_other_version(&snap_dir) {
                let current = env!("CARGO_PKG_VERSION");
                eprintln!(
                    "supermachine: snapshot at {} was baked under v{baked}; \
                     current binaries are v{current}. Auto-rebaking.",
                    snap_dir.display()
                );
                invalidate_stale_snapshot_tree(&snap_dir);
                false
            } else {
                true
            }
        } else {
            cache_loadable
        };

        match policy {
            PullPolicy::Never => {
                if cache_loadable {
                    return Self::from_snapshot(&snap_dir);
                }
                let restore_snap = snap_dir.join("restore.snap");
                if restore_snap.is_file() {
                    return Err(Error::cache_invalid(format!(
                        "snapshot present at {} but not loadable on this binary; \
                         rebake required (PullPolicy::Never won't auto-rebake)",
                        snap_dir.display()
                    )));
                }
                return Err(Error::cache_miss(format!(
                    "no cached snapshot for {image_ref} at {} (PullPolicy::Never)",
                    snap_dir.display()
                )));
            }
            PullPolicy::Missing if cache_loadable => {
                return Self::from_snapshot(&snap_dir);
            }
            // Missing+invalid OR Always: fall through to bake.
            _ => {}
        }

        // 2. Bake (cache-miss path). The two backends bake differently:
        //
        //  - KVM (Linux/x86_64): bake the OCI ref straight into the snapshot dir
        //    via the self-contained KVM pipeline (registry pull → rootfs
        //    squashfs → agent initramfs, kernel/busybox/agent from the bundled
        //    supermachine-kernel). No external worker process.
        //
        //  - HVF (macOS/aarch64): the existing run_push worker pipeline (pull →
        //    squashfs → boot worker once → capture snapshot).
        //
        // Both leave a loadable `"backend":...` snapshot under `snap_dir`, so
        // the cache-hit branch above and Image::from_snapshot are shared.
        //  - Sentry (Linux/x86_64, NO KVM): when hardware virt is unavailable
        //    (nested guest / CI / customer sandbox), bake for the no-virt
        //    process-isolation backend instead, so the image still runs. The
        //    `runsc` is the Linux default for now, because it is the current
        //    green no-KVM parity backend. `SUPERMACHINE_BACKEND`
        //    (`runsc` | `kvm` | `sentry` | `kboxlike`) can still force another
        //    backend for testing or KVM/kboxlike bring-up.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            match linux_default_backend() {
                "runsc" => return Self::bake_runsc_from_ref(image_ref, &snap_dir),
                "sentry" => return Self::bake_sentry_from_ref(image_ref, &snap_dir),
                "kboxlike" => return Self::bake_kboxlike_from_ref(image_ref, &snap_dir),
                "kvm" => return Self::bake_kvm_auto(image_ref, &snap_dir),
                other => {
                    return Err(Error::bake_msg(format!(
                        "unsupported SUPERMACHINE_BACKEND={other:?}; expected runsc, kvm, sentry, kboxlike, or auto"
                    )));
                }
            }
        }

        #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
        {
            let root = repo_root_for_bake()?;
            let request = crate::bake::BakeRequest {
                image: image_ref.to_owned(),
                name: name.map(|s| s.to_owned()),
                runtime: "supermachine".to_owned(),
                guest_port: 80,
                memory_mib: 256,
                vcpus: 1,
                pull_policy: policy.as_bake_str().to_owned(),
                snapshots_dir: snapshots_dir.to_path_buf(),
                cmd_override: None,
                extra_args: Vec::new(),
                platform: "linux/arm64".to_owned(),
            };
            let bake_t0 = std::time::Instant::now();
            crate::bake::run_push(&request, bake_t0, &root)
                .map_err(|e| map_bake_error(&request.image, e))?;

            // 3. Load the freshly-baked snapshot.
            Self::from_snapshot(&snap_dir)
        }
    }

    /// Builder for configurable bakes — env vars, cmd override,
    /// custom memory / port, custom snapshot name.
    ///
    /// ```no_run
    /// # use supermachine::Image;
    /// let image = Image::builder("nginx:1.27-alpine")
    ///     .with_name("nginx-prod")
    ///     .with_memory_mib(512)
    ///     .with_env("FOO", "bar")
    ///     .with_cmd(["nginx", "-g", "daemon off;"])
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    ///
    /// The builder produces a different snapshot for each
    /// configuration — bake-time inputs are part of the snapshot
    /// fingerprint. Reuse a name across configurations and the
    /// previous snapshot is invalidated; pick distinct names if
    /// you need both side-by-side.
    pub fn builder(image_ref: impl Into<String>) -> OciImageBuilder {
        OciImageBuilder::new(image_ref)
    }

    /// Get an [`Image`] for `name`, baking it from `image_ref`
    /// only if a compatible snapshot doesn't already exist.
    ///
    /// This is the right call for app startup. The first run
    /// bakes (one-time cost: the registry pull + snapshot build,
    /// e.g. ~12 s for `rust:1-slim`); subsequent runs see the
    /// cached snapshot and return in microseconds. After a
    /// `cargo update` that bumped the supermachine version, the
    /// cached snapshot's bake-key no longer matches the current
    /// worker binary, and `ensure_baked` rebakes automatically —
    /// no shell scripts, no manual `rm -rf snapshots/`.
    ///
    /// `configure` is a builder closure: chain
    /// [`OciImageBuilder`] methods like `with_memory_mib`,
    /// `with_cmd`, `with_env` to customize the bake. Pass
    /// `|b| b` for defaults.
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use supermachine::{Image, VmConfig};
    ///
    /// // Bake once on first run, reuse forever after — including
    /// // across supermachine version upgrades.
    /// let image = Image::ensure_baked("rust_1_slim", "rust:1-slim", |b| {
    ///     b.with_memory_mib(2048)
    /// })?;
    /// // Configure pool: 5 always-warm, scale to 50 under burst.
    /// let pool = image.pool().min(5).max(50).build()?;
    ///
    /// // Per-task path:
    /// let vm = pool.acquire()?;
    /// vm.write_file("/tmp/main.rs", b"fn main() { println!(\"hi\"); }")?;
    /// let out = vm.exec_builder()
    ///     .argv(["sh", "-c", "rustc /tmp/main.rs -o /tmp/m && /tmp/m"])
    ///     .timeout(Duration::from_secs(30))
    ///     .output()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn ensure_baked<F>(
        name: impl Into<String>,
        image_ref: impl Into<String>,
        configure: F,
    ) -> Result<Image, Error>
    where
        F: FnOnce(OciImageBuilder) -> OciImageBuilder,
    {
        let builder = configure(OciImageBuilder::new(image_ref).with_name(name));
        builder.build()
    }

    /// Path to the snapshot file backing this image.
    pub fn snapshot_path(&self) -> &Path {
        &self.snapshot_path
    }

    /// Memory the snapshot was baked with. [`Vm::start`] uses
    /// this if [`VmConfig::with_memory_mib`] isn't set.
    pub fn memory_mib(&self) -> u32 {
        self.memory_mib
    }

    /// vCPUs the snapshot was baked with.
    pub fn vcpus(&self) -> u32 {
        self.vcpus
    }

    /// Test-only accessor for `balloon_target_pages` — the
    /// integration tests assert the metadata round-trip. Hidden
    /// from rustdoc; not part of the stable surface.
    #[doc(hidden)]
    pub fn balloon_target_pages_for_test(&self) -> Option<u32> {
        self.balloon_target_pages
    }

    /// Start a one-shot microVM from this image. Equivalent to
    /// [`Vm::start(self, config)`][Vm::start] but reads more
    /// naturally at the call site:
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// let image = Image::from_snapshot("path/to/snapshot")?;
    /// let vm = image.start(&VmConfig::new())?;
    /// // ... use vm ...
    /// vm.stop()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    ///
    /// Use [`Image::acquire`] instead if you want a `PooledVm`
    /// that returns to a (hidden) pool on `Drop` for cheaper
    /// reuse — typical for evaluation harnesses, CI verifiers,
    /// or any code that runs many short-lived VMs of the same
    /// image back-to-back.
    #[cfg(any(
        all(target_os = "macos", target_arch = "aarch64"),
        all(target_os = "linux", target_arch = "x86_64")
    ))]
    pub fn start(&self, config: &VmConfig) -> Result<Vm, Error> {
        Vm::start(self, config)
    }

    /// Bake a KVM-bootable [`Image`] from OCI layer tarballs (Linux/x86_64).
    ///
    /// Merges `layer_tars` (bottom-up, OCI whiteouts applied) into one rootfs
    /// squashfs attached as `/dev/vda`, and writes a `"backend":"kvm"` snapshot
    /// dir under `dest_dir` referencing `kernel` (bzImage) and `agent_initrd`
    /// (the PID-1 exec agent). The result loads + runs via [`Image::start`] /
    /// [`Image::acquire`].
    ///
    /// Remaining KVM-bake pieces (not yet automated here): OCI-ref → layer tars
    /// (registry pull / `docker save` extraction) and a self-contained agent
    /// initramfs. This consumes already-materialized layer tars + a prebuilt
    /// agent initramfs.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kvm(
        layer_tars: &[PathBuf],
        kernel: &Path,
        agent_initrd: &Path,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        Self::bake_kvm_with_workload(layer_tars, kernel, agent_initrd, None, dest_dir)
    }

    /// Like [`bake_kvm`](Image::bake_kvm) but also bakes the OCI workload-launch
    /// script (`Entrypoint`/`Cmd`/`Env`/`WorkingDir` → `sh`) into the rootfs at
    /// `/.supermachine/run-workload`, so the guest starts the image's command
    /// (nginx, a server, …) and not just the agent. `bake_kvm_from_ref` derives
    /// the script from the pulled image config; `bake_kvm` passes `None` (the
    /// agent-only path, for prebuilt layer tars with no resolvable config).
    pub fn bake_kvm_with_workload(
        layer_tars: &[PathBuf],
        kernel: &Path,
        agent_initrd: &Path,
        workload_script: Option<&str>,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        let dest = dest_dir.into();
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let rootfs = dest.join("rootfs.squashfs");
        let stage = dest.join("rootfs-stage");
        crate::bake::build_kvm_rootfs_squashfs(layer_tars, &stage, &rootfs, workload_script)
            .map_err(Error::bake_msg)?;
        let _ = std::fs::remove_dir_all(&stage);
        // Physical footprint (rootfs + kernel + initrd) so `supermachine images`
        // can show a SIZE without a separate HVF-style `snapshot_physical_bytes`
        // probe; `baked_at` (RFC3339) matches the HVF metadata so `images` sorts
        // newest-first across backends.
        let phys = std::fs::metadata(&rootfs).map(|m| m.len()).unwrap_or(0)
            + std::fs::metadata(kernel).map(|m| m.len()).unwrap_or(0)
            + std::fs::metadata(agent_initrd)
                .map(|m| m.len())
                .unwrap_or(0);
        let metadata = serde_json::json!({
            "backend": "kvm",
            "kvm_kernel": kernel.to_string_lossy(),
            "kvm_initrd": agent_initrd.to_string_lossy(),
            "kvm_disk": rootfs.to_string_lossy(),
            "memory_mib": 512,
            "vcpus": 1,
            // Bake-time balloon inflation target (~75% of memory in 4 KiB pages),
            // so a restored KVM VM auto-inflates idle RAM like HVF.
            "balloon_target_pages": crate::bake::compute_balloon_target_pages(512),
            "baked_at": chrono_rfc3339_now(),
            "snapshot_physical_bytes": phys,
        });
        std::fs::write(
            dest.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::bake_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        Image::from_snapshot(&dest)
    }

    /// Bake a KVM-bootable [`Image`] directly from an OCI image reference
    /// (Linux/x86_64) — e.g. `"alpine:3.20"` or `"docker.io/library/busybox"`.
    ///
    /// Pulls the image (registry-direct by default — no Docker daemon; honors
    /// `SUPERMACHINE_IMAGE_SOURCE` + `oci-layout:` / `oci-archive:` refs),
    /// resolves its amd64 layers, and delegates to [`Image::bake_kvm`]. Still
    /// takes a prebuilt `agent_initrd` (the self-contained agent cpio is the
    /// remaining bake piece).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kvm_from_ref(
        image_ref: &str,
        kernel: &Path,
        agent_initrd: &Path,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        let dest = dest_dir.into();
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let pull_work = dest.join("oci-pull");
        let t_pull = std::time::Instant::now();
        let (layers, workload, oci_config) =
            crate::bake::pull_oci_layers(image_ref, "amd64", &pull_work)
                .map_err(Error::bake_msg)?;
        let pull_ms = t_pull.elapsed().as_millis();
        let t_build = std::time::Instant::now();
        let img = Self::bake_kvm_with_workload(
            &layers,
            kernel,
            agent_initrd,
            workload.as_deref(),
            dest.clone(),
        )?;
        if crate::trace::enabled("run") {
            eprintln!(
                "supermachine: kvm bake phases pull_oci_ms={} build_rootfs_ms={}",
                pull_ms,
                t_build.elapsed().as_millis()
            );
        }
        // Record the original image ref into metadata.json so `supermachine images`
        // shows the IMAGE column (the bake itself only knows resolved layers) —
        // plus the image's RUNTIME CONFIG. The HVF bake persists the config;
        // the KVM bake silently didn't, so anything reading it back from a
        // cached snapshot got nothing: the in-VM builder's FROM-base env
        // inheritance (builder #7) was a no-op on linux while working on HVF
        // (caught by integration_builder_base_env on the box), and the #122
        // version gate stayed permissive forever for KVM bakes (no
        // baked_by_version stamp).
        let meta_path = dest.join("metadata.json");
        if let Ok(text) = std::fs::read_to_string(&meta_path) {
            if let Ok(mut json) = serde_json::from_str::<serde_json::Value>(&text) {
                if let Some(obj) = json.as_object_mut() {
                    obj.insert("image".to_string(), serde_json::json!(image_ref));
                    obj.insert(
                        "baked_by_version".to_string(),
                        serde_json::json!(env!("CARGO_PKG_VERSION")),
                    );
                    if let Some(cfg) = &oci_config {
                        // Env arrives as OCI ["K=V", …]; persist as the same
                        // `image_env` object shape the HVF bake records (what
                        // builder::base_image_env reads).
                        let mut env_obj = serde_json::Map::new();
                        for kv in cfg
                            .get("Env")
                            .and_then(|v| v.as_array())
                            .into_iter()
                            .flatten()
                            .filter_map(|v| v.as_str())
                        {
                            if let Some(eq) = kv.find('=') {
                                env_obj
                                    .insert(kv[..eq].to_string(), serde_json::json!(&kv[eq + 1..]));
                            }
                        }
                        obj.insert("image_env".to_string(), serde_json::Value::Object(env_obj));
                        for (oci_key, meta_key) in [
                            ("Cmd", "cmd"),
                            ("Entrypoint", "entrypoint"),
                            ("WorkingDir", "working_dir"),
                            ("User", "user"),
                        ] {
                            if let Some(v) = cfg.get(oci_key) {
                                if !v.is_null() {
                                    obj.insert(meta_key.to_string(), v.clone());
                                }
                            }
                        }
                    }
                    if let Ok(pretty) = serde_json::to_string_pretty(&json) {
                        let _ = std::fs::write(&meta_path, pretty);
                    }
                }
            }
        }
        Ok(img)
    }

    /// Bake a [`Image`] for the **sentry** backend directly from an OCI image
    /// reference (Linux/x86_64) — the no-virt path, for hosts where
    /// [`Vm::kvm_usable`] is false (nested guests, CI, customer sandboxes).
    ///
    /// Pulls the image (same registry-direct puller as [`bake_kvm_from_ref`]),
    /// merges its amd64 layers into an extracted rootfs DIRECTORY under
    /// `dest_dir/rootfs` (no kernel, no squashfs — the sentry serves files from
    /// the dir), bakes the OCI workload-launch script into it, and writes a
    /// `"backend":"sentry"` `metadata.json`. Run the result with
    /// [`Image::run_sentry`].
    ///
    /// This is the no-config entry point (the image's own Entrypoint/Cmd/Env);
    /// the [`OciImageBuilder`] routes through [`Self::bake_sentry_with_config`]
    /// to apply `with_cmd` / `with_env` / `with_extra_file` / `with_mount` /
    /// `with_volume` / `with_warmup`.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_sentry_from_ref(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        Self::bake_sentry_with_config(image_ref, dest_dir, SentryBakeConfig::default())
    }

    /// Bake a [`Image`] for the experimental **runsc** backend directly from an
    /// OCI image reference (Linux/x86_64). This intentionally shares the OCI
    /// extraction/rootfs materialization path with sentry, but publishes
    /// `"backend":"runsc"` metadata so the runtime dispatch can be implemented
    /// independently around gVisor/runsc checkpoint/restore.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_runsc_from_ref(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        Self::bake_runsc_with_config(image_ref, dest_dir, SentryBakeConfig::default())
    }

    /// Bake an [`Image`] for the experimental native **kboxlike** backend
    /// directly from an OCI image reference (Linux/x86_64). This is a metadata
    /// and rootfs materialization step only; runtime/warmup support lands with
    /// the native execution layer.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kboxlike_from_ref(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        Self::bake_kboxlike_with_config(image_ref, dest_dir, SentryBakeConfig::default())
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_runsc_with_config(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
        mut config: SentryBakeConfig,
    ) -> Result<Image, Error> {
        let runsc_bake_key = sentry_bake_cache_key(image_ref, &config)?;
        let warmup = config.warmup.take();
        // The sentry rootfs materialization step is reused only to produce the
        // extracted filesystem and metadata. runsc warmup is handled below as a
        // real runsc checkpoint so live daemons/process state survive.
        config.warmup = None;
        let dest = dest_dir.into();
        let _ = Self::bake_sentry_with_config(image_ref, &dest, config)?;
        let meta_path = dest.join("metadata.json");
        let meta_text = std::fs::read_to_string(&meta_path)
            .map_err(|e| Error::bake_msg(format!("read {}: {e}", meta_path.display())))?;
        let mut meta: serde_json::Value = serde_json::from_str(&meta_text)
            .map_err(|e| Error::bake_msg(format!("parse {}: {e}", meta_path.display())))?;
        if let Some(obj) = meta.as_object_mut() {
            obj.insert("backend".to_owned(), serde_json::json!("runsc"));
            if let Some(rootfs) = obj.remove("sentry_rootfs") {
                obj.insert("runsc_rootfs".to_owned(), rootfs);
            }
            if let Some(has_workload) = obj.remove("sentry_has_workload") {
                obj.insert("runsc_has_workload".to_owned(), has_workload);
            }
            if let Some(key) = obj.get("sentry_bake_key").cloned() {
                obj.insert("runsc_bake_key".to_owned(), key);
            }
            obj.insert(
                "runsc_bake_key".to_owned(),
                serde_json::json!(runsc_bake_key),
            );
        }
        let rootfs = meta
            .get("runsc_rootfs")
            .and_then(|v| v.as_str())
            .map(PathBuf::from)
            .ok_or_else(|| Error::bake_msg("runsc metadata missing runsc_rootfs".to_owned()))?;
        let agent_path = rootfs.join(".supermachine/supermachine-agent");
        if let Some(parent) = agent_path.parent() {
            std::fs::create_dir_all(parent).map_err(Error::Io)?;
        }
        if let Some(agent_override) = std::env::var_os("SUPERMACHINE_RUNSC_AGENT_PATH")
            .or_else(|| std::env::var_os("SUPERMACHINE_X86_AGENT_PATH"))
        {
            std::fs::copy(&agent_override, &agent_path).map_err(|e| {
                Error::bake_msg(format!(
                    "stage runsc agent {} -> {}: {e}",
                    PathBuf::from(agent_override).display(),
                    agent_path.display()
                ))
            })?;
            set_executable(&agent_path).map_err(Error::Io)?;
        } else {
            supermachine_kernel::extract_supermachine_agent_to(&agent_path).map_err(Error::Io)?;
        }
        if let Some(obj) = meta.as_object_mut() {
            obj.insert(
                "runsc_agent_path".to_owned(),
                serde_json::json!("/.supermachine/supermachine-agent"),
            );
            obj.insert(
                "runsc_agent_unix_env".to_owned(),
                serde_json::json!("SUPERMACHINE_AGENT_UNIX_SOCKET"),
            );
        }
        let meta_out = serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::bake_msg(format!("runsc metadata serialize: {e}")))?;
        std::fs::write(&meta_path, meta_out).map_err(Error::Io)?;
        if let Some(warmup) = warmup {
            let image = Image::from_snapshot(&dest)?;
            runsc_warmup_checkpoint(&image, &dest, warmup)?;
        }
        Image::from_snapshot(&dest)
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kboxlike_with_config(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
        config: SentryBakeConfig,
    ) -> Result<Image, Error> {
        let kboxlike_bake_key = sentry_bake_cache_key(image_ref, &config)?;
        if config.warm_daemon {
            return Err(Error::bake_msg(
                "kboxlike warm-daemon images are not implemented yet; use runsc or kvm".to_owned(),
            ));
        }
        let dest = dest_dir.into();
        let _ = Self::bake_sentry_with_config(image_ref, &dest, config)?;
        let meta_path = dest.join("metadata.json");
        let meta_text = std::fs::read_to_string(&meta_path)
            .map_err(|e| Error::bake_msg(format!("read {}: {e}", meta_path.display())))?;
        let mut meta: serde_json::Value = serde_json::from_str(&meta_text)
            .map_err(|e| Error::bake_msg(format!("parse {}: {e}", meta_path.display())))?;
        if let Some(obj) = meta.as_object_mut() {
            obj.insert("backend".to_owned(), serde_json::json!("kboxlike"));
            if let Some(rootfs) = obj.remove("sentry_rootfs") {
                obj.insert("kboxlike_rootfs".to_owned(), rootfs);
            }
            if let Some(has_workload) = obj.remove("sentry_has_workload") {
                obj.insert("kboxlike_has_workload".to_owned(), has_workload);
            }
            obj.insert(
                "kboxlike_bake_key".to_owned(),
                serde_json::json!(kboxlike_bake_key),
            );
        }
        let meta_out = serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::bake_msg(format!("kboxlike metadata serialize: {e}")))?;
        std::fs::write(&meta_path, meta_out).map_err(Error::Io)?;
        let restore_snap = dest.join("restore.snap");
        if !restore_snap.is_file() {
            std::fs::write(&restore_snap, b"kboxlike-rootfs\n").map_err(Error::Io)?;
        }
        Image::from_snapshot(&dest)
    }

    /// Bake a sentry image applying an [`OciImageBuilder`]'s run-config
    /// (Linux/x86_64). The config-aware counterpart of
    /// [`Self::bake_sentry_from_ref`] — the builder's `cmd` / `env` /
    /// `working_dir` / `user` / `extra_files` / `mounts` / `volumes` / `warmup`
    /// are mapped into the baked rootfs + metadata, mirroring what the KVM/HVF
    /// bakes do for their backends:
    ///
    ///   - **cmd/env/working_dir** override the `/.supermachine/run-workload`
    ///     script (env merged OVER the image Env) AND the recorded metadata
    ///     `cmd`/`entrypoint`/`image_env`/`working_dir`/`user`.
    ///   - **extra_files** are written into the rootfs at bake time, confined
    ///     (their guest paths are joined under the rootfs, `..`/absolute
    ///     escapes rejected).
    ///   - **mounts/volumes** are persisted in `metadata.json` (the sentry has
    ///     no KVM-volume tail; this is how the mapping survives a reload).
    ///   - **warmup** is run after the rootfs is built, against a transient
    ///     sentry [`Vm`] over the freshly-baked image — its filesystem writes
    ///     land IN-PLACE in the rootfs (the artifact), so the warm state is
    ///     captured without an extra snapshot.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_sentry_with_config(
        image_ref: &str,
        dest_dir: impl Into<PathBuf>,
        config: SentryBakeConfig,
    ) -> Result<Image, Error> {
        let dest = dest_dir.into();
        let sentry_bake_key = sentry_bake_cache_key(image_ref, &config)?;
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let pull_work = dest.join("oci-pull");
        let (layers, image_workload, oci_config) =
            crate::bake::pull_oci_layers(image_ref, "amd64", &pull_work)
                .map_err(Error::bake_msg)?;

        // Effective env = image Env merged UNDER the builder's env (builder
        // wins on a key collision), recorded as the `image_env` object the
        // KVM/HVF bakes use and exported by the workload script.
        let mut env_pairs: Vec<(String, String)> = Vec::new();
        if let Some(cfg) = &oci_config {
            for kv in cfg
                .get("Env")
                .and_then(|v| v.as_array())
                .into_iter()
                .flatten()
                .filter_map(|v| v.as_str())
            {
                if let Some(eq) = kv.find('=') {
                    env_pairs.push((kv[..eq].to_string(), kv[eq + 1..].to_string()));
                }
            }
        }
        for (k, v) in &config.env {
            // Builder override: drop any earlier (image) value for this key,
            // then append so the builder's value wins and dedups.
            env_pairs.retain(|(ek, _)| ek != k);
            env_pairs.push((k.clone(), v.clone()));
        }

        // Effective workdir/user: builder override, else image config.
        let image_workdir = oci_config
            .as_ref()
            .and_then(|c| c.get("WorkingDir"))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());
        let effective_workdir = config
            .working_dir
            .clone()
            .filter(|s| !s.is_empty())
            .or(image_workdir);
        let image_user = oci_config
            .as_ref()
            .and_then(|c| c.get("User"))
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());
        let effective_user = config.user.clone().filter(|s| !s.is_empty()).or(image_user);

        // Effective workload script. When the builder overrides cmd (or env, in
        // which case the exported env must change), render the script from the
        // explicit argv + merged env + workdir; otherwise reuse the image's own
        // script from `pull_oci_layers`.
        let workload: Option<String> = if let Some(cmd) = &config.cmd {
            crate::bake::sentry_workload_script(cmd, &env_pairs, effective_workdir.as_deref())
        } else if !config.env.is_empty() || effective_workdir.is_some() {
            // No cmd override, but env/workdir changed: rebuild from the image's
            // own argv (Entrypoint ++ Cmd) so the new env/workdir take effect.
            let mut argv: Vec<String> = Vec::new();
            if let Some(cfg) = &oci_config {
                for v in cfg
                    .get("Entrypoint")
                    .and_then(|v| v.as_array())
                    .into_iter()
                    .flatten()
                    .filter_map(|v| v.as_str())
                {
                    argv.push(v.to_string());
                }
                for v in cfg
                    .get("Cmd")
                    .and_then(|v| v.as_array())
                    .into_iter()
                    .flatten()
                    .filter_map(|v| v.as_str())
                {
                    argv.push(v.to_string());
                }
            }
            if argv.is_empty() {
                // Image declared no command; keep the image's script (None).
                image_workload.clone()
            } else {
                crate::bake::sentry_workload_script(&argv, &env_pairs, effective_workdir.as_deref())
            }
        } else {
            image_workload.clone()
        };

        let rootfs = dest.join("rootfs");
        crate::bake::build_sentry_rootfs(&layers, &rootfs, workload.as_deref())
            .map_err(Error::bake_msg)?;
        // The rootfs dir IS the artifact; the OCI pull scratch isn't needed.
        let _ = std::fs::remove_dir_all(&pull_work);

        // Stage extra files into the rootfs, CONFINED: each guest path is joined
        // under the rootfs (rejecting absolute / `..` escapes), parent dirs are
        // created, and the host file is copied in. This is the sentry analogue
        // of the KVM bake's `--extra-file` delta-layer staging.
        for (host, guest) in &config.extra_files {
            let rel = guest.trim_start_matches('/');
            let target = confined_rootfs_join(&rootfs, rel).ok_or_else(|| {
                Error::bake_msg(format!(
                    "extra-file guest path escapes the rootfs: {guest:?}"
                ))
            })?;
            if let Some(parent) = target.parent() {
                std::fs::create_dir_all(parent).map_err(Error::Io)?;
            }
            std::fs::copy(host, &target).map_err(|e| {
                Error::bake_msg(format!(
                    "stage extra-file {} -> {}: {e}",
                    host.display(),
                    target.display()
                ))
            })?;
        }

        let phys = dir_size_bytes(&rootfs);
        let mut metadata = serde_json::json!({
            "backend": "sentry",
            "sentry_rootfs": rootfs.to_string_lossy(),
            "sentry_has_workload": workload.is_some(),
            "memory_mib": config.memory_mib.unwrap_or(512),
            "vcpus": config.vcpus.unwrap_or(1),
            "image": image_ref,
            "sentry_bake_key": sentry_bake_key,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
            "baked_at": chrono_rfc3339_now(),
            "snapshot_physical_bytes": phys,
        });
        // Persist the EFFECTIVE runtime config (Env/Cmd/Entrypoint/WorkingDir/
        // User) in the same shape the KVM/HVF bakes record, so the in-VM
        // builder's FROM-base env inheritance + `supermachine images` see it.
        // The builder's overrides win over the image's recorded config.
        if let Some(obj) = metadata.as_object_mut() {
            let mut env_obj = serde_json::Map::new();
            for (k, v) in &env_pairs {
                env_obj.insert(k.clone(), serde_json::json!(v));
            }
            obj.insert("image_env".to_string(), serde_json::Value::Object(env_obj));
            // Record argv: a builder cmd override goes in `cmd` (entrypoint
            // cleared so cmd is authoritative); otherwise carry the image's
            // recorded Cmd/Entrypoint forward.
            if let Some(cmd) = &config.cmd {
                obj.insert("cmd".to_string(), serde_json::json!(cmd));
                obj.remove("entrypoint");
            } else if let Some(cfg) = &oci_config {
                for (oci_key, meta_key) in [("Cmd", "cmd"), ("Entrypoint", "entrypoint")] {
                    if let Some(v) = cfg.get(oci_key) {
                        if !v.is_null() {
                            obj.insert(meta_key.to_string(), v.clone());
                        }
                    }
                }
            }
            if let Some(dir) = &effective_workdir {
                obj.insert("working_dir".to_string(), serde_json::json!(dir));
            }
            if let Some(user) = &effective_user {
                obj.insert("user".to_string(), serde_json::json!(user));
            }
            // Warm-daemon pool intent + warmup tag (round-trip parity with KVM/HVF;
            // the sentry path previously dropped warmup_tag). `warm_daemon` is ALWAYS
            // written so the reader's default (false) and the persisted value agree;
            // `warmup_tag` is omitted when None (reader defaults None). The daemon
            // argv itself rides the `cmd`/`entrypoint` keys written above.
            obj.insert(
                "warm_daemon".to_string(),
                serde_json::json!(config.warm_daemon),
            );
            if let Some(tag) = &config.warmup_tag {
                obj.insert("warmup_tag".to_string(), serde_json::json!(tag));
            }
        }
        // Persist mounts/volumes so a reload re-attaches them (the sentry has no
        // KVM persist_kvm_builder_volumes tail). Shapes match what
        // `Image::from_snapshot` parses (mounts: {host_path, guest_tag,
        // guest_path[, symlinks]}; volumes: {host_file, guest_path, size_bytes}).
        if let Some(obj) = metadata.as_object_mut() {
            if !config.mounts.is_empty() {
                let arr: Vec<serde_json::Value> = config
                    .mounts
                    .iter()
                    .map(|(host, tag, policy, guest_path)| {
                        let mut m = serde_json::Map::new();
                        m.insert(
                            "host_path".to_string(),
                            serde_json::json!(host.to_string_lossy()),
                        );
                        m.insert("guest_tag".to_string(), serde_json::json!(tag));
                        m.insert("guest_path".to_string(), serde_json::json!(guest_path));
                        // Opaque is the default the parser assumes; only record a
                        // non-default policy (matches the HVF `--mount` encoding).
                        match policy {
                            crate::vmm::resources::SymlinkPolicy::Opaque => {}
                            crate::vmm::resources::SymlinkPolicy::Deny => {
                                m.insert("symlinks".to_string(), serde_json::json!("deny"));
                            }
                            crate::vmm::resources::SymlinkPolicy::Follow => {
                                m.insert("symlinks".to_string(), serde_json::json!("follow"));
                            }
                        }
                        serde_json::Value::Object(m)
                    })
                    .collect();
                obj.insert("mounts".to_string(), serde_json::json!(arr));
            }
            if !config.volumes.is_empty() {
                let arr: Vec<serde_json::Value> = config
                    .volumes
                    .iter()
                    .map(|(host, guest, size)| {
                        serde_json::json!({
                            "host_file": host.to_string_lossy(),
                            "guest_path": guest,
                            "size_bytes": size,
                        })
                    })
                    .collect();
                obj.insert("volumes".to_string(), serde_json::json!(arr));
            }
        }
        // Atomic publish (a peer's from_snapshot / verify cell may read `dest`
        // concurrently — see persist_run_config). Unique tmp (threads share pid)
        // then rename(2) so the live file is never observed half-written.
        {
            static SENTRY_META_TMP_SEQ: std::sync::atomic::AtomicU64 =
                std::sync::atomic::AtomicU64::new(0);
            let meta_out = serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::bake_msg(format!("metadata serialize: {e}")))?;
            let seq = SENTRY_META_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let tmp = dest.join(format!(".metadata.json.tmp.{}.{seq}", std::process::id()));
            std::fs::write(&tmp, meta_out).map_err(Error::Io)?;
            if let Err(e) = std::fs::rename(&tmp, dest.join("metadata.json")) {
                let _ = std::fs::remove_file(&tmp);
                return Err(Error::Io(e));
            }
        }

        // Warmup: start a transient sentry supervisor over the freshly-baked image
        // and run the warmup closure against it. The cells share the rootfs DIR,
        // so filesystem writes land in-place. Unlike the old filesystem-only
        // path, preserve background children during this bake-time warmup and C4
        // capture them into `restore.snap`/`mem.blob`, matching KVM/HVF warmups
        // that leave live daemons/listeners ready at restore time.
        let img = Image::from_snapshot(&dest)?;
        if let Some(warmup) = config.warmup {
            let parts = img
                .sentry
                .as_ref()
                .ok_or_else(|| Error::vm_msg("sentry warmup image missing sentry metadata"))?;
            let warm_sock = std::env::temp_dir().join(format!(
                ".supermachine-sentry-warmup-{}-{}.sock",
                std::process::id(),
                unique_suffix()
            ));
            let sandbox = img
                .sentry_sandbox_with(&VmConfig::new())
                .map_err(|e| Error::vm_msg(format!("sentry warmup sandbox: {e}")))?
                .without_netns()
                .with_preserve_stragglers(true);
            let pool = sandbox
                .pool_with_exec(warm_sock.clone())
                .map_err(|e| Error::vm_msg(format!("sentry warmup pool: {e}")))?;
            let deadline = std::time::Instant::now() + Duration::from_secs(15);
            while !warm_sock.exists() {
                if std::time::Instant::now() >= deadline {
                    pool.stop();
                    return Err(Error::vm_msg(
                        "sentry warmup exec socket never appeared (supervisor bind failed)",
                    ));
                }
                std::thread::sleep(Duration::from_millis(5));
            }
            if parts.has_workload && parts.rootfs.join(".supermachine/run-workload").is_file() {
                let wrapped = vec![
                    "/.supermachine/sm-checkpoint".to_string(),
                    "/bin/sh".to_string(),
                    "/.supermachine/run-workload".to_string(),
                ];
                if pool.warm(wrapped.iter().cloned()).is_ok() {
                    if let Ok(wpid) = pool.acquire_running() {
                        let run_dir = parts.rootfs.join("run");
                        let _ = std::fs::create_dir_all(&run_dir);
                        let _ = std::fs::write(
                            run_dir.join("supermachine-workload.pid"),
                            format!("{wpid}\n"),
                        );
                    }
                }
            }
            let pool = Arc::new(pool);
            let vm = Vm {
                running: None,
                sentry_exec: None,
                sentry_src_rootfs: Some(parts.rootfs.clone()),
                vsock_mux_path: warm_sock.clone(),
                vsock_exec_path: warm_sock,
                own_vsock_mux_dir: None,
                skip_cleanup: false,
                time_sync_stop: Arc::new(AtomicBool::new(false)),
                _sentry_mem_admission: None,
                sentry_warm_pool: None,
                sentry_unified_pool: Some(Arc::clone(&pool)),
                runsc: None,
                kboxlike: None,
            };
            let res = warmup(&vm);
            let snap_res = if res.is_ok() {
                match pool.snapshot(&dest) {
                    Ok(()) => Ok(()),
                    Err(e) if e.raw_os_error() == Some(libc::EINVAL) => Ok(()),
                    Err(e) => Err(Error::vm_msg(format!("sentry warmup C4 snapshot: {e}"))),
                }
            } else {
                Ok(())
            };
            let _ = vm.stop();
            res?;
            snap_res?;
            // Re-load so the returned Image reflects warm filesystem and any C4
            // live-state sidecars (and re-validates the rootfs is intact).
            return Image::from_snapshot(&dest);
        }
        Ok(img)
    }

    /// Run this sentry image's baked workload to completion, confined to its
    /// rootfs, and return the workload's exit code (Linux/x86_64).
    ///
    /// This is the no-virt counterpart of cold-booting a KVM image: it launches
    /// the image's Entrypoint/Cmd (via the rootfs's `/bin/sh` running the baked
    /// `/.supermachine/run-workload` script, which exports the image Env and
    /// `cd`s into WorkingDir) under [`crate::sentry::run`]. Blocks until the
    /// workload exits — the sentry has no long-lived exec channel yet (live
    /// `exec`/`expose_tcp` into a running sentry workload is a later milestone),
    /// so this is the current run surface, not [`Vm::start`].
    ///
    /// Errors if the image isn't a sentry image. If the image declares no
    /// command (`has_workload == false`), returns `Ok(0)` — nothing to launch.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn run_sentry(&self) -> Result<i32, Error> {
        let parts = self.sentry.as_ref().ok_or_else(|| {
            Error::vm_msg(
                "Image is not a sentry image (metadata.json needs \"backend\":\"sentry\"); \
                 bake with Image::bake_sentry_from_ref."
                    .to_owned(),
            )
        })?;
        if !parts.has_workload {
            return Ok(0);
        }
        // `/bin/sh` runs the baked script; its `#!/.supermachine/busybox sh`
        // first line is an ordinary comment to /bin/sh, so the same script the
        // KVM bake stages works unchanged. The script sets the image Env + cwd
        // and execs the workload. PATH resolution + env are the shell's job.
        crate::sentry::run(
            std::path::Path::new("/bin/sh"),
            &["/.supermachine/run-workload".to_string()],
            Some(&parts.rootfs),
        )
        .map_err(|e| Error::vm_msg(format!("sentry run: {e}")))
    }

    /// As [`run_sentry`](Image::run_sentry), but also returns the structured
    /// [`SentryError`](crate::sentry::SentryError) reason when the workload ended
    /// other than a plain exit — so a caller can tell a **sandbox-policy kill**
    /// (e.g. a forbidden-syscall `SeccompViolation`, which would otherwise just be
    /// an ambiguous exit `159`) apart from the workload's own non-zero status. The
    /// integer code is identical to [`run_sentry`](Image::run_sentry).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn run_sentry_classified(
        &self,
    ) -> Result<(i32, Option<crate::sentry::SentryError>), Error> {
        let parts = self.sentry.as_ref().ok_or_else(|| {
            Error::vm_msg(
                "Image is not a sentry image (metadata.json needs \"backend\":\"sentry\"); \
                 bake with Image::bake_sentry_from_ref."
                    .to_owned(),
            )
        })?;
        if !parts.has_workload {
            return Ok((0, None));
        }
        crate::sentry::run_classified(
            std::path::Path::new("/bin/sh"),
            &["/.supermachine/run-workload".to_string()],
            Some(&parts.rootfs),
        )
        .map_err(|e| Error::vm_msg(format!("sentry run: {e}")))
    }

    /// Open a handle-based [`Sandbox`](crate::sentry::Sandbox) on this sentry
    /// image's rootfs (Linux/x86_64). Unlike [`run_sentry`](Image::run_sentry)
    /// (which runs the workload to completion), a `Sandbox` lets the image's
    /// workload run in the background ([`start_workload`](crate::sentry::Sandbox::start_workload))
    /// while you [`exec`](crate::sentry::Sandbox::exec) additional confined
    /// commands against the same rootfs — the no-virt analogue of `docker exec`
    /// (filesystem-shared; PID/net-namespace sharing is the later M5 work).
    ///
    /// Errors if the image isn't a sentry image.
    ///
    /// This is the no-config entry point: it builds the sandbox with the image's
    /// own baked defaults (memory/vCPU-derived caps, a default `pids.max`, the
    /// baked `User` uid-drop, the baked `Env`, the recorded egress policy). To
    /// override the caps from a [`VmConfig`] (e.g. a smaller memory cap, a
    /// different pids cap, or an uncapped run), use
    /// [`sentry_sandbox_with`](Image::sentry_sandbox_with).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn sentry_sandbox(&self) -> Result<crate::sentry::Sandbox, Error> {
        self.sentry_sandbox_with(&VmConfig::new())
    }

    /// Build a fully-configured [`Sandbox`](crate::sentry::Sandbox) on this sentry
    /// image's rootfs, applying BOTH the image's baked metadata AND `config`
    /// (Linux/x86_64). This is the ONE place that builds + configures the sandbox
    /// for the whole sentry surface (`Vm::start`'s sentry path, the pool, the
    /// handle API), so a single tenant's guest is host-safe by default:
    ///
    /// - **memory** — `cgroup-v2 memory.max` = `config.with_memory_mib` if set,
    ///   else the image's baked `memory_mib` (MiB → bytes). Over-budget guest
    ///   trees are OOM-killed; the host + neighbors are protected.
    /// - **CPU** — `cgroup-v2 cpu.max` = `vcpus * 100ms` per `100ms`
    ///   (`config.with_vcpus` if set, else the image's baked `vcpus`), i.e. that
    ///   many cores' worth of CPU.
    /// - **pids** — `cgroup-v2 pids.max` = `config.with_sentry_pids_max` if set,
    ///   else `SENTRY_DEFAULT_PIDS_MAX` (fork-bomb protection).
    /// - **uid-drop** — the baked image `User` (numeric `uid`/`uid:gid`) drops the
    ///   guest cell to that unprivileged host uid/gid before sealing.
    /// - **env** — the baked image `Env` seeds every cell (the per-`exec` env
    ///   overlays it).
    /// - **egress** — the recorded `egress_policy` is enforced on every outbound
    ///   TCP.
    ///
    /// [`with_sentry_uncapped`](VmConfig::with_sentry_uncapped) disables the three
    /// cgroup caps (trusted single-tenant tooling only). Errors if the image isn't
    /// a sentry image.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn sentry_sandbox_with(&self, config: &VmConfig) -> Result<crate::sentry::Sandbox, Error> {
        let parts = self.sentry.as_ref().ok_or_else(|| {
            Error::vm_msg(
                "Image is not a sentry image (metadata.json needs \"backend\":\"sentry\"); \
                 bake with Image::bake_sentry_from_ref."
                    .to_owned(),
            )
        })?;
        let mut sandbox = crate::sentry::Sandbox::new(parts.rootfs.clone());
        // Honor the image's recorded egress policy (metadata.json["egress_policy"],
        // e.g. deny_private) — the supervisor enforces it on every outbound TCP.
        if let Some(policy) = &self.egress_policy {
            sandbox = sandbox.with_egress(policy.clone());
        }
        // Drop the guest cell to an unprivileged host uid/gid — defense in depth, and
        // the CROSS-TENANT barrier: distinct uids per tenant make the kernel deny
        // every cross-tenant process_vm / ptrace / signal / same-uid file access, so
        // one tenant's cell cannot reach another's even at the same supervisor uid.
        // `config.sentry_uid` (per-INSTANCE, set by the orchestration to a UNIQUE uid
        // per tenant) overrides the image's baked `User`; falling back to the baked
        // User, then to no drop (the sentry's own uid). A username / root / empty
        // image User was already filtered to None by parse_numeric_user.
        if let Some((uid, gid)) = config.sentry_uid.or(parts.user) {
            sandbox = sandbox.with_uid(uid, gid);
        }
        // Seed the baked image Env as the exec env base (the per-request env
        // overlays it), and inherit host proxy/CA knobs when the image did not
        // already define them. Dockerfile RUN layers for kboxlike currently use
        // sentry as the mature layer executor, so this keeps build-step HTTPS
        // behavior aligned with kboxlike runtime guests under MITM proxies.
        let mut image_env = parts.image_env.clone();
        crate::kboxlike::merge_host_proxy_env_if_absent(&mut image_env);
        // Skip when empty so the sentry's built-in PATH/PWD/LANG fallback still
        // applies.
        if !image_env.is_empty() {
            sandbox = sandbox.with_env(image_env);
        }
        // Baked virtio-fs mounts persisted in image metadata. The KVM/HVF restore
        // path replays these into the worker; sentry has no virtio-fs device, so
        // attach them as the same confined bind mounts used for per-run config.
        for m in &self.mounts {
            sandbox = sandbox.with_mount(
                std::path::PathBuf::from(&m.guest_path),
                std::path::PathBuf::from(&m.host_path),
                m.read_only,
            );
        }
        // Writable volumes. KVM/HVF attach a host FILE as a virtio-blk device; the
        // sentry has no block layer, so a volume is a persistent host DIRECTORY
        // bind-mounted at the guest path (served by the same confined-dirfd
        // machinery as any mount). The data lives in the host dir, so it survives
        // snapshot (it's external to the rootfs copy) and is re-attached on restore
        // (the volume list round-trips through metadata.json → `self.volumes`),
        // giving the same "volume-backed cache survives snapshot+resume" contract
        // the KVM/HVF backends provide.
        for (host_path, guest_path, _size, _pristine) in &self.volumes {
            std::fs::create_dir_all(host_path).map_err(|e| {
                Error::vm_msg(format!(
                    "sentry volume backing dir {}: {e}",
                    host_path.display()
                ))
            })?;
            sandbox = sandbox.with_mount(guest_path.clone(), host_path.clone(), false);
        }
        // Resource caps: bound the guest cell tree so one tenant can't exhaust the
        // host. Off only when explicitly uncapped (trusted single-tenant tooling).
        if !config.sentry_uncapped {
            // memory.max: the VmConfig override, else the image's baked default.
            let mem_mib = config.memory_mib.unwrap_or(self.memory_mib) as u64;
            if mem_mib > 0 {
                sandbox = sandbox.with_memory_limit(mem_mib * 1024 * 1024);
            }
            // cpu.max: `vcpus` cores' worth of CPU (quota = vcpus * period).
            let vcpus = config.vcpus.unwrap_or(self.vcpus).max(1) as u64;
            sandbox = sandbox.with_cpu_limit(vcpus * SENTRY_CPU_PERIOD_US, SENTRY_CPU_PERIOD_US);
            // pids.max: the VmConfig override, else the sentry default.
            let pids = config.sentry_pids_max.unwrap_or(SENTRY_DEFAULT_PIDS_MAX);
            sandbox = sandbox.with_pids_limit(pids);
        }
        // Bounded-execution watchdog — THE RELEASE GATE. This is the single place
        // that builds + configures the Sandbox for the whole sentry surface (both
        // `Vm::start`'s sentry path AND `SentryPool::build` route through here), so
        // applying the timeout HERE bounds production by default: a fork+signal-
        // trapping RUN (or the deferred C1 reentrancy hang) can never hang the
        // caller forever — it becomes a SIGKILL + `SentryError::Timeout` (137).
        // Independent of the cgroup caps so it applies even under `sentry_uncapped`.
        // `None` → the generous 10-min default; `Some(ZERO)` opts out (unlimited).
        // Bound only the TENANT-FACING exec surface by default. A build pool's RUN
        // steps are the operator's OWN (trusted) Dockerfile commands — a legitimate
        // compile can run many minutes — so the generous production ceiling does NOT
        // apply to `for_build` pools; they stay unbounded (timeout 0 ⇒ the plain
        // `waitpid` wait, byte-identical to the pre-watchdog build path) unless the
        // operator opts in with an explicit `with_sentry_exec_timeout`. (Reserving the
        // pidfd+poll watchdog for non-build execs also keeps the concurrent-build
        // path — two builds cloning the same base, the `task_96ba9a6d` rootfs race —
        // on its original, validated timing.)
        let exec_timeout = match config.sentry_exec_timeout {
            Some(explicit) => explicit, // operator opt-in: honor for ANY sandbox
            None if config.for_build => Duration::ZERO, // trusted build: unbounded by default
            None => SENTRY_DEFAULT_EXEC_TIMEOUT, // production default ceiling
        };
        sandbox = sandbox.with_exec_timeout(exec_timeout);
        // virtio-fs mounts (config.virtiofs) → confined bind-mounts. The sentry has
        // no FUSE-over-virtio; each MountSpec becomes an `openat2(RESOLVE_IN_ROOT)`
        // bind of `host_path` at `guest_path`, honoring the spec's read_only flag.
        // The `guest_tag` (a virtio-fs device tag) and `symlinks` policy have no
        // analogue in the sentry's confinement and are dropped (documented in the
        // workstream risks). The host dir must already exist (the FUSE backend
        // would have required the same).
        for m in &config.virtiofs {
            sandbox = sandbox.with_mount(
                std::path::PathBuf::from(&m.guest_path),
                std::path::PathBuf::from(&m.host_path),
                m.read_only,
            );
        }
        // Data volumes (config.volumes) → read-write host-dir binds. The sentry has
        // no block layer, so a "volume" is just a confined bind of the host backing
        // DIRECTORY at `guest_path`; `size_bytes` is NOT enforced (no quota — see
        // the workstream risks). Ensure the host dir exists (create it like the KVM
        // path lazily creates a backing file) so first-run volumes are writable.
        for v in &config.volumes {
            let host_dir = std::path::PathBuf::from(&v.host_path);
            std::fs::create_dir_all(&host_dir).map_err(Error::Io)?;
            sandbox = sandbox.with_mount(std::path::PathBuf::from(&v.guest_path), host_dir, false);
        }
        Ok(sandbox)
    }

    /// Start a PERSISTENT-supervisor [`Pool`](crate::sentry::Pool) on this sentry
    /// image's rootfs (Linux/x86_64): one long-lived supervisor (rootfs dirfd +
    /// rings + servicers set up once) that forks a fresh cell per
    /// [`exec`](crate::sentry::Pool::exec) and fork-from-warm
    /// [`acquire`](crate::sentry::Pool::acquire) instance, amortizing the per-exec
    /// setup. The image's recorded egress policy is enforced on every cell. To
    /// configure mounts / cgroup limits / uid-drop, build the pool from a
    /// configured [`Sandbox`](crate::sentry::Sandbox):
    /// `image.sentry_sandbox()?.with_memory_limit(..).pool()`. Errors if the image
    /// isn't a sentry image.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn sentry_pool(&self) -> Result<crate::sentry::Pool, Error> {
        // Inherit the image's egress policy (and any future config) by routing
        // through the same configured Sandbox the handle API builds.
        self.sentry_sandbox()?
            .pool()
            .map_err(|e| Error::vm_msg(format!("sentry pool: {e}")))
    }

    /// Bake a KVM-bootable [`Image`] from an OCI reference with **zero asset
    /// paths** (Linux/x86_64) — the fully hands-off entry point:
    ///
    /// ```no_run
    /// let img = supermachine::Image::bake_kvm_auto("alpine", "/tmp/alpine-vm")?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    ///
    /// The guest kernel, `busybox`, and in-VM agent are all sourced from the
    /// bundled `supermachine-kernel` crate (its x86_64 sub-crate, selected by
    /// `target_arch`), so the caller never points at a kernel build or builds
    /// an initramfs. Internally it extracts the bundled minimal module-free
    /// bzImage, assembles the agent initramfs in-process from the bundled
    /// busybox + agent (no kernel modules — vsock/squashfs/overlay are built
    /// in), then delegates to [`bake_kvm_from_ref`](Image::bake_kvm_from_ref).
    /// All artifacts land under `dest_dir`, so the snapshot is self-contained.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kvm_auto(image_ref: &str, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        let dest = dest_dir.into();
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let t_assets = std::time::Instant::now();
        let (kernel, initrd) = Self::extract_bundled_kvm_boot_assets(&dest)?;
        if crate::trace::enabled("run") {
            eprintln!(
                "supermachine: kvm boot-assets extract_ms={}",
                t_assets.elapsed().as_millis()
            );
        }
        Self::bake_kvm_from_ref(image_ref, &kernel, &initrd, dest)
    }

    /// Extract the bundled, hands-off KVM boot assets into `dest`: the minimal
    /// module-free x86_64 guest kernel (`dest/kernel`) and an in-process-assembled
    /// agent initramfs (`dest/agent.cpio`, from the bundled busybox + agent — the
    /// kernel has virtio-vsock/squashfs/overlayfs built in, MODULES=n, so no
    /// modules are staged). Shared by [`bake_kvm_auto`](Image::bake_kvm_auto) and
    /// [`bake_kvm_from_squashfs_auto`](Image::bake_kvm_from_squashfs_auto) so both
    /// hands-off bake entry points source boot assets the one same way.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn extract_bundled_kvm_boot_assets(dest: &Path) -> Result<(PathBuf, PathBuf), Error> {
        let kernel = dest.join("kernel");
        // `SUPERMACHINE_KVM_KERNEL=/path/to/bzImage` overrides the bundled guest
        // kernel — used to validate experimental kernels (e.g. the virtio-fs/DAX
        // build) without re-bundling. Falls back to the bundled kernel if unset.
        match std::env::var_os("SUPERMACHINE_KVM_KERNEL") {
            Some(p) if std::path::Path::new(&p).is_file() => {
                std::fs::copy(&p, &kernel).map_err(Error::Io)?;
            }
            _ => supermachine_kernel::extract_kernel_to(&kernel).map_err(Error::Io)?,
        }
        let assets = dest.join("agent-assets");
        std::fs::create_dir_all(&assets).map_err(Error::Io)?;
        let agent_bin = assets.join("supermachine-agent");
        let busybox_bin = assets.join("busybox");
        supermachine_kernel::extract_supermachine_agent_to(&agent_bin).map_err(Error::Io)?;
        supermachine_kernel::extract_busybox_to(&busybox_bin).map_err(Error::Io)?;
        let initrd = dest.join("agent.cpio");
        crate::bake::build_kvm_agent_initramfs(&agent_bin, &busybox_bin, &[], &initrd)
            .map_err(Error::bake_msg)?;
        let _ = std::fs::remove_dir_all(&assets);
        Ok((kernel, initrd))
    }

    /// Wrap an already-built read-only `rootfs.squashfs` as a KVM-bootable
    /// [`Image`] — the same rootfs format [`bake_kvm`](Image::bake_kvm) produces,
    /// but with **no layer re-extraction**. This is the re-import side of the
    /// in-VM builder's RAM-density loop: a built image is flattened to a shared
    /// read-only squashfs by [`commit_squashfs`](crate::builder::commit_squashfs),
    /// then booted back with an EMPTY tmpfs overlay upper — so the build's files
    /// live in the squashfs (page-cache shared CoW across every booted VM) instead
    /// of each VM's private tmpfs RAM. The squashfs is placed at `dest/rootfs.squashfs`
    /// (copied in only if it isn't already there — `commit_squashfs` can write it
    /// straight into `dest`, making this copy-free).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kvm_from_squashfs(
        squashfs: &Path,
        kernel: &Path,
        agent_initrd: &Path,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        let dest = dest_dir.into();
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let rootfs = dest.join("rootfs.squashfs");
        if squashfs != rootfs {
            std::fs::copy(squashfs, &rootfs).map_err(Error::Io)?;
        }
        let metadata = serde_json::json!({
            "backend": "kvm",
            "kvm_kernel": kernel.to_string_lossy(),
            "kvm_initrd": agent_initrd.to_string_lossy(),
            "kvm_disk": rootfs.to_string_lossy(),
            "memory_mib": 512,
            "vcpus": 1,
            "balloon_target_pages": crate::bake::compute_balloon_target_pages(512),
        });
        std::fs::write(
            dest.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::bake_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        Image::from_snapshot(&dest)
    }

    /// Hands-off variant of [`bake_kvm_from_squashfs`](Image::bake_kvm_from_squashfs):
    /// source the guest kernel + agent initramfs from the bundled crate assets
    /// (like [`bake_kvm_auto`](Image::bake_kvm_auto)), so the caller only supplies
    /// the committed squashfs + a destination.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn bake_kvm_from_squashfs_auto(
        squashfs: &Path,
        dest_dir: impl Into<PathBuf>,
    ) -> Result<Image, Error> {
        let dest = dest_dir.into();
        std::fs::create_dir_all(&dest).map_err(Error::Io)?;
        let (kernel, initrd) = Self::extract_bundled_kvm_boot_assets(&dest)?;
        Self::bake_kvm_from_squashfs(squashfs, &kernel, &initrd, dest)
    }

    /// Assemble a self-contained KVM agent initramfs (Linux/x86_64) in-process,
    /// for use as the `agent_initrd` of [`bake_kvm`](Image::bake_kvm) /
    /// [`bake_kvm_from_ref`](Image::bake_kvm_from_ref).
    ///
    /// Builds a `newc` cpio whose PID-1 init mounts `/proc` + `/dev`, `insmod`s
    /// `ordered_modules` (`.ko` or `.ko.zst`, in order), mounts the rootfs disk
    /// (`/dev/vda`) at `/mnt`, and execs the agent — no external `cpio`/busybox
    /// build step. (A vsock-built-in kernel would drop the module list.)
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn build_kvm_initramfs(
        agent_bin: &Path,
        busybox_bin: &Path,
        ordered_modules: &[PathBuf],
        out_cpio: &Path,
    ) -> Result<(), Error> {
        crate::bake::build_kvm_agent_initramfs(agent_bin, busybox_bin, ordered_modules, out_cpio)
            .map_err(Error::bake_msg)
    }

    /// Acquire a microVM from this image's hidden pool. Returns
    /// a [`PooledVm`] which `Deref`s to [`Vm`] and returns to
    /// the pool on `Drop`. Use this for the common
    /// "spin up a VM, do one task, throw it away, do another"
    /// loop — the pool keeps re-restoring from the same snapshot
    /// behind the scenes so per-iteration cost stays at the
    /// snapshot-restore floor (~5 ms on Apple Silicon).
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// # use std::time::Duration;
    /// let image = Image::from_snapshot("path/to/rust-slim")?;
    /// for src in ["fn main() {}", "fn main() { panic!() }"] {
    ///     let vm = image.acquire()?;
    ///     vm.write_file("/tmp/main.rs", src.as_bytes())?;
    ///     let out = vm.exec_builder()
    ///         .argv(["sh", "-c", "rustc /tmp/main.rs -o /tmp/m && /tmp/m"])
    ///         .timeout(Duration::from_secs(30))
    ///         .output()?;
    ///     println!("status={:?} out={:?}", out.status.code(), out.stdout);
    ///     // vm dropped here — returned to pool, restored from snapshot
    /// }
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    ///
    /// ## Pool sizing
    ///
    /// `Image::acquire` uses an ambient pool with default policy
    /// (`min=0`, `max=64`, `idle_timeout=60s`,
    /// `acquire_timeout=60s`). For an explicit policy use
    /// [`Image::pool`] to build a [`Pool`] and call
    /// `pool.acquire()` instead.
    ///
    /// Per-acquire cost is the snapshot restore (~3 ms on Apple
    /// Silicon) when an idle worker is available; cold spawn
    /// (lazy-grow path) is ~15 ms. The pool auto-grows up to
    /// `max` under burst and auto-evicts above-`min` workers
    /// after they sit idle for `idle_timeout`.
    #[cfg(any(
        all(target_os = "macos", target_arch = "aarch64"),
        all(target_os = "linux", target_arch = "x86_64")
    ))]
    pub fn acquire(&self) -> Result<PooledVm<'_>, Error> {
        self.acquire_with(&VmConfig::new())
    }

    /// Like [`Image::acquire`] but with an explicit
    /// [`VmConfig`] (overrides for memory, vCPUs, asset paths,
    /// **pool size**, etc.). The config is honored on **first**
    /// acquire — when the pool is built. Subsequent acquires
    /// reuse the existing pool regardless of `config`. This is
    /// fine for most use cases; create a fresh `Image` if you
    /// need a different config without restarting your app.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn acquire_with(&self, config: &VmConfig) -> Result<PooledVm<'_>, Error> {
        let _span = tracing::info_span!(
            "supermachine.acquire",
            memory_mib = self.memory_mib,
            vcpus = self.vcpus,
        )
        .entered();
        let pool_arc = self.ensure_default_pool(config)?;
        let worker = pool_arc.acquire()?;
        let vm = Vm {
            pool: None,
            vsock_mux_path: worker.vsock_mux_path.clone(),
            vsock_exec_path: worker.vsock_exec_path.clone(),
            own_vsock_mux_dir: None,
            skip_cleanup: true,
            // Populate image_meta from the source Image so
            // `Vm::snapshot` can build metadata.json. The
            // capture itself runs over the worker subprocess's
            // supervisor protocol — see `Vm::snapshot`'s pool-
            // worker dispatch path. No HVF-entitlement
            // requirement on the calling binary.
            image_meta: Some(Arc::new(ImageMeta {
                memory_mib: config.memory_mib.unwrap_or(self.memory_mib),
                vcpus: config.vcpus.unwrap_or(self.vcpus),
                layers: self.layers.clone(),
                delta_squashfs: self.delta_squashfs.clone(),
                baker_runtime_sha16: self.baker_runtime_sha16.clone(),
                tsi_token: self.tsi_token.clone(),
                egress_policy: self.egress_policy.clone(),
                pre_exec_sync: self.pre_exec_sync,
            })),
        };
        Ok(PooledVm {
            vm: Some(vm),
            worker: Some(worker),
            pool_arc: Arc::clone(pool_arc),
            _image: std::marker::PhantomData,
        })
    }

    /// Linux/KVM `Image::acquire_with`: acquires from an ambient warm pool built
    /// lazily on first use (boot → snapshot once), so each acquire is a CoW
    /// restore (~ms) instead of a cold boot (~1s). The pool is cached on the
    /// Image (shared across clones); the first call's `config` fixes its policy/
    /// memory — for per-acquire control use an explicit [`Image::pool`]. Falls
    /// back to a cold [`Vm::start`] if warming fails.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn acquire_with(&self, config: &VmConfig) -> Result<PooledVm<'_>, Error> {
        // No-virt sentry image: an ambient pool over ONE shared, always-warm
        // exec server (forks a fresh sealed cell per exec). Cached in the same
        // `kvm_pool` OnceLock the KVM ambient pool uses; warmed once.
        if self.sentry.is_some() {
            if self.kvm_pool.get().is_none() {
                let pol = PoolPolicy::default();
                if let Ok(sp) = SentryPool::build(
                    self,
                    config,
                    pol.max,
                    pol.acquire_timeout,
                    pol.restore_on_release,
                ) {
                    let _ = self.kvm_pool.set(Arc::new(Pool {
                        kvm: None,
                        sentry: Some(sp),
                        runsc: None,
                        kboxlike: None,
                    }));
                }
            }
            if let Some(pool) = self.kvm_pool.get() {
                return pool.acquire();
            }
            // Server build failed — cold per-acquire fallback (still correct).
            let vm = Vm::start(self, config)?;
            return Ok(PooledVm {
                vm: Some(vm),
                pool: None,
                sentry_pool: None,
                runsc_pool: None,
                kboxlike_pool: None,
                sentry_mem_admission: None,
                sentry_running_pid: None,
                sentry_running_pool: None,
                sentry_stop_running_pool_on_drop: false,
                sentry_touched: AtomicBool::new(false),
                _image: std::marker::PhantomData,
            });
        }
        if self.runsc.is_some() {
            if self.kvm_pool.get().is_none() {
                let pol = PoolPolicy::default();
                if let Ok(rp) = RunscPoolInner::build(
                    self,
                    config,
                    pol.min,
                    pol.max,
                    pol.acquire_timeout,
                    pol.restore_on_release,
                ) {
                    let _ = self.kvm_pool.set(Arc::new(Pool {
                        kvm: None,
                        sentry: None,
                        runsc: Some(rp),
                        kboxlike: None,
                    }));
                }
            }
            if let Some(pool) = self.kvm_pool.get() {
                return pool.acquire();
            }
            // Pool build failed — cold per-acquire fallback (still correct).
            let vm = Vm::start(self, config)?;
            return Ok(PooledVm {
                vm: Some(vm),
                pool: None,
                sentry_pool: None,
                runsc_pool: None,
                kboxlike_pool: None,
                sentry_mem_admission: None,
                sentry_running_pid: None,
                sentry_running_pool: None,
                sentry_stop_running_pool_on_drop: false,
                sentry_touched: AtomicBool::new(false),
                _image: std::marker::PhantomData,
            });
        }
        if self.kboxlike.is_some() {
            if self.kvm_pool.get().is_none() {
                let pol = PoolPolicy::default();
                if let Ok(kp) = KboxlikePoolInner::build(
                    self,
                    config,
                    pol.min,
                    pol.max,
                    pol.acquire_timeout,
                    pol.restore_on_release,
                ) {
                    let _ = self.kvm_pool.set(Arc::new(Pool {
                        kvm: None,
                        sentry: None,
                        runsc: None,
                        kboxlike: Some(kp),
                    }));
                }
            }
            if let Some(pool) = self.kvm_pool.get() {
                return pool.acquire();
            }
            let vm = Vm::start(self, config)?;
            return Ok(PooledVm {
                vm: Some(vm),
                pool: None,
                sentry_pool: None,
                runsc_pool: None,
                kboxlike_pool: None,
                sentry_mem_admission: None,
                sentry_running_pid: None,
                sentry_running_pool: None,
                sentry_stop_running_pool_on_drop: false,
                sentry_touched: AtomicBool::new(false),
                _image: std::marker::PhantomData,
            });
        }
        if self.kvm_pool.get().is_none() {
            // Warm once + cache. A lost race just wastes one warm-up; the first
            // value stored in the OnceLock wins and both threads use it. The
            // ambient pool uses default policy (min=0 → no idle pre-warm; each
            // acquire is a ~ms CoW restore). Use an explicit Image::pool for a
            // min>0 always-warm idle set.
            if let Ok(warm) = warm_snapshot_for_pool(self, config) {
                let pol = PoolPolicy::default();
                let inner = Arc::new(KvmPoolInner {
                    image: warm,
                    vm_config: config.clone(),
                    min: 0,
                    idle: std::sync::Mutex::new(Vec::new()),
                    admission: Admission::new(pol.max, pol.acquire_timeout),
                    restore_on_release: pol.restore_on_release,
                    refilling: std::sync::atomic::AtomicBool::new(false),
                    shut_down: std::sync::atomic::AtomicBool::new(false),
                });
                let _ = self.kvm_pool.set(Arc::new(Pool {
                    kvm: Some(inner),
                    sentry: None,
                    runsc: None,
                    kboxlike: None,
                }));
            }
        }
        if let Some(pool) = self.kvm_pool.get() {
            return pool.acquire();
        }
        // Warming failed (e.g. agent never came up) — cold start as a fallback.
        let vm = Vm::start(self, config)?;
        Ok(PooledVm {
            vm: Some(vm),
            pool: None,
            sentry_pool: None,
            runsc_pool: None,
            kboxlike_pool: None,
            sentry_mem_admission: None,
            sentry_running_pid: None,
            sentry_running_pool: None,
            sentry_stop_running_pool_on_drop: false,
            sentry_touched: AtomicBool::new(false),
            _image: std::marker::PhantomData,
        })
    }

    /// Configure an explicit pool against this image. Use when
    /// you want auto-scaling or fine control over min/max/idle/
    /// acquire timeouts; for the simple case
    /// `image.acquire()` already manages an ambient default-
    /// policy pool for you.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use supermachine::Image;
    /// let image = Image::ensure_baked("rust_warm", "rust:1-slim", |b| b)?;
    /// // Auto-scale 5..=50, evict idle workers after 60s,
    /// // fail acquire if pool stays at max for >10s:
    /// let pool = image.pool()
    ///     .min(5)
    ///     .max(50)
    ///     .idle_timeout(Duration::from_secs(60))
    ///     .acquire_timeout(Duration::from_secs(10))
    ///     .build()?;
    /// let vm = pool.acquire()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn pool(&self) -> PoolBuilder<'_> {
        PoolBuilder {
            image: self,
            policy: PoolPolicy::default(),
            vm_config: VmConfig::new(),
        }
    }

    /// Build a fresh `HiddenPool` against `policy`, store it in
    /// `self.hidden_pool`, return the borrowed Arc.
    /// Build a fresh standalone `HiddenPool`. Caller decides
    /// what to do with the Arc — `acquire()` parks it in the
    /// per-Image `hidden_pool` OnceLock; `pool().build()`
    /// returns it as a `Pool` to the caller.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn build_pool_arc(
        &self,
        config: &VmConfig,
        policy: PoolPolicy,
    ) -> Result<Arc<HiddenPool>, Error> {
        // 0.7.49+ best-effort sweep of stranded COW volume temps in
        // /tmp left by previously-crashed processes. Idempotent + per-
        // process (a OnceLock latches the first call). Cheap when /tmp
        // is clean; bounded by /tmp entry count on a busy host.
        sweep_volume_temps_once();
        // Find supermachine-worker. Tries env override, sibling-
        // of-current-exe (cargo install layout), dev-tree
        // target/release (workspace).
        #[cfg(target_os = "macos")]
        let worker_bin = {
            // Three resolution modes:
            //
            //   1. `SUPERMACHINE_WORKER_BIN` set:
            //      Explicit user override. Use the path AS-IS — no
            //      copy, no codesign mutation. Devs running a custom
            //      worker against the library expect this.
            //
            //   2. `SUPERMACHINE_WORKER_BIN_BUNDLED` set:
            //      The npm JS shim (`npm/supermachine-core/index.js`)
            //      sets this to `@supermachine/core-darwin-arm64/
            //      supermachine-worker`. We treat it as a SOURCE and
            //      copy to the per-version user-data dir, signing
            //      the COPY there. Critical for npm consumers: the
            //      node_modules path is never codesign-rewritten, so
            //      npm's integrity model isn't violated and the
            //      stuck-`.cstemp`-with-uchg recovery loop that
            //      wedged 0.7.27 installs can't happen on
            //      node_modules.
            //
            //   3. Neither set:
            //      Fall back to `codesign::locate_worker_bin`'s
            //      sibling-of-current-exe + ~/.cargo/bin + $PATH
            //      walk. The found path is then copied to user-dir
            //      and signed there, same as mode 2.
            if let Some(p) = std::env::var_os("SUPERMACHINE_WORKER_BIN") {
                let p = PathBuf::from(p);
                if !p.is_file() {
                    return Err(Error::assets_msg(format!(
                        "SUPERMACHINE_WORKER_BIN={} does not exist or is not a file",
                        p.display()
                    )));
                }
                p
            } else {
                let source =
                    if let Some(bundled) = std::env::var_os("SUPERMACHINE_WORKER_BIN_BUNDLED") {
                        let p = PathBuf::from(bundled);
                        if !p.is_file() {
                            return Err(Error::assets_msg(format!(
                            "SUPERMACHINE_WORKER_BIN_BUNDLED={} does not exist or is not a file",
                            p.display()
                        )));
                        }
                        p
                    } else {
                        crate::codesign::locate_worker_bin().ok_or_else(|| {
                            Error::assets_msg(
                                "supermachine-worker binary not found (looked for sibling of \
                             current_exe and target/release/supermachine-worker). Set \
                             SUPERMACHINE_WORKER_BIN if you have it elsewhere."
                                    .to_owned(),
                            )
                        })?
                    };
                crate::assets::ensure_worker_in_user_dir(&source).map_err(Error::assets_msg)?
            }
        };
        #[cfg(not(target_os = "macos"))]
        let worker_bin: PathBuf = std::env::var_os("SUPERMACHINE_WORKER_BIN")
            .map(PathBuf::from)
            .ok_or_else(|| {
                Error::assets_msg("SUPERMACHINE_WORKER_BIN must be set on this platform".to_owned())
            })?;
        // HARD: verify the worker binary matches the library
        // version. The supervisor protocol evolves between
        // releases; a stale ~/.cargo/bin/supermachine-worker from
        // an older `cargo install supermachine` deadlocks
        // pipelined-bake silently otherwise. See
        // codesign::verify_worker_version for the diagnostic
        // signature and the upgrade hint we surface to the user.
        #[cfg(target_os = "macos")]
        {
            crate::codesign::verify_worker_version(&worker_bin).map_err(Error::vm_msg)?;
            // Ensure the user-dir worker carries the HVF entitlement.
            // We used to silently ignore the result here on the
            // theory that `hv_vm_create` would surface its own
            // error if signing failed. In practice that lost the
            // actual diagnostic (`HV_DENIED` is opaque; users
            // couldn't tell whether codesign failed, the
            // entitlements plist was wrong, the binary was already
            // signed but with a different entitlement, …) and the
            // autopilot's stuck-`.cstemp` recovery loop went
            // undetected for entire sessions. Surface the codesign
            // failure with its exact stderr + a recovery hint
            // instead of letting the downstream bake fail with a
            // cryptic supervisor-closed message.
            //
            // Idempotent — a successful sign caches via a per-version
            // sentinel and subsequent calls return immediately.
            //
            // Signing happens on the user-dir copy (see
            // ensure_worker_in_user_dir above), so node_modules is
            // never touched.
            if let Err(e) = crate::codesign::ensure_worker_signed(&worker_bin) {
                return Err(Error::vm_msg(format!(
                    "supermachine-worker codesign failed: {e}"
                )));
            }
        }

        // Unix socket paths are capped at 104 bytes on macOS
        // (SUN_LEN). Default to /tmp instead of $TMPDIR, which on
        // macOS resolves to /var/folders/.../T/ and burns ~50
        // characters before we even start. `/tmp/supermachine-
        // pool-<pid>-<suffix>/` leaves room for a meaningful
        // socket name underneath.
        let socks_dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => PathBuf::from(format!(
                "/tmp/supermachine-pool-{}-{:x}",
                std::process::id(),
                unique_suffix(),
            )),
        };
        std::fs::create_dir_all(&socks_dir).map_err(Error::Io)?;

        // Sweep `~/.cache/supermachine/rosetta-aot/` for AOT cache
        // orphans before the worker spawns. Two classes get evicted:
        //
        //   1. **Zero-byte `<x>.aotcache` files.** Migration cleanup
        //      for caches built with supermachine ≤ 0.7.25, before
        //      the FUSE-layer `.partial`-then-rename publish protocol
        //      (`fn create` / `fn release` in posix.rs) closed the
        //      orphan window. A 0-byte file from a pre-fix lifetime
        //      will still trigger the rosetta interpreter's
        //      `aot_hdr->segment_count <= kMaxSegments` assertion
        //      (ImageInfo.cpp:71 — pread of an empty file returns 0
        //      and stack-garbage at offset 8 is parsed as
        //      segment_count) or SIGBUS-on-mmap-past-EOF on the
        //      first amd64 exec that hashes to that build-id.
        //   2. **`.<x>.aotcache.partial` leftovers.** Crash recovery
        //      for the new publish protocol. If a prior VM was
        //      SIGKILLed or the host crashed between FUSE_CREATE and
        //      FUSE_RELEASE, the partial file is on disk and would
        //      block a fresh `O_CREAT|O_EXCL` open of the same name.
        //      posix.rs's create-time retry handles this inline, but
        //      cleaning up at acquire keeps the cache dir tidy and
        //      avoids EEXIST surprises in narrower acquire-time
        //      windows.
        //
        // Cheap: one readdir + one stat per entry, runs in <5 ms on
        // a fully populated cache. Silently no-op when the cache
        // dir doesn't exist (no `rosettad-cache` mount in this
        // image).
        if let Some(home) = std::env::var_os("HOME") {
            let cache_dir = PathBuf::from(home)
                .join(".cache")
                .join("supermachine")
                .join("rosetta-aot");
            if cache_dir.is_dir() {
                let _ = scrub_aotcache_orphans(&cache_dir);
            }
        }

        let memory_mib = config.memory_mib.unwrap_or(self.memory_mib);
        let vcpus = config.vcpus.unwrap_or(self.vcpus);
        let spawn_timeout = config
            .restore_timeout
            .unwrap_or_else(|| Duration::from_secs(30));
        // Same SUN_LEN concern: use a small token instead of the
        // full snapshot dir name. Per-pool counter would be even
        // shorter; for now an 8-char hash is enough.
        let name_prefix = "w".to_owned();
        let spawn_cfg = Arc::new(SpawnConfig {
            observed_footprint_mib: std::sync::atomic::AtomicU64::new(0),
            worker_bin,
            snapshot_path: self.snapshot_path.clone(),
            layers: self.layers.clone(),
            delta_squashfs: self.delta_squashfs.clone(),
            mounts: self.mounts.clone(),
            volumes: self.volumes.clone(),
            memory_mib,
            vcpus,
            socks_dir: socks_dir.clone(),
            name_prefix,
            spawn_timeout,
            baker_runtime_sha16: self.baker_runtime_sha16.clone(),
            balloon_target_pages: self.balloon_target_pages,
            tsi_token: self.tsi_token.clone(),
            egress_policy: self.egress_policy.clone(),
            pre_exec_sync: self.pre_exec_sync,
            restore_on_release: policy.restore_on_release,
        });
        // Spawn `min` workers in parallel up front so the pool
        // is ready to serve immediately. `max - min` more can be
        // spawned later by the auto-grow path in `acquire`.
        //
        // WARM HANDOFF: claim the bake-time worker (if any) and
        // use it as one of the initial idle entries — saves spawn
        // (~50 ms) + restore (~5 ms) for the FIRST acquire. This
        // is the per-Image atomic claim: only the first
        // PoolBuilder::build() to run on a given Image gets the
        // warm worker; concurrent / subsequent calls take None
        // and spawn fresh as today.
        //
        // If the warm worker's child has already died (e.g. user
        // kept the Image around so long the worker exited on its
        // own, or HVF returned an error), we fall through cleanly
        // to spawn-from-disk.
        let claimed_warm = self.warm_baked_worker.take().and_then(|mut bw| {
            // Liveness check — if the child reaped itself, ditch it.
            match bw.child.try_wait() {
                Ok(None) => Some(bw), // still running, claim it
                Ok(Some(_)) => None,  // exited, fall through
                Err(_) => None,       // EBADF or similar
            }
        });
        let initial = policy.min;
        let mut idle: Vec<IdleEntry> = Vec::with_capacity(initial.max(1));
        let extra_warm: usize;
        if let Some(bw) = claimed_warm {
            // 0.7.49+ COW-volume use-once flag. When the pool is
            // configured for restore_on_release AND the snapshot
            // ships pristines, the warm-handoff worker's volume
            // fds point at the user's host file (no COW). Mark it
            // use-once so the first release kills it; the
            // replenisher will then spawn a fresh COW-backed worker.
            let warm_use_once = policy.restore_on_release
                && spawn_cfg.volumes.iter().any(|(_, _, _, p)| p.is_some());
            let worker = warm_baked_to_worker(
                bw,
                spawn_cfg.memory_mib,
                !spawn_cfg.mounts.is_empty() || !spawn_cfg.volumes.is_empty(),
                spawn_cfg
                    .volumes
                    .iter()
                    .map(|(_, gp, _, _)| gp.clone())
                    .collect(),
                spawn_cfg.vcpus,
                warm_use_once,
            );
            // Even though this worker never went through a
            // RESTORE — it's the live bake worker reused — its
            // VFS caches still reflect "what the host looked
            // like during bake". If the user edited bound files
            // between Image.build and Pool.acquire, those reads
            // would return stale bytes. Drop now to force
            // re-LOOKUP on first access.
            //
            // 0.7.44+ probe-skip: same logic as `spawn_one`'s
            // restore path — drop only when the snapshot has a
            // host-backed surface (mounts or volumes). Pure-image
            // snapshots save ~5-15 ms.
            if !spawn_cfg.mounts.is_empty() || !spawn_cfg.volumes.is_empty() {
                let _ = drop_vfs_caches_via_agent(&worker.vsock_exec_path, spawn_cfg.memory_mib);
            }
            // 0.7.51+ wall-clock sync. The warm-handoff worker
            // was launched at bake time; if the snapshot has
            // sat on disk for hours/days before this pool build
            // claimed it, the in-guest CLOCK_REALTIME is just
            // as stale as on a cold restore. Same RPC fixes it.
            let _ = sync_time_via_agent(&worker.vsock_exec_path);
            // Deliberately NOT seeded into the pool's footprint
            // high-water-mark: this worker COLD-BOOTED and ran the bake,
            // so its resident footprint is near the guest ceiling
            // (measured ~2.2 GiB for a 2 GiB cap) — wildly
            // unrepresentative of the CoW restores the rest of the pool
            // spawns (~MiBs dirty). Seeding it would poison the learned
            // admission charge up to the cap and stall the prewarm. Its
            // own admission charge (inside warm_baked_to_worker) does
            // use its real measurement — that part is honest.
            idle.push(IdleEntry {
                worker,
                last_used: Instant::now(),
            });
            extra_warm = 1;
        } else {
            extra_warm = 0;
        }
        // We need `initial` idle entries total. The warm worker (if
        // claimed) covers one slot; spawn (initial - 1) fresh ones.
        // For min=0 with a warm worker, we still keep the warm one
        // around (it's effectively a free min=1).
        let to_spawn = initial.saturating_sub(extra_warm);
        if to_spawn == 1 {
            idle.push(IdleEntry {
                worker: spawn_cfg.spawn_one()?,
                last_used: Instant::now(),
            });
        } else if to_spawn > 1 {
            let mut handles = Vec::with_capacity(to_spawn);
            for _ in 0..to_spawn {
                let cfg = Arc::clone(&spawn_cfg);
                handles.push(std::thread::spawn(move || cfg.spawn_one()));
            }
            for h in handles {
                let w = h
                    .join()
                    .map_err(|_| Error::vm_msg("pool spawn thread panicked".to_owned()))??;
                idle.push(IdleEntry {
                    worker: w,
                    last_used: Instant::now(),
                });
            }
        }
        // Pool's `alive` accounting: total idle count (incl. warm
        // handoff entry).
        let initial = idle.len();
        let pool = Arc::new(HiddenPool {
            state: Arc::new(Mutex::new(PoolState {
                idle,
                alive: initial,
                waiting: 0,
                reaped: 0,
            })),
            available: Arc::new(Condvar::new()),
            dirty: Some(Arc::new(Mutex::new(VecDeque::new()))),
            dirty_pending: Some(Arc::new(Condvar::new())),
            socks_dir,
            shutting_down: Arc::new(AtomicBool::new(false)),
            spawn_cfg: Arc::clone(&spawn_cfg),
            policy,
        });
        // Spawn the housekeeping threads: replenisher (handles
        // genuine worker death + maintains `min`), restorer
        // (recycles dirty workers via RESTORE), janitor (evicts
        // idle-too-long workers above `min` to free RAM). All
        // detach naturally when the pool Arc drops via
        // `Weak::upgrade` failure.
        let wait_handles = pool.wait_handles();
        let h_replenish = {
            let h = wait_handles.clone();
            std::thread::Builder::new()
                .name("supermachine-pool-replenish".into())
                .spawn(move || replenisher_loop(h))
                .map_err(|e| Error::vm_msg(format!("spawn replenisher thread: {e}")))?
        };
        // Restorer threads only run when `restore_on_release`
        // is on. With it off, drop pushes workers straight to
        // idle and the restorer would have nothing to do.
        let mut handles = vec![h_replenish];
        if policy.restore_on_release {
            // Multi-restorer: scale the recycle thread count
            // with pool size. Each RESTORE RPC is ~3 ms in-
            // place; under bursty drop patterns a single
            // restorer becomes the serialization point and
            // shows up as a phantom delay on the *next* acquire
            // (acquire pops the idle queue, restorer's still
            // chewing through dirty, idle is empty → user
            // blocks ~3 ms × queue depth).
            //
            // Formula: ⌈max/2⌉ clamped [1, 4], capped at `max`.
            // 1 restorer for max=2, 3 for max=5, 4 for max=8+.
            let restorer_count = ((policy.max + 1) / 2).clamp(1, 4).min(policy.max.max(1));
            for _ in 0..restorer_count {
                let h = wait_handles.clone();
                let h_restore = std::thread::Builder::new()
                    .name("supermachine-pool-restore".into())
                    .spawn(move || restorer_loop(h))
                    .map_err(|e| Error::vm_msg(format!("spawn restorer thread: {e}")))?;
                handles.push(h_restore);
            }
        }
        // Janitor: only spawn if eviction is enabled. Saves a
        // sleeping thread for fixed-size pools.
        if pool.policy.idle_timeout != Duration::MAX {
            let h = wait_handles.clone();
            let h_janitor = std::thread::Builder::new()
                .name("supermachine-pool-janitor".into())
                .spawn(move || janitor_loop(h))
                .map_err(|e| Error::vm_msg(format!("spawn janitor thread: {e}")))?;
            handles.push(h_janitor);
        }
        // Detach the handles. Threads exit on their own when
        // `shutting_down` is set in `HiddenPool::drop`; we don't
        // need to join them — they hold no `Arc<HiddenPool>` and
        // don't block the user-side drop from firing.
        drop(handles);
        Ok(pool)
    }

    /// Initialise (once) the per-Image default pool used by
    /// `image.acquire()`. Lazy: subsequent calls return the
    /// same pool regardless of `config`. Distinct from
    /// `pool().build()` — that always returns a fresh pool.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn ensure_default_pool(&self, config: &VmConfig) -> Result<&Arc<HiddenPool>, Error> {
        if let Some(p) = self.hidden_pool.get() {
            return Ok(p);
        }
        let pool = self.build_pool_arc(config, PoolPolicy::default())?;
        // Race-friendly: if another thread set this in parallel,
        // the new pool is dropped (and its housekeeping threads
        // exit on the dropped Arc's strong-count → 0). The
        // observable result is "either pool wins, all subsequent
        // calls see the same one".
        let _ = self.hidden_pool.set(pool);
        Ok(self
            .hidden_pool
            .get()
            .expect("hidden pool just initialized"))
    }
}

/// Bundle of clonable handles into the pool's wait state. Each
/// housekeeping thread owns one of these; no one holds a strong
/// `Arc<HiddenPool>` across a condvar wait, so user-side `Pool`
/// + `Image` drops fire immediately and the threads exit on
/// `shutting_down` after their next short timed wait.
#[derive(Clone)]
struct PoolWaitHandles {
    state: Arc<Mutex<PoolState>>,
    available: Arc<Condvar>,
    dirty: Option<Arc<Mutex<VecDeque<Worker>>>>,
    dirty_pending: Option<Arc<Condvar>>,
    shutting_down: Arc<AtomicBool>,
    spawn_cfg: Arc<SpawnConfig>,
    policy: PoolPolicy,
}

impl HiddenPool {
    fn wait_handles(&self) -> PoolWaitHandles {
        PoolWaitHandles {
            state: Arc::clone(&self.state),
            available: Arc::clone(&self.available),
            dirty: self.dirty.as_ref().map(Arc::clone),
            dirty_pending: self.dirty_pending.as_ref().map(Arc::clone),
            shutting_down: Arc::clone(&self.shutting_down),
            spawn_cfg: Arc::clone(&self.spawn_cfg),
            policy: self.policy,
        }
    }
}

/// Restorer thread: drain the dirty queue, send RESTORE on each
/// worker's supervisor control socket to reset guest state to
/// the snapshot, then push back to idle. This is the steady-
/// state recycle path — replaces the old "kill + respawn fresh"
/// loop. Saves ~10 ms per cycle (no fork+exec+dyld+restore;
/// just an in-place restore).
fn restorer_loop(h: PoolWaitHandles) {
    let (Some(dirty), Some(pending)) = (h.dirty.as_ref(), h.dirty_pending.as_ref()) else {
        return;
    };
    loop {
        if h.shutting_down.load(Ordering::SeqCst) {
            return;
        }
        // Wait for a dirty worker (or shutdown). Bounded wait so
        // we re-check shutting_down even if no notify_all arrives.
        let mut worker = {
            let mut q = match dirty.lock() {
                Ok(q) => q,
                Err(_) => return,
            };
            loop {
                if h.shutting_down.load(Ordering::SeqCst) {
                    return;
                }
                if let Some(w) = q.pop_front() {
                    break w;
                }
                q = match pending.wait_timeout(q, Duration::from_millis(100)) {
                    Ok((g, _)) => g,
                    Err(_) => return,
                };
            }
        };

        let snap_path = h.spawn_cfg.snapshot_path.clone();
        match worker.send_restore(&snap_path) {
            Ok(()) => {
                if let Ok(mut s) = h.state.lock() {
                    s.idle.push(IdleEntry {
                        worker,
                        last_used: Instant::now(),
                    });
                    h.available.notify_all();
                }
            }
            Err(_) => {
                // Restore protocol broke — kill this worker so the
                // replenisher spawns a fresh replacement.
                worker.shutdown();
                if let Ok(mut s) = h.state.lock() {
                    s.alive = s.alive.saturating_sub(1);
                }
                h.available.notify_all();
            }
        }
    }
}

/// Replenisher: maintains `alive >= min`. Spawns workers when
/// below the floor (worker died, was evicted into a regrow gap,
/// etc.). Sleeps on `available` otherwise.
fn replenisher_loop(h: PoolWaitHandles) {
    loop {
        if h.shutting_down.load(Ordering::SeqCst) {
            return;
        }
        let need_more = {
            let s = match h.state.lock() {
                Ok(s) => s,
                Err(_) => return,
            };
            s.alive < h.policy.min
        };
        if !need_more {
            let s = match h.state.lock() {
                Ok(s) => s,
                Err(_) => return,
            };
            // Bounded wait — see PoolWaitHandles docs for why.
            let _ = h.available.wait_timeout(s, Duration::from_millis(100));
            continue;
        }
        // Reserve a slot before spawning so a concurrent
        // acquire's auto-grow doesn't double-spawn.
        if let Ok(mut s) = h.state.lock() {
            if s.alive >= h.policy.min {
                continue;
            }
            s.alive += 1;
        }
        match h.spawn_cfg.spawn_one() {
            Ok(w) => {
                if let Ok(mut s) = h.state.lock() {
                    s.idle.push(IdleEntry {
                        worker: w,
                        last_used: Instant::now(),
                    });
                    h.available.notify_all();
                }
            }
            Err(_) => {
                if let Ok(mut s) = h.state.lock() {
                    s.alive = s.alive.saturating_sub(1);
                }
                std::thread::sleep(Duration::from_millis(500));
            }
        }
    }
}

/// Janitor: every `idle_timeout / 4`, walk the idle queue and
/// shut down workers above `min` that have been idle longer than
/// `idle_timeout`. Frees host RAM during quiet periods.
fn janitor_loop(h: PoolWaitHandles) {
    let timeout = h.policy.idle_timeout;
    let min = h.policy.min;
    if timeout == Duration::MAX {
        return;
    }
    // Cap each individual wait so we re-check shutting_down often
    // enough to drop within ~100 ms of pool teardown.
    let tick = (timeout / 4).max(Duration::from_millis(100));
    let wait_unit = Duration::from_millis(100).min(tick);
    loop {
        if h.shutting_down.load(Ordering::SeqCst) {
            return;
        }
        // Collect workers to evict under the lock; shut down
        // outside it so we don't hold up acquires.
        let mut to_evict: Vec<Worker> = Vec::new();
        let mut reaped_now = 0u64;
        if let Ok(mut s) = h.state.lock() {
            let now = Instant::now();
            // Watchdog reap: a worker that died WHILE IDLE (and was never
            // popped) would otherwise sit as a phantom `alive` count
            // forever — acquire's `try_wait` only catches it on pop, and
            // a low-traffic pool may never pop it. Sweep the whole idle
            // queue for dead processes and reap them, INDEPENDENT of `min`
            // (a dead worker is never useful; the replenisher backfills).
            // `try_wait` is a cheap non-blocking waitpid; the actual
            // teardown runs outside the lock below.
            let mut i = 0;
            while i < s.idle.len() {
                let dead = match s.idle[i].worker.child.try_wait() {
                    Ok(Some(_)) => true, // process exited
                    Ok(None) => false,   // alive
                    Err(_) => true,      // can't stat → treat as dead
                };
                if dead {
                    let entry = s.idle.remove(i);
                    s.alive = s.alive.saturating_sub(1);
                    s.reaped += 1;
                    reaped_now += 1;
                    to_evict.push(entry.worker);
                } else {
                    i += 1;
                }
            }
            // Walk from the front (oldest entries) and evict
            // while we're above min and the entry is stale. Stop
            // as soon as we hit a fresh one — LIFO ordering means
            // older entries pile up at the front.
            while s.alive > min && !s.idle.is_empty() {
                let oldest = &s.idle[0];
                if now.duration_since(oldest.last_used) < timeout {
                    break;
                }
                let entry = s.idle.remove(0);
                s.alive -= 1;
                to_evict.push(entry.worker);
            }
        }
        if reaped_now > 0 {
            // A freed slot means the replenisher should backfill toward
            // `min`; wake it (and any blocked acquirer) so recovery is
            // prompt rather than waiting for the next tick.
            h.available.notify_all();
            eprintln!(
                "[pool-watchdog] reaped {reaped_now} dead idle worker(s) — pool will respawn \
                 toward min"
            );
        }
        for mut w in to_evict {
            w.shutdown();
        }
        // Sleep up to `tick` total in `wait_unit` slices so we
        // observe shutting_down promptly.
        let mut remaining = tick;
        while remaining > Duration::ZERO && !h.shutting_down.load(Ordering::SeqCst) {
            let chunk = remaining.min(wait_unit);
            if let Ok(s) = h.state.lock() {
                let _ = h.available.wait_timeout(s, chunk);
            }
            remaining = remaining.saturating_sub(chunk);
        }
    }
}

/// A [`Vm`] checked out of an [`Image`]'s hidden pool. `Deref`s
/// to `Vm`, so every method on `Vm` is callable. On `Drop` the
/// VM returns to the pool — the next [`Image::acquire`] gets
/// a freshly snapshot-restored worker in ~5 ms.
///
/// Bound to the `Image`'s lifetime so the pool can't outlive
/// its owner. Acquires currently serialize on the pool's single
/// worker; concurrent acquires from one process block until the
/// previous PooledVm is dropped.
pub struct PooledVm<'a> {
    vm: Option<Vm>,
    /// Worker subprocess we checked out. On Drop, returned to
    /// the pool (which kills + replenishes). macOS/HVF only — the
    /// Linux/KVM pool runs VMs in-process (no worker subprocess).
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    worker: Option<Worker>,
    /// Keeps the pool alive for the lifetime of this PooledVm.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pool_arc: Arc<HiddenPool>,
    /// Linux/KVM: the pool to return to on Drop (discard the dirty VM + refill
    /// the idle queue). `None` for a poolless cold-start fallback.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pool: Option<Arc<KvmPoolInner>>,
    /// Linux no-virt sentry: the shared-exec-server pool whose admission slot
    /// this checkout holds; released on Drop. `None` for KVM/cold-start.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_pool: Option<Arc<SentryPool>>,
    /// Linux/runsc: checkpoint-backed pool whose admission slot this restored
    /// container holds. Dropping the inner Vm deletes the runsc container.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    runsc_pool: Option<Arc<RunscPoolInner>>,
    /// Linux/kboxlike: native no-KVM process-tree pool. Dropping the inner Vm
    /// kills the restored tree, unless dirty warm reuse is explicitly enabled.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    kboxlike_pool: Option<Arc<KboxlikePoolInner>>,
    /// Linux no-virt sentry: per-checkout memory-admission reservation. Sentry
    /// cells are forked on demand, so charging live checkouts matches KVM's
    /// worker-lifetime accounting better than reserving the pool's whole `max`
    /// at build time.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_mem_admission: Option<crate::memory_admission::AdmissionGuard>,
    /// WarmDaemon pool: the detached daemon pid forked at acquire
    /// (`Pool::acquire_running`). Released (SIGKILL+reap via `Pool::release`) in
    /// Drop BEFORE the admission slot frees. `None` for the ExecServer pooled path /
    /// KVM / cold-start.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_running_pid: Option<i32>,
    /// WarmDaemon/live-C4 pool that owns `sentry_running_pid` and serves this
    /// checkout's exec/snapshot route. Shared for warm-zygote pools; per-checkout
    /// for live-tree C4 restores.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_running_pool: Option<Arc<crate::sentry::Pool>>,
    /// True for per-checkout live-tree C4 supervisors; stop them on Drop after
    /// releasing the restored root pid.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_stop_running_pool_on_drop: bool,
    /// Linux no-virt sentry: set the first time this checkout is dereferenced
    /// into a `Vm`. Untouched checkouts have not run guest code or host-side file
    /// APIs, so `restore_on_release(true)` can skip the rootfs reset fast path.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry_touched: AtomicBool,
    _image: std::marker::PhantomData<&'a Image>,
}

impl std::ops::Deref for PooledVm<'_> {
    type Target = Vm;
    fn deref(&self) -> &Vm {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if self.sentry_pool.is_some() {
            self.sentry_touched.store(true, Ordering::Relaxed);
        }
        // Invariant: vm is `Some` until Drop runs.
        self.vm.as_ref().expect("PooledVm used after drop")
    }
}

impl std::ops::DerefMut for PooledVm<'_> {
    fn deref_mut(&mut self) -> &mut Vm {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if self.sentry_pool.is_some() {
            self.sentry_touched.store(true, Ordering::Relaxed);
        }
        self.vm.as_mut().expect("PooledVm used after drop")
    }
}

impl PooledVm<'_> {
    /// Capture a live snapshot of this pooled VM, non-consuming, so the builder
    /// can snapshot one checked-out machine repeatedly across layers. KVM
    /// delegates to [`Vm::snapshot_live`].
    ///
    /// **Sentry backend:** a pooled sentry `Vm` shares the pool supervisor
    /// (`running` and `sentry_src_rootfs` are both `None`), so it cannot use the
    /// KVM `RunningVm` path. It copies the served rootfs into `dest_dir/rootfs`,
    /// then asks the supervisor to capture any owned live process tree, memory,
    /// loopback, fd, cwd, and proc metadata into `restore.snap`/`mem.blob`.
    /// Capture at a quiescent point, matching the KVM/HVF live-snapshot contract.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot(&self, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        // Sentry-backed pooled VM: copy the served rootfs and append supervisor
        // C4 state. The pool keeps serving — non-consuming.
        if let Some(sp) = &self.sentry_pool {
            let dest_dir = dest_dir.into();
            let image = write_sentry_snapshot_dir_inner(
                &sp.rootfs,
                &dest_dir,
                "Vm::snapshot_live",
                true,
                Some(sp.mem_mib as u32),
                Some(sp.vcpus),
            )?;
            if let Some(pool) = &self.sentry_running_pool {
                pool.snapshot(&dest_dir)
                    .map_err(|e| Error::vm_msg(format!("sentry live snapshot capture: {e}")))?;
            } else {
                sp.capture_live_state_into(&dest_dir)?;
            }
            return Ok(image);
        }
        if self.runsc_pool.is_some() {
            let dest_dir = dest_dir.into();
            let vm = self
                .vm
                .as_ref()
                .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?;
            let runsc = vm.runsc.as_ref().ok_or_else(|| {
                Error::vm_msg("PooledVm::snapshot: runsc pool checkout has no runtime".to_owned())
            })?;
            return write_runsc_snapshot_dir(runsc, &dest_dir, "Vm::snapshot_live", true);
        }
        if self
            .kboxlike_pool
            .as_ref()
            .map(|pool| pool.vm_config.for_build)
            .unwrap_or(false)
        {
            let dest_dir = dest_dir.into();
            let vm = self
                .vm
                .as_ref()
                .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?;
            let kboxlike = vm.kboxlike.as_ref().ok_or_else(|| {
                Error::vm_msg(
                    "PooledVm::snapshot: kboxlike pool checkout has no runtime".to_owned(),
                )
            })?;
            return write_kboxlike_snapshot_dir(kboxlike, &dest_dir, "Vm::snapshot_live");
        }
        self.vm
            .as_ref()
            .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?
            .snapshot_live(dest_dir)
    }

    /// Live differential snapshot against `base_path` (a full snapshot's
    /// `restore.snap`) — non-consuming. Delegates to [`Vm::snapshot_diff_live`].
    ///
    /// **Sentry backend:** C4 state is not page-diffed yet, so this degrades to a
    /// full rootfs plus full owned-state capture, ignoring `base_path`. The
    /// returned layer dir is a complete, self-contained, loadable sentry image
    /// rather than a space-saving delta.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot_diff(
        &self,
        dest_dir: impl Into<PathBuf>,
        base_path: &Path,
    ) -> Result<Image, Error> {
        if let Some(sp) = &self.sentry_pool {
            // No page-level diff for sentry C4 yet: full rootfs + state capture.
            let _ = base_path;
            let dest_dir = dest_dir.into();
            let image = write_sentry_snapshot_dir_inner(
                &sp.rootfs,
                &dest_dir,
                "Vm::snapshot_live",
                true,
                Some(sp.mem_mib as u32),
                Some(sp.vcpus),
            )?;
            if let Some(pool) = &self.sentry_running_pool {
                pool.snapshot(&dest_dir)
                    .map_err(|e| Error::vm_msg(format!("sentry live snapshot capture: {e}")))?;
            } else {
                sp.capture_live_state_into(&dest_dir)?;
            }
            return Ok(image);
        }
        if self.runsc_pool.is_some() {
            let _ = base_path;
            let dest_dir = dest_dir.into();
            let vm = self
                .vm
                .as_ref()
                .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?;
            let runsc = vm.runsc.as_ref().ok_or_else(|| {
                Error::vm_msg(
                    "PooledVm::snapshot_diff: runsc pool checkout has no runtime".to_owned(),
                )
            })?;
            return write_runsc_snapshot_dir(runsc, &dest_dir, "Vm::snapshot_live", true);
        }
        if self
            .kboxlike_pool
            .as_ref()
            .map(|pool| pool.vm_config.for_build)
            .unwrap_or(false)
        {
            let _ = base_path;
            let dest_dir = dest_dir.into();
            let vm = self
                .vm
                .as_ref()
                .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?;
            let kboxlike = vm.kboxlike.as_ref().ok_or_else(|| {
                Error::vm_msg(
                    "PooledVm::snapshot_diff: kboxlike pool checkout has no runtime".to_owned(),
                )
            })?;
            return write_kboxlike_snapshot_dir(kboxlike, &dest_dir, "Vm::snapshot_live");
        }
        self.vm
            .as_ref()
            .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?
            .snapshot_diff_live(dest_dir, base_path)
    }

    /// Capture a snapshot of this VM's current state and return
    /// a new [`Image`] pointing at it. Equivalent to
    /// [`Vm::snapshot`] but works on the subprocess-pool path
    /// — the entitled worker subprocess does the HVF capture
    /// over the supervisor RPC, so the calling binary doesn't
    /// need the `com.apple.security.hypervisor` entitlement.
    ///
    /// Borrows `self` rather than consuming, so you can
    /// continue using the VM after capturing — handy for the
    /// "warm up + snapshot + keep working" pattern. The guest
    /// is paused for the duration of the capture (typically
    /// 10s of ms; bounded by disk write time for large RAM).
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn snapshot(&self, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        self.snapshot_with_opt_base(dest_dir, None)
    }

    /// Differential snapshot against `base_path` (another snapshot's
    /// `restore.snap`). The worker clonefiles the base + writes only the pages
    /// that changed, and (because the base is kept in memory) a *chain* of
    /// these — the in-VM builder's per-layer snapshots — each diffs against the
    /// previous in memory. `inline` so the file is on disk when this returns.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn snapshot_diff(
        &self,
        dest_dir: impl Into<PathBuf>,
        base_path: &Path,
    ) -> Result<Image, Error> {
        self.snapshot_with_opt_base(dest_dir, Some(base_path))
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn snapshot_with_opt_base(
        &self,
        dest_dir: impl Into<PathBuf>,
        base_path: Option<&Path>,
    ) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        let _span = tracing::info_span!(
            "supermachine.snapshot",
            dest_dir = %dest_dir.display(),
        )
        .entered();
        let worker = self
            .worker
            .as_ref()
            .ok_or_else(|| Error::vm_msg("PooledVm: no worker (already dropped?)".to_owned()))?;
        let vm = self
            .vm
            .as_ref()
            .ok_or_else(|| Error::vm_msg("PooledVm: no vm (already dropped?)".to_owned()))?;
        let meta = vm.image_meta.clone().ok_or_else(|| {
            Error::vm_msg(
                "PooledVm::snapshot: image metadata missing (acquire from a 0.3.8+ Image)"
                    .to_owned(),
            )
        })?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        let snap_path = dest_dir.join("restore.snap");
        // Flush guest dirty pages to host-persistent backing files
        // (virtio-blk volumes, writeback-cached virtio-fs) so the
        // capture doesn't leave them torn on the host — see
        // `guest_sync_via_agent`. Before park: parked secondaries
        // can't run writeback kworkers.
        let _ = guest_sync_via_agent(&worker.vsock_exec_path);
        // Multi-vCPU: park secondaries via smpark.ko before the
        // capture rendezvous. The agent ioctls /dev/smpark, which
        // broadcasts an IPI to all secondaries; each one drains
        // local LRs, masks IRQs, and spins in WFI. The captured
        // per-vCPU state is then byte-identical-trivial across
        // secondaries — HVF can round-trip THAT, fixing the
        // "restored guest RCU-stalls / NULL-derefs in interrupt
        // context" failure class. Best-effort: if smpark.ko isn't
        // loaded (older snapshots, single-vCPU bake), the agent
        // returns ok=false and we fall through to the existing
        // rendezvous-only capture path.
        let parked = if meta.vcpus > 1 {
            worker.send_smpark_park()?
        } else {
            false
        };
        // The diff-via-clone path with `last_restore_path` as
        // base would in principle win 200+ ms here, but the
        // runner needs base in memory and lazy-loading from
        // disk costs ~700 ms on first call. Without warm-cache
        // hits across pool cycles, that's net-negative for
        // single-shot snapshots. We use the plain streaming
        // save (parallel sparse pwrite, ~290 ms on 2 GiB).
        //
        // SUPERMACHINE_DIFF_CYCLE_SNAPSHOT was a pre-0.7.38
        // opt-in to the diff path; no production caller used it
        // and the diff path requires base-in-memory which the
        // pool's cycle-snapshot flow doesn't guarantee. Deleted.
        let snap_result = match base_path {
            Some(base) => worker.send_snapshot_with_base(&snap_path, base, true),
            None => worker.send_snapshot(&snap_path),
        };
        // Always unpark, even on snapshot failure — otherwise
        // secondaries stay stuck in WFI and the next acquire of
        // this VM is a brick. Best-effort: if park failed in the
        // first place, unpark is also a no-op.
        if parked {
            let _ = worker.send_smpark_unpark()?;
        }
        let _stats = snap_result?;
        let metadata = serde_json::json!({
            "backend": "hvf",
            "memory_mib": meta.memory_mib,
            "vcpus": meta.vcpus,
            "layers": meta
                .layers
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
            "delta_squashfs": meta
                .delta_squashfs
                .as_ref()
                .map(|p| p.to_string_lossy().to_string()),
            "snapshot_base": snap_path.to_string_lossy().to_string(),
            "runtime_sha16": meta.baker_runtime_sha16,
            "tsi_token": meta.tsi_token,
            "egress_policy": meta.egress_policy,
            "pre_exec_sync": meta.pre_exec_sync,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
            "baked_at": chrono_rfc3339_now(),
            "source": "PooledVm::snapshot",
        });
        std::fs::write(
            dest_dir.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::vm_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        Image::from_snapshot(&dest_dir)
    }
}

impl Drop for PooledVm<'_> {
    fn drop(&mut self) {
        // macOS: the inner Vm's Drop is a no-op (skip_cleanup=true; the worker
        // owns the sockets). Hand the worker back to the pool, which kills it
        // (snapshot state may be dirty) and replenishes to target N.
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            let _ = self.vm.take();
            if let Some(worker) = self.worker.take() {
                self.pool_arc.release(worker);
            }
        }
        // Linux no-virt sentry: drop the cheap Vm (skip_cleanup → no socket
        // unlink, no server teardown — the SentryPool owns the shared server)
        // and release the admission slot so a blocked acquirer can proceed.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(sp) = self.sentry_pool.take() {
            let touched = self.sentry_touched.load(Ordering::Relaxed);
            let had_running_checkout = self.sentry_running_pid.is_some();
            // WarmDaemon: SIGKILL+reap the detached daemon (frees its ring slot + host
            // fds) BEFORE freeing the admission slot — so a blocked acquirer doesn't
            // fork into a still-occupied ring. Best-effort (Drop can't ?-propagate);
            // Pool::release is idempotent for an unknown pid.
            if let (Some(pid), Some(pool)) = (
                self.sentry_running_pid.take(),
                self.sentry_running_pool.take(),
            ) {
                let _ = pool.release(pid);
                let _ = self.vm.take();
                if self.sentry_stop_running_pool_on_drop {
                    pool.stop();
                }
            } else {
                let _ = self.vm.take();
            }
            let shutting_down = sp.shut_down.load(std::sync::atomic::Ordering::SeqCst);
            if !shutting_down && (touched || had_running_checkout) {
                if let Err(e) = sp.restore_rootfs_from_baseline() {
                    eprintln!(
                        "supermachine: sentry rootfs restore_on_release reset failed ({e}); \
                         next acquire may observe dirty filesystem state"
                    );
                }
            }
            let _ = self.sentry_mem_admission.take();
            sp.admission.release();
            sp.cleanup_if_shutdown_idle();
            return;
        }
        // Linux/runsc: drop the restored container and release its admission slot.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(pool) = self.runsc_pool.take() {
            if let Some(vm) = self.vm.take() {
                pool.release_vm(vm);
            } else {
                pool.release_checkout();
                pool.admission.release();
            }
            return;
        }
        // Linux/kboxlike: drop or dirty-reuse the restored process tree and
        // release its admission slot.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(pool) = self.kboxlike_pool.take() {
            if let Some(vm) = self.vm.take() {
                pool.release_vm(vm);
            } else {
                pool.admission.release();
            }
            return;
        }
        // Linux/KVM.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(pool) = self.pool.take() {
            let Some(vm) = self.vm.take() else {
                return;
            };
            // Keep the VM warm (return ALIVE to idle for reuse) only up to the
            // `min` always-warm floor; beyond min, tear it down + free its slot.
            // This bounds idle at min when load subsides (so `min=0` drains to
            // zero — no leak, no janitor needed) while a `min=N` pool keeps N
            // VMs hot for full warm reuse. Concurrent releases may transiently
            // settle idle a little above min, still bounded by `max` — benign,
            // and those extras are warm-reusable.
            let warm_slot = {
                let idle = pool.idle.lock().unwrap_or_else(|e| e.into_inner());
                idle.len() < pool.min
            };
            if !warm_slot {
                // Above the warm floor: stop the VM (inner Vm Drop) + free slot.
                drop(vm);
                pool.admission.release();
                return;
            }
            // Within the warm floor: return the VM ALIVE to idle for reuse,
            // keeping its admission slot (it IS the replenishment, so no refill).
            //   - restore_on_release=true (default): in-place reset to the
            //     snapshot baseline FIRST (RAM + CPU + intc/clock + serial +
            //     device state) for clean per-cycle isolation — far cheaper than
            //     teardown + fresh restore since the KVM VM/vCPUs/threads/RAM all
            //     persist. On reset failure, tear down (never reuse a half-reset
            //     VM). Mirrors HVF's restore_on_release(true) in-place RESTORE.
            //   - restore_on_release=false (opt-in): reuse as-is — fastest, but
            //     the guest carries state across cycles (trusted/idempotent only).
            if pool.restore_on_release {
                if let Err(e) = vm.reset_to_snapshot() {
                    eprintln!(
                        "supermachine: KVM in-place reset failed ({e}); \
                         tearing down this VM instead of reusing it"
                    );
                    drop(vm);
                    pool.admission.release();
                    // We lost a within-floor warm VM; background-restore a fresh
                    // one to keep the idle set at `min`.
                    pool.refill_async();
                    return;
                }
                // The reset rewound guest RAM — including the kernel
                // timekeeper — to the warm BASELINE, so the guest wall
                // clock is now however far in the past the baseline
                // capture is. Re-anchor it exactly like the restore
                // path does (the 7a contract: monotonic survives,
                // REALTIME tracks the host); without this, a pool
                // serving traffic hours after its bake hands out VMs
                // whose TLS/signature validation lives in the past.
                // Caught by wall_clock_tracks_host_across_pool_reset_
                // cycles (drift == idle time between cycles).
                let _ = sync_time_via_agent(&vm.vsock_exec_path);
            }
            pool.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
            pool.admission.notify(); // wake an acquirer blocked at the cap
        } else {
            // Poolless cold-start fallback: just stop the VM.
            let _ = self.vm.take();
        }
    }
}

/// Configurable bake of an OCI image. Built via [`Image::builder`];
/// terminate with [`OciImageBuilder::build`] to produce an
/// [`Image`].
/// Builder for an explicitly configured worker pool. Started
/// with [`Image::pool`]; terminated with [`PoolBuilder::build`].
///
/// Defaults: `min=0`, `max=64`, `idle_timeout=60s`,
/// `acquire_timeout=60s` — i.e. lazy spawn, auto-evict, fail-
/// noisily on saturation. Override any of these with the
/// chainable setters below.
pub struct PoolBuilder<'a> {
    image: &'a Image,
    policy: PoolPolicy,
    /// Runtime overrides applied at pool-build time. Memory / vCPU
    /// changes here don't re-bake the snapshot — they override what
    /// the worker subprocess advertises to HVF at restore. Lazily
    /// committed (CoW page-fault), so a larger memory_mib than
    /// what was baked just raises the guest-visible ceiling without
    /// committing host pages.
    vm_config: VmConfig,
}

impl PoolBuilder<'_> {
    /// Always-warm baseline. The pool keeps at least this many
    /// workers alive — even if everyone drops their `PooledVm`,
    /// the next `acquire` finds these waiting in idle. Default 0
    /// (lazy-spawn on first acquire).
    pub fn min(mut self, n: usize) -> Self {
        self.policy.min = n;
        self
    }

    /// Hard concurrency cap. `acquire` blocks (with timeout) when
    /// `max` peers are checked out simultaneously. Default 64;
    /// raise for large multi-tenant fleets. Pass `usize::MAX` for
    /// effectively unbounded.
    pub fn max(mut self, n: usize) -> Self {
        self.policy.max = n.max(1);
        self
    }

    /// Idle workers above `min` that have been unused for longer
    /// than this get killed by the janitor — frees host RAM
    /// during quiet periods. Default 60 s. Pass `Duration::MAX`
    /// to disable eviction (fixed-size pool with no churn).
    pub fn idle_timeout(mut self, d: Duration) -> Self {
        self.policy.idle_timeout = d;
        self
    }

    /// Caller's `acquire` blocks at most this long when the pool
    /// is at `max` and no worker is idle. After that the call
    /// returns [`Error::PoolExhausted`]. Default 60 s. Pass `None`
    /// (via this method's twin if added) to block forever; pass
    /// `Duration::ZERO` to fail-fast.
    pub fn acquire_timeout(mut self, d: Duration) -> Self {
        self.policy.acquire_timeout = Some(d);
        self
    }

    /// Disable the acquire timeout — `acquire` blocks forever
    /// when at `max`. Useful for batch workloads where you'd
    /// rather wait than fail. Equivalent to passing `None`
    /// internally.
    pub fn no_acquire_timeout(mut self) -> Self {
        self.policy.acquire_timeout = None;
        self
    }

    /// Skip the per-cycle snapshot RESTORE on `PooledVm::drop`.
    /// Workers go straight back to the idle queue carrying
    /// whatever guest state the previous user left.
    ///
    /// Default `true`: every acquire starts from a clean
    /// snapshot-state guest. Pay ~3 ms restore per cycle (off
    /// the user's critical path with a buddy slot).
    ///
    /// `false`: opt into "warm worker reuse" — guest page cache
    /// stays warm across cycles. For workloads that re-read the
    /// same files every invocation (rustc + sysroot, python +
    /// stdlib, node + node_modules), this is a 3-6× speedup
    /// because the second compile/import doesn't re-fault
    /// pages from the squashfs layer.
    ///
    /// Safe when the workload always overwrites its own outputs
    /// (e.g. `rustc -o /tmp/m && /tmp/m` overwrites both source
    /// and binary on every cycle). Unsafe if the workload trusts
    /// `/tmp` to be clean or accumulates files unboundedly —
    /// the guest's RAM+fs accumulates state forever in this mode,
    /// so pair with periodic pool rebuild for long runs.
    pub fn restore_on_release(mut self, on: bool) -> Self {
        self.policy.restore_on_release = on;
        self
    }

    /// Mark this pool as backing a Dockerfile BUILD stage.
    /// `on = true` makes no-KVM rootfs backends serve the stage's `RUN` steps from
    /// a PER-BUILD PRIVATE clone of the warm rootfs — so each build/stage mutates
    /// its own throwaway filesystem (per-build/per-stage isolation + failed-RUN
    /// rollback + no cross-stage collision, all discarded on pool Drop) — and
    /// suppresses the base image's baked-workload auto-start (a build base must
    /// not run its `CMD` while `RUN` steps execute). Sentry uses its shared exec
    /// server; kboxlike uses its rootfs/chroot exec path. An explicit flag (NOT
    /// `restore_on_release(false)`, which a non-build caller legitimately sets);
    /// the KVM/HVF backends ignore it (they isolate per-layer via a tmpfs
    /// overlay-upper). Off by default.
    pub fn for_build(mut self, on: bool) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_for_build(on);
        self
    }

    /// Per-acquire restore timeout. Forwarded to the inner
    /// [`VmConfig::with_restore_timeout`] used to spawn pool
    /// workers. Default 30 s (set at spawn time inside the pool).
    /// Bump for slow disks or large RAM snapshots; restore time
    /// scales roughly linearly with snapshot size.
    pub fn with_restore_timeout(mut self, timeout: Duration) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_restore_timeout(timeout);
        self
    }

    /// Override the baked image's memory ceiling for this pool's
    /// workers. Pure runtime override — doesn't re-bake the
    /// snapshot. Pages are lazy-committed (CoW page-fault), so
    /// raising the ceiling beyond what was baked doesn't increase
    /// host commit unless the guest actually writes to the new
    /// pages.
    pub fn with_memory_mib(mut self, mib: u32) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_memory_mib(mib);
        self
    }

    /// Bound how long any single `exec` in this pool may run before the supervisor
    /// SIGKILLs it and reports `SentryError::Timeout` (exit `137`) — sentry backend
    /// only. Forwarded to [`VmConfig::with_sentry_exec_timeout`]. UNSET = the
    /// generous default ceiling (10 min) so a wedged exec can't hang the pool
    /// forever; `Duration::ZERO` runs UNLIMITED.
    pub fn with_sentry_exec_timeout(mut self, dur: Duration) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_sentry_exec_timeout(dur);
        self
    }

    /// Override where this pool places host-side communication sockets and, for
    /// the sentry backend, the private runtime/baseline rootfs copies owned by
    /// the pool. Mainly useful for lifecycle tests and embedders that want all
    /// transient pool state under a known parent.
    pub fn with_vsock_mux_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_vsock_mux_dir(dir);
        self
    }

    /// Override the baked image's vCPU count for this pool's
    /// workers. Pure runtime override.
    pub fn with_vcpus(mut self, vcpus: u32) -> Self {
        self.vm_config = std::mem::take(&mut self.vm_config).with_vcpus(vcpus);
        self
    }

    /// Build the pool against this image's snapshot. Spawns
    /// the initial `min` workers in parallel, starts the
    /// housekeeping threads (replenisher / restorer / janitor),
    /// returns a [`Pool`] handle.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn build(self) -> Result<Pool, Error> {
        let image = self.image;
        // Normalize: min must not exceed max — otherwise the
        // pre-spawn loop in build_hidden_pool would create more
        // workers than the auto-grow ceiling allows, and the
        // `alive ≤ max` invariant breaks.
        let mut policy = self.policy;
        if policy.min > policy.max {
            policy.min = policy.max;
        }
        let arc = image.build_pool_arc(&self.vm_config, policy)?;
        // Try to install this pool as the per-Image default so
        // subsequent `image.acquire()` / `image.acquire_with()`
        // calls go through the same configured pool. If the
        // OnceLock is already set (the user called acquire()
        // before pool().build()), we error rather than silently
        // returning a config-less default — that's the bug the
        // 0.4.1 docs accidentally created.
        match image.hidden_pool.set(Arc::clone(&arc)) {
            Ok(()) => Ok(Pool { inner: arc }),
            Err(_) => Err(Error::vm_msg(
                "this Image already has a Pool — pool() can only be called \
                 once per Image handle.\n\n\
                 To run two independent pools off the same snapshot, load the \
                 Image twice via Image.fromSnapshot:\n\n  \
                 const a = await Image.fromSnapshot(snapshotPath);\n  \
                 const b = await Image.fromSnapshot(snapshotPath);\n  \
                 const poolA = await a.pool(...);\n  \
                 const poolB = await b.pool(...);\n\n\
                 If you called image.acquire() before image.pool(), the \
                 Image has been bound to a default pool whose policy can't \
                 be changed in place — either reorder the calls or use \
                 fromSnapshot() to get a fresh handle."
                    .to_owned(),
            )),
        }
    }

    /// Build the pool (Linux/KVM). Warms the source image into a snapshot once
    /// (boot → agent-ready → capture), so every [`Pool::acquire`] is a CoW
    /// snapshot restore (~ms) instead of a cold boot (~1 s). If the image is
    /// already snapshot-backed it's used as-is.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn build(self) -> Result<Pool, Error> {
        // Parity with macOS/KVM, checked for BOTH backends: if the image is
        // already bound to a default pool (the user called image.acquire() before
        // pool().build() — both the sentry and KVM acquire paths latch the
        // `kvm_pool` OnceLock), error rather than silently returning a second,
        // unrelated pool whose policy the default-acquire path ignores.
        if self.image.kvm_pool.get().is_some() {
            return Err(Error::vm_msg(
                "this Image already has a default Pool — image.acquire() was \
                 called before pool().build(), binding a default pool whose \
                 policy can't be changed in place. Reorder so pool().build() \
                 runs first, or load a fresh handle via Image::from_snapshot."
                    .to_owned(),
            ));
        }
        // No-virt sentry image: build a pool over one shared, always-warm exec
        // server. `max` bounds concurrent checkouts; `min` is a no-op (the
        // server IS the warm set — there are no idle instances to pre-restore).
        if self.image.sentry.is_some() {
            let sp = SentryPool::build(
                self.image,
                &self.vm_config,
                self.policy.max,
                self.policy.acquire_timeout,
                self.policy.restore_on_release,
            )?;
            return Ok(Pool {
                kvm: None,
                sentry: Some(sp),
                runsc: None,
                kboxlike: None,
            });
        }
        if self.image.runsc.is_some() {
            let min = self.policy.min.min(self.policy.max.max(1));
            let rp = RunscPoolInner::build(
                self.image,
                &self.vm_config,
                min,
                self.policy.max,
                self.policy.acquire_timeout,
                self.policy.restore_on_release,
            )?;
            return Ok(Pool {
                kvm: None,
                sentry: None,
                runsc: Some(rp),
                kboxlike: None,
            });
        }
        if self.image.kboxlike.is_some() {
            let min = self.policy.min.min(self.policy.max.max(1));
            let kp = KboxlikePoolInner::build(
                self.image,
                &self.vm_config,
                min,
                self.policy.max,
                self.policy.acquire_timeout,
                self.policy.restore_on_release,
            )?;
            return Ok(Pool {
                kvm: None,
                sentry: None,
                runsc: None,
                kboxlike: Some(kp),
            });
        }
        let warm = warm_snapshot_for_pool(self.image, &self.vm_config)?;
        // min must not exceed max, or the pre-warm loop would over-spawn beyond
        // the admission cap.
        let min = self.policy.min.min(self.policy.max.max(1));
        let inner = Arc::new(KvmPoolInner {
            image: warm,
            vm_config: self.vm_config,
            min,
            idle: std::sync::Mutex::new(Vec::new()),
            admission: Admission::new(self.policy.max, self.policy.acquire_timeout),
            restore_on_release: self.policy.restore_on_release,
            refilling: std::sync::atomic::AtomicBool::new(false),
            shut_down: std::sync::atomic::AtomicBool::new(false),
        });
        // Eager pre-warm to `min` idle VMs SYNCHRONOUSLY, so the returned pool's
        // stats() immediately reflect the configured baseline (no-op when
        // min == 0 — lazy pools stay lazy).
        inner.prewarm_to_min();
        Ok(Pool {
            kvm: Some(inner),
            sentry: None,
            runsc: None,
            kboxlike: None,
        })
    }
}

/// Prepare KVM data volumes: for each [`VolumeSpec`], ensure the host backing
/// file exists (created sparse to `size_bytes` and formatted ext4 on first use,
/// reused otherwise so data persists), and return the per-volume attach specs
/// for [`crate::kvm::run::LinuxVmConfig`]. Formatting is done host-side with
/// the in-process `crate::ext4` synthesizer so the guest init only has to
/// mount — no host e2fsprogs needed.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn prepare_kvm_volumes(
    specs: &[crate::vmm::resources::VolumeSpec],
) -> Result<Vec<crate::kvm::run::VolumeAttach>, Error> {
    let mut out = Vec::with_capacity(specs.len());
    for spec in specs {
        let path = std::path::Path::new(&spec.host_path);
        let fresh = !path.exists();
        if fresh {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(Error::Io)?;
            }
            // Synthesize an empty, journal-less ext4 in-process (sparse
            // file; cleans up after itself on failure). No host mke2fs
            // needed — see `crate::ext4` for the format choices.
            crate::ext4::make_empty_ext4(path, spec.size_bytes)
                .map_err(|e| Error::vm_msg(format!("format volume {}: {e}", spec.host_path)))?;
        }
        out.push(crate::kvm::run::VolumeAttach {
            path: spec.host_path.clone(),
            size: spec.size_bytes,
            mount: spec.guest_path.clone(),
        });
    }
    Ok(out)
}

/// Join a guest-relative path under `rootfs`, rejecting any component that would
/// escape it (an absolute path or a `..`/root component). Used to stage
/// `with_extra_file` payloads into a sentry rootfs at bake time without a
/// traversal surface — the sentry analogue of the KVM bake's confined
/// delta-layer staging. Returns `None` on a hostile path.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn confined_rootfs_join(rootfs: &Path, rel: &str) -> Option<PathBuf> {
    let p = Path::new(rel);
    let escapes = p.is_absolute()
        || p.components().any(|c| {
            matches!(
                c,
                std::path::Component::ParentDir | std::path::Component::RootDir
            )
        });
    if escapes || rel.is_empty() {
        return None;
    }
    Some(rootfs.join(p))
}

/// Persist the OciImageBuilder's data volumes into a baked KVM snapshot's
/// `metadata.json` (the `volumes: [{host_file, guest_path, size_bytes}]` array
/// that [`Image::from_snapshot`] parses into `Image::volumes`). On every start,
/// `Vm::start` merges these baked volumes into `prepare_kvm_volumes` — parity
/// with the HVF backend's bake-time `with_volume`.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn persist_kvm_builder_volumes(
    snap_dir: &Path,
    volumes: &[(PathBuf, String, u64)],
) -> Result<(), Error> {
    let meta_path = snap_dir.join("metadata.json");
    let text = std::fs::read_to_string(&meta_path).map_err(Error::Io)?;
    let mut meta: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| Error::vm_msg(format!("parse {}: {e}", meta_path.display())))?;
    let arr: Vec<serde_json::Value> = volumes
        .iter()
        .map(|(host, guest, size)| {
            serde_json::json!({
                "host_file": host.to_string_lossy(),
                "guest_path": guest,
                "size_bytes": size,
            })
        })
        .collect();
    if let Some(obj) = meta.as_object_mut() {
        obj.insert("volumes".into(), serde_json::json!(arr));
    }
    std::fs::write(
        &meta_path,
        serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::vm_msg(format!("serialize metadata: {e}")))?,
    )
    .map_err(Error::Io)?;
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kvm_bake_key_matches(snap_dir: &Path, expected: &str) -> bool {
    std::fs::read_to_string(snap_dir.join("metadata.json"))
        .ok()
        .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
        .and_then(|meta| {
            meta.get("kvm_bake_key")
                .and_then(|v| v.as_str())
                .map(str::to_owned)
        })
        .as_deref()
        == Some(expected)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn builder_mount_specs(
    mounts: &[(
        PathBuf,
        String,
        crate::vmm::resources::SymlinkPolicy,
        String,
    )],
) -> Vec<crate::vmm::resources::MountSpec> {
    mounts
        .iter()
        .map(|(host, tag, policy, guest_path)| {
            crate::vmm::resources::MountSpec::new(
                host.to_string_lossy().to_string(),
                tag.clone(),
                guest_path.clone(),
            )
            .with_symlinks(policy.clone())
        })
        .collect()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn effective_builder_workload(
    image_workload: Option<String>,
    oci_config: Option<&serde_json::Value>,
    cmd: Option<&Vec<String>>,
    envs: &[(String, String)],
) -> (
    Option<String>,
    Vec<(String, String)>,
    Option<String>,
    Option<String>,
) {
    let mut env_pairs: Vec<(String, String)> = Vec::new();
    if let Some(cfg) = oci_config {
        for kv in cfg
            .get("Env")
            .and_then(|v| v.as_array())
            .into_iter()
            .flatten()
            .filter_map(|v| v.as_str())
        {
            if let Some(eq) = kv.find('=') {
                env_pairs.push((kv[..eq].to_string(), kv[eq + 1..].to_string()));
            }
        }
    }
    for (k, v) in envs {
        env_pairs.retain(|(ek, _)| ek != k);
        env_pairs.push((k.clone(), v.clone()));
    }

    let effective_workdir = oci_config
        .and_then(|c| c.get("WorkingDir"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    let effective_user = oci_config
        .and_then(|c| c.get("User"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_owned);

    let workload = if let Some(cmd) = cmd {
        crate::bake::sentry_workload_script(cmd, &env_pairs, effective_workdir.as_deref())
    } else if !envs.is_empty() || effective_workdir.is_some() {
        let mut argv: Vec<String> = Vec::new();
        if let Some(cfg) = oci_config {
            for v in cfg
                .get("Entrypoint")
                .and_then(|v| v.as_array())
                .into_iter()
                .flatten()
                .filter_map(|v| v.as_str())
            {
                argv.push(v.to_string());
            }
            for v in cfg
                .get("Cmd")
                .and_then(|v| v.as_array())
                .into_iter()
                .flatten()
                .filter_map(|v| v.as_str())
            {
                argv.push(v.to_string());
            }
        }
        if argv.is_empty() {
            image_workload
        } else {
            crate::bake::sentry_workload_script(&argv, &env_pairs, effective_workdir.as_deref())
        }
    } else {
        image_workload
    };

    (workload, env_pairs, effective_workdir, effective_user)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn mount_specs_metadata(mounts: &[crate::vmm::resources::MountSpec]) -> Vec<serde_json::Value> {
    mounts
        .iter()
        .map(|m| {
            let mut obj = serde_json::Map::new();
            obj.insert("host_path".to_string(), serde_json::json!(m.host_path));
            obj.insert("guest_tag".to_string(), serde_json::json!(m.guest_tag));
            obj.insert("guest_path".to_string(), serde_json::json!(m.guest_path));
            match m.symlinks {
                crate::vmm::resources::SymlinkPolicy::Opaque => {}
                crate::vmm::resources::SymlinkPolicy::Deny => {
                    obj.insert("symlinks".to_string(), serde_json::json!("deny"));
                }
                crate::vmm::resources::SymlinkPolicy::Follow => {
                    obj.insert("symlinks".to_string(), serde_json::json!("follow"));
                }
            }
            serde_json::Value::Object(obj)
        })
        .collect()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn volume_specs_metadata(volumes: &[(PathBuf, String, u64)]) -> Vec<serde_json::Value> {
    volumes
        .iter()
        .map(|(host, guest, size)| {
            serde_json::json!({
                "host_file": host.to_string_lossy(),
                "guest_path": guest,
                "size_bytes": size,
            })
        })
        .collect()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn insert_kvm_builder_run_config(
    obj: &mut serde_json::Map<String, serde_json::Value>,
    image_ref: &str,
    kvm_bake_key: &str,
    env_pairs: &[(String, String)],
    cmd: Option<&Vec<String>>,
    oci_config: Option<&serde_json::Value>,
    effective_workdir: Option<&str>,
    effective_user: Option<&str>,
    warm_daemon: bool,
    warmup_tag: Option<&str>,
    mounts: &[crate::vmm::resources::MountSpec],
    volumes: &[(PathBuf, String, u64)],
) {
    obj.insert("image".to_string(), serde_json::json!(image_ref));
    obj.insert("kvm_bake_key".to_string(), serde_json::json!(kvm_bake_key));
    obj.insert(
        "baked_by_version".to_string(),
        serde_json::json!(env!("CARGO_PKG_VERSION")),
    );
    let mut env_obj = serde_json::Map::new();
    for (k, v) in env_pairs {
        env_obj.insert(k.clone(), serde_json::json!(v));
    }
    obj.insert("image_env".to_string(), serde_json::Value::Object(env_obj));
    if let Some(cmd) = cmd {
        obj.insert("cmd".to_string(), serde_json::json!(cmd));
        obj.remove("entrypoint");
    } else if let Some(cfg) = oci_config {
        for (oci_key, meta_key) in [("Cmd", "cmd"), ("Entrypoint", "entrypoint")] {
            if let Some(v) = cfg.get(oci_key) {
                if !v.is_null() {
                    obj.insert(meta_key.to_string(), v.clone());
                }
            }
        }
    }
    if let Some(dir) = effective_workdir {
        obj.insert("working_dir".to_string(), serde_json::json!(dir));
    }
    if let Some(user) = effective_user {
        obj.insert("user".to_string(), serde_json::json!(user));
    }
    obj.insert("warm_daemon".to_string(), serde_json::json!(warm_daemon));
    if let Some(tag) = warmup_tag {
        obj.insert("warmup_tag".to_string(), serde_json::json!(tag));
    }
    if !mounts.is_empty() {
        obj.insert(
            "mounts".to_string(),
            serde_json::Value::Array(mount_specs_metadata(mounts)),
        );
    }
    if !volumes.is_empty() {
        obj.insert(
            "volumes".to_string(),
            serde_json::Value::Array(volume_specs_metadata(volumes)),
        );
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[allow(clippy::too_many_arguments)]
fn write_kvm_cold_builder_metadata(
    dest_dir: &Path,
    image_ref: &str,
    kvm_bake_key: &str,
    kernel: &Path,
    initrd: &Path,
    rootfs: &Path,
    memory_mib: u32,
    vcpus: u32,
    physical_bytes: u64,
    env_pairs: &[(String, String)],
    cmd: Option<&Vec<String>>,
    oci_config: Option<&serde_json::Value>,
    effective_workdir: Option<&str>,
    effective_user: Option<&str>,
    warm_daemon: bool,
    warmup_tag: Option<&str>,
    mounts: &[crate::vmm::resources::MountSpec],
    volumes: &[(PathBuf, String, u64)],
) -> Result<(), Error> {
    let mut metadata = serde_json::json!({
        "backend": "kvm",
        "kvm_kernel": kernel.to_string_lossy(),
        "kvm_initrd": initrd.to_string_lossy(),
        "kvm_disk": rootfs.to_string_lossy(),
        "memory_mib": memory_mib,
        "vcpus": vcpus,
        "balloon_target_pages": crate::bake::compute_balloon_target_pages(memory_mib),
        "baked_at": chrono_rfc3339_now(),
        "snapshot_physical_bytes": physical_bytes,
    });
    if let Some(obj) = metadata.as_object_mut() {
        insert_kvm_builder_run_config(
            obj,
            image_ref,
            kvm_bake_key,
            env_pairs,
            cmd,
            oci_config,
            effective_workdir,
            effective_user,
            warm_daemon,
            warmup_tag,
            mounts,
            volumes,
        );
    }
    std::fs::write(
        dest_dir.join("metadata.json"),
        serde_json::to_string_pretty(&metadata)
            .map_err(|e| Error::bake_msg(format!("metadata serialize: {e}")))?,
    )
    .map_err(Error::Io)?;
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[allow(clippy::too_many_arguments)]
fn persist_kvm_builder_run_config(
    snap_dir: &Path,
    image_ref: &str,
    kvm_bake_key: &str,
    env_pairs: &[(String, String)],
    cmd: Option<&Vec<String>>,
    oci_config: Option<&serde_json::Value>,
    effective_workdir: Option<&str>,
    effective_user: Option<&str>,
    warm_daemon: bool,
    warmup_tag: Option<&str>,
    mounts: &[crate::vmm::resources::MountSpec],
    volumes: &[(PathBuf, String, u64)],
) -> Result<(), Error> {
    let meta_path = snap_dir.join("metadata.json");
    let text = std::fs::read_to_string(&meta_path).map_err(Error::Io)?;
    let mut meta: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| Error::vm_msg(format!("parse {}: {e}", meta_path.display())))?;
    let obj = meta
        .as_object_mut()
        .ok_or_else(|| Error::vm_msg("KVM metadata is not an object".to_owned()))?;
    insert_kvm_builder_run_config(
        obj,
        image_ref,
        kvm_bake_key,
        env_pairs,
        cmd,
        oci_config,
        effective_workdir,
        effective_user,
        warm_daemon,
        warmup_tag,
        mounts,
        volumes,
    );
    std::fs::write(
        &meta_path,
        serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::vm_msg(format!("serialize metadata: {e}")))?,
    )
    .map_err(Error::Io)?;
    Ok(())
}

/// Write a `"backend":"kvm"` metadata.json next to a captured snapshot so
/// [`Image::from_snapshot`] can load it. `snap_rel` is the snapshot filename
/// RELATIVE to `dest_dir` (resolved dir-relative on load, so a cloned dir stays
/// loadable). `base` set → a differential snapshot (records the base ref).
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_kvm_snapshot_metadata(
    dest_dir: &Path,
    snap_rel: &str,
    base: Option<&Path>,
    mem_size: usize,
    num_cpus: u8,
) -> Result<(), Error> {
    let mut meta = serde_json::json!({
        "backend": "kvm",
        "kvm_snapshot": snap_rel,
        "memory_mib": (mem_size >> 20) as u32,
        "vcpus": num_cpus as u32,
        "baked_at": chrono_rfc3339_now(),
        "source": "Vm::snapshot_live",
    });
    if let Some(b) = base {
        meta["kvm_snapshot_base"] = serde_json::json!(b.to_string_lossy());
        meta["source"] = serde_json::json!("Vm::snapshot_diff_live");
    }
    std::fs::write(
        dest_dir.join("metadata.json"),
        serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::vm_msg(format!("metadata serialize: {e}")))?,
    )
    .map_err(Error::Io)?;
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kvm_effective_vcpus(requested: u32, context: &str) -> u32 {
    let requested = requested.max(1);
    if requested > 1 {
        eprintln!(
            "supermachine(KVM): {context} requested {requested} vCPUs, but Linux/x86_64 KVM \
             SMP is not enabled in this backend yet; using 1 vCPU"
        );
        1
    } else {
        requested
    }
}

/// Warm an image into a snapshot-backed [`Image`] for the pool's fast restore
/// path (Linux/KVM). A snapshot-backed image is returned unchanged; a cold-boot
/// image is booted once, the agent comes up, then it is captured to a PERSISTENT
/// warm snapshot in the shared snapshots dir, keyed by (cold-image family,
/// memory, vcpus, worker-binary identity). Restoring from the result is a CoW
/// mmap (~ms).
///
/// Persistence is the macOS warm-snapshot model brought to KVM: the warm
/// snapshot is reused across PROCESSES (a second pool/process for the same image
/// skips boot + the 3.5 s warmup entirely — a `cache hit`), and co-located warm
/// snapshots are memory-deduped against a shared golden base so concurrent VMs
/// of different images share the golden's RAM page cache (see
/// `dedup_warm_against_golden` + `docs/design/linux-memory-dedup-2026-06-08.md`).
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn warm_snapshot_for_pool(image: &Image, config: &VmConfig) -> Result<Image, Error> {
    // Already snapshot-backed (e.g. produced by Vm::snapshot): nothing to do.
    if image
        .kvm
        .as_ref()
        .and_then(|k| k.snapshot.as_ref())
        .is_some()
    {
        return Ok(image.clone());
    }
    let trace = crate::trace::enabled("pool");

    // Effective resources the VM will boot with (config overrides image
    // defaults) — part of the cache key so a 512m/1v warm is never reused for a
    // 1g/4v request.
    let mem = config.memory_mib.unwrap_or(image.memory_mib);
    let vcpus = kvm_effective_vcpus(
        config.vcpus.unwrap_or(image.vcpus),
        "warm_snapshot_for_pool",
    );

    let snapshots_dir = default_snapshots_dir();
    let family = warm_family_key(image);
    // Worker-binary fingerprint: a rebuilt/reinstalled worker (new SHA) yields a
    // new key, so a stale warm snapshot baked by an incompatible worker is never
    // reused — it just re-warms under the new key.
    let worker_fp = warm_worker_fingerprint();
    let warm_name = format!("{family}__kvmwarm__{mem}m{vcpus}v__{worker_fp}");
    let warm_dir = snapshots_dir.join(&warm_name);

    // Fast path: a valid cached warm snapshot exists → reuse (CoW restore, ~ms;
    // no boot, no warmup).
    if let Ok(img) = Image::from_snapshot(&warm_dir) {
        if trace {
            eprintln!("[warm-pool] cache hit: {}", warm_dir.display());
        }
        return Ok(img);
    }

    // Serialize same-key warmers (across processes) so we boot+warm exactly once.
    let _lock = WarmDirLock::acquire(&snapshots_dir, &warm_name);
    // Re-check under the lock — another process may have just produced it.
    if let Ok(img) = Image::from_snapshot(&warm_dir) {
        if trace {
            eprintln!("[warm-pool] cache hit (post-lock): {}", warm_dir.display());
        }
        return Ok(img);
    }

    // Cold warm: boot once and wait until the in-VM agent can service a
    // CONTROL sync. A fixed sleep is not enough on slow nested KVM: the kernel
    // can RCU-stall for tens of seconds, and capturing anyway preserves a
    // mid-boot / half-wired AF_VSOCK state that later accepts connections but
    // never completes exec requests.
    if trace {
        eprintln!(
            "[warm-pool] cold warm: boot + warmup -> {}",
            warm_dir.display()
        );
    }
    let vm = Vm::start(image, config)?;
    let sync_deadline = std::time::Instant::now() + std::time::Duration::from_secs(180);
    loop {
        if guest_sync_via_agent(&vm.vsock_exec_path) {
            break;
        }
        if std::time::Instant::now() >= sync_deadline {
            let _ = vm.stop();
            return Err(Error::vm_msg(
                "KVM warm-pool capture refused: guest agent did not answer sync before deadline"
                    .to_owned(),
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }

    // Capture into a sibling `.partial` dir, finalize metadata + dedup, then
    // atomically rename into place so a concurrent reader never sees a
    // half-written warm dir.
    let partial = snapshots_dir.join(format!("{warm_name}.partial.{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&partial);
    // Consumes the boot VM (capture quiesces + tears down its vCPUs).
    let _ = vm.snapshot(&partial)?;
    finalize_warm_snapshot_metadata(&partial, &family, mem, &worker_fp)?;
    // Cross-family memory dedup vs a shared golden (best-effort; on any failure
    // the warm snapshot stays a full, still-correct snapshot).
    dedup_warm_against_golden(&snapshots_dir, &partial, mem, vcpus, &worker_fp, trace);

    // Atomic publish. If the target appeared meanwhile (a racing process), keep
    // theirs and drop ours.
    match std::fs::rename(&partial, &warm_dir) {
        Ok(()) => {}
        Err(_) if warm_dir.is_dir() => {
            let _ = std::fs::remove_dir_all(&partial);
        }
        Err(e) => {
            let _ = std::fs::remove_dir_all(&partial);
            return Err(Error::Io(e));
        }
    }
    // Best-effort GC of warm artifacts left by a previous worker binary (now
    // unreachable — the cache key only matches the current worker fingerprint).
    prune_stale_warm_artifacts(&snapshots_dir, &worker_fp);
    Image::from_snapshot(&warm_dir)
}

/// Garbage-collect persistent warm artifacts keyed by a DIFFERENT worker
/// fingerprint than `current_fp`. A rebuilt/reinstalled worker shifts the cache
/// key, so prior `<family>__kvmwarm__…__<old-fp>` dirs and their
/// `.kvmgolden/…__<old-fp>.snap` bases are never reused again — pure garbage.
/// We only touch STALE-fp artifacts (never the current fleet), and only past a
/// grace window, so a concurrent old-binary process mid-warm isn't disturbed
/// (and on Linux an unlinked file an old process still has `mmap`'d survives
/// until unmap anyway). Best-effort; all errors ignored.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn prune_stale_warm_artifacts(snapshots_dir: &Path, current_fp: &str) {
    let grace = std::time::Duration::from_secs(60);
    let now = std::time::SystemTime::now();
    let old_enough = |p: &Path| -> bool {
        std::fs::metadata(p)
            .and_then(|m| m.modified())
            .map(|mt| now.duration_since(mt).map(|d| d >= grace).unwrap_or(false))
            .unwrap_or(false)
    };
    // The worker fingerprint is the final `__`-separated segment of the name.

    // 1. Stale warm family dirs.
    if let Ok(rd) = std::fs::read_dir(snapshots_dir) {
        for entry in rd.flatten() {
            let p = entry.path();
            let Some(name) = p.file_name().and_then(|s| s.to_str()) else {
                continue;
            };
            if name.contains("__kvmwarm__")
                && name.rsplit("__").next() != Some(current_fp)
                && p.is_dir()
                && old_enough(&p)
            {
                let _ = std::fs::remove_dir_all(&p);
            }
        }
    }
    // 2. Stale goldens (their only referrers were the stale warm dirs above).
    let golden_dir = snapshots_dir.join(".kvmgolden");
    if let Ok(rd) = std::fs::read_dir(&golden_dir) {
        for entry in rd.flatten() {
            let p = entry.path();
            if p.extension().and_then(|s| s.to_str()) != Some("snap") {
                continue;
            }
            let stale = p
                .file_stem()
                .and_then(|s| s.to_str())
                .and_then(|s| s.rsplit("__").next())
                .map(|fp| fp != current_fp)
                .unwrap_or(false);
            if stale && old_enough(&p) {
                let _ = std::fs::remove_file(&p);
            }
        }
    }
}

#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
mod warm_gc_tests {
    use super::*;

    fn set_mtime_secs_ago(p: &Path, secs_ago: i64) {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let tv = libc::timeval {
            tv_sec: now - secs_ago,
            tv_usec: 0,
        };
        let times = [tv, tv];
        let c = std::ffi::CString::new(p.to_str().unwrap()).unwrap();
        unsafe {
            libc::utimes(c.as_ptr(), times.as_ptr());
        }
    }

    #[test]
    fn prune_removes_stale_fp_keeps_current_and_fresh() {
        let root = std::env::temp_dir().join(format!("sm-gc-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let golden_dir = root.join(".kvmgolden");
        std::fs::create_dir_all(&golden_dir).unwrap();

        let cur = "aaaa11112222";
        let old = "bbbb33334444";

        // Warm dirs: current-fp (keep), stale-fp old (remove), stale-fp fresh (keep — grace).
        let warm_cur = root.join(format!("nginx__kvmwarm__512m1v__{cur}"));
        let warm_old = root.join(format!("nginx__kvmwarm__512m1v__{old}"));
        let warm_old_fresh = root.join(format!("alpine__kvmwarm__512m1v__{old}"));
        for d in [&warm_cur, &warm_old, &warm_old_fresh] {
            std::fs::create_dir_all(d).unwrap();
            std::fs::write(d.join("vm.snap"), b"x").unwrap();
        }
        // Goldens: current-fp (keep), stale-fp old (remove).
        let gold_cur = golden_dir.join(format!("512m1v__{cur}.snap"));
        let gold_old = golden_dir.join(format!("512m1v__{old}.snap"));
        std::fs::write(&gold_cur, b"x").unwrap();
        std::fs::write(&gold_old, b"x").unwrap();

        // Age everything past the grace window EXCEPT warm_old_fresh + its inode.
        for p in [&warm_cur, &warm_old, &gold_cur, &gold_old] {
            set_mtime_secs_ago(p, 120);
        }
        set_mtime_secs_ago(&warm_old_fresh, 1);

        prune_stale_warm_artifacts(&root, cur);

        assert!(warm_cur.is_dir(), "current-fp warm dir must be kept");
        assert!(
            !warm_old.exists(),
            "stale-fp warm dir (aged) must be pruned"
        );
        assert!(
            warm_old_fresh.is_dir(),
            "stale-fp warm dir within grace must be kept"
        );
        assert!(gold_cur.exists(), "current-fp golden must be kept");
        assert!(!gold_old.exists(), "stale-fp golden (aged) must be pruned");

        let _ = std::fs::remove_dir_all(&root);
    }
}

/// Stable per-cold-image-family key for a warm snapshot dir name: the cold
/// snapshot DIR's name (sanitized to path-safe chars), falling back to a hash of
/// the full path. Note `snapshot_path` for a cold KVM image loaded from a dir is
/// `<dir>/restore.snap`, so we key on the PARENT dir name (the family), not the
/// file name (which is the constant `restore.snap` for every cold image).
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn warm_family_key(image: &Image) -> String {
    let dir = image.snapshot_path.parent().unwrap_or(&image.snapshot_path);
    let raw = dir.file_name().and_then(|s| s.to_str()).unwrap_or("");
    let sanitized: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                c
            } else {
                '_'
            }
        })
        .collect();
    if sanitized.is_empty() || sanitized == "." || sanitized == ".." {
        // Hash the full path so distinct images never collide.
        use std::hash::{Hash, Hasher};
        let mut h = std::collections::hash_map::DefaultHasher::new();
        image.snapshot_path.hash(&mut h);
        format!("img-{:016x}", h.finish())
    } else {
        sanitized
    }
}

/// 12-hex-prefix fingerprint of the host's `supermachine-worker` binary, or
/// `"noworker"` if it can't be resolved/hashed. Folds the worker identity into
/// the warm-snapshot cache key so a rebuilt worker invalidates stale warms.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn warm_worker_fingerprint() -> String {
    std::env::var_os("SUPERMACHINE_WORKER_BIN")
        .map(PathBuf::from)
        .and_then(|p| current_worker_sha16(&p))
        .map(|sha| sha.chars().take(12).collect::<String>())
        .unwrap_or_else(|| "noworker".to_owned())
}

/// Rewrite a freshly-captured warm snapshot's `metadata.json` so it survives the
/// atomic dir rename and carries the fields the golden-base dedup matches on:
/// a dir-RELATIVE `kvm_snapshot` (`vm.snap`, resolved against the dir on load),
/// plus `image` (family) + `baked_by_version`. Preserves all other fields.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn finalize_warm_snapshot_metadata(
    partial: &Path,
    family: &str,
    mem: u32,
    worker_fp: &str,
) -> Result<(), Error> {
    let meta_path = partial.join("metadata.json");
    let text = std::fs::read_to_string(&meta_path).map_err(Error::Io)?;
    let mut meta: serde_json::Value =
        serde_json::from_str(&text).map_err(|e| Error::vm_msg(format!("warm metadata: {e}")))?;
    let obj = meta
        .as_object_mut()
        .ok_or_else(|| Error::vm_msg("warm metadata is not an object".to_owned()))?;
    obj.insert("kvm_snapshot".into(), serde_json::json!("vm.snap"));
    obj.insert("image".into(), serde_json::json!(family));
    obj.insert("memory_mib".into(), serde_json::json!(mem));
    obj.insert(
        "baked_by_version".into(),
        serde_json::json!(env!("CARGO_PKG_VERSION")),
    );
    obj.insert("warm_worker_fp".into(), serde_json::json!(worker_fp));
    obj.insert("source".into(), serde_json::json!("warm_snapshot_for_pool"));
    std::fs::write(
        &meta_path,
        serde_json::to_string_pretty(&meta)
            .map_err(|e| Error::vm_msg(format!("warm metadata serialize: {e}")))?,
    )
    .map_err(Error::Io)?;
    Ok(())
}

/// Cross-image memory dedup against a shared golden base (best-effort).
///
/// Maintains ONE golden full snapshot per `(mem, vcpus, worker_fp)` under
/// `<snapshots_dir>/.kvmgolden/`. The first warm of a given key promotes its own
/// full as the golden (hardlinked — instant, same inode); every warm (including
/// that first one) is then rewritten as a diff against the golden. On restore
/// the golden is `mmap`'d copy-on-write and SHARED across every VM on it, so N
/// concurrent VMs of different images cost ~golden-once + per-VM diff (~14% of a
/// full) instead of N full guests. Same-offset diffing captures ~86% sharing
/// (mostly the ~88% zero pages, which align across images); KSM mops up the
/// rest at runtime.
///
/// Any failure leaves the warm snapshot a full (still correct) snapshot.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn dedup_warm_against_golden(
    snapshots_dir: &Path,
    partial: &Path,
    mem: u32,
    vcpus: u32,
    worker_fp: &str,
    trace: bool,
) {
    if std::env::var("SUPERMACHINE_AUTO_DEDUP").as_deref() == Ok("0") {
        return;
    }
    let warm_snap = partial.join("vm.snap");
    let golden_dir = snapshots_dir.join(".kvmgolden");
    if std::fs::create_dir_all(&golden_dir).is_err() {
        return;
    }
    let golden = golden_dir.join(format!("{mem}m{vcpus}v__{worker_fp}.snap"));

    // Serialize golden creation across processes.
    let _lock = WarmDirLock::acquire(&golden_dir, &format!("{mem}m{vcpus}v__{worker_fp}"));

    if !golden.exists() {
        // Promote this full as the shared golden. Hardlink (instant, same
        // inode) so rewriting `warm_snap` below replaces only the warm dir's
        // entry — the golden keeps the original full bytes. Fall back to copy
        // across filesystems.
        if std::fs::hard_link(&warm_snap, &golden).is_err() {
            let tmp = golden.with_extension("snap.tmp");
            if std::fs::copy(&warm_snap, &tmp).is_err() || std::fs::rename(&tmp, &golden).is_err() {
                let _ = std::fs::remove_file(&tmp);
                return;
            }
        }
    }

    match crate::kvm::run::rewrite_full_as_diff(&warm_snap, &golden) {
        Ok(diff_size) => {
            // Record the base so future fleet hygiene knows the dependency.
            let meta_path = partial.join("metadata.json");
            if let Ok(text) = std::fs::read_to_string(&meta_path) {
                if let Ok(mut meta) = serde_json::from_str::<serde_json::Value>(&text) {
                    if let Some(obj) = meta.as_object_mut() {
                        obj.insert(
                            "kvm_snapshot_base".into(),
                            serde_json::json!(golden.to_string_lossy()),
                        );
                        if let Ok(s) = serde_json::to_string_pretty(&meta) {
                            let _ = std::fs::write(&meta_path, s);
                        }
                    }
                }
            }
            if trace {
                eprintln!(
                    "[warm-pool] deduped vs golden {}: diff {:.1} MiB",
                    golden.display(),
                    diff_size as f64 / 1048576.0
                );
            }
        }
        Err(e) => {
            if trace {
                eprintln!("[warm-pool] dedup skipped ({e}); warm snapshot kept full");
            }
        }
    }
}

/// Cross-process advisory lock for a warm/golden snapshot key. A sibling lock
/// file (`<dir>/.<name>.warmlock`) under `flock(LOCK_EX)`; released when the
/// guard drops (the OS also reclaims it on process death). Best-effort: if the
/// lock can't be taken we proceed unlocked (the atomic rename + exists-checks
/// keep correctness; we just risk a redundant warm).
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct WarmDirLock {
    _file: Option<std::fs::File>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl WarmDirLock {
    fn acquire(dir: &Path, name: &str) -> Self {
        use std::os::fd::AsRawFd;
        if std::fs::create_dir_all(dir).is_err() {
            return Self { _file: None };
        }
        let lock_path = dir.join(format!(".{name}.warmlock"));
        let Ok(file) = std::fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&lock_path)
        else {
            return Self { _file: None };
        };
        // Blocking exclusive lock with a hard deadline so a wedged holder can't
        // gate forever.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
        loop {
            let r = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
            if r == 0 {
                return Self { _file: Some(file) };
            }
            if std::time::Instant::now() > deadline {
                return Self { _file: None };
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
    }
}

/// Explicit, configured worker pool. Returned by
/// [`PoolBuilder::build`]. `Pool` is `Clone` (Arc-shared);
/// dropping every clone tears the pool down.
#[derive(Clone)]
pub struct Pool {
    /// macOS/HVF: the subprocess-worker pool.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    inner: Arc<HiddenPool>,
    /// Linux/KVM: shared pool state (warm image + idle pre-restored VMs).
    /// Exactly one of `kvm` / `sentry` is `Some`, chosen by the image backend.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    kvm: Option<Arc<KvmPoolInner>>,
    /// Linux no-virt: shared persistent exec-server pool (sentry backend).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    sentry: Option<Arc<SentryPool>>,
    /// Linux no-virt: external gVisor/runsc checkpoint-backed pool.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    runsc: Option<Arc<RunscPoolInner>>,
    /// Linux no-virt: native Rust kboxlike process-tree pool.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    kboxlike: Option<Arc<KboxlikePoolInner>>,
}

/// Linux/KVM pool state: the warm (snapshot-backed) source image plus a queue of
/// idle, pre-restored VMs kept topped up to `min` (so `acquire` is a ~µs pop
/// instead of a ~ms restore). A single background refiller tops the idle queue
/// back to `min` after each acquire / release.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct KvmPoolInner {
    image: Image,
    vm_config: VmConfig,
    min: usize,
    idle: Mutex<Vec<Vm>>,
    /// Hard max-concurrency admission: bounds total live VMs to `max` and blocks
    /// `acquire` at the cap instead of growing without bound (which would OOM the
    /// host). Carries the live count + `max` + `acquire_timeout`.
    admission: Admission,
    /// Warm-reuse switch (mirrors HVF's `restore_on_release`). When `false`,
    /// a released VM is returned ALIVE to `idle` and reused in place on the next
    /// acquire (guest stays parked, page cache hot) instead of being torn down
    /// and a fresh one restored — turning a ~ms restore + cold re-fault into a
    /// ~µs idle-pop. When `true` (default), each cycle tears down + restores
    /// fresh (clean isolation; the safe default for untrusted multi-tenant use).
    restore_on_release: bool,
    /// Ensures at most one background refiller runs at a time.
    refilling: std::sync::atomic::AtomicBool,
    /// Set by [`Pool::shutdown`]; once true, [`Self::take_or_restore`] refuses
    /// new acquires with [`Error::PoolExhausted`] instead of restoring more VMs.
    shut_down: std::sync::atomic::AtomicBool,
}

/// No-virt **sentry** pool state (Linux/x86_64). Most backends amortize one
/// persistent supervisor across the pool and hand out cheap [`PooledVm`] handles
/// pointing at that supervisor. Live-tree C4 snapshots are the exception: they
/// must start one restored supervisor per checkout so `max > 1` has the same
/// independent-restored-machine semantics as KVM/HVF.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
enum SentryBackend {
    /// Legacy/default: one persistent ExecServer whose accept loop forks a fresh
    /// sealed cell per exec connection. Pooled `Vm`s dial `exec_path`.
    ExecServer {
        server: crate::sentry::ExecServer,
        exec_path: PathBuf,
    },
    /// Warm-daemon pool: one persistent supervisor ([`crate::sentry::Pool`]) with a
    /// parked warm cell (warmed on the image's `cmd` to its SENTINEL checkpoint).
    /// `acquire` forks a detached daemon (`Pool::acquire_running`); a pooled `Vm`'s
    /// `exec` runs a CLIENT cell via `Pool::exec_capture` that reaches the daemon
    /// over the supervisor-global owned loopback. `Arc` so each acquired `Vm` carries
    /// a clone for its exec route without moving the `Pool` out of the `SentryPool`.
    WarmDaemon {
        pool: Arc<crate::sentry::Pool>,
        #[allow(dead_code)]
        daemon_argv: Vec<String>,
    },
    /// Live C4 snapshot restore: each acquire starts an independent supervisor,
    /// restores the captured process tree into it, and returns that restored root
    /// directly. This mirrors KVM/HVF's "one restored machine per checkout"
    /// behavior for `max > 1`; no process/fd/proctree state is shared between
    /// concurrent checkouts.
    LiveTreeC4 {
        image: Image,
        config: VmConfig,
        snapshot_dir: PathBuf,
    },
    /// Unified workload+exec backend (the faithful mac/linux model): ONE persistent
    /// supervisor backgrounds the image CMD (if any) and serves a STREAMING exec
    /// socket whose cells fork IN-PROCESS — so `exec` shares the workload's loopback
    /// + proctree. A pooled `Vm` dials `exec_path` with the normal `ExecBuilder`
    /// protocol (full streaming/stdin/separate-stderr/timeout/tty). `Arc` so each
    /// acquired `Vm` keeps the pool alive for its exec route.
    Unified {
        pool: Arc<crate::sentry::Pool>,
        exec_path: PathBuf,
        captures_live_state: bool,
    },
}

/// sentry analogue of the KVM warm pool — the supervisor is amortized across the
/// whole pool instead of cold-started by `Vm::start` on every acquire.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct SentryPool {
    /// The pool's backend (ExecServer per-exec-fresh-cell, or a warm-daemon
    /// persistent supervisor). Outlives every [`PooledVm`]; torn down on `Drop`
    /// (the build-pool path stops it before removing `build_root`).
    backend: SentryBackend,
    /// The warm rootfs dir the shared server serves from (`image.sentry.rootfs`).
    /// Pooled `Vm`s don't own snapshot machinery (`sentry_src_rootfs: None`), so
    /// the pool keeps the rootfs path here for [`PooledVm::snapshot`] to copy.
    rootfs: PathBuf,
    /// Optional temp dir we created for the socket (unlinked on pool Drop).
    own_dir: Option<PathBuf>,
    /// Private mutable rootfs scaffold for this sentry pool.
    ///
    /// Sentry serves a host directory directly. Unlike KVM/HVF, there is no block
    /// device or RAM overlay that naturally absorbs guest writes, so every pool
    /// gets a private clone of the image rootfs. For `restore_on_release=false`
    /// that private clone is reused dirty only for this pool's lifetime; the
    /// source image snapshot stays immutable. For build pools it is the layer
    /// under construction. [`rootfs`](Self::rootfs) points INTO this dir; Drop
    /// removes the whole tree after stopping the backend.
    build_root: Option<PathBuf>,
    /// Private clean copy of [`rootfs`](Self::rootfs), captured before the pool
    /// starts serving. Runtime pools with `restore_on_release=true` swap the
    /// served rootfs back to this baseline on every release; build pools disable
    /// this because their private rootfs is the layer-under-construction.
    baseline_rootfs: Option<PathBuf>,
    /// Owns the temp parent that contains [`baseline_rootfs`](Self::baseline_rootfs)
    /// so it can be removed on pool drop.
    baseline_root: Option<PathBuf>,
    /// Serializes rootfs reset with concurrent release paths. Sentry pools share
    /// one served rootfs, so reset must be a single pool-wide operation.
    restore_lock: Mutex<()>,
    /// Effective runtime restore policy for this sentry pool.
    restore_on_release: bool,
    /// Bounds concurrent checkouts to `max`, blocking `acquire` at the cap.
    admission: Admission,
    /// No-op pool-lifetime admission guard kept for struct layout churn
    /// containment; live sentry checkouts are charged per [`PooledVm`] instead
    /// so idle pools do not reserve their whole `max` concurrency footprint.
    _mem_admission: crate::memory_admission::AdmissionGuard,
    /// The cgroup memory limit one live sentry checkout charges.
    mem_mib: u64,
    /// The effective vCPU count exposed to this pool's guests.
    vcpus: u32,
    /// Set by [`Pool::shutdown`]; refuses further acquires once true.
    shut_down: std::sync::atomic::AtomicBool,
    /// True iff this pool backs a warm-daemon image (`parts.warm_daemon`). The
    /// warm state may include a live process tree, so pooled snapshots must use
    /// supervisor C4 capture in addition to copying the rootfs.
    warm_daemon: bool,
    /// Guards the idempotent shutdown cleanup path. JS users can call
    /// `pool.shutdown()` while the `Pool` object remains reachable until process
    /// exit, so cleanup cannot rely only on `Drop`.
    cleanup_done: std::sync::atomic::AtomicBool,
}

/// Remove the per-build private rootfs scaffold (if any) on pool Drop — RAII, so
/// it runs even on a panicking/aborted build. We `stop()` the shared exec server
/// FIRST (it joins the accept thread, kills the baked workload, and its
/// per-connection supervisors SIGKILL their straggler cells), so no exec is still
/// holding a cwd under `build_root` when we `remove_dir_all` it (else EBUSY /
/// leftover dirs would accumulate). `stop()` is idempotent — the `_server` field's
/// own `Drop` re-runs it harmlessly afterward.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Drop for SentryPool {
    fn drop(&mut self) {
        self.shut_down
            .store(true, std::sync::atomic::Ordering::SeqCst);
        self.cleanup_now();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl SentryPool {
    /// Build the persistent exec server from a sentry image + config, ready to
    /// back a pool. Mirrors `Vm::start_sentry`'s socket+sandbox setup, but the
    /// server is owned by the pool (shared) instead of by a single `Vm`.
    fn build(
        image: &Image,
        config: &VmConfig,
        max: usize,
        acquire_timeout: Option<Duration>,
        policy_restore_on_release: bool,
    ) -> Result<Arc<SentryPool>, Error> {
        let parts = image
            .sentry
            .as_ref()
            .ok_or_else(|| Error::vm_msg("SentryPool::build on a non-sentry image"))?;
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        let mut own_dir = None;
        if !dir.is_dir() {
            std::fs::create_dir_all(&dir).map_err(Error::Io)?;
            own_dir = Some(dir.clone());
        }
        let exec_path = dir.join(format!(
            "supermachine-sentry-pool-{}-{}.sock",
            std::process::id(),
            unique_suffix(),
        ));
        // Runtime pools mirror `Vm::start_sentry`: a pooled `Vm`'s workload is
        // host-reachable via [`expose_tcp`] (host-proxy to a real
        // `127.0.0.1:guest_port` host socket), so the pool's shared server runs in
        // the host netns. Build pools are different: Dockerfile `RUN` steps do not
        // expose host-reachable listeners, and the default sentry netns gives them
        // the mediated egress path (`rehome_to_host_netns`) used for isolated
        // sandbox networking. Keeping build pools on that default avoids the
        // locked no-KVM sandbox split where runtime VMs could reach hosts that
        // shared-host-netns build steps could not.
        let mut sandbox = image
            .sentry_sandbox_with(config)
            .map_err(|e| Error::vm_msg(format!("sentry sandbox: {e}")))?;
        if !config.for_build {
            sandbox = sandbox.without_netns();
        }
        // The rootfs the pool serves AND `PooledVm::snapshot` copies. Always use a
        // PRIVATE clone: sentry path mutations operate on real host files, so
        // serving `parts.rootfs` directly would let `restoreOnRelease:false` dirty
        // the source image snapshot after pool shutdown. KVM/HVF dirty VMs never
        // mutate their source snapshot; this clone gives sentry the same lifetime
        // boundary. For build pools the private tree is also the layer under
        // construction.
        // A build pool must NOT auto-launch the base image's baked workload while
        // RUN steps execute — suppress it (KVM/HVF build pools likewise don't run
        // the base CMD; the builder drives every exec).
        let mut start_workload = parts.has_workload;
        if config.for_build {
            start_workload = false;
        }
        let private_kind = if config.for_build { "build" } else { "runtime" };
        let priv_dir = dir.join(format!(
            "supermachine-sentry-{private_kind}-{}-{}",
            std::process::id(),
            unique_suffix(),
        ));
        let private_rootfs = priv_dir.join("rootfs");
        copy_dir_recursive(&parts.rootfs, &private_rootfs).map_err(|e| {
            Error::vm_msg(format!("sentry {private_kind} private rootfs clone: {e}"))
        })?;
        // Place the base image's metadata.json as the SIBLING of the private
        // rootfs so `write_sentry_snapshot_dir` (which reads
        // `src_rootfs.parent()/metadata.json`) re-emits the run-config
        // (`image_env`/`cmd`/`sentry_has_workload`/…) — not a bare
        // `{"backend":"sentry"}` fallback.
        if let Some(base_meta) = parts.rootfs.parent().map(|p| p.join("metadata.json")) {
            if base_meta.is_file() {
                let _ = std::fs::copy(&base_meta, priv_dir.join("metadata.json"));
            }
        }
        crate::kboxlike::prepare_rootfs_network_config(&private_rootfs).map_err(|e| {
            Error::vm_msg(format!(
                "sentry {private_kind} private rootfs network config: {e}"
            ))
        })?;
        // Repoint the sandbox's confined ROOT to the private clone — identical
        // sandbox otherwise (egress/uid/mounts/limits unchanged), same
        // openat2(RESOLVE_IN_ROOT) confinement.
        sandbox = sandbox.with_root(private_rootfs.clone());
        let rootfs = private_rootfs;
        let build_root = Some(priv_dir);
        let restore_on_release = !config.for_build && policy_restore_on_release;
        let mut baseline_rootfs = None;
        let mut baseline_root = None;
        if restore_on_release {
            let base_dir = dir.join(format!(
                "supermachine-sentry-baseline-{}-{}",
                std::process::id(),
                unique_suffix(),
            ));
            let base_rootfs = base_dir.join("rootfs");
            copy_dir_recursive(&rootfs, &base_rootfs)
                .map_err(|e| Error::vm_msg(format!("sentry rootfs baseline clone: {e}")))?;
            baseline_rootfs = Some(base_rootfs);
            baseline_root = Some(base_dir);
        }
        // MEMORY admission is charged per checked-out PooledVm, not up front for
        // the pool's whole `max`. This mirrors KVM worker-lifetime accounting and
        // avoids a lazy sentry pool with default `max=64` reserving tens of GiB
        // while idle.
        let mem_mib = sentry_cell_mem_mib(image, config);
        let vcpus = config.vcpus.unwrap_or(image.vcpus).max(1);
        let mem_admission = crate::memory_admission::charge(0);
        let c4_snapshot_dir = (!config.for_build)
            .then(|| image.snapshot_path.parent())
            .flatten()
            .filter(|dir| dir.join("restore.snap").is_file() && dir.join("mem.blob").is_file())
            .map(Path::to_path_buf);
        let c4_entry_kind = if let Some(dir) = &c4_snapshot_dir {
            let mut f = std::fs::File::open(dir.join("restore.snap")).map_err(Error::Io)?;
            Some(
                crate::sentry::state_snap::StateSnapshot::read_from(&mut f)
                    .map_err(Error::Io)?
                    .entry_kind,
            )
        } else {
            None
        };
        // Unified workload+exec backend is the DEFAULT (mac/linux parity: one guest
        // runs the CMD + serves execs sharing its loopback + proctree). SENTRY_UNIFIED=0
        // selects the legacy per-exec ExecServer as an escape hatch during rollout.
        let unified = std::env::var("SENTRY_UNIFIED")
            .map(|v| v != "0")
            .unwrap_or(true);
        let c4_live_tree = matches!(
            c4_entry_kind,
            Some(crate::sentry::state_snap::SnapshotEntryKind::LiveTree)
        );
        let backend = if c4_live_tree {
            let snapshot_dir = c4_snapshot_dir
                .clone()
                .ok_or_else(|| Error::vm_msg("sentry live-tree C4 missing snapshot dir"))?;
            SentryBackend::LiveTreeC4 {
                image: image.clone(),
                config: config.clone(),
                snapshot_dir,
            }
        } else if unified && !parts.warm_daemon {
            // UNIFIED workload+exec backend: one persistent
            // supervisor serving a streaming exec socket whose cells fork in-process
            // (shared loopback + proctree). A pooled Vm dials `exec_path` with the full
            // ExecBuilder protocol. (Workload backgrounding + pid-file = the next step.)
            let unified_sock = dir.join(format!(
                "supermachine-sentry-unified-{}-{}.sock",
                std::process::id(),
                unique_suffix(),
            ));
            let pool = sandbox
                .pool_with_exec(unified_sock.clone())
                .map_err(|e| Error::vm_msg(format!("sentry unified pool: {e}")))?;
            // The supervisor binds the exec socket ASYNC (it forks + re-execs + runs
            // setup before binding), unlike ExecServer which binds synchronously. Wait
            // for the socket to appear so the first acquire/exec doesn't race a missing
            // path (ENOENT). Bounded; a never-appearing socket fails the build cleanly.
            let deadline = std::time::Instant::now() + Duration::from_secs(15);
            while !unified_sock.exists() {
                if std::time::Instant::now() >= deadline {
                    return Err(Error::vm_msg(
                        "sentry unified exec socket never appeared (supervisor bind failed)",
                    ));
                }
                std::thread::sleep(Duration::from_millis(5));
            }
            // Background the image's workload (mac/linux parity: the guest boots its
            // CMD). The bake renders `/.supermachine/run-workload` — a script that
            // exports the image Env, `cd`s into WORKDIR, then exec's Entrypoint+Cmd —
            // exactly what the ExecServer's start_workload runs. Background THAT (not
            // parts.cmd, which is empty for non-warm-daemon images and skips WORKDIR/Env)
            // as a detached instance IN this supervisor, so it shares the exec cells'
            // owned loopback + proctree: the checkpoint helper `warm`s to the SENTINEL,
            // `acquire_running` resumes past it into the script in its OWN ring slot
            // (execs borrow slot 0). Record the pid where the KVM/HVF init writes it. A
            // workload that exits immediately (a base image's `bash`) is fine — the
            // supervisor stays up serving execs, exactly like a booted VM.
            let mut captures_live_state = false;
            if start_workload && rootfs.join(".supermachine/run-workload").is_file() {
                let wrapped = vec![
                    "/.supermachine/sm-checkpoint".to_string(),
                    "/bin/sh".to_string(),
                    "/.supermachine/run-workload".to_string(),
                ];
                if pool.warm(wrapped.iter().cloned()).is_ok() {
                    if let Ok(wpid) = pool.acquire_running() {
                        captures_live_state = true;
                        let run_dir = rootfs.join("run");
                        let _ = std::fs::create_dir_all(&run_dir);
                        let _ = std::fs::write(
                            run_dir.join("supermachine-workload.pid"),
                            format!("{wpid}\n"),
                        );
                    }
                }
            }
            SentryBackend::Unified {
                pool: Arc::new(pool),
                exec_path: unified_sock,
                captures_live_state,
            }
        } else if parts.warm_daemon && !parts.cmd.is_empty() {
            // Warm-daemon: build a control-socket Pool over the (possibly
            // private-clone) rootfs, then park a warm cell at the daemon's SENTINEL
            // checkpoint. `Pool::warm` blocks until the workload checkpoints (syscall
            // 0x5359) — a warm-daemon image's workload MUST do so once listen-ready
            // (see `with_warm_daemon`). A workload that never checkpoints (or a cell
            // that dies first) no longer hangs the build: the supervisor's bounded
            // ready-wait (`wait_ready_deadline`, keyed on `exec_timeout_ms`) kills the
            // wedged cell and `warm` returns an Err surfaced here.
            {
                let pool = sandbox
                    .pool()
                    .map_err(|e| Error::vm_msg(format!("sentry warm-daemon pool: {e}")))?;
                if let Some(snapshot_dir) = &c4_snapshot_dir {
                    pool.warm_restore(snapshot_dir).map_err(|e| {
                        Error::vm_msg(format!(
                            "sentry warm_restore({}): {e}",
                            snapshot_dir.display()
                        ))
                    })?;
                } else {
                    pool.warm(parts.cmd.iter().cloned())
                        .map_err(|e| Error::vm_msg(format!("sentry warm({:?}): {e}", parts.cmd)))?;
                }
                SentryBackend::WarmDaemon {
                    pool: Arc::new(pool),
                    daemon_argv: parts.cmd.clone(),
                }
            }
        } else {
            let server = sandbox
                .serve_exec(&exec_path, start_workload)
                .map_err(|e| Error::vm_msg(format!("sentry serve_exec: {e}")))?;
            SentryBackend::ExecServer { server, exec_path }
        };
        Ok(Arc::new(SentryPool {
            backend,
            rootfs,
            own_dir,
            build_root,
            baseline_rootfs,
            baseline_root,
            restore_lock: Mutex::new(()),
            restore_on_release,
            admission: Admission::new(max, acquire_timeout),
            _mem_admission: mem_admission,
            mem_mib,
            vcpus,
            shut_down: std::sync::atomic::AtomicBool::new(false),
            warm_daemon: parts.warm_daemon,
            cleanup_done: std::sync::atomic::AtomicBool::new(false),
        }))
    }

    fn stop_backend(&self) {
        // Stop the active backend BEFORE remove_dir_all(build_root) (a cell may
        // hold a cwd under it). All stop paths are idempotent: the field's own
        // Drop re-runs teardown harmlessly.
        match &self.backend {
            SentryBackend::ExecServer { server, .. } => server.stop(),
            SentryBackend::WarmDaemon { pool, .. } => pool.stop(),
            SentryBackend::LiveTreeC4 { .. } => {}
            SentryBackend::Unified { pool, .. } => pool.stop(),
        }
    }

    fn cleanup_now(&self) {
        if self
            .cleanup_done
            .compare_exchange(
                false,
                true,
                std::sync::atomic::Ordering::SeqCst,
                std::sync::atomic::Ordering::SeqCst,
            )
            .is_err()
        {
            return;
        }
        self.stop_backend();
        if let Some(br) = &self.build_root {
            let _ = std::fs::remove_dir_all(br);
        }
        if let Some(br) = &self.baseline_root {
            let _ = std::fs::remove_dir_all(br);
        }
        if let Some(d) = &self.own_dir {
            let _ = std::fs::remove_dir_all(d);
        }
    }

    fn cleanup_if_shutdown_idle(&self) {
        if !self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        if self.admission.alive() != 0 {
            return;
        }
        self.cleanup_now();
    }

    fn restore_rootfs_from_baseline(&self) -> std::io::Result<()> {
        if !self.restore_on_release {
            return Ok(());
        }
        let Some(baseline) = &self.baseline_rootfs else {
            return Ok(());
        };
        let _guard = self.restore_lock.lock().unwrap_or_else(|e| e.into_inner());
        let parent = self.rootfs.parent().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("sentry rootfs has no parent: {}", self.rootfs.display()),
            )
        })?;
        let suffix = format!("{}-{}", std::process::id(), unique_suffix());
        let staging = parent.join(format!(".supermachine-sentry-restore-{suffix}"));
        let _ = std::fs::remove_dir_all(&staging);
        copy_dir_recursive(baseline, &staging)?;
        replace_dir_contents_from_staging(&staging, &self.rootfs)
    }

    fn capture_live_state_into(&self, dest_dir: &Path) -> Result<(), Error> {
        match &self.backend {
            SentryBackend::WarmDaemon { pool, .. } => pool
                .snapshot(dest_dir)
                .map_err(|e| Error::vm_msg(format!("sentry live snapshot capture: {e}"))),
            SentryBackend::Unified {
                pool,
                captures_live_state: true,
                ..
            } => pool
                .snapshot(dest_dir)
                .map_err(|e| Error::vm_msg(format!("sentry live snapshot capture: {e}"))),
            SentryBackend::Unified {
                captures_live_state: false,
                ..
            } => Ok(()),
            SentryBackend::ExecServer { .. } | SentryBackend::LiveTreeC4 { .. } => Ok(()),
        }
    }

    /// Admission-gate (blocking up to `acquire_timeout`) then hand back a cheap
    /// `PooledVm` whose `Vm` execs against the shared server's socket. The slot
    /// is released in `PooledVm::drop`.
    fn acquire(self: &Arc<Self>) -> Result<PooledVm<'static>, Error> {
        use std::sync::atomic::Ordering::SeqCst;
        let deadline = self
            .admission
            .acquire_timeout
            .map(|d| std::time::Instant::now() + d);
        loop {
            if self.shut_down.load(SeqCst) {
                return Err(Error::vm_msg("sentry pool is shutting down"));
            }
            if self.admission.try_reserve() {
                break;
            }
            if !self.admission.wait_for_change(deadline)? {
                // Same error VARIANT as the KVM/HVF pool so callers can `matches!`
                // on `Error::PoolExhausted` regardless of backend (parity).
                return Err(Error::pool_exhausted(
                    "sentry pool acquire timed out (all max slots in use)",
                ));
            }
        }
        crate::memory_admission::await_pressure_relief();
        let sentry_mem_admission =
            crate::memory_admission::admit_with(|| sentry_admission_charge_mib(self.mem_mib, 1));
        // Per-backend: the ExecServer path dials the shared exec socket; the
        // WarmDaemon path forks a DETACHED daemon (acquire_running) and routes
        // `vm.exec` through the Pool over loopback (no exec socket).
        let mut exec_path = match &self.backend {
            SentryBackend::ExecServer { exec_path, .. } => exec_path.clone(),
            SentryBackend::Unified { exec_path, .. } => exec_path.clone(),
            SentryBackend::WarmDaemon { .. } => PathBuf::new(),
            SentryBackend::LiveTreeC4 { .. } => PathBuf::new(),
        };
        let (running_pid, warm_pool, running_pool, stop_running_pool_on_drop) = match &self.backend
        {
            SentryBackend::WarmDaemon { pool, .. } => {
                match pool.acquire_running() {
                    Ok(pid) => (
                        Some(pid),
                        Some(Arc::clone(pool)),
                        Some(Arc::clone(pool)),
                        false,
                    ),
                    Err(e) => {
                        // Release the just-claimed admission slot before erroring (the
                        // slot-leak guard) so a blocked acquirer isn't stranded.
                        self.admission.release();
                        return Err(Error::vm_msg(format!(
                            "sentry warm-daemon acquire_running: {e}"
                        )));
                    }
                }
            }
            SentryBackend::LiveTreeC4 {
                image,
                config,
                snapshot_dir,
            } => {
                let sandbox = match image.sentry_sandbox_with(config) {
                    Ok(s) => s.with_root(snapshot_dir.join("rootfs")).without_netns(),
                    Err(e) => {
                        self.admission.release();
                        return Err(e);
                    }
                };
                let dir = match &config.vsock_mux_dir {
                    Some(d) => d.clone(),
                    None => std::env::temp_dir(),
                };
                let live_exec_path = dir.join(format!(
                    "supermachine-sentry-live-c4-{}-{}.sock",
                    std::process::id(),
                    unique_suffix(),
                ));
                let pool = match sandbox.pool_with_exec(live_exec_path.clone()) {
                    Ok(pool) => Arc::new(pool),
                    Err(e) => {
                        self.admission.release();
                        return Err(Error::vm_msg(format!("sentry live-tree pool: {e}")));
                    }
                };
                let deadline = std::time::Instant::now() + Duration::from_secs(15);
                while !live_exec_path.exists() {
                    if std::time::Instant::now() >= deadline {
                        pool.stop();
                        self.admission.release();
                        return Err(Error::vm_msg(
                            "sentry live-tree exec socket never appeared (supervisor bind failed)",
                        ));
                    }
                    std::thread::sleep(Duration::from_millis(5));
                }
                if let Err(e) = pool.warm_restore(snapshot_dir) {
                    pool.stop();
                    self.admission.release();
                    return Err(Error::vm_msg(format!(
                        "sentry live-tree warm_restore({}): {e}",
                        snapshot_dir.display()
                    )));
                }
                let checkout = match pool.acquire_running() {
                    Ok(pid) => (Some(pid), None, Some(pool), true),
                    Err(e) => {
                        pool.stop();
                        self.admission.release();
                        return Err(Error::vm_msg(format!(
                            "sentry live-tree acquire_running: {e}"
                        )));
                    }
                };
                exec_path = live_exec_path;
                checkout
            }
            SentryBackend::ExecServer { .. } => (None, None, None, false),
            // Unified: exec dials the streaming socket (vsock_exec_path); no
            // per-acquire daemon fork and no warm-pool exec route.
            SentryBackend::Unified { .. } => (None, None, None, false),
        };
        // A pooled Vm: references the SHARED socket / warm Pool, owns no server,
        // never unlinks (skip_cleanup) — the SentryPool owns the lifecycle.
        let vm = Vm {
            running: None,
            sentry_exec: None,
            // Pooled sentry VMs share the served rootfs. Warm/live C4 checkouts
            // carry a Pool route for exec and snapshot state; ExecServer/Unified
            // use the shared socket path instead.
            sentry_src_rootfs: None,
            vsock_mux_path: exec_path.clone(),
            vsock_exec_path: exec_path,
            own_vsock_mux_dir: None,
            skip_cleanup: true,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            // The PooledVm carries the per-checkout memory reservation; the inner
            // Vm owns none separately.
            _sentry_mem_admission: None,
            // WarmDaemon: route `exec` through this Pool (Pool::exec_capture over
            // loopback). `None` for the ExecServer path (dials vsock_exec_path).
            sentry_warm_pool: warm_pool,
            sentry_unified_pool: None,
            runsc: None,
            kboxlike: None,
        };
        Ok(PooledVm {
            vm: Some(vm),
            pool: None,
            sentry_pool: Some(Arc::clone(self)),
            runsc_pool: None,
            kboxlike_pool: None,
            sentry_mem_admission: Some(sentry_mem_admission),
            // WarmDaemon: the detached daemon pid, released (SIGKILL+reap) in Drop.
            sentry_running_pid: running_pid,
            sentry_running_pool: running_pool,
            sentry_stop_running_pool_on_drop: stop_running_pool_on_drop,
            sentry_touched: AtomicBool::new(false),
            _image: std::marker::PhantomData,
        })
    }

    /// Cumulative exec metrics for the warm-daemon backend (counts, latency,
    /// seccomp/timeout/signal tallies), recorded library-side by the inner
    /// control-socket Pool's `record_exec`. `None` for the ExecServer backend,
    /// which routes execs over a shared socket with no per-Pool counter object.
    fn sentry_stats(&self) -> Option<crate::sentry::SentryPoolStats> {
        match &self.backend {
            SentryBackend::WarmDaemon { pool, .. } => Some(pool.stats()),
            SentryBackend::ExecServer { .. } => None,
            SentryBackend::LiveTreeC4 { .. } => None,
            SentryBackend::Unified { .. } => None,
        }
    }
}

/// Hard max-concurrency admission for the KVM pool. Bounds total live VMs
/// (idle + checked-out) to `max`: a fresh restore must `reserve_blocking` a slot,
/// blocking up to `acquire_timeout` when all `max` are in use until a peer
/// `release`s — rather than spawning unboundedly (which would exhaust host RAM).
/// Idle reuse does NOT reserve (the slot was claimed when that VM was created).
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
struct Admission {
    max: usize,
    alive: std::sync::atomic::AtomicUsize,
    lock: std::sync::Mutex<()>,
    available: std::sync::Condvar,
    acquire_timeout: Option<Duration>,
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Admission {
    fn new(max: usize, acquire_timeout: Option<Duration>) -> Self {
        Self {
            max: max.max(1),
            alive: std::sync::atomic::AtomicUsize::new(0),
            lock: std::sync::Mutex::new(()),
            available: std::sync::Condvar::new(),
            acquire_timeout,
        }
    }

    fn alive(&self) -> usize {
        self.alive.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Claim a slot if under `max`, non-blocking. Returns false at the cap. Used
    /// by the background refiller (which must never block).
    fn try_reserve(&self) -> bool {
        use std::sync::atomic::Ordering::SeqCst;
        loop {
            let cur = self.alive.load(SeqCst);
            if cur >= self.max {
                return false;
            }
            if self
                .alive
                .compare_exchange(cur, cur + 1, SeqCst, SeqCst)
                .is_ok()
            {
                return true;
            }
        }
    }

    /// Bounded wait for a slot-release OR a refiller idle-push, used by
    /// [`KvmPoolInner::take_or_restore`]'s acquire loop. Returns `Ok(true)` to
    /// retry the loop (re-check idle + try_reserve), or `Ok(false)` if the
    /// `acquire_timeout` deadline has passed. Each wait is capped at 100ms so a
    /// missed notify is a short stall, never a hang.
    ///
    /// CRITICAL: the acquire loop must re-check the IDLE QUEUE between waits,
    /// not just the slot count. A background refiller holds an admission slot
    /// while it restores, then pushes the VM to `idle` WITHOUT releasing the
    /// slot — so a caller that blocked purely on `alive < max` (the old
    /// `reserve_blocking`) would never observe that VM and would hang forever
    /// when `min == max` (the single slot is permanently the refiller's). This
    /// is why the wait lives here as a primitive and the idle re-check lives in
    /// `take_or_restore`.
    fn wait_for_change(&self, deadline: Option<std::time::Instant>) -> Result<bool, Error> {
        let g = self.lock.lock().unwrap_or_else(|e| e.into_inner());
        let wait = match deadline {
            Some(dl) => {
                let now = std::time::Instant::now();
                if now >= dl {
                    return Ok(false);
                }
                (dl - now).min(Duration::from_millis(100))
            }
            None => Duration::from_millis(100),
        };
        let _ = self.available.wait_timeout(g, wait);
        Ok(true)
    }

    /// Free a slot + wake one waiter.
    fn release(&self) {
        self.alive.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        self.available.notify_one();
    }

    /// Wake ALL acquirers blocked in [`wait_for_change`]. Called by a refiller
    /// after pushing a fresh VM to the idle queue — that push does not call
    /// [`release`] (the slot stays claimed by the now-idle VM), so blocked
    /// acquirers must be woken explicitly to re-check idle promptly.
    fn notify(&self) {
        self.available.notify_all();
    }
}

#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
mod admission_tests {
    use super::Admission;
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    #[test]
    fn try_reserve_bounds_at_max() {
        let a = Admission::new(3, None);
        assert!(a.try_reserve());
        assert!(a.try_reserve());
        assert!(a.try_reserve());
        assert_eq!(a.alive(), 3);
        // At the cap: further non-blocking reservations fail.
        assert!(!a.try_reserve());
        assert_eq!(a.alive(), 3);
        // Releasing frees exactly one slot.
        a.release();
        assert_eq!(a.alive(), 2);
        assert!(a.try_reserve());
        assert_eq!(a.alive(), 3);
    }

    #[test]
    fn max_zero_clamps_to_one() {
        let a = Admission::new(0, None);
        assert_eq!(a.max, 1);
        assert!(a.try_reserve());
        assert!(!a.try_reserve());
    }

    #[test]
    fn wait_for_change_reports_deadline_passed() {
        // A past deadline → Ok(false) (the take_or_restore loop maps this to a
        // pool-saturated error) without blocking.
        let a = Admission::new(1, Some(Duration::from_millis(50)));
        assert!(a.try_reserve());
        let past = Instant::now() - Duration::from_secs(1);
        let start = Instant::now();
        assert_eq!(a.wait_for_change(Some(past)).unwrap(), false);
        assert!(
            start.elapsed() < Duration::from_millis(50),
            "a passed deadline must not block"
        );
        // No slot leaked by the wait.
        assert_eq!(a.alive(), 1);
    }

    #[test]
    fn wait_for_change_wakes_on_notify() {
        // A blocked acquirer is woken by notify() (the refiller-idle-push wake)
        // well before the 100ms cap, then re-loops to re-check idle.
        let a = Arc::new(Admission::new(1, Some(Duration::from_secs(5))));
        assert!(a.try_reserve());
        let peer = Arc::clone(&a);
        let waker = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(20));
            peer.notify();
        });
        let start = Instant::now();
        let deadline = Some(Instant::now() + Duration::from_secs(5));
        assert_eq!(a.wait_for_change(deadline).unwrap(), true);
        let elapsed = start.elapsed();
        waker.join().unwrap();
        assert!(
            elapsed < Duration::from_millis(100),
            "notify must wake the waiter promptly, waited {elapsed:?}"
        );
    }

    #[test]
    fn wait_for_change_caps_each_wait_without_notify() {
        // With no notify and a far deadline, a single wait returns within ~100ms
        // (the cap) so the acquire loop re-checks idle frequently — this is the
        // backstop that makes the min==max deadlock impossible even if a notify
        // is ever missed.
        let a = Admission::new(1, Some(Duration::from_secs(10)));
        assert!(a.try_reserve());
        let start = Instant::now();
        let deadline = Some(Instant::now() + Duration::from_secs(10));
        assert_eq!(a.wait_for_change(deadline).unwrap(), true);
        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_millis(250),
            "each wait must cap at ~100ms, waited {elapsed:?}"
        );
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl KvmPoolInner {
    fn restore_one(&self) -> Result<Vm, Error> {
        Vm::start(&self.image, &self.vm_config)
    }

    /// Pop an idle pre-warmed VM (~µs) or restore a fresh one (~ms). A fresh
    /// restore reserves one of the `max` concurrency slots, BLOCKING (up to
    /// `acquire_timeout`) when the pool is saturated rather than over-spawning.
    /// Idle reuse takes no slot (it was reserved when that VM was created).
    fn take_or_restore(&self) -> Result<Vm, Error> {
        let deadline = self
            .admission
            .acquire_timeout
            .map(|d| std::time::Instant::now() + d);
        loop {
            if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
                return Err(Error::pool_exhausted("pool is shut down"));
            }
            // Re-check idle EVERY iteration. A background refiller holds an
            // admission slot while it restores, then pushes the VM here without
            // releasing the slot — so an acquirer that blocked purely on the
            // slot count would never see it and would hang forever when
            // min == max (the lone slot is the refiller's). Popping idle here
            // each loop is what breaks that deadlock.
            if let Some(vm) = self.idle.lock().unwrap_or_else(|e| e.into_inner()).pop() {
                return Ok(vm);
            }
            // No idle VM: claim a fresh slot if under `max` and restore.
            if self.admission.try_reserve() {
                return self.restore_one().inspect_err(|_| self.admission.release());
            }
            // At the cap with nothing idle: wait for a peer release OR a
            // refiller idle-push, then re-loop (which re-checks idle).
            if !self.admission.wait_for_change(deadline)? {
                return Err(Error::pool_exhausted(format!(
                    "pool saturated: all {} VM slots in use and none freed within \
                     acquire_timeout",
                    self.admission.max
                )));
            }
        }
    }

    /// Synchronously pre-warm the idle queue up to `min` (best-effort). Used at
    /// `build()` so eager pre-spawn (`min > 0`) is observable in `stats()` the
    /// instant `build()` returns, rather than racing a background thread.
    fn prewarm_to_min(&self) {
        loop {
            let idle_len = self.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
            // Stop at the idle target, or when another slot would exceed `max`.
            if idle_len >= self.min || !self.admission.try_reserve() {
                break;
            }
            match self.restore_one() {
                Ok(vm) => {
                    self.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
                    // Wake any acquirer blocked at the cap so it re-checks idle.
                    self.admission.notify();
                }
                Err(_) => {
                    self.admission.release();
                    break;
                }
            }
        }
    }

    /// Spawn (at most one) background refiller to top the idle queue up to `min`.
    fn refill_async(self: &Arc<Self>) {
        use std::sync::atomic::Ordering::SeqCst;
        if self.min == 0 {
            return;
        }
        if self
            .refilling
            .compare_exchange(false, true, SeqCst, SeqCst)
            .is_err()
        {
            return; // a refiller is already running
        }
        let inner = Arc::clone(self);
        std::thread::spawn(move || {
            loop {
                let idle_len = inner.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
                // Stop at the idle target, or when claiming another slot would
                // exceed `max` (try_reserve returns false at the cap).
                if idle_len >= inner.min || !inner.admission.try_reserve() {
                    break;
                }
                match inner.restore_one() {
                    Ok(vm) => {
                        inner
                            .idle
                            .lock()
                            .unwrap_or_else(|e| e.into_inner())
                            .push(vm);
                        // Wake an acquirer blocked at the cap to re-check idle.
                        inner.admission.notify();
                    }
                    Err(_) => {
                        inner.admission.release();
                        break;
                    }
                }
            }
            inner.refilling.store(false, SeqCst);
        });
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl KboxlikePoolInner {
    fn build(
        image: &Image,
        config: &VmConfig,
        min: usize,
        max: usize,
        acquire_timeout: Option<Duration>,
        restore_on_release: bool,
    ) -> Result<Arc<Self>, Error> {
        let mut parts = image
            .kboxlike
            .as_ref()
            .ok_or_else(|| Error::vm_msg("KboxlikePoolInner::build on a non-kboxlike image"))?
            .clone();
        let mut build_root = None;
        if config.for_build {
            let dir = match &config.vsock_mux_dir {
                Some(d) => d.clone(),
                None => std::env::temp_dir(),
            };
            std::fs::create_dir_all(&dir).map_err(Error::Io)?;
            let priv_dir = dir.join(format!(
                "supermachine-kboxlike-build-{}-{}",
                std::process::id(),
                unique_suffix()
            ));
            let private_rootfs = priv_dir.join("rootfs");
            copy_dir_recursive(&parts.rootfs, &private_rootfs)
                .map_err(|e| Error::vm_msg(format!("kboxlike build private rootfs clone: {e}")))?;
            if let Some(base_meta) = parts.rootfs.parent().map(|p| p.join("metadata.json")) {
                if base_meta.is_file() {
                    let _ = std::fs::copy(&base_meta, priv_dir.join("metadata.json"));
                }
            }
            crate::kboxlike::prepare_rootfs_network_config(&private_rootfs).map_err(|e| {
                Error::vm_msg(format!("kboxlike build private rootfs network config: {e}"))
            })?;
            parts.rootfs = private_rootfs;
            build_root = Some(priv_dir);
        }
        let max = max.max(1);
        let min = min.min(max);
        let inner = Arc::new(Self {
            parts,
            vm_config: config.clone(),
            build_root,
            min,
            admission: Admission::new(max, acquire_timeout),
            idle: Mutex::new(Vec::new()),
            restore_on_release,
            refilling: std::sync::atomic::AtomicBool::new(false),
            shut_down: std::sync::atomic::AtomicBool::new(false),
        });
        inner.prewarm_to_min();
        Ok(inner)
    }

    fn restore_one(&self) -> Result<Vm, Error> {
        if self.vm_config.for_build {
            return Vm::start_kboxlike_build_root(&self.parts, &self.vm_config);
        }
        Vm::start_kboxlike_parts(&self.parts, &self.vm_config)
    }

    fn take_or_restore(&self) -> Result<Vm, Error> {
        let deadline = self
            .admission
            .acquire_timeout
            .map(|d| std::time::Instant::now() + d);
        loop {
            if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
                return Err(Error::pool_exhausted("pool is shut down"));
            }
            if let Some(vm) = self.idle.lock().unwrap_or_else(|e| e.into_inner()).pop() {
                return Ok(vm);
            }
            if self.admission.try_reserve() {
                return self.restore_one().inspect_err(|_| self.admission.release());
            }
            if !self.admission.wait_for_change(deadline)? {
                return Err(Error::pool_exhausted(format!(
                    "kboxlike pool saturated: all {} VM slots in use and none freed within \
                     acquire_timeout",
                    self.admission.max
                )));
            }
        }
    }

    fn prewarm_to_min(&self) {
        loop {
            let idle_len = self.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
            if idle_len >= self.min || !self.admission.try_reserve() {
                break;
            }
            match self.restore_one() {
                Ok(vm) => {
                    self.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
                    self.admission.notify();
                }
                Err(e) => {
                    eprintln!("supermachine(kboxlike): prewarm restore failed: {e}");
                    self.admission.release();
                    break;
                }
            }
        }
    }

    fn refill_async(self: &Arc<Self>) {
        use std::sync::atomic::Ordering::SeqCst;
        if self.min == 0 {
            return;
        }
        if self
            .refilling
            .compare_exchange(false, true, SeqCst, SeqCst)
            .is_err()
        {
            return;
        }
        let inner = Arc::clone(self);
        std::thread::spawn(move || {
            loop {
                let idle_len = inner.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
                if idle_len >= inner.min || !inner.admission.try_reserve() {
                    break;
                }
                match inner.restore_one() {
                    Ok(vm) => {
                        inner
                            .idle
                            .lock()
                            .unwrap_or_else(|e| e.into_inner())
                            .push(vm);
                        inner.admission.notify();
                    }
                    Err(e) => {
                        eprintln!("supermachine(kboxlike): refill restore failed: {e}");
                        inner.admission.release();
                        break;
                    }
                }
            }
            inner.refilling.store(false, SeqCst);
        });
    }

    fn release_vm(self: &Arc<Self>, vm: Vm) {
        if self.shut_down.load(std::sync::atomic::Ordering::SeqCst) {
            drop(vm);
            self.admission.release();
            return;
        }

        let warm_slot = {
            let idle = self.idle.lock().unwrap_or_else(|e| e.into_inner());
            idle.len() < self.min
        };
        if !warm_slot {
            drop(vm);
            self.admission.release();
            return;
        }

        if !self.restore_on_release {
            self.idle.lock().unwrap_or_else(|e| e.into_inner()).push(vm);
            self.admission.notify();
            return;
        }

        drop(vm);
        self.admission.release();
        self.refill_async();
    }
}

// Opaque Debug: the KVM `Pool` holds an `Image`, and `Image` (which derives
// Debug) caches an `Arc<Pool>` — a derived Debug would recurse infinitely if
// ever printed. Print opaquely instead.
impl std::fmt::Debug for Pool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Pool").finish_non_exhaustive()
    }
}

/// Snapshot of pool state at a point in time. Cheap to fetch —
/// one mutex acquire — so it's safe to graph at modest rates.
#[derive(Debug, Clone, Copy)]
pub struct PoolStats {
    /// Total workers alive: idle + checked-out + in-flight spawn.
    pub alive: usize,
    /// Currently checked out (in use by a `PooledVm`).
    pub in_use: usize,
    /// Sitting in the idle queue waiting for next acquire.
    pub idle: usize,
    /// Acquire callers currently blocked waiting for a slot.
    pub waiting: usize,
    /// Configured maximum concurrency.
    pub max: usize,
    /// Configured baseline / always-warm count.
    pub min: usize,
    /// Cumulative dead-while-idle workers the watchdog has reaped. A
    /// steadily climbing value points at workers crashing post-restore.
    pub reaped: u64,
    /// High-water-mark resident footprint (phys_footprint, MiB) observed
    /// across this pool's workers, vs the configured `memory_mib` cap.
    /// `0` until the first measurement. Memory admission charges this
    /// (+25% margin) instead of the cap once measured, so the gap
    /// between this and `memory_mib` is density reclaimed for free.
    pub observed_footprint_mib: u64,
}

impl Pool {
    /// Acquire a fresh VM from this pool. Identical fast path to
    /// [`Image::acquire`] — on a hit, ~µs to pop the idle queue.
    /// On miss, follows the policy: auto-grow up to `max`, or
    /// block (with timeout) if at `max`.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn acquire(&self) -> Result<PooledVm<'_>, Error> {
        let _span = tracing::info_span!(
            "supermachine.pool.acquire",
            memory_mib = self.inner.spawn_cfg.memory_mib,
            vcpus = self.inner.spawn_cfg.vcpus,
        )
        .entered();
        let worker = self.inner.acquire()?;
        let vm = Vm {
            pool: None,
            vsock_mux_path: worker.vsock_mux_path.clone(),
            vsock_exec_path: worker.vsock_exec_path.clone(),
            own_vsock_mux_dir: None,
            skip_cleanup: true,
            // image_meta is filled in via Image's ensure_pool path;
            // when the pool is explicitly built we don't have
            // direct access to the source Image, so leave it None
            // and rely on `Vm::start`-derived snapshots if the
            // user wants `PooledVm::snapshot` to work. Most
            // pool-based callers don't need it.
            image_meta: Some(Arc::new(ImageMeta {
                memory_mib: self.inner.spawn_cfg.memory_mib,
                vcpus: self.inner.spawn_cfg.vcpus,
                layers: self.inner.spawn_cfg.layers.clone(),
                delta_squashfs: self.inner.spawn_cfg.delta_squashfs.clone(),
                baker_runtime_sha16: self.inner.spawn_cfg.baker_runtime_sha16.clone(),
                tsi_token: self.inner.spawn_cfg.tsi_token.clone(),
                egress_policy: self.inner.spawn_cfg.egress_policy.clone(),
                pre_exec_sync: self.inner.spawn_cfg.pre_exec_sync,
            })),
        };
        Ok(PooledVm {
            vm: Some(vm),
            worker: Some(worker),
            pool_arc: Arc::clone(&self.inner),
            _image: std::marker::PhantomData,
        })
    }

    /// Acquire a VM (Linux/KVM). Pops a pre-warmed idle VM (~µs) when one is
    /// ready, else restores a fresh one from the warm snapshot (~ms). Triggers a
    /// background refill back to `min`. Torn down + replaced when the
    /// [`PooledVm`] drops. The warming happened once at [`PoolBuilder::build`].
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn acquire(&self) -> Result<PooledVm<'_>, Error> {
        // No-virt sentry pool: admission-gate + cheap checkout against the
        // shared exec server (no idle queue / restore).
        if let Some(sp) = &self.sentry {
            return sp.acquire();
        }
        if let Some(rp) = &self.runsc {
            let vm = rp.acquire_vm()?;
            return Ok(PooledVm {
                vm: Some(vm),
                pool: None,
                sentry_pool: None,
                runsc_pool: Some(Arc::clone(rp)),
                kboxlike_pool: None,
                sentry_mem_admission: None,
                sentry_running_pid: None,
                sentry_running_pool: None,
                sentry_stop_running_pool_on_drop: false,
                sentry_touched: AtomicBool::new(false),
                _image: std::marker::PhantomData,
            });
        }
        if let Some(kp) = &self.kboxlike {
            let vm = kp.take_or_restore()?;
            return Ok(PooledVm {
                vm: Some(vm),
                pool: None,
                sentry_pool: None,
                runsc_pool: None,
                kboxlike_pool: Some(Arc::clone(kp)),
                sentry_mem_admission: None,
                sentry_running_pid: None,
                sentry_running_pool: None,
                sentry_stop_running_pool_on_drop: false,
                sentry_touched: AtomicBool::new(false),
                _image: std::marker::PhantomData,
            });
        }
        let kvm = self.kvm.as_ref().expect("Pool has no backend");
        let vm = kvm.take_or_restore()?;
        // No background refill on acquire: BOTH release modes now return the VM
        // ALIVE to idle (isolated = in-place reset, dirty = as-is), so the
        // checked-out VM IS its own replenishment. A refill here would restore
        // redundant fresh VMs during the checkout window and grow the pool past
        // its working set. The only teardown is the reset-failure fallback in
        // PooledVm::drop, which refills itself.
        Ok(PooledVm {
            vm: Some(vm),
            pool: Some(Arc::clone(kvm)),
            sentry_pool: None,
            runsc_pool: None,
            kboxlike_pool: None,
            sentry_mem_admission: None,
            sentry_running_pid: None,
            sentry_running_pool: None,
            sentry_stop_running_pool_on_drop: false,
            sentry_touched: AtomicBool::new(false),
            _image: std::marker::PhantomData,
        })
    }

    /// Snapshot of current pool state.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn stats(&self) -> PoolStats {
        let s = self.inner.state.lock().ok();
        let alive = s.as_ref().map(|s| s.alive).unwrap_or(0);
        let idle = s.as_ref().map(|s| s.idle.len()).unwrap_or(0);
        let waiting = s.as_ref().map(|s| s.waiting).unwrap_or(0);
        let reaped = s.as_ref().map(|s| s.reaped).unwrap_or(0);
        let observed_footprint_mib = self
            .inner
            .spawn_cfg
            .observed_footprint_mib
            .load(std::sync::atomic::Ordering::Relaxed);
        PoolStats {
            alive,
            in_use: alive.saturating_sub(idle),
            idle,
            waiting,
            max: self.inner.policy.max,
            min: self.inner.policy.min,
            reaped,
            observed_footprint_mib,
        }
    }

    /// Snapshot of current pool state (Linux/KVM): idle = pre-warmed VMs ready,
    /// alive = idle + checked-out, against the configured min/max.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn stats(&self) -> PoolStats {
        // Sentry pool: one always-warm shared server, no idle queue. `alive` =
        // concurrent checkouts, `max` = admission cap, `min`/`idle` = 0.
        if let Some(sp) = &self.sentry {
            let alive = sp.admission.alive();
            return PoolStats {
                alive,
                in_use: alive,
                idle: 0,
                waiting: 0,
                max: sp.admission.max,
                min: 0,
                reaped: 0,
                observed_footprint_mib: 0,
            };
        }
        if let Some(rp) = &self.runsc {
            let alive = rp.admission.alive();
            let idle = rp.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
            let in_use = rp.checked_out.load(std::sync::atomic::Ordering::SeqCst);
            return PoolStats {
                alive,
                in_use,
                idle,
                waiting: 0,
                max: rp.max,
                min: rp.min,
                reaped: 0,
                observed_footprint_mib: 0,
            };
        }
        if let Some(kp) = &self.kboxlike {
            let alive = kp.admission.alive();
            let idle = kp.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
            return PoolStats {
                alive,
                in_use: alive.saturating_sub(idle),
                idle,
                waiting: 0,
                max: kp.admission.max,
                min: kp.min,
                reaped: 0,
                observed_footprint_mib: 0,
            };
        }
        let kvm = self.kvm.as_ref().expect("Pool has no backend");
        let idle = kvm.idle.lock().unwrap_or_else(|e| e.into_inner()).len();
        let alive = kvm.admission.alive();
        PoolStats {
            alive,
            in_use: alive.saturating_sub(idle),
            idle,
            waiting: 0,
            max: kvm.admission.max,
            min: kvm.min,
            reaped: 0,
            observed_footprint_mib: 0,
        }
    }

    /// Sentry-only: cumulative exec metrics for a **warm-daemon** pool — exec
    /// count, ok/nonzero/seccomp/signal/timeout/error tallies, and mean/max exec
    /// latency. Additive observability on top of the hypervisor-agnostic
    /// [`stats`](Self::stats) (which reports admission/liveness only). Returns
    /// `None` for non-sentry pools and for the sentry exec-server backend (no
    /// per-pool counter). The counters are cumulative over the pool's lifetime.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn sentry_stats(&self) -> Option<crate::sentry::SentryPoolStats> {
        self.sentry.as_ref().and_then(|sp| sp.sentry_stats())
    }

    /// Shut the pool down explicitly. Wakes any caller blocked on
    /// [`Self::acquire`] — they receive
    /// `Err(Error::vm_msg("pool is shutting down"))` instead of
    /// hanging — drains idle + dirty workers, and stops
    /// housekeeping threads.
    ///
    /// Idempotent. Pool is also shut down on Drop, so explicit
    /// `shutdown()` is for embedders who want a synchronous "the
    /// pool is gone now" guarantee (e.g. before re-creating a pool
    /// at a different size, or before a process-shutdown hook).
    pub fn shutdown(&self) {
        // macOS: tear down the worker pool. Linux/KVM no-reuse pool holds no
        // shared resources — per-acquire VMs stop when their PooledVm drops.
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        self.inner.shutdown_pool();
        // Linux/KVM: mark the pool dead so subsequent acquires error (instead of
        // restoring fresh VMs) + drain any pre-warmed idle VMs now.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            if let Some(sp) = &self.sentry {
                // Sentry: refuse new acquires; the shared exec server is torn
                // down (socket unlinked + workload killed) immediately when no
                // checkout is active, or by the last `PooledVm` release when a
                // shutdown races an active checkout. This mirrors the API
                // contract on KVM/HVF: explicit shutdown frees host resources
                // without waiting for JS GC to drop the Pool object.
                sp.shut_down
                    .store(true, std::sync::atomic::Ordering::SeqCst);
                sp.admission.notify();
                sp.cleanup_if_shutdown_idle();
            } else if let Some(kvm) = &self.kvm {
                kvm.shut_down
                    .store(true, std::sync::atomic::Ordering::SeqCst);
                let drained: Vec<Vm> =
                    std::mem::take(&mut *kvm.idle.lock().unwrap_or_else(|e| e.into_inner()));
                for vm in drained {
                    kvm.admission.release();
                    drop(vm);
                }
            } else if let Some(runsc) = &self.runsc {
                runsc
                    .shut_down
                    .store(true, std::sync::atomic::Ordering::SeqCst);
                let drained: Vec<Vm> =
                    std::mem::take(&mut *runsc.idle.lock().unwrap_or_else(|e| e.into_inner()));
                for vm in drained {
                    drop(vm);
                    runsc.admission.release();
                }
                runsc.admission.notify();
            } else if let Some(kboxlike) = &self.kboxlike {
                kboxlike
                    .shut_down
                    .store(true, std::sync::atomic::Ordering::SeqCst);
                let drained: Vec<Vm> =
                    std::mem::take(&mut *kboxlike.idle.lock().unwrap_or_else(|e| e.into_inner()));
                for vm in drained {
                    drop(vm);
                    kboxlike.admission.release();
                }
                kboxlike.admission.notify();
            }
        }
    }
}

///
/// Every setter that affects the workload's behavior (env, cmd,
/// memory, guest_port) is part of the bake's input fingerprint:
/// changing it forces a re-bake and produces a different snapshot.
/// Use distinct `with_name` values if you want side-by-side
/// snapshots for the same image ref with different configs.
pub struct OciImageBuilder {
    image: String,
    name: Option<String>,
    pull_policy: PullPolicy,
    memory_mib: Option<u32>,
    vcpus: Option<u32>,
    guest_port: Option<u16>,
    cmd: Option<Vec<String>>,
    envs: Vec<(String, String)>,
    snapshots_dir: Option<PathBuf>,
    /// Optional post-bake warmup. After the bake completes, we
    /// `acquire` a VM from the freshly-baked image, run this
    /// closure, snapshot the post-warmup state, and replace
    /// `restore.snap` with the warm version. Subsequent acquires
    /// land at warm state — guest page cache for the workload
    /// already populated, so e.g. `rustc` cold-start drops from
    /// ~370 ms to ~50–100 ms.
    warmup: Option<Box<dyn FnOnce(&Vm) -> Result<(), Error> + Send>>,
    /// Stable tag for the warmup. Folded into the snapshot's
    /// cached fingerprint so changing the warmup invalidates the
    /// previous warm snapshot. If `None`, warmup is treated as
    /// "any change re-runs" (we use a hash-of-empty as the tag,
    /// which is stable across runs).
    warmup_tag: Option<String>,
    /// Bake for the warm-daemon pool backend (sentry only): forwarded into
    /// `SentryBakeConfig.warm_daemon` in `build_kvm`. No effect on KVM/HVF.
    warm_daemon: bool,
    /// Extra files to stage into the bake's delta layer at
    /// (host_path, guest_path). Useful for bundling per-snapshot
    /// auxiliary binaries (e.g. the snapshot-park kernel module
    /// at `/supermachine-smpark.ko`). Plumbed through to the
    /// bake step as `--extra-file <host>:<guest>` args.
    extra_files: Vec<(PathBuf, String)>,
    /// virtio-fs DAX mounts: (host_path, guest_tag, symlink_policy)
    /// (host_path, guest_tag, symlinks_policy, guest_path). Each is
    /// exposed as a virtio-fs device and auto-mounted by init-oci
    /// at `guest_path` before the workload starts. Plumbed through
    /// to the bake step as
    /// `--mount <host>:<tag>:<guest_path>[:<policy>]` args.
    mounts: Vec<(
        PathBuf,
        String,
        crate::vmm::resources::SymlinkPolicy,
        String,
    )>,
    /// Writable virtio-blk volumes: (host_path, guest_path, size_bytes).
    /// Each is plumbed through to the bake step as
    /// `--volume <host>:<guest>:<size_bytes>` args. Use for
    /// dependency caches (`node_modules`, `target/`) — block I/O
    /// bypasses the FUSE round-trip cost that makes `mounts` slow
    /// for thousands-of-small-files write workloads. Volume bytes
    /// persist across restores; only the mapping is snapshotted.
    volumes: Vec<(PathBuf, String, u64)>,
    /// Extra kernel cmdline tokens appended after supermachine's
    /// own defaults. Power-user / testing escape hatch — e.g.
    /// `["init=/nope"]` in a test to deliberately trigger an
    /// early-init kernel panic. Plumbed through to the bake step
    /// as `--cmdline-extra <token>` args.
    extra_kernel_args: Vec<String>,
    /// When `Some(true)`, the no-warmup `.build()` path waits for
    /// the workload's listener to come up (or the parked-PID-1
    /// fallback) before capturing — same as v0.4.22 behavior.
    /// When `None` or `Some(false)`, the default v0.4.23+ behavior
    /// applies: snapshot is captured at the pre-exec marker, BEFORE
    /// the workload runs. Each restore re-execs the workload fresh.
    ///
    /// Set to `true` for service-image bakes (nginx, redis, etc.)
    /// where you want the listener pre-bound at restore time but
    /// don't want the cost of routing through `with_warmup`. See
    /// [`OciImageBuilder::with_listener_required`].
    require_listener: Option<bool>,
    /// Target platform, in Docker `--platform` form. `None` →
    /// default `"linux/arm64"`. Setting `"linux/amd64"` makes the
    /// bake pull the amd64 variant of multi-arch images AND
    /// auto-mounts Apple's Rosetta runtime share, giving the
    /// guest end-to-end amd64-binary execution via the M1
    /// Rosetta-in-VM plumbing. See
    /// `docs/design/chrome-amd64-gap-2026-05-17.md`.
    pub(crate) platform: Option<String>,
}

impl OciImageBuilder {
    /// Start a new builder for `image_ref` (e.g. `"nginx:1.27-alpine"`,
    /// `"ghcr.io/owner/image@sha256:..."`).
    pub fn new(image_ref: impl Into<String>) -> Self {
        Self {
            image: image_ref.into(),
            name: None,
            pull_policy: PullPolicy::default(),
            memory_mib: None,
            vcpus: None,
            guest_port: None,
            cmd: None,
            envs: Vec::new(),
            snapshots_dir: None,
            warmup: None,
            warmup_tag: None,
            warm_daemon: false,
            extra_files: Vec::new(),
            mounts: Vec::new(),
            volumes: Vec::new(),
            extra_kernel_args: Vec::new(),
            require_listener: None,
            platform: None,
        }
    }

    /// Set the target platform for the image pull, in Docker
    /// `--platform` form. Two values are supported:
    ///
    ///   - `"linux/arm64"` (default) — native arm64 path, full perf.
    ///   - `"linux/amd64"` — pull the amd64 variant from a multi-
    ///     arch index; auto-mount Apple's Rosetta runtime share at
    ///     `/run/rosetta`; register binfmt_misc so amd64 ELFs run
    ///     via Rosetta translation. Requires Rosetta to be
    ///     installed on the host (`softwareupdate --install-rosetta`).
    ///
    /// ```no_run
    /// # use supermachine::Image;
    /// let img = Image::builder("mcr.microsoft.com/playwright:v1.59.1-jammy")
    ///     .with_platform("linux/amd64")
    ///     .with_memory_mib(4096)
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_platform(mut self, platform: impl Into<String>) -> Self {
        self.platform = Some(platform.into());
        self
    }

    /// Stage `host_path` into the snapshot's delta layer at
    /// `guest_path`. The file appears at `guest_path` inside the
    /// guest's root filesystem after restore. Folded into the
    /// bake's content hash so changing the host file invalidates
    /// the cached snapshot.
    ///
    /// Used (e.g.) to ship `supermachine-smpark.ko` so init-oci
    /// can `finit_module` it on boot for multi-vCPU snapshot
    /// support.
    pub fn with_extra_file(
        mut self,
        host_path: impl Into<PathBuf>,
        guest_path: impl Into<String>,
    ) -> Self {
        self.extra_files.push((host_path.into(), guest_path.into()));
        self
    }

    /// Override where the image bytes come from. Default (when not
    /// called) treats the constructor's `image_ref` as a registry
    /// reference and pulls from Docker Hub or the registry encoded
    /// in the ref.
    ///
    /// Internally the bake driver also accepts `image_ref` directly
    /// in the prefixed forms `oci-archive:/path` and `oci-layout:/path`;
    /// this method is the structured convenience: the user keeps
    /// `image_ref` as a logical identifier (used to derive the
    /// snapshot dir name) and points at a local source separately.
    ///
    /// ```no_run
    /// # use supermachine::{Image, PullPolicy};
    /// let img = Image::builder("shopify-test-sm:latest")
    ///     .with_oci_archive("/tmp/shopify.tar")
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_oci_archive(mut self, archive_path: impl Into<PathBuf>) -> Self {
        // Rewrite image ref to the prefix form; keep the user's
        // original ref as the auto-derived snapshot name if no
        // explicit `with_name` was called.
        let path: PathBuf = archive_path.into();
        let original =
            std::mem::replace(&mut self.image, format!("oci-archive:{}", path.display()));
        if self.name.is_none() {
            self.name = Some(crate::bake::snapshot_name_for_image(&original));
        }
        self
    }

    /// Like `with_oci_archive` but points at an OCI layout DIRECTORY
    /// (the un-tar'd form, with `index.json` + `oci-layout` +
    /// `blobs/sha256/...` at the top level).
    pub fn with_oci_layout(mut self, layout_dir: impl Into<PathBuf>) -> Self {
        let path: PathBuf = layout_dir.into();
        let original = std::mem::replace(&mut self.image, format!("oci-layout:{}", path.display()));
        if self.name.is_none() {
            self.name = Some(crate::bake::snapshot_name_for_image(&original));
        }
        self
    }

    /// Expose a host directory to the guest via virtio-fs (with DAX).
    /// The guest mounts it inside `init-oci` as
    /// `mount -t virtiofs <tag> <target>` — by convention init-oci
    /// mounts each declared tag at `/mnt/<tag>` and bind-mounts into
    /// the workload's filesystem if a per-image policy says so.
    ///
    /// Reads from the guest land in the host's page cache (DAX-mapped
    /// via `hv_vm_map`; validated by spike 22 to be zero-copy + shared
    /// across VMs that mount the same host path). The mount is added
    /// to the bake's input hash so changing `host_path` invalidates the
    /// cached snapshot.
    ///
    /// ```no_run
    /// # use supermachine::Image;
    /// let img = Image::builder("node:22-alpine")
    ///     .with_mount("/Users/me/myapp", "myapp", "/workspace")
    ///     .with_cmd(["node", "/workspace/index.js"])
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_mount(
        mut self,
        host_path: impl Into<PathBuf>,
        guest_tag: impl Into<String>,
        guest_path: impl Into<String>,
    ) -> Self {
        self.mounts.push((
            host_path.into(),
            guest_tag.into(),
            crate::vmm::resources::SymlinkPolicy::default(),
            guest_path.into(),
        ));
        self
    }

    /// Like [`Self::with_mount`] but lets the caller pick a
    /// [`SymlinkPolicy`] other than the default `Opaque`.
    pub fn with_mount_symlinks(
        mut self,
        host_path: impl Into<PathBuf>,
        guest_tag: impl Into<String>,
        guest_path: impl Into<String>,
        symlinks: crate::vmm::resources::SymlinkPolicy,
    ) -> Self {
        self.mounts.push((
            host_path.into(),
            guest_tag.into(),
            symlinks,
            guest_path.into(),
        ));
        self
    }

    /// Attach a writable virtio-blk volume backing `host_path`
    /// (created sparse if missing, sized to `spec.size_bytes`) at
    /// `spec.guest_path` inside the guest. Use for dependency caches
    /// and other write-heavy paths where you'd otherwise pay the
    /// per-file FUSE round-trip cost of `with_mount`.
    ///
    /// # Durability contract (both backends)
    ///
    /// Volume writes become durable at **snapshot capture**: the bake
    /// (boot + warmup) writes the volume's canonical content, and every
    /// capture records the volume's at-capture bytes alongside the
    /// snapshot (macOS: a clonefile "pristine"; KVM: a materialized
    /// `volumes/<i>.img`) so restores always see content that matches
    /// the captured ext4-in-RAM state.
    ///
    /// Writes made **during a pool cycle are ephemeral by design**:
    /// each acquired VM works on an isolated copy-on-write view
    /// (macOS: per-worker temp clone; KVM: MAP_PRIVATE pages reset in
    /// O(1) on release), so the next acquire sees capture-time bytes
    /// again — never another cycle's half-written state. To persist a
    /// cycle's volume writes, snapshot the VM (`vm.snapshot(...)`)
    /// before releasing it.
    ///
    /// ```no_run
    /// # use supermachine::{Image, VolumeSpec};
    /// let img = Image::builder("node:22-alpine")
    ///     .with_volume(VolumeSpec::new("/var/cache/sm/node_modules.img",
    ///                                  "/work/node_modules"))
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_volume(mut self, spec: crate::vmm::resources::VolumeSpec) -> Self {
        self.volumes.push((
            PathBuf::from(spec.host_path),
            spec.guest_path,
            spec.size_bytes,
        ));
        self
    }

    /// Append one extra token to the kernel cmdline. Tokens go
    /// after supermachine's own defaults (`earlycon`, `console`,
    /// `tsi_hijack`, etc.) but before the per-bake `tsi_token`.
    /// Power-user / testing escape hatch — e.g. pass
    /// `"init=/nope"` in a test to deliberately trigger an
    /// early-init kernel panic, or `"panic=1"` to make the
    /// kernel panic on any warning. Folded into the bake's input
    /// hash so changing this re-bakes.
    pub fn with_extra_kernel_arg(mut self, arg: impl Into<String>) -> Self {
        self.extra_kernel_args.push(arg.into());
        self
    }

    /// Override the number of vCPUs the snapshot is baked with.
    /// Default `1`. Multi-vCPU is opt-in: it lifts sustained
    /// HTTP-serving throughput (single-vCPU is the c=32+
    /// bottleneck) at the cost of slightly higher cold boot and
    /// some snapshot/restore caveats. See
    /// docs/design/concurrency-floor-2026-05-04.md.
    pub fn with_vcpus(mut self, vcpus: u32) -> Self {
        self.vcpus = Some(vcpus);
        self
    }

    /// Snapshot name. Default: derived from the image ref via
    /// `bake::snapshot_name_for_image`. Use this when you want
    /// `nginx:1.27-alpine` baked twice with different configs.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Cache + registry policy. See [`PullPolicy`].
    pub fn with_pull_policy(mut self, policy: PullPolicy) -> Self {
        self.pull_policy = policy;
        self
    }

    /// Override the bake-time memory budget (MiB). The runtime
    /// memory is set on [`VmConfig`]; this is the size the
    /// snapshot is captured at.
    pub fn with_memory_mib(mut self, mib: u32) -> Self {
        self.memory_mib = Some(mib);
        self
    }

    /// Override the guest service port the bake waits for as the
    /// readiness signal. Default `80`.
    pub fn with_guest_port(mut self, port: u16) -> Self {
        self.guest_port = Some(port);
        self
    }

    /// Override the image's `CMD`. Pass an argv array, same shape
    /// as Docker's `--entrypoint` + arguments combined.
    ///
    /// ```no_run
    /// # use supermachine::Image;
    /// let img = Image::builder("python:3.12-alpine")
    ///     .with_cmd(["python", "-m", "http.server", "8080"])
    ///     .with_guest_port(8080)
    ///     .build()?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_cmd<I, S>(mut self, cmd: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.cmd = Some(cmd.into_iter().map(Into::into).collect());
        self
    }

    /// Add an environment variable for the workload. Repeatable.
    /// Mirrors `docker run -e KEY=VAL`.
    pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.envs.push((key.into(), value.into()));
        self
    }

    /// Override the directory snapshots are stored in. Default
    /// is `~/.local/supermachine-snapshots`. Use this to keep
    /// per-project snapshot stores isolated from each other.
    pub fn with_snapshots_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.snapshots_dir = Some(dir.into());
        self
    }

    /// Run a warmup closure once after the bake, then re-snapshot
    /// the post-warmup state. Future restores from this image
    /// land at the warm state — guest page cache for the
    /// workload already populated, so e.g. compiling a small
    /// Rust program drops from ~370 ms to ~50–100 ms.
    ///
    /// Cached: if the warm snapshot already exists with a
    /// matching warmup tag (see [`Self::with_warmup_tag`]), the
    /// warmup is skipped on subsequent builds. Without an
    /// explicit tag, the warmup re-runs whenever the snapshot
    /// is invalidated by other inputs (image_ref, memory, etc.)
    /// — set a tag if you change the closure body and want the
    /// cache to invalidate.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use supermachine::Image;
    /// let image = Image::ensure_baked("rust_warm", "rust:1-slim", |b| b
    ///     .with_memory_mib(2048)
    ///     .with_warmup(|vm| {
    ///         vm.write_file("/tmp/probe.rs", b"fn main(){}")?;
    ///         vm.exec_builder()
    ///             .argv(["sh", "-c", "rustc -O /tmp/probe.rs -o /tmp/probe && /tmp/probe"])
    ///             .timeout(Duration::from_secs(60))
    ///             .output()?;
    ///         Ok(())
    ///     })
    ///     .with_warmup_tag("v1")
    /// )?;
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_warmup<F>(mut self, warmup: F) -> Self
    where
        F: FnOnce(&Vm) -> Result<(), Error> + Send + 'static,
    {
        self.warmup = Some(Box::new(warmup));
        self
    }

    /// Stable tag for the warmup closure (see [`Self::with_warmup`]).
    /// Bump when you change the warmup body and want the previously
    /// cached warm snapshot invalidated.
    pub fn with_warmup_tag(mut self, tag: impl Into<String>) -> Self {
        self.warmup_tag = Some(tag.into());
        self
    }

    /// Bake this image for the warm-daemon pool backend (sentry only):
    /// `Image::builder(x).with_warm_daemon().build().pool().acquire()` warms a
    /// PERSISTENT sentry cell at the workload's SENTINEL checkpoint and forks a
    /// detached daemon per acquire; the acquired `Vm`'s `exec` runs client cells
    /// that reach the warm daemon over the supervisor-global owned loopback.
    ///
    /// The workload (the image's Cmd/Entrypoint) MUST checkpoint itself once it is
    /// ready to serve (`syscall(0x5359)`), exactly like a listening daemon — else
    /// `.pool().build()` blocks waiting for the checkpoint. Snapshotting a
    /// warm-daemon pool is refused (the warm state is a live cell, not the rootfs).
    pub fn with_warm_daemon(mut self) -> Self {
        self.warm_daemon = true;
        self
    }

    /// For the no-warmup `.build()` path, wait for the workload's
    /// in-guest listener to come up before capturing the snapshot
    /// (the v0.4.22 behavior). Without this, v0.4.23+ defaults to
    /// the `pre-exec` trigger which captures BEFORE the workload
    /// runs — fast bake, but each restore re-execs the workload
    /// fresh (workload's own startup time is paid per acquire).
    ///
    /// **When to call this:**
    ///
    /// - **You're baking a service image** (nginx, redis, postgres,
    ///   anything that binds a listener and stays up) AND you want
    ///   the listener pre-bound at restore-time so first acquire's
    ///   port-traffic works immediately, but you don't want to pay
    ///   the cost of routing through `with_warmup` (which adds a
    ///   warm-snapshot round-trip).
    ///
    /// **When NOT to call this:**
    ///
    /// - **You're using `vm.exec(...)`** for arbitrary commands and
    ///   don't care about the workload's listener. Default (pre-exec
    ///   trigger) is faster and gives you the same agent behavior.
    ///
    /// - **The workload doesn't bind a listener and doesn't exit
    ///   quickly** (e.g. a long-running daemon that never serves a
    ///   port). With `require_listener=true` you'd time out at
    ///   `--snapshot-after-ms` (~7 s default). The pre-exec trigger
    ///   handles this case in ~150 ms regardless.
    ///
    /// No effect when `with_warmup` is also set — the warmup path
    /// always uses listener-ready (or the warmup callback would run
    /// against a not-yet-ready guest).
    pub fn with_listener_required(mut self) -> Self {
        self.require_listener = Some(true);
        self
    }

    /// Run the bake (or reuse a cached snapshot per
    /// `with_pull_policy`) and return the resulting [`Image`].
    ///
    /// Dispatches by backend: KVM (Linux/x86_64) bakes through the
    /// self-contained KVM pipeline; HVF (macOS/aarch64) through the worker
    /// pipeline. The cache / pull-policy / version-skew handling is shared.
    pub fn build(self) -> Result<Image, Error> {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            self.build_kvm()
        }
        #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
        {
            self.build_native()
        }
    }

    /// Linux/x86_64 bake. Routes through runsc by default for now, with explicit
    /// `SUPERMACHINE_BACKEND=kvm` / `sentry` overrides for backend bring-up.
    ///
    /// When backend selection resolves to the no-virt **runsc** or **sentry**
    /// backend, the builder's run-config
    /// (`with_cmd` / `with_env` / `with_mount` / `with_volume` /
    /// `with_extra_file` / `with_warmup`) IS applied — routed through
    /// [`Image::bake_sentry_with_config`] instead of the config-less
    /// `from_oci_to_dir` → `bake_sentry_from_ref` tail. (On the KVM backend
    /// only volumes are applied; the rest are still ignored with a warning.)
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn build_kvm(self) -> Result<Image, Error> {
        let snapshots_dir = self
            .snapshots_dir
            .clone()
            .unwrap_or_else(default_snapshots_dir);
        let derived_name = self
            .name
            .clone()
            .unwrap_or_else(|| crate::bake::snapshot_name_for_image(&self.image));
        let snap_dir = snapshots_dir.join(&derived_name);

        // Backend selection — same as `from_oci_to_dir`: Linux defaults to
        // runsc for now; explicit SUPERMACHINE_BACKEND can force kvm/sentry/
        // kboxlike.
        let backend = linux_default_backend();
        let use_runsc = backend == "runsc";
        let use_sentry = backend == "sentry";
        let use_kboxlike = backend == "kboxlike";
        if use_sentry || use_runsc || use_kboxlike {
            let backend_name = if use_runsc {
                "runsc"
            } else if use_kboxlike {
                "kboxlike"
            } else {
                "sentry"
            };
            let has_warmup = self.warmup.is_some();
            let warmup_tag = self.warmup_tag.as_deref().unwrap_or("default");
            let no_virt_snap_dir = if has_warmup {
                snapshots_dir.join(format!("{}__warm__{}", derived_name, warmup_tag))
            } else {
                snap_dir.clone()
            };
            let requested_mounts: Vec<crate::vmm::resources::MountSpec> = self
                .mounts
                .iter()
                .map(|(host, tag, policy, guest_path)| {
                    crate::vmm::resources::MountSpec::new(
                        host.to_string_lossy().to_string(),
                        tag.clone(),
                        guest_path.clone(),
                    )
                    .with_symlinks(policy.clone())
                })
                .collect();
            let cfg = SentryBakeConfig {
                memory_mib: self.memory_mib,
                vcpus: self.vcpus,
                cmd: self.cmd,
                env: self.envs,
                working_dir: None,
                user: None,
                extra_files: self.extra_files,
                mounts: self.mounts,
                volumes: self.volumes,
                warmup: self.warmup,
                // Footgun fix: the sentry branch previously DROPPED warmup_tag (the
                // struct had no field) and had no warm-daemon flag, so both were lost
                // before the bake ran. Thread them through now.
                warmup_tag: self.warmup_tag,
                warm_daemon: self.warm_daemon,
            };
            let no_virt_bake_key = sentry_bake_cache_key(&self.image, &cfg)?;
            // Cache fast-path for PullPolicy::Missing: reuse a loadable no-virt
            // snapshot only when the builder inputs match. Artifacts are named by
            // `with_name`, so without this key a changed extra file/env/cmd could
            // silently serve an old rootfs under the same name.
            if self.pull_policy == PullPolicy::Missing {
                if let Ok(img) = Image::from_snapshot(&no_virt_snap_dir) {
                    let backend_matches = if use_runsc {
                        img.runsc.is_some()
                    } else if use_kboxlike {
                        img.kboxlike.is_some()
                    } else {
                        img.sentry.is_some()
                    };
                    if backend_matches {
                        let meta_matches = std::fs::read(no_virt_snap_dir.join("metadata.json"))
                            .ok()
                            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
                            .map(|m| {
                                let key_matches = m
                                    .get(if use_runsc {
                                        "runsc_bake_key"
                                    } else if use_kboxlike {
                                        "kboxlike_bake_key"
                                    } else {
                                        "sentry_bake_key"
                                    })
                                    .or_else(|| m.get("sentry_bake_key"))
                                    .and_then(|v| v.as_str())
                                    == Some(no_virt_bake_key.as_str());
                                let memory_matches = match cfg.memory_mib {
                                    Some(expected) => {
                                        m.get("memory_mib").and_then(|v| v.as_u64())
                                            == Some(expected as u64)
                                    }
                                    None => true,
                                };
                                let vcpus_matches = match cfg.vcpus {
                                    Some(expected) => {
                                        m.get("vcpus").and_then(|v| v.as_u64())
                                            == Some(expected as u64)
                                    }
                                    None => true,
                                };
                                key_matches && memory_matches && vcpus_matches
                            })
                            == Some(true);
                        if !meta_matches {
                            invalidate_stale_snapshot_tree(&no_virt_snap_dir);
                        } else if has_warmup && img.mounts != requested_mounts {
                            eprintln!(
                                "supermachine: {backend_name} warm snapshot at {} was baked with mounts \
                                 {:?} but this build requests {:?}. Auto-rebaking with the current mounts.",
                                no_virt_snap_dir.display(),
                                img.mounts,
                                requested_mounts,
                            );
                            invalidate_stale_snapshot_tree(&no_virt_snap_dir);
                        } else {
                            return Ok(img);
                        }
                    }
                }
            }
            if use_runsc {
                return Image::bake_runsc_with_config(&self.image, &no_virt_snap_dir, cfg);
            }
            if use_kboxlike {
                return Image::bake_kboxlike_with_config(&self.image, &no_virt_snap_dir, cfg);
            }
            return Image::bake_sentry_with_config(&self.image, &no_virt_snap_dir, cfg);
        }

        // KVM backend: build through the in-process KVM runtime. The old native
        // worker pipeline is macOS/HVF-only on Linux, so routing KVM warmup
        // through it wedges waiting for a worker control socket.
        self.build_kvm_in_process(snapshots_dir, derived_name, snap_dir)
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn build_kvm_in_process(
        self,
        snapshots_dir: PathBuf,
        derived_name: String,
        snap_dir: PathBuf,
    ) -> Result<Image, Error> {
        if self.platform.as_deref().is_some_and(|p| p != "linux/amd64") {
            return Err(Error::bake_msg(format!(
                "KVM backend on linux/x86_64 only supports platform=linux/amd64, got {}",
                self.platform.as_deref().unwrap_or_default()
            )));
        }

        let has_warmup = self.warmup.is_some();
        let tag = self.warmup_tag.as_deref().unwrap_or("default");
        let output_dir = if has_warmup {
            snapshots_dir.join(format!("{}__warm__{}", derived_name, tag))
        } else {
            snap_dir.clone()
        };
        let requested_vcpus = self.vcpus.unwrap_or(1);
        let effective_vcpus = kvm_effective_vcpus(requested_vcpus, "Image.build");
        let key_config = SentryBakeConfig {
            memory_mib: self.memory_mib,
            vcpus: Some(effective_vcpus),
            cmd: self.cmd.clone(),
            env: self.envs.clone(),
            working_dir: None,
            user: None,
            extra_files: self.extra_files.clone(),
            mounts: self.mounts.clone(),
            volumes: self.volumes.clone(),
            warmup: if has_warmup {
                Some(Box::new(|_| Ok(())))
            } else {
                None
            },
            warm_daemon: self.warm_daemon,
            warmup_tag: self.warmup_tag.clone(),
        };
        let kvm_bake_key = sentry_bake_cache_key(&self.image, &key_config)?;

        match self.pull_policy {
            PullPolicy::Never => {
                let image = Image::from_snapshot(&output_dir)?;
                if kvm_bake_key_matches(&output_dir, &kvm_bake_key) {
                    return Ok(image);
                }
                return Err(Error::cache_invalid(format!(
                    "cached KVM snapshot at {} was baked with different builder inputs \
                     (PullPolicy::Never won't auto-rebake)",
                    output_dir.display()
                )));
            }
            PullPolicy::Missing => {
                if let Ok(image) = Image::from_snapshot(&output_dir) {
                    if kvm_bake_key_matches(&output_dir, &kvm_bake_key) {
                        return Ok(image);
                    }
                    invalidate_stale_snapshot_tree(&snap_dir);
                    if output_dir != snap_dir {
                        let _ = std::fs::remove_dir_all(&output_dir);
                    }
                }
            }
            PullPolicy::Always => {
                invalidate_stale_snapshot_tree(&snap_dir);
                if output_dir != snap_dir {
                    let _ = std::fs::remove_dir_all(&output_dir);
                }
            }
        }

        let cold_dir = snap_dir.clone();
        std::fs::create_dir_all(&cold_dir).map_err(Error::Io)?;
        let (kernel, initrd) = Image::extract_bundled_kvm_boot_assets(&cold_dir)?;
        let pull_work = cold_dir.join("oci-pull");
        let (layers, image_workload, oci_config) =
            crate::bake::pull_oci_layers(&self.image, "amd64", &pull_work)
                .map_err(Error::bake_msg)?;
        let (workload, env_pairs, effective_workdir, effective_user) = effective_builder_workload(
            image_workload,
            oci_config.as_ref(),
            self.cmd.as_ref(),
            &self.envs,
        );

        let rootfs = cold_dir.join("rootfs.squashfs");
        let stage = cold_dir.join("rootfs-stage");
        let _ = std::fs::remove_dir_all(&stage);
        crate::bake::build_sentry_rootfs(&layers, &stage, workload.as_deref())
            .map_err(Error::bake_msg)?;
        for (host, guest) in &self.extra_files {
            let rel = guest.trim_start_matches('/');
            let target = confined_rootfs_join(&stage, rel).ok_or_else(|| {
                Error::bake_msg(format!(
                    "extra-file guest path escapes the rootfs: {guest:?}"
                ))
            })?;
            if let Some(parent) = target.parent() {
                std::fs::create_dir_all(parent).map_err(Error::Io)?;
            }
            std::fs::copy(host, &target).map_err(|e| {
                Error::bake_msg(format!(
                    "stage extra-file {} -> {}: {e}",
                    host.display(),
                    target.display()
                ))
            })?;
        }
        crate::bake::write_kvm_rootfs_squashfs(&stage, &rootfs).map_err(Error::bake_msg)?;
        let _ = std::fs::remove_dir_all(&stage);
        let _ = std::fs::remove_dir_all(&pull_work);

        let memory_mib = self.memory_mib.unwrap_or(512);
        let vcpus = effective_vcpus;
        let phys = std::fs::metadata(&rootfs).map(|m| m.len()).unwrap_or(0)
            + std::fs::metadata(&kernel).map(|m| m.len()).unwrap_or(0)
            + std::fs::metadata(&initrd).map(|m| m.len()).unwrap_or(0);
        let mounts = builder_mount_specs(&self.mounts);
        write_kvm_cold_builder_metadata(
            &cold_dir,
            &self.image,
            &kvm_bake_key,
            &kernel,
            &initrd,
            &rootfs,
            memory_mib,
            vcpus,
            phys,
            &env_pairs,
            self.cmd.as_ref(),
            oci_config.as_ref(),
            effective_workdir.as_deref(),
            effective_user.as_deref(),
            self.warm_daemon,
            self.warmup_tag.as_deref(),
            &mounts,
            &self.volumes,
        )?;
        let cold_image = Image::from_snapshot(&cold_dir)?;

        let Some(warmup) = self.warmup else {
            return Ok(cold_image);
        };

        let vm = Vm::start(&cold_image, &VmConfig::new())?;
        let result = warmup(&vm);
        if let Err(e) = result {
            let _ = vm.stop();
            return Err(e);
        }
        let warm_image = vm.snapshot_live(&output_dir);
        let _ = vm.stop();
        let warm_image = warm_image?;
        persist_kvm_builder_run_config(
            &output_dir,
            &self.image,
            &kvm_bake_key,
            &env_pairs,
            self.cmd.as_ref(),
            oci_config.as_ref(),
            effective_workdir.as_deref(),
            effective_user.as_deref(),
            self.warm_daemon,
            self.warmup_tag.as_deref(),
            &mounts,
            &self.volumes,
        )?;
        // Re-load so the returned Image sees the post-snapshot metadata update.
        drop(warm_image);
        Image::from_snapshot(&output_dir)
    }

    /// Native hypervisor bake (macOS/HVF or Linux/KVM worker pipeline).
    fn build_native(self) -> Result<Image, Error> {
        let snapshots_dir = self.snapshots_dir.unwrap_or_else(default_snapshots_dir);
        let derived_name = self
            .name
            .clone()
            .unwrap_or_else(|| crate::bake::snapshot_name_for_image(&self.image));
        let snap_dir = snapshots_dir.join(&derived_name);

        // Cache fast-path: same as Image::from_oci_to_dir, but on
        // the builder we have to assume the cache might be stale
        // for a different config under the same name. We trust the
        // bake pipeline's input-hash check (`native_bake_key`) to
        // re-bake when the inputs changed; on cache hit it's a
        // no-op and we just load the existing snapshot.
        let cache_loadable = Image::from_snapshot(&snap_dir).is_ok();
        // Version-skew check: if the cached snapshot was baked under
        // a different supermachine binary, the init/kernel/agent
        // shipped IN the snapshot are stale and likely missing
        // recent fixes. Treat as cache-miss and silently invalidate
        // — the user sees a fresh re-bake, not a runtime warning
        // they have to act on. (For PullPolicy::Never, we keep the
        // hard error so the operator notices.)
        if cache_loadable {
            if let Some(baked) = snap_dir_baked_under_other_version(&snap_dir) {
                let current = env!("CARGO_PKG_VERSION");
                eprintln!(
                    "supermachine: snapshot at {} was baked under v{baked}; \
                     current binaries are v{current}. Auto-rebaking \
                     (this is a one-time cost on the next build after upgrade).",
                    snap_dir.display()
                );
                invalidate_stale_snapshot_tree(&snap_dir);
            }
        }
        // Re-check after potential invalidation — the dir may have
        // gone away.
        let cache_loadable = cache_loadable && snap_dir.is_dir();
        match self.pull_policy {
            PullPolicy::Never => {
                if cache_loadable {
                    return Image::from_snapshot(&snap_dir);
                }
                let restore_snap = snap_dir.join("restore.snap");
                if restore_snap.is_file() {
                    return Err(Error::cache_invalid(format!(
                        "snapshot present at {} but not loadable on this binary; \
                         rebake required (PullPolicy::Never won't auto-rebake)",
                        snap_dir.display()
                    )));
                }
                return Err(Error::cache_miss(format!(
                    "no cached snapshot for {} at {} (PullPolicy::Never)",
                    self.image,
                    snap_dir.display()
                )));
            }
            // Missing+invalid OR Always: fall through to bake. The
            // bake pipeline will short-circuit on input-hash match
            // even on Always policy.
            _ => {}
        }

        // Encode env / cmd into the form `bake::run_push` accepts.
        let mut extra_args: Vec<String> = Vec::new();
        for (k, v) in &self.envs {
            extra_args.push("--env".to_owned());
            extra_args.push(format!("{k}={v}"));
        }
        for (host, guest) in &self.extra_files {
            extra_args.push("--extra-file".to_owned());
            extra_args.push(format!("{}:{}", host.display(), guest));
        }
        // Effective mounts = user mounts + (Rosetta auto-mount when amd64).
        // For `linux/amd64` we silently add two mounts that wire up
        // Apple's Rosetta translation pipeline end-to-end:
        //
        //   1. Tag `"rosetta"` → the read-only Rosetta runtime share at
        //      `/Library/Apple/usr/libexec/oah/RosettaLinux` on the host
        //      (the `rosetta` interpreter + `rosettad` daemon). init-oci
        //      mounts this at `/run/rosetta` and registers binfmt_misc
        //      for the amd64 ELF magic.
        //
        //   2. Tag `"rosettad-cache"` → a writable host-side cache dir at
        //      `~/.cache/supermachine/rosetta-aot/`. init-oci mounts this
        //      at `/var/cache/rosettad` and starts the rosettad daemon
        //      against it. `rosettad` writes `.aotcache` files there
        //      (content-addressable by the amd64 binary's build-id), so
        //      repeated runs of the same binary skip retranslation —
        //      across VM restarts, across snapshot bakes, across
        //      separate images that happen to share binaries (the
        //      build-id keying makes cross-image sharing safe).
        //
        // If the host doesn't have Rosetta installed, error out *here*
        // with an actionable hint rather than letting the bake fail
        // downstream with a confusing "mount: no such directory".
        use crate::vmm::resources::SymlinkPolicy;
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        let effective_mounts: Vec<(PathBuf, String, SymlinkPolicy, String)> = {
            let mut effective_mounts = self.mounts.clone();
            let platform_amd64 = self.platform.as_deref() == Some("linux/amd64");
            if platform_amd64
                && !effective_mounts
                    .iter()
                    .any(|(_, tag, _, _)| tag == "rosetta")
            {
                const ROSETTA_HOST: &str = "/Library/Apple/usr/libexec/oah/RosettaLinux";
                let rosetta_path = PathBuf::from(ROSETTA_HOST);
                if !rosetta_path.join("rosetta").is_file()
                    || !rosetta_path.join("rosettad").is_file()
                {
                    return Err(Error::bake_msg(format!(
                        "platform=linux/amd64 requires Apple Rosetta runtime at \
                         {ROSETTA_HOST}; install with `softwareupdate --install-rosetta`"
                    )));
                }
                effective_mounts.push((
                    rosetta_path,
                    "rosetta".to_owned(),
                    SymlinkPolicy::Opaque,
                    "/run/rosetta".to_owned(),
                ));
            }
            // Auto-mount the persistent AOT cache for amd64. Skipped when the
            // user explicitly provided a `"rosettad-cache"` tag (escape
            // hatch for tests / sandboxed environments) or when HOME isn't
            // resolvable.
            if platform_amd64
                && !effective_mounts
                    .iter()
                    .any(|(_, tag, _, _)| tag == "rosettad-cache")
            {
                if let Some(home) = std::env::var_os("HOME") {
                    let cache_dir = PathBuf::from(home)
                        .join(".cache")
                        .join("supermachine")
                        .join("rosetta-aot");
                    if let Err(e) = std::fs::create_dir_all(&cache_dir) {
                        eprintln!(
                            "supermachine: could not create Rosetta AOT cache dir \
                             {}: {} — amd64 binaries will still run via JIT but \
                             translations won't persist across VM restarts",
                            cache_dir.display(),
                            e
                        );
                    } else {
                        effective_mounts.push((
                            cache_dir,
                            "rosettad-cache".to_owned(),
                            SymlinkPolicy::Opaque,
                            "/var/cache/rosettad".to_owned(),
                        ));
                    }
                }
            }
            effective_mounts
        };
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        let effective_mounts: Vec<(PathBuf, String, SymlinkPolicy, String)> = self.mounts.clone();
        for (host, tag, symlinks, guest_path) in &effective_mounts {
            extra_args.push("--mount".to_owned());
            // Encoding: `HOST:TAG:GUEST_PATH` (Opaque default policy)
            // or `HOST:TAG:GUEST_PATH:POLICY` when the user picked
            // a non-default policy. Parallel to `--volume HOST:GUEST:
            // SIZE_BYTES`. Splits left-to-right on `:`.
            let s = match symlinks {
                SymlinkPolicy::Opaque => {
                    format!("{}:{}:{}", host.display(), tag, guest_path)
                }
                SymlinkPolicy::Deny => {
                    format!("{}:{}:{}:deny", host.display(), tag, guest_path)
                }
                SymlinkPolicy::Follow => {
                    format!("{}:{}:{}:follow", host.display(), tag, guest_path)
                }
            };
            extra_args.push(s);
        }
        for (host, guest, size_bytes) in &self.volumes {
            extra_args.push("--volume".to_owned());
            // Encoding: HOST:GUEST:SIZE_BYTES. The bake-time worker
            // parses this and creates the sparse backing file +
            // attaches it as a virtio-blk to the guest.
            extra_args.push(format!("{}:{}:{}", host.display(), guest, size_bytes));
        }
        for token in &self.extra_kernel_args {
            extra_args.push("--cmdline-extra".to_owned());
            extra_args.push(token.clone());
        }
        // Signal to the bake pipeline whether the caller asked for
        // listener-required semantics. When set, the bake's
        // `--snapshot-after-ms` fallback stays at the conservative
        // 7s (room for postgres/JVM-class slow binds). When unset,
        // it drops to 200 ms — there's no listener to wait for in
        // the pre-exec / cmd-is-`sleep` / warmup-no-listener cases,
        // and the 7s wait was wasted on every bake of those shapes.
        if self.require_listener.unwrap_or(false) {
            extra_args.push("--supermachine-listener-required".to_owned());
        }
        let cmd_override = match &self.cmd {
            Some(argv) => Some(
                serde_json::to_string(argv)
                    .map_err(|e| Error::bake_msg(format!("encode cmd: {e}")))?,
            ),
            None => None,
        };

        let root = repo_root_for_bake()?;
        let request = crate::bake::BakeRequest {
            image: self.image.clone(),
            name: self.name.clone(),
            runtime: "supermachine".to_owned(),
            guest_port: self.guest_port.unwrap_or(80),
            memory_mib: self.memory_mib.unwrap_or(256),
            vcpus: self.vcpus.unwrap_or(1),
            pull_policy: self.pull_policy.as_bake_str().to_owned(),
            snapshots_dir: snapshots_dir.clone(),
            cmd_override,
            extra_args,
            platform: self.platform.clone().unwrap_or_else(default_guest_platform),
        };
        // No warmup → ALWAYS-PIPELINED-SKIP-WARM path.
        //
        // We route plain `.build()` through the pipelined-bake
        // driver with `skip_warm_snapshot=true` AND
        // `keep_alive=true`. The driver:
        //   1. Boots the worker, signals BAKE_READY.
        //   2. Issues SNAPSHOT_ASYNC for the user's snapshot —
        //      capture is fast (~5 ms), the disk write runs in a
        //      background thread on the worker.
        //   3. Skips the warm SNAPSHOT entirely (no second capture).
        //   4. Returns the live worker (BakedWorker) to us before
        //      the bg save necessarily completes. The first
        //      `Pool::acquire()` claims this worker as a pre-warm
        //      idle entry — saves ~50 ms spawn + ~5 ms restore
        //      versus a cold-from-disk worker.
        //
        // Synchronization: `save_compact_to_file` writes to
        // `<path>.partial` and atomic-renames to `<path>`, so file
        // existence ↔ save complete. `Pool::spawn_one` polls for
        // `snapshot_path.is_file()` before invoking the worker
        // (which would otherwise fail-fast on `--restore-from`
        // pointing at a missing file). The first acquire doesn't
        // need the file at all — it uses the warm worker's
        // in-memory state.
        //
        // Returned `Image` uses `from_snapshot_pending` because
        // metadata.json IS on disk by the time we reach here, but
        // restore.snap may still be in flight. The non-pending
        // `Image::from_snapshot` would reject that; the pending
        // variant is identical except for the file-existence check.
        if self.warmup.is_none() {
            let trace = crate::trace::enabled("bake");
            let bake_t0 = std::time::Instant::now();
            // Empty warm_dir path: skip_warm_snapshot=true
            // suppresses both the warm SNAPSHOT round-trip AND
            // the warm metadata write, so warm_dir is unused.
            // Keep a sibling sentinel for diagnostic clarity in
            // case bake-trace logs reference it.
            // Default trigger: pre-exec (fast, ~150 ms bake on
            // slow-listener images, ~17× speedup on workloads that
            // would otherwise hit the 7-second wall-clock fallback).
            // Caller can opt out via `.with_listener_required()` to
            // get the v0.4.22 listener-ready capture instead — slower
            // bake, but guaranteed listener-up at restore time.
            #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
            let use_pre_exec = false;
            #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
            let use_pre_exec = !self.require_listener.unwrap_or(false);
            let pipelined = crate::bake::PipelinedWarmup {
                warm_dir: snapshots_dir.join(format!("{}__warm__unused", derived_name)),
                warm_tag: "unused".to_owned(),
                keep_alive: cfg!(all(target_os = "macos", target_arch = "aarch64")),
                skip_warm_snapshot: true,
                use_pre_exec_trigger: use_pre_exec,
                callback: Box::new(|_ctx| Ok(())),
            };
            match crate::bake::run_push_pipelined(&request, bake_t0, &root, pipelined) {
                Ok(warm_handoff) => {
                    if trace {
                        eprintln!(
                            "[bake-trace] always-pipelined (skip-warm) total: {:?} (bg save \
                             may still be in flight)",
                            bake_t0.elapsed()
                        );
                    }
                    let img = Image::from_snapshot_pending(&snap_dir)?;
                    if let Some(bw) = warm_handoff {
                        *img.warm_baked_worker.inner.lock().unwrap() = Some(bw);
                    }
                    return Ok(img);
                }
                Err(msg) => {
                    return Err(map_bake_error(&request.image, msg));
                }
            }
        }
        let warmup = self.warmup.unwrap();
        // Warmup path: derive a sibling directory keyed by the
        // warmup tag. Same name → cache hit (no warmup re-run);
        // different name → fresh warm bake.
        let tag = self.warmup_tag.as_deref().unwrap_or("default");
        let warm_dir = snapshots_dir.join(format!("{}__warm__{}", derived_name, tag));
        if let Ok(image) = Image::from_snapshot(&warm_dir) {
            // The warm cache hit is keyed only by name + warmup tag —
            // unlike the base path it never compared bake inputs. If
            // THIS request's mount config differs from what the cached
            // warm snapshot recorded, reusing it would restore a VM
            // wired to the OLD host dirs (stale FDT device set + stale
            // paths; the missing-dir case is already a from_snapshot
            // error above). Treat as a cache miss: invalidate and fall
            // through to a fresh warm bake against the current mounts.
            let requested_mounts = crate::bake::mounts_meta_from_extra_args(&request.extra_args);
            let recorded_mounts = std::fs::read_to_string(warm_dir.join("metadata.json"))
                .ok()
                .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
                .and_then(|m| m.get("mounts").cloned())
                .and_then(|v| v.as_array().cloned())
                .unwrap_or_default();
            if recorded_mounts != requested_mounts {
                eprintln!(
                    "supermachine: warm snapshot at {} was baked with mounts {} but \
                     this build requests {}. Auto-rebaking with the current mounts.",
                    warm_dir.display(),
                    serde_json::Value::Array(recorded_mounts),
                    serde_json::Value::Array(requested_mounts),
                );
                invalidate_stale_snapshot_tree(&warm_dir);
            } else if let Some(baked) = snap_dir_baked_under_other_version(&warm_dir) {
                let current = env!("CARGO_PKG_VERSION");
                eprintln!(
                    "supermachine: warm snapshot at {} was baked under v{baked}; \
                     current binaries are v{current}. Auto-rebaking.",
                    warm_dir.display()
                );
                invalidate_stale_snapshot_tree(&warm_dir);
                // Also invalidate the base snapshot — re-running the
                // bake pipeline below needs a fresh base it can warm
                // up from. The base may be the same version as warm
                // (paired bake) or different (rare).
                invalidate_stale_snapshot_tree(&snap_dir);
            } else {
                return Ok(image);
            }
        }

        // Pipelined bake. The bake worker boots, signals
        // BAKE_READY, captures the base async (background save
        // overlapping with warmup), runs the warmup closure
        // against the still-live guest, captures warm sync, then
        // QUITs. Cuts ~900 ms vs the sequential path on
        // rust:1-slim because the base save and warmup overlap,
        // and we save one boot+restore round-trip.
        let trace = crate::trace::enabled("bake");
        let bake_t0 = std::time::Instant::now();

        // The user's warmup is `FnOnce(&Vm) -> Result<(), Error>`.
        // Inside the pipelined-bake driver we have only the
        // worker's vsock paths, so we synthesize a minimal `Vm`
        // around them and hand that to the user. The synthetic
        // Vm has `pool: None` and `image_meta: None` — neither
        // matters for warmup workloads (which call `vm.exec`,
        // `vm.write_file`, `vm.read_file`, etc., all of which
        // talk over vsock-exec).
        //
        // We capture any error in a Mutex so the bake driver can
        // surface it. The Box<FnOnce> escape-hatch dodges the
        // type system limitation that we can't move a non-Send
        // FnOnce through a closure without a wrapper.
        let warmup_err: std::sync::Arc<std::sync::Mutex<Option<Error>>> =
            std::sync::Arc::new(std::sync::Mutex::new(None));
        let warmup_err_inner = warmup_err.clone();
        let warmup_t0_capture: std::sync::Arc<std::sync::Mutex<Option<std::time::Instant>>> =
            std::sync::Arc::new(std::sync::Mutex::new(None));
        let warmup_t0_inner = warmup_t0_capture.clone();
        let pipelined = crate::bake::PipelinedWarmup {
            warm_dir: warm_dir.clone(),
            warm_tag: tag.to_owned(),
            // Opt in to warm-handoff: bake driver returns the live
            // worker; first Pool::acquire() claims it. Saves the
            // ~50 ms spawn + ~5 ms restore on the first cycle for
            // every with_warmup user. Falls back transparently if
            // the worker is dropped without anyone claiming it.
            keep_alive: cfg!(all(target_os = "macos", target_arch = "aarch64")),
            // Take the warm SNAPSHOT — this is the with-warmup path,
            // user expects a separate warm artifact at warm_dir.
            skip_warm_snapshot: false,
            // Use pre-exec as the BASE trigger for warmup bakes too
            // (0.7.0): init-oci's "workload-pre-exec" marker fires
            // BAKE_READY at the exact moment the guest is ready to
            // be probed by the warmup callback — no timer, no
            // listener-wait, no 7s/200ms fallback. The previous
            // contract said "warmup needs the workload running" but
            // the vsock_exec channel is live from boot independent
            // of the workload's state, so user-supplied vm.exec
            // calls inside the warmup work the same against an
            // init-oci-in-nanosleep guest as against a
            // post-workload-fork one. Caller can opt out via
            // `.with_listener_required()` if they really do depend
            // on the workload binding a port before warmup runs.
            use_pre_exec_trigger: {
                #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
                {
                    false
                }
                #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
                {
                    !self.require_listener.unwrap_or(false)
                }
            },
            callback: Box::new(move |ctx| {
                if let Ok(mut g) = warmup_t0_inner.lock() {
                    *g = Some(std::time::Instant::now());
                }
                #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
                {
                    let synth_vm = Vm {
                        pool: None,
                        vsock_mux_path: ctx.vsock_mux_path.clone(),
                        vsock_exec_path: ctx.vsock_exec_path.clone(),
                        own_vsock_mux_dir: None,
                        skip_cleanup: true,
                        image_meta: None,
                    };
                    let result = warmup(&synth_vm);
                    // Drop the synth Vm without running cleanup
                    // (skip_cleanup=true already; explicit drop for
                    // clarity).
                    drop(synth_vm);
                    match result {
                        Ok(()) => Ok(()),
                        Err(e) => {
                            let msg = e.to_string();
                            if let Ok(mut g) = warmup_err_inner.lock() {
                                *g = Some(e);
                            }
                            Err(msg)
                        }
                    }
                }
                #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
                {
                    let synth_vm = Vm {
                        running: None,
                        sentry_exec: None,
                        sentry_src_rootfs: None,
                        vsock_mux_path: ctx.vsock_mux_path.clone(),
                        vsock_exec_path: ctx.vsock_exec_path.clone(),
                        own_vsock_mux_dir: None,
                        skip_cleanup: true,
                        time_sync_stop: Arc::new(AtomicBool::new(false)),
                        _sentry_mem_admission: None,
                        sentry_warm_pool: None,
                        sentry_unified_pool: None,
                        runsc: None,
                        kboxlike: None,
                    };
                    let result = warmup(&synth_vm);
                    drop(synth_vm);
                    match result {
                        Ok(()) => Ok(()),
                        Err(e) => {
                            let msg = e.to_string();
                            if let Ok(mut g) = warmup_err_inner.lock() {
                                *g = Some(e);
                            }
                            Err(msg)
                        }
                    }
                }
                #[cfg(not(any(
                    all(target_os = "macos", target_arch = "aarch64"),
                    all(target_os = "linux", target_arch = "x86_64")
                )))]
                {
                    let _ = (&ctx, &warmup, &warmup_err_inner);
                    Ok(())
                }
            }),
        };

        match crate::bake::run_push_pipelined(&request, bake_t0, &root, pipelined) {
            Ok(warm_handoff) => {
                if trace {
                    eprintln!("[bake-trace] pipelined bake total: {:?}", bake_t0.elapsed());
                    if let Some(t0) = warmup_t0_capture.lock().ok().and_then(|g| *g) {
                        eprintln!("[bake-trace] (warmup ran at +{:?})", t0 - bake_t0);
                    }
                }
                let img = Image::from_snapshot(&warm_dir)?;
                // Stash the bake-time warm worker so the first
                // Pool::acquire() can claim it instead of spawning
                // fresh + restoring from disk. See
                // `Image::warm_baked_worker` for the full lifecycle
                // contract (claim-or-drop, race semantics, fall-
                // through behavior on worker death).
                if let Some(bw) = warm_handoff {
                    *img.warm_baked_worker.inner.lock().unwrap() = Some(bw);
                }
                Ok(img)
            }
            Err(msg) => {
                // If the warmup callback was the failure source,
                // bubble the typed Error back instead of the
                // stringified bake message.
                if let Some(e) = warmup_err.lock().ok().and_then(|mut g| g.take()) {
                    return Err(e);
                }
                Err(map_bake_error(&request.image, msg))
            }
        }
    }
}

fn default_guest_platform() -> String {
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    {
        "linux/amd64".to_owned()
    }
    #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
    {
        "linux/arm64".to_owned()
    }
}

/// Returns `Some(baked_version)` if the snapshot was baked under a
/// version different from `CARGO_PKG_VERSION`, or `None` if it's
/// current (or version can't be determined).
///
/// Used by:
///  - [`Image::from_snapshot`] (HARD error on load — a version-skewed
///    restore can yield a silently broken VM, e.g. no egress).
///  - [`OciImageBuilder::build`] (treats version-skewed snapshots
///    as cache-miss → silently re-bakes).
fn snapshot_baked_under_other_version(meta: &serde_json::Value) -> Option<String> {
    let current = env!("CARGO_PKG_VERSION");
    let baked = meta
        .get("baked_by_version")
        .and_then(|v| v.as_str())
        .map(|s| s.to_owned())
        .or_else(|| {
            meta.get("kernel")
                .and_then(|v| v.as_str())
                .and_then(parse_version_segment)
        })?;
    if baked == current {
        None
    } else {
        Some(baked)
    }
}

/// Read `<snap_dir>/metadata.json` and return `Some(baked_version)`
/// if the snapshot was baked under a non-current version. Returns
/// `None` on parse errors / missing fields / version match — every
/// "can't tell" case is treated as up-to-date (we'd rather miss a
/// re-bake than churn through an unnecessary one).
fn snap_dir_baked_under_other_version(snap_dir: &Path) -> Option<String> {
    let meta_text = std::fs::read_to_string(snap_dir.join("metadata.json")).ok()?;
    let meta: serde_json::Value = serde_json::from_str(&meta_text).ok()?;
    snapshot_baked_under_other_version(&meta)
}

fn snap_dir_backend(snap_dir: &Path) -> Option<String> {
    let meta_text = std::fs::read_to_string(snap_dir.join("metadata.json")).ok()?;
    let meta: serde_json::Value = serde_json::from_str(&meta_text).ok()?;
    meta.get("backend")
        .and_then(|v| v.as_str())
        .map(|s| s.to_owned())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn linux_default_backend() -> &'static str {
    match std::env::var("SUPERMACHINE_BACKEND").as_deref() {
        Ok("kvm") => "kvm",
        Ok("sentry") => "sentry",
        Ok("kboxlike") => "kboxlike",
        Ok("runsc") | Ok("auto") | Err(_) => "runsc",
        Ok(other) => {
            eprintln!(
                "supermachine: warning: unsupported SUPERMACHINE_BACKEND={other:?}; \
                 defaulting to runsc"
            );
            "runsc"
        }
    }
}

/// Delete a snapshot directory + all its `__warm__<tag>` siblings.
/// Used to invalidate version-skewed caches before re-bake, so the
/// next build produces a clean snapshot tree under the same name.
///
/// Best-effort: any path that fails to remove (e.g. user lacks
/// permission, file in use) is logged via stderr and skipped. The
/// caller's re-bake will surface a clearer error if the leftover
/// blocks it.
fn invalidate_stale_snapshot_tree(snap_dir: &Path) {
    // Base dir (`<name>/`).
    if let Err(e) = std::fs::remove_dir_all(snap_dir) {
        if e.kind() != std::io::ErrorKind::NotFound {
            eprintln!(
                "supermachine: warning: failed to remove stale snapshot {}: {e}",
                snap_dir.display()
            );
        }
    }
    // Warm siblings (`<name>__warm__<tag>/`). Read the parent dir
    // and match by prefix so we catch every tag the user has ever
    // used, not just the well-known ones.
    let Some(parent) = snap_dir.parent() else {
        return;
    };
    let Some(base_name) = snap_dir.file_name().and_then(|s| s.to_str()) else {
        return;
    };
    let prefix = format!("{base_name}__warm__");
    let Ok(read) = std::fs::read_dir(parent) else {
        return;
    };
    for entry in read.flatten() {
        let path = entry.path();
        if path
            .file_name()
            .and_then(|s| s.to_str())
            .is_some_and(|n| n.starts_with(&prefix))
        {
            if let Err(e) = std::fs::remove_dir_all(&path) {
                if e.kind() != std::io::ErrorKind::NotFound {
                    eprintln!(
                        "supermachine: warning: failed to remove stale warm snapshot {}: {e}",
                        path.display()
                    );
                }
            }
        }
    }
}

/// Extract the `v0.4.27` slug from a path like
/// `/…/supermachine/v0.4.27/kernel` → `Some("0.4.27")`. Returns `None`
/// for paths that don't follow this layout (custom kernel paths,
/// SUPERMACHINE_KERNEL_PATH overrides, etc.) — in that case we can't
/// reason about version skew so we don't warn.
fn parse_version_segment(kernel_path: &str) -> Option<String> {
    let p = Path::new(kernel_path);
    for comp in p.components() {
        let Some(s) = comp.as_os_str().to_str() else {
            continue;
        };
        let Some(rest) = s.strip_prefix('v') else {
            continue;
        };
        if rest.matches('.').count() < 2 {
            continue;
        }
        if !rest
            .split('.')
            .all(|seg| seg.chars().all(|c| c.is_ascii_digit()))
        {
            continue;
        }
        return Some(rest.to_owned());
    }
    None
}

/// Parse the wire / metadata representation of a [`SymlinkPolicy`]
/// (`"deny" | "opaque" | "follow"`). Returns `None` for unrecognized
/// inputs so callers can fall back to the default.
fn parse_symlink_policy(s: &str) -> Option<crate::vmm::resources::SymlinkPolicy> {
    use crate::vmm::resources::SymlinkPolicy;
    match s {
        "deny" => Some(SymlinkPolicy::Deny),
        "opaque" => Some(SymlinkPolicy::Opaque),
        "follow" => Some(SymlinkPolicy::Follow),
        _ => None,
    }
}

/// Sweep `cache_dir` (typically `~/.cache/supermachine/rosetta-aot`)
/// for AOT cache orphans before worker spawn. See the call site in
/// `build_pool_arc` for the rationale.
///
/// Evicts two classes of file:
///   - `<x>.aotcache` with `st_size == 0`: migration cleanup for
///     caches built before the FUSE-layer atomic-publish protocol
///     existed. These would trigger rosetta's segment_count
///     assertion or SIGBUS-on-mmap-past-EOF on the next load.
///   - `.<x>.aotcache.partial`: crash-recovery cleanup for the new
///     publish protocol. A `.partial` exists on disk iff a prior
///     VM was SIGKILLed mid-write; it's safe to unlink because by
///     construction the partial belongs to no currently-running
///     writer (the live writer holds an O_CREAT|O_EXCL fd and
///     would lose it on VM teardown).
///
/// Best-effort: silently no-op if the dir doesn't exist or any
/// individual stat / unlink fails (e.g. a file vanishes between
/// stat and unlink — fine, it's gone). Returns the count of
/// evicted entries for tests / observability.
fn scrub_aotcache_orphans(cache_dir: &Path) -> usize {
    use std::os::unix::ffi::OsStrExt;
    let entries = match std::fs::read_dir(cache_dir) {
        Ok(it) => it,
        Err(_) => return 0,
    };
    let mut evicted_zero = 0usize;
    let mut evicted_partial = 0usize;
    for ent in entries.flatten() {
        let name = ent.file_name();
        let bytes = name.as_bytes();
        // Class 1: `<x>.aotcache` of size 0 (pre-fix orphan)
        let is_aotcache_final = bytes.ends_with(b".aotcache") && !bytes.starts_with(b".");
        // Class 2: `.<x>.aotcache.partial` (post-fix crash recovery)
        let is_aotcache_partial = bytes.starts_with(b".") && bytes.ends_with(b".aotcache.partial");
        if !is_aotcache_final && !is_aotcache_partial {
            continue;
        }
        let path = ent.path();
        let Ok(md) = std::fs::metadata(&path) else {
            continue;
        };
        if !md.is_file() {
            continue;
        }
        if is_aotcache_partial {
            // Unconditionally unlink partials — by construction they
            // belong to no currently-running writer.
            if std::fs::remove_file(&path).is_ok() {
                evicted_partial += 1;
            }
        } else if md.len() == 0 {
            // Final-name aotcache with zero size — migration cleanup.
            if std::fs::remove_file(&path).is_ok() {
                evicted_zero += 1;
            }
        }
    }
    let evicted = evicted_zero + evicted_partial;
    if evicted > 0 {
        eprintln!(
            "supermachine: scrubbed {} AOT cache orphan(s) from {} \
             ({} zero-byte aotcache, {} mid-flight partial) \u{2014} \
             would have trapped rosetta with the segment_count \
             assertion or SIGBUS on mmap past EOF",
            evicted,
            cache_dir.display(),
            evicted_zero,
            evicted_partial,
        );
    }
    evicted
}

/// Default snapshots directory: `~/.local/supermachine-snapshots`,
/// matching the CLI's default. Customizable via
/// [`Image::from_oci_to_dir`] or `$SUPERMACHINE_SNAPSHOTS`.
fn default_snapshots_dir() -> PathBuf {
    if let Some(d) = std::env::var_os("SUPERMACHINE_SNAPSHOTS") {
        return PathBuf::from(d);
    }
    let home = std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    home.join(".local/supermachine-snapshots")
}

/// `bake::run_push` wants a "repo root" so it can locate the
/// supermachine-worker binary, the kernel image, the entitlements
/// plist, etc. The CLI walks up from its own exe to find it. From
/// a library context the same auto-discovery applies (an embedder
/// running their app from the dev tree finds the workspace; a
/// release-tarball install finds `<prefix>/share/supermachine`).
fn repo_root_for_bake() -> Result<PathBuf, Error> {
    if let Some(root) = std::env::var_os("SUPERMACHINE_ROOT") {
        return Ok(PathBuf::from(root));
    }
    let exe = std::env::current_exe().map_err(|e| Error::bake_msg(format!("current_exe: {e}")))?;
    for ancestor in exe.ancestors() {
        if ancestor.join("tools/supermachine-push").is_file() {
            return Ok(ancestor.to_path_buf());
        }
        if ancestor.join("share/supermachine/kernel").is_file() {
            return Ok(ancestor.to_path_buf());
        }
    }
    std::env::current_dir().map_err(|e| Error::bake_msg(format!("current_dir: {e}")))
}

/// Map a `bake::run_push` error string into the right
/// [`Error`] variant. The bake pipeline returns flat strings, so
/// we pattern-match keywords.
fn map_bake_error(image: &str, msg: String) -> Error {
    // Kernel-panic sentinel emitted by bake.rs when its serial-log
    // watcher detects a panic banner. Format:
    //   `KERNEL_PANIC|<first_line>|<stack_line_1>\x1F<stack_line_2>...`
    // We turn that into a typed `Error::KernelPanic` so callers can
    // pattern-match (vs. groveling through the bake message string).
    if let Some(rest) = msg.strip_prefix("KERNEL_PANIC|") {
        let mut parts = rest.splitn(2, '|');
        let first_line = parts.next().unwrap_or("").to_owned();
        let stack: Vec<String> = parts
            .next()
            .map(|s| s.split('\x1F').map(ToOwned::to_owned).collect())
            .unwrap_or_default();
        return Error::kernel_panic(first_line, stack);
    }
    let lc = msg.to_ascii_lowercase();

    // Registry HTTP-status-based classification. The bake produces
    // strings like "registry manifest request failed for X with HTTP 404"
    // or "registry token request failed with HTTP 401" — match those
    // shapes.
    let has_status = |code: u16| -> bool {
        let needle = format!("http {code}");
        lc.contains(&needle)
    };
    if has_status(404)
        || lc.contains("manifest unknown")
        || lc.contains("name unknown")
        || lc.contains("not found")
            && (lc.contains("registry") || lc.contains("manifest") || lc.contains("image"))
    {
        return Error::image_not_found(image, msg);
    }
    if has_status(401)
        || has_status(403)
        || lc.contains("unauthorized")
        || lc.contains("forbidden")
        || lc.contains("auth challenge")
    {
        return Error::registry_auth(image, msg);
    }
    if lc.contains("could not resolve")
        || lc.contains("dns")
        || lc.contains("connection refused")
        || lc.contains("connection reset")
        || lc.contains("network is unreachable")
        || lc.contains("ssl_connect")
        || lc.contains("tls handshake")
        || lc.contains("curl: (6)")  // Couldn't resolve host
        || lc.contains("curl: (7)")  // Failed to connect
        || lc.contains("curl: (28)") // Operation timeout
        || lc.contains("curl: (35)") // SSL connect error
        || lc.contains("curl: (56)")
    // Recv failure
    {
        return Error::registry_unreachable(msg);
    }

    // Generic registry/manifest/auth strings that didn't match a
    // specific HTTP status fall through to the catch-all Network
    // variant — same as before.
    if lc.contains("registry") || lc.contains("manifest") || lc.contains("docker pull") {
        Error::network_msg(msg)
    } else {
        // Snapshot timeouts, listener-readiness failures, and
        // anything else that wasn't a network-layer issue.
        Error::bake_msg(msg)
    }
}

/// Configuration for [`Vm::start`]. Built via the chainable
/// `VmConfig::with_*` methods or constructed directly:
///
/// ```
/// use supermachine::VmConfig;
/// let cfg = VmConfig::new()
///     .with_memory_mib(512)
///     .with_vcpus(2);
/// # let _ = cfg;
/// ```
#[derive(Debug, Clone, Default)]
pub struct VmConfig {
    /// Override the image's baked memory. `None` = use Image's value.
    memory_mib: Option<u32>,
    /// Override the image's baked vCPUs. `None` = use Image's value.
    vcpus: Option<u32>,
    assets: Option<AssetPaths>,
    vsock_mux_dir: Option<PathBuf>,
    restore_timeout: Option<Duration>,
    /// Data volumes to attach + mount in the guest (KVM). Each is a host-backed
    /// virtio-blk (vdb, vdc, …) mounted at its `guest_path`. Honored on the
    /// cold-boot path; data persists in the host backing files.
    volumes: Vec<crate::vmm::resources::VolumeSpec>,
    /// virtio-fs mounts (KVM): each exposes a host directory to the guest over
    /// FUSE-over-virtio, mounted at its `guest_path`. Cold-boot only for now
    /// (no DAX window yet — see docs/design/kvm-virtiofs-dax-2026-06-07.md).
    virtiofs: Vec<crate::vmm::resources::MountSpec>,
    /// Attach a virtio-balloon device (KVM cold boot). When set, the guest's
    /// balloon driver binds and the host can reclaim guest memory via
    /// [`Vm::request_balloon_inflate`]. Cold-boot only ([`Image::start`]); the
    /// warm-pool `acquire` path ignores it (balloon isn't snapshotted).
    enable_balloon: bool,
    /// Sentry-only cap on the guest cell tree's total processes+threads
    /// (cgroup-v2 `pids.max`, fork-bomb protection). `None` = the sentry default
    /// (`SENTRY_DEFAULT_PIDS_MAX`). Has no effect on the KVM/HVF backends.
    sentry_pids_max: Option<u64>,
    /// Sentry-only: drop the guest cell to this `(uid, gid)`, OVERRIDING the image's
    /// baked `User`. Set by the orchestration to a UNIQUE uid per tenant — the
    /// cross-tenant isolation barrier: distinct uids make the kernel deny every
    /// cross-tenant process_vm / ptrace / signal / same-uid file access. `None` =
    /// fall back to the image's baked User (then the sentry's own uid). No effect on
    /// the KVM/HVF backends (hardware-isolated).
    sentry_uid: Option<(u32, u32)>,
    /// Sentry-only opt-out from the default memory + CPU + pids caps. `true` =
    /// the guest cell tree runs UNCAPPED (only the syscall wall + page-table
    /// isolation apply). Off by default — the sentry caps every guest from the
    /// image's `memory_mib`/`vcpus` so a single tenant can't exhaust the host.
    sentry_uncapped: bool,
    /// Sentry-only: this pool backs a Dockerfile BUILD stage (the executor's
    /// build-pool chains set it). `true` makes [`SentryPool::build`] (a) serve the
    /// stage's RUN steps from a PER-BUILD private reflink clone of the warm rootfs
    /// — so each build/stage gets an isolated, throwaway filesystem (per-build
    /// isolation + failed-RUN rollback + no cross-stage collision) discarded on
    /// pool Drop — and (b) NOT auto-launch the base image's baked workload (a build
    /// base must not run its `CMD` while `RUN` steps execute). Default `false`; the
    /// KVM/HVF backends ignore it (they already isolate per-layer via a tmpfs
    /// overlay-upper).
    for_build: bool,
    /// Sentry-only bounded-execution watchdog applied to every `exec` cell tree.
    /// `None` = the generous production default (`SENTRY_DEFAULT_EXEC_TIMEOUT`,
    /// 10 min) is applied in `Image::sentry_sandbox_with`, so a wedged or
    /// fork-and-signal-trapping `RUN` can never hang the production caller forever
    /// while a legitimate long install/build still completes. `Some(d)` (non-zero)
    /// sets the ceiling to `d`; `Some(Duration::ZERO)` opts OUT (unlimited —
    /// trusted tooling only). No effect on the KVM/HVF backends.
    sentry_exec_timeout: Option<Duration>,
}

/// Default sentry `pids.max` when neither [`VmConfig::with_sentry_pids_max`] nor
/// an opt-out is set — a generous ceiling that still stops a runaway fork bomb.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const SENTRY_DEFAULT_PIDS_MAX: u64 = 4096;
/// CPU-quota accounting period for the sentry's derived `cpu.max` (microseconds).
/// The quota is `vcpus * SENTRY_CPU_PERIOD_US`, i.e. `vcpus` cores' worth of CPU.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const SENTRY_CPU_PERIOD_US: u64 = 100_000;
/// Default sentry per-`exec` watchdog when [`VmConfig::with_sentry_exec_timeout`]
/// is unset — a GENEROUS 10-minute ceiling. Production-bounded out of the box: a
/// forked workload that traps signals (or the deferred C1 reentrancy hang) becomes
/// a bounded, reported [`crate::sentry::SentryError::Timeout`] (exit 137) instead
/// of hanging `Vm::start` / the `SentryPool` forever, while a long but legitimate
/// install/build `RUN` still finishes. Opt out (unlimited) with
/// `VmConfig::with_sentry_exec_timeout(Duration::ZERO)`.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const SENTRY_DEFAULT_EXEC_TIMEOUT: Duration = Duration::from_secs(600);

impl VmConfig {
    /// Use the image's baked defaults for memory + vCPUs;
    /// auto-discover assets; vsock-mux socket in `$TMPDIR`;
    /// 10 s restore timeout.
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the image's baked memory.
    pub fn with_memory_mib(mut self, mib: u32) -> Self {
        self.memory_mib = Some(mib);
        self
    }

    /// Override the image's baked vCPU count.
    pub fn with_vcpus(mut self, vcpus: u32) -> Self {
        self.vcpus = Some(vcpus);
        self
    }

    /// Attach a virtio-balloon device so the host can reclaim guest memory via
    /// [`Vm::request_balloon_inflate`] (KVM cold boot — [`Image::start`]). The
    /// guest needs `CONFIG_VIRTIO_BALLOON` (the bundled supermachine kernel has
    /// it). Off by default; the warm-pool `acquire` path ignores it (balloon is
    /// a cold-boot reclaim lever, not snapshotted — matching HVF's restore default).
    pub fn with_balloon(mut self, enable: bool) -> Self {
        self.enable_balloon = enable;
        self
    }

    /// Attach a data volume (KVM): a host-backed virtio-blk mounted in the guest
    /// at `spec.guest_path`. The backing file is created sparse + formatted ext4
    /// on first use and reused (so data persists across runs); pass the same
    /// `host_path` to keep state. Multiple volumes become vdb, vdc, … Honored on
    /// the cold-boot start path (snapshots/pools don't carry volume mounts yet).
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// # use supermachine::vmm::resources::VolumeSpec;
    /// let image = Image::from_oci("postgres:16-alpine")?;
    /// let cfg = VmConfig::new()
    ///     .with_volume(VolumeSpec::new("/srv/pgdata.img", "/var/lib/postgresql/data"));
    /// let vm = image.start(&cfg)?;
    /// # let _ = vm; Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_volume(mut self, spec: crate::vmm::resources::VolumeSpec) -> Self {
        self.volumes.push(spec);
        self
    }

    /// Expose a host directory to the guest over virtio-fs (KVM), mounted at
    /// `spec.guest_path`. Served by an in-process FUSE backend with a DAX window
    /// (the guest init mounts `-o dax` for zero-copy reads). Mounts survive a
    /// snapshot: the device + FUSE backend tables + DAX slot table are captured
    /// (SMSNAP05) and re-attached on restore (lazy fd reopen + eager DAX rebind).
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// # use supermachine::vmm::resources::MountSpec;
    /// let image = Image::from_oci("alpine")?;
    /// let cfg = VmConfig::new()
    ///     .with_virtiofs(MountSpec::new("/srv/assets", "assets", "/mnt/assets"));
    /// let vm = image.start(&cfg)?;
    /// # let _ = vm; Ok::<(), supermachine::Error>(())
    /// ```
    pub fn with_virtiofs(mut self, spec: crate::vmm::resources::MountSpec) -> Self {
        self.virtiofs.push(spec);
        self
    }

    /// Cap the sentry guest cell tree's total processes+threads (cgroup-v2
    /// `pids.max`) — fork-bomb protection. Sentry backend only. Default is
    /// `SENTRY_DEFAULT_PIDS_MAX`; the KVM/HVF backends ignore this.
    pub fn with_sentry_pids_max(mut self, n: u64) -> Self {
        self.sentry_pids_max = Some(n);
        self
    }

    /// Drop the sentry guest cell to `(uid, gid)`, overriding the image's baked
    /// `User`. The MULTI-TENANT isolation knob: assign a UNIQUE uid per tenant and
    /// the kernel denies every cross-tenant process_vm / ptrace / signal / same-uid
    /// file access — one tenant's cell cannot reach another's. Sentry backend only
    /// (KVM/HVF are hardware-isolated and ignore this). Requires the sentry to run
    /// privileged enough to drop to the uid (it does the confined fs as its own uid;
    /// the guest loses no capability).
    pub fn with_sentry_uid(mut self, uid: u32, gid: u32) -> Self {
        self.sentry_uid = Some((uid, gid));
        self
    }

    /// Run the sentry guest cell tree UNCAPPED (no cgroup-v2 memory/CPU/pids
    /// caps). Sentry backend only; the syscall wall + page-table isolation still
    /// apply. Off by default — leave it off in production so a single tenant
    /// can't exhaust the host. Use it only for trusted single-tenant tooling that
    /// legitimately needs the whole box.
    pub fn with_sentry_uncapped(mut self, uncapped: bool) -> Self {
        self.sentry_uncapped = uncapped;
        self
    }

    /// Bound how long any single sentry `exec` cell tree may run before the
    /// supervisor SIGKILLs it and reports `SentryError::Timeout` (exit `137`).
    /// Sentry backend only; the KVM/HVF backends ignore it.
    ///
    /// The production release-gate knob: left UNSET, the sentry path applies a
    /// generous default ceiling (`SENTRY_DEFAULT_EXEC_TIMEOUT`, 10 min) in
    /// `Image::sentry_sandbox_with`, so `Vm::start` (sentry path) and a
    /// `SentryPool` are bounded out of the box — a wedged or fork-and-signal-
    /// trapping `RUN` can't hang the caller forever — while a long but legitimate
    /// install/build still completes. Pass a tighter `dur` for snappier SLAs, or
    /// `Duration::ZERO` to run UNLIMITED (trusted single-tenant tooling).
    pub fn with_sentry_exec_timeout(mut self, dur: Duration) -> Self {
        self.sentry_exec_timeout = Some(dur);
        self
    }

    /// Mark this config as backing a Dockerfile BUILD stage. No-KVM rootfs
    /// backends serve the stage from a per-build private clone of the warm rootfs
    /// (per-build/per-stage filesystem isolation + failed-RUN rollback) and
    /// suppress the base image's baked-workload auto-start. Set by the builder's
    /// build-pool chains via [`PoolBuilder::for_build`]; KVM/HVF ignore it. Off
    /// by default.
    pub fn with_for_build(mut self, on: bool) -> Self {
        self.for_build = on;
        self
    }

    /// Override asset auto-discovery. Useful for `.app` bundles
    /// that ship the kernel + init shim under
    /// `Contents/Resources/`.
    pub fn with_assets(mut self, assets: AssetPaths) -> Self {
        self.assets = Some(assets);
        self
    }

    /// Where to put the host-side vsock-mux unix socket. Default
    /// is `$TMPDIR`. Use this if you need the socket inside an
    /// app-private dir for sandboxing reasons.
    pub fn with_vsock_mux_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.vsock_mux_dir = Some(dir.into());
        self
    }

    /// How long to wait for the snapshot to restore. Default 10 s.
    pub fn with_restore_timeout(mut self, timeout: Duration) -> Self {
        self.restore_timeout = Some(timeout);
        self
    }
}

/// A running microVM. Holds an internal worker process and the
/// host-side vsock-mux unix socket through which you talk to the
/// guest.
///
/// Drop the value to stop the VM, or call [`Vm::stop`] for an
/// explicit shutdown report.
///
/// The in-process `Vm` runtime needs a hypervisor backend; gated to
/// macOS/HVF until the KVM backend lands (broaden the gate then).
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
pub struct Vm {
    pool: Option<WarmPool>,
    vsock_mux_path: PathBuf,
    /// `<vsock_mux>-exec.sock` for the in-guest exec agent. Only
    /// useful once the agent crate ships in the initramfs (see
    /// `docs/design/exec-2026-05-03.md`); until then dialing this
    /// path will fail with "no listener" because the agent isn't
    /// running guest-side. The unix socket itself is created
    /// unconditionally so `Vm::exec` can wire to it once the agent
    /// lands.
    vsock_exec_path: PathBuf,
    /// Best-effort cleanup of the temp socket dir we created.
    own_vsock_mux_dir: Option<PathBuf>,
    /// `true` for [`PooledVm`]'s wrapped Vm — Drop must NOT
    /// shut down the pool or unlink sockets, since those are
    /// owned by [`Image`]'s [`HiddenPool`] and reused across
    /// [`Image::acquire`] calls.
    skip_cleanup: bool,
    /// Source image metadata for [`Vm::snapshot`] — needed to
    /// emit a `metadata.json` describing the new snapshot's
    /// layers / memory / vCPUs (the snapshot file alone isn't
    /// loadable as an Image without these).  `None` for VMs
    /// that didn't come from an Image (currently impossible via
    /// the public API; reserved for future use cases).
    image_meta: Option<Arc<ImageMeta>>,
}

/// Linux/KVM backend `Vm`: holds the [`RunningVm`](crate::kvm::run::RunningVm)
/// control handle (vCPU threads + on-demand snapshot/stop) plus the shared
/// vsock socket paths. The agnostic exec/file/forward methods operate against
/// the same fields as the macOS `Vm`.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub struct Vm {
    running: Option<crate::kvm::run::RunningVm>,
    /// No-virt sentry backend: when the image was baked for the sentry (no KVM),
    /// `running` is `None` and this holds the exec server that speaks the agent
    /// wire protocol on `vsock_exec_path`. Dropped on stop/Drop (unlinks + kills
    /// the workload). See [`crate::sentry::ExecServer`].
    sentry_exec: Option<crate::sentry::ExecServer>,
    /// Sentry backend: the live rootfs dir this Vm's cells run against (==
    /// `image.sentry.rootfs`). `Some` only for a cold-start sentry `Vm` from
    /// [`Image::start`]; `Vm::snapshot` copies it to capture the warm filesystem.
    /// `None` for KVM and for pooled sentry VMs (which can't snapshot the rootfs).
    sentry_src_rootfs: Option<PathBuf>,
    vsock_mux_path: PathBuf,
    vsock_exec_path: PathBuf,
    own_vsock_mux_dir: Option<PathBuf>,
    skip_cleanup: bool,
    /// Stops the background clock-resync thread (spawned in [`Vm::start`]) when
    /// the VM is dropped. Without it that thread keeps retrying for its full
    /// 30 s deadline against a dead VM — leaking a thread per VM across pool
    /// churn. Drop sets it; the thread checks it each iteration and exits.
    time_sync_stop: Arc<AtomicBool>,
    /// No-virt sentry one-shot: MEMORY admission reservation for this `Vm`'s
    /// single cell's worst-case footprint (cgroup `memory.max` + overhead),
    /// charged in [`Vm::start_sentry`] and freed when the `Vm` drops. `None` for
    /// the KVM backend (the in-process VM thread isn't memory-admitted here) and
    /// for pooled sentry VMs (the [`SentryPool`] holds the pool-wide reservation).
    /// Underscore-prefixed: held purely for its `Drop`.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    _sentry_mem_admission: Option<crate::memory_admission::AdmissionGuard>,
    /// No-virt sentry WARM-DAEMON pool: the shared `Pool` this pooled `Vm`'s `exec`
    /// routes client cells through ([`crate::sentry::Pool::exec_capture`] over the
    /// supervisor-global owned loopback). `Some` only for a warm-daemon pooled `Vm`;
    /// `None` for the ExecServer pooled path, cold sentry `Vm`s, and KVM (they dial
    /// `vsock_exec_path`).
    sentry_warm_pool: Option<Arc<crate::sentry::Pool>>,
    /// No-virt sentry cold unified supervisor: held only to keep the persistent
    /// workload+exec supervisor alive while this cold `Vm` exists. Exec still dials
    /// `vsock_exec_path` for the streaming agent protocol; do not route it through
    /// `sentry_warm_pool`, which is the warm-daemon request/response special case.
    sentry_unified_pool: Option<Arc<crate::sentry::Pool>>,
    /// External no-KVM runsc backend runtime. `running` is `None` for this path
    /// too, so code that wants the sentry supervisor must check this first.
    runsc: Option<RunscRuntime>,
    /// Native kbox-inspired no-KVM backend runtime. This currently owns the
    /// captured/restored host process tree; exec/file/network parity is wired in
    /// later and must fail explicitly until then.
    kboxlike: Option<KboxlikeRuntime>,
}

/// Transient stub for platforms with NO hypervisor backend (neither macOS/HVF
/// nor Linux/KVM): the `Vm` TYPE is still named in portable signatures
/// (`PooledVm::vm`, `OciImageBuilder::warmup: FnOnce(&Vm)`,
/// `Image::start -> Result<Vm>`), so this uninhabitable stub lets them resolve.
#[cfg(not(any(
    all(target_os = "macos", target_arch = "aarch64"),
    all(target_os = "linux", target_arch = "x86_64")
)))]
pub struct Vm {
    _never: std::convert::Infallible,
}

/// Subset of [`Image`] fields snapshotted into [`Vm`] so
/// [`Vm::snapshot`] can write a self-contained `metadata.json`
/// next to the captured snapshot file.
#[derive(Clone, Debug)]
pub(crate) struct ImageMeta {
    pub memory_mib: u32,
    pub vcpus: u32,
    pub layers: Vec<PathBuf>,
    pub delta_squashfs: Option<PathBuf>,
    pub baker_runtime_sha16: Option<String>,
    pub tsi_token: Option<String>,
    pub egress_policy: Option<String>,
    pub pre_exec_sync: bool,
}

#[cfg(any(
    all(target_os = "macos", target_arch = "aarch64"),
    all(target_os = "linux", target_arch = "x86_64")
))]
impl Vm {
    /// Start a microVM from `image` with the supplied configuration.
    ///
    /// What this does, in order:
    ///
    /// 1. Resolves the kernel path. Preferences (first hit wins):
    ///    `image`'s bundled kernel (if the snapshot dir shipped one),
    ///    `config.assets.kernel` (if set explicitly), then
    ///    [`AssetPaths::discover`]. Fails with [`Error::Assets`] if
    ///    none is found.
    /// 2. Creates a unique unix socket path for vsock-mux under
    ///    the configured directory.
    /// 3. Spawns an in-process VM thread that restores from
    ///    `image.snapshot_path()`. (The library runs the VM
    ///    in-process via [`crate::internal::vmm::pool::WarmPool`].
    ///    The standalone `supermachine-worker` binary is only used
    ///    by the router daemon for SCM_RIGHTS process isolation.)
    /// 4. Waits up to [`VmConfig::with_restore_timeout`] for the
    ///    restore to complete.
    /// 5. Returns the [`Vm`] handle. The vsock-mux socket is
    ///    available immediately at [`Vm::vsock_path`].
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn start(image: &Image, config: &VmConfig) -> Result<Vm, Error> {
        // Vm::start runs the VM thread in this process, so this
        // process itself calls hv_vm_create. Without the HVF
        // entitlement that fails with HV_DENIED (Hv(-85377017)),
        // which is cryptic. Surface a clear error up front instead.
        // Image::acquire callers don't pay this cost — the worker
        // subprocess handles HVF for them.
        #[cfg(target_os = "macos")]
        if let Err(msg) = crate::codesign::check_self_has_hvf_entitlement() {
            return Err(Error::vm_msg(msg));
        }
        let assets = match &config.assets {
            Some(a) => a.clone(),
            None => AssetPaths::discover(),
        };
        // Kernel preference: bundled (snapshot dir) > config.assets >
        // AssetPaths::discover. A bundled kernel makes the snapshot
        // self-contained so a `.app` ships everything it needs.
        let kernel: PathBuf = if let Some(k) = image.bundled_kernel.as_ref() {
            k.clone()
        } else if let Some(k) = assets.kernel.as_ref() {
            k.clone()
        } else {
            return Err(Error::assets_msg(
                "no kernel found: snapshot dir has no bundled kernel and AssetPaths::discover() came up empty; set VmConfig::with_assets() or $SUPERMACHINE_ASSETS_DIR".to_owned(),
            ));
        };
        let kernel = kernel.as_path();

        // Per-VM unix socket path under the chosen dir.
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        let mut own_dir = None;
        if !dir.is_dir() {
            std::fs::create_dir_all(&dir).map_err(Error::Io)?;
            own_dir = Some(dir.clone());
        }
        let vsock_mux_path = dir.join(format!(
            "supermachine-vm-{}-{}.sock",
            std::process::id(),
            unique_suffix(),
        ));
        // `<vsock_mux>-exec` is the convention that worker.rs and
        // the design doc agree on. Same parent dir so unlinking the
        // mux on shutdown sweeps it too.
        let vsock_exec_path = {
            let mut p = vsock_mux_path.clone();
            let mut name = p.file_name().unwrap().to_owned();
            name.push("-exec");
            p.set_file_name(name);
            p
        };

        // Build VmResources for snapshot restore. Memory + vCPUs
        // come from the image's bake metadata unless the caller
        // explicitly overrode them.
        let memory_mib = config.memory_mib.unwrap_or(image.memory_mib);
        let vcpus = config.vcpus.unwrap_or(image.vcpus);
        let mut resources = VmResources::new()
            .with_kernel_path(kernel.to_string_lossy().to_string())
            .with_memory_mib(memory_mib as usize)
            .with_vcpus(vcpus)
            .with_cow_restore(true)
            .with_restore(image.snapshot_path.to_string_lossy().to_string())
            .with_vsock_mux(vsock_mux_path.to_string_lossy().to_string())
            .with_vsock_exec(vsock_exec_path.to_string_lossy().to_string());

        // Attach the OCI image's virtio-blk layers in bake order.
        // The guest's overlayfs union is built bottom-up over these.
        for layer in &image.layers {
            resources = resources.with_block_device(layer.to_string_lossy().to_string());
        }
        if let Some(delta) = &image.delta_squashfs {
            resources = resources.with_block_device(delta.to_string_lossy().to_string());
        }

        // Pool of size 1 — single worker, single VM.
        let options = RunOptions::default();
        let pool = WarmPool::start(resources, options).map_err(Error::from)?;

        // Restore from the snapshot. WarmPool's restore_timeout
        // dispatches the RESTORE command to the pre-spawned worker
        // and blocks until the guest is up.
        let timeout = config
            .restore_timeout
            .unwrap_or_else(|| Duration::from_secs(10));
        let _ = pool
            .restore_timeout(image.snapshot_path.to_string_lossy().to_string(), timeout)
            .map_err(Error::from)?;

        Ok(Vm {
            pool: Some(pool),
            vsock_mux_path,
            vsock_exec_path,
            own_vsock_mux_dir: own_dir,
            skip_cleanup: false,
            image_meta: Some(Arc::new(ImageMeta {
                memory_mib,
                vcpus,
                layers: image.layers.clone(),
                delta_squashfs: image.delta_squashfs.clone(),
                baker_runtime_sha16: image.baker_runtime_sha16.clone(),
                tsi_token: image.tsi_token.clone(),
                egress_policy: image.egress_policy.clone(),
                pre_exec_sync: image.pre_exec_sync,
            })),
        })
    }

    /// Linux/KVM `Vm::start` — not yet wired to the bake/Image rootfs pipeline.
    ///
    /// The KVM runtime exists and is validated end-to-end (boot → exec over
    /// vsock → snapshot) via [`crate::kvm::run::LinuxVm`] /
    /// [`RunningVm`](crate::kvm::run::RunningVm) and the `kvm_boot` example. The
    /// remaining work is the Linux bake path that produces a LinuxVm-runnable
    /// rootfs (a single merged squashfs + the agent init cpio) and an `Image`
    /// that carries them — see the KVM product-wiring plan (Step 2/4). Until
    /// then this returns a clear error rather than silently doing nothing.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn start(image: &Image, config: &VmConfig) -> Result<Vm, Error> {
        use crate::kvm::run::{LinuxVm, LinuxVmConfig};
        // No-virt sentry backend: a `"backend":"sentry"` image carries an extracted
        // rootfs (no kernel/disk/snapshot) and runs under process isolation. The
        // bake path selects sentry when KVM is unavailable; dispatch to it here so
        // the exec/file surface is identical to the KVM/HVF backends.
        if image.sentry.is_some() {
            return Vm::start_sentry(image, config);
        }
        if image.runsc.is_some() {
            return Vm::start_runsc(image, config);
        }
        if image.kboxlike.is_some() {
            return Vm::start_kboxlike(image, config);
        }
        let parts = image.kvm.as_ref().ok_or_else(|| {
            Error::vm_msg(
                "Image has no KVM artifacts: metadata.json needs \"backend\":\"kvm\" \
                 with kvm_kernel + kvm_initrd (produced by the KVM bake path)."
                    .to_owned(),
            )
        })?;
        // Restore from a snapshot if the image carries one (CoW mmap, ~ms);
        // otherwise cold-boot from kernel + agent initramfs (+ optional disk).
        let vm = if let Some(snap) = &parts.snapshot {
            if !config.volumes.is_empty() {
                eprintln!(
                    "supermachine(KVM): {} volume(s) requested via VmConfig but this image \
                     restores from a snapshot — the snapshot's OWN recorded volume attachments \
                     are re-attached (SMSNAP04), so the config volumes are ignored. To attach \
                     different volumes, cold-boot the image (e.g. bake_kvm_auto) with them.",
                    config.volumes.len()
                );
            }
            if !config.virtiofs.is_empty() {
                eprintln!(
                    "supermachine(KVM): {} virtio-fs mount(s) requested via VmConfig but this image \
                     restores from a snapshot — the snapshot's OWN recorded virtio-fs mounts are \
                     re-attached (SMSNAP05, DAX slots eagerly re-bound), so the config mounts are \
                     ignored. To attach different mounts, cold-boot the image with them.",
                    config.virtiofs.len()
                );
            }
            LinuxVm::restore_from_file(snap)
                .map_err(|e| Error::vm_msg(format!("restore snapshot {}: {e}", snap.display())))?
        } else {
            let kernel_path = parts
                .kernel
                .as_ref()
                .expect("kvm cold-boot kernel (validated in from_snapshot)");
            let initrd_path = parts
                .initrd
                .as_ref()
                .expect("kvm cold-boot initrd (validated in from_snapshot)");
            let kernel = std::fs::read(kernel_path).map_err(|e| {
                Error::vm_msg(format!("read kernel {}: {e}", kernel_path.display()))
            })?;
            let initrd = std::fs::read(initrd_path).map_err(|e| {
                Error::vm_msg(format!("read initrd {}: {e}", initrd_path.display()))
            })?;
            let disk_str: Option<String> = parts
                .disk
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned());
            let disk_size = parts
                .disk
                .as_ref()
                .and_then(|p| std::fs::metadata(p).ok())
                .map(|m| m.len())
                .unwrap_or(0);
            let mem_mib = config.memory_mib.unwrap_or(image.memory_mib).max(1);
            let num_cpus = kvm_effective_vcpus(config.vcpus.unwrap_or(image.vcpus), "Vm::start")
                .clamp(1, 255) as u8;
            // The agent initramfs is PID 1 (exec over AF_VSOCK 1028); a rootfs
            // disk, if present, is attached at /dev/vda for the guest to mount.
            //
            // `tsi_hijack` turns on transparent egress: the AF_TSI-patched guest
            // kernel routes the workload's AF_INET/AF_INET6 connect()/sendto()
            // over vsock to the host vsock muxer, which opens the real host
            // socket (subject to egress_policy). No virtio-net, no guest NIC —
            // the same transparent-networking model as the HVF backend. Requires
            // the TSI-enabled guest kernel (CONFIG_TSI=y + af-tsi patch series).
            // `supermachine.host_time=<epoch_secs>` lets the generated init set
            // the guest wall clock from the host: a KVM guest has no RTC and
            // boots at ~1999, which makes TLS cert validation fail ("certificate
            // not trusted") and breaks apk/pip/https in workloads + builder RUNs.
            let host_time = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let cmdline = format!(
                "console=ttyS0 panic=-1 reboot=t tsi_hijack supermachine.host_time={host_time}"
            );
            // Mint a per-VM vsock TSI control-channel auth token. `LinuxVm::new`
            // appends `supermachine.tsi_token=<hex>` (the guest's af_tsi driver
            // stamps it on every control DGRAM) and arms the muxer to reject any
            // control packet without it — so an in-guest workload can't forge TSI
            // egress ops to bypass egress policy. Best-effort: if the CSPRNG read
            // fails we boot without enforcement rather than failing the VM.
            let tsi_token = crate::cli::TsiToken::generate()
                .map(|t| t.bytes)
                .map_err(|e| {
                    eprintln!("supermachine(KVM): tsi token generation failed ({e}); booting without vsock control-channel auth");
                })
                .ok();
            // Data volumes: ensure each host backing file exists + is ext4, then
            // attach as vdb/vdc/… mounted at guest_path (the init reads the
            // sm.volume cmdline tokens run.rs appends). Runtime volumes
            // (VmConfig::with_volume) take precedence; baked-in volumes from the
            // image (OciImageBuilder::with_volume, persisted in metadata) are
            // appended for any guest_path the runtime didn't already cover.
            let mut vol_specs: Vec<crate::vmm::resources::VolumeSpec> = config.volumes.clone();
            for (host_file, guest_path, size_bytes, _pristine) in &image.volumes {
                if !vol_specs.iter().any(|v| v.guest_path == *guest_path) {
                    vol_specs.push(
                        crate::vmm::resources::VolumeSpec::new(
                            host_file.to_string_lossy().to_string(),
                            guest_path.clone(),
                        )
                        .with_size_bytes(*size_bytes),
                    );
                }
            }
            let volumes = prepare_kvm_volumes(&vol_specs)?;
            // virtio-fs mounts: expose each host dir to the guest over
            // FUSE-over-virtio (init reads the sm.virtiofs cmdline tokens).
            let mut mount_specs: Vec<crate::vmm::resources::MountSpec> = config.virtiofs.clone();
            for m in &image.mounts {
                if !mount_specs.iter().any(|existing| {
                    existing.guest_tag == m.guest_tag || existing.guest_path == m.guest_path
                }) {
                    mount_specs.push(m.clone());
                }
            }
            let virtiofs: Vec<crate::kvm::run::VirtioFsAttach> = mount_specs
                .iter()
                .map(|m| crate::kvm::run::VirtioFsAttach {
                    host_path: m.host_path.clone(),
                    tag: m.guest_tag.clone(),
                    mount: m.guest_path.clone(),
                })
                .collect();
            let lcfg = LinuxVmConfig {
                mem_size: (mem_mib as usize) * 1024 * 1024,
                num_cpus,
                kernel: &kernel,
                initrd: Some(&initrd),
                disk_path: disk_str.as_deref(),
                disk_size,
                cmdline: &cmdline,
                enable_vsock: true,
                volumes: &volumes,
                virtiofs: &virtiofs,
                tsi_token,
                // Balloon is a cold-boot-only memory-reclaim lever (not
                // snapshotted). Honored here on the cold-boot path; the warm-pool
                // restore path (above) never reaches this branch.
                enable_balloon: config.enable_balloon,
            };
            LinuxVm::new(&lcfg).map_err(|e| Error::vm_msg(format!("LinuxVm::new: {e}")))?
        };
        // Host-side unix socket bridged to the guest exec agent (AF_VSOCK 1028);
        // crate::exec dials this for exec/write_file/read_file/workload_signal.
        let exec_path = vm
            .start_exec_bridge(1028)
            .map_err(|e| Error::vm_msg(format!("start_exec_bridge: {e}")))?;
        // Workload TSI listener frontend (host→guest ingress for `expose_tcp` /
        // `connect`). Egress (guest→host `connect`) needs no frontend — the
        // shared vsock muxer terminates the guest's TSI control packets off the
        // TX queue and opens real host sockets (subject to egress_policy). If
        // binding the mux socket fails, fall back to an unwired path so exec
        // still works and only ingress is unavailable.
        let mux_path = vm
            .start_tsi_mux()
            .unwrap_or_else(|_| exec_path.with_extension("mux-unwired"));
        // Launch the vCPUs on background threads — the guest is now live and the
        // agent comes up to serve exec. The handle is held for stop/Drop.
        let running = vm.start_running();
        // Re-sync the guest clock to host time once the agent is up. The cold-boot
        // init already sets it from the cmdline, but a RESTORE inherits the
        // snapshot's (possibly stale) captured clock — so refresh it in the
        // background (non-blocking) to keep TLS/cert validation correct. Retries
        // until the agent answers or a deadline.
        let sync_path = exec_path.clone();
        let time_sync_stop = Arc::new(AtomicBool::new(false));
        let stop_c = time_sync_stop.clone();
        std::thread::spawn(move || {
            let deadline = std::time::Instant::now() + Duration::from_secs(30);
            loop {
                // Exit promptly once the VM is dropped, instead of retrying
                // against a dead VM for the whole deadline (per-VM thread leak).
                if stop_c.load(Ordering::SeqCst) {
                    break;
                }
                if sync_time_via_agent(&sync_path) {
                    break;
                }
                if std::time::Instant::now() >= deadline {
                    break;
                }
                std::thread::sleep(Duration::from_millis(200));
            }
        });
        Ok(Vm {
            running: Some(running),
            sentry_exec: None,
            sentry_src_rootfs: None,
            vsock_mux_path: mux_path,
            vsock_exec_path: exec_path,
            own_vsock_mux_dir: None,
            skip_cleanup: false,
            time_sync_stop,
            // KVM: the in-process VM thread is not memory-admitted on this path.
            _sentry_mem_admission: None,
            sentry_warm_pool: None,
            sentry_unified_pool: None,
            runsc: None,
            kboxlike: None,
        })
    }

    /// Start the no-virt **sentry** backend for a `"backend":"sentry"` image: run
    /// a process-isolation sandbox over the image's extracted rootfs and expose an
    /// [`ExecServer`](crate::sentry::ExecServer) speaking the SAME framed exec
    /// protocol the in-guest agent speaks. The returned [`Vm`] has no
    /// `RunningVm`; its `exec`/`write_file`/`read_file`/`spawn` go straight to the
    /// server socket, so the product surface is unchanged. The image's baked CMD
    /// (if any) is launched in the background, mirroring a VM booting its CMD.
    ///
    /// Used by [`Vm::start`] when [`kvm_usable`](Image::kvm_usable) is false /
    /// the image was sentry-baked. `expose_tcp` works (host-side proxy to the
    /// guest's host-netns listener) and `Vm::snapshot` captures the warm rootfs.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn start_sentry(image: &Image, config: &VmConfig) -> Result<Vm, Error> {
        let parts = image
            .sentry
            .as_ref()
            .expect("start_sentry called on a non-sentry image");
        // Exec socket under the configured vsock dir (or a temp dir), named like
        // the KVM exec socket so tooling that scans the dir behaves the same.
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        let mut own_dir = None;
        if !dir.is_dir() {
            std::fs::create_dir_all(&dir).map_err(Error::Io)?;
            own_dir = Some(dir.clone());
        }
        let exec_path = dir.join(format!(
            "supermachine-sentry-{}-{}.sock",
            std::process::id(),
            unique_suffix(),
        ));
        // Build the sandbox from the image (egress policy etc. from metadata),
        // then serve the exec protocol; launch the baked workload in the
        // background like a VM boots its CMD.
        //
        // SHARED host netns (`without_netns`): a `Vm`'s workload is meant to be
        // host-reachable — [`expose_tcp`]/[`expose_tls`] host-proxy to the guest's
        // listener on `127.0.0.1:guest_port`, which must be a real host socket.
        // The handle API (`Image::sentry_sandbox`) keeps the isolation-safe netns
        // default; this single-tenant exposed `Vm` is the documented opt-out.
        let sandbox = image
            .sentry_sandbox_with(config)
            .map_err(|e| Error::vm_msg(format!("sentry sandbox: {e}")))?
            .without_netns();
        // MEMORY admission: reserve this one cell's worst-case footprint (its
        // cgroup `memory.max` + overhead) against the process-wide budget before
        // serving — the one-shot analogue of `SentryPool::build`'s pool-wide
        // charge and of the KVM worker's per-VM charge. The guard rides in the
        // returned `Vm` and frees on Drop. Pressure backstop first, like
        // `spawn_one` / the pool path.
        crate::memory_admission::await_pressure_relief();
        let mem_mib = sentry_cell_mem_mib(image, config);
        let mem_admission =
            crate::memory_admission::admit_with(|| sentry_admission_charge_mib(mem_mib, 1));
        let (sentry_exec, sentry_unified_pool) = if !parts.warm_daemon {
            let pool = sandbox
                .pool_with_exec(exec_path.clone())
                .map_err(|e| Error::vm_msg(format!("sentry unified pool: {e}")))?;
            let deadline = std::time::Instant::now() + Duration::from_secs(15);
            while !exec_path.exists() {
                if std::time::Instant::now() >= deadline {
                    return Err(Error::vm_msg(
                        "sentry unified exec socket never appeared (supervisor bind failed)",
                    ));
                }
                std::thread::sleep(Duration::from_millis(5));
            }
            if parts.has_workload && parts.rootfs.join(".supermachine/run-workload").is_file() {
                let wrapped = vec![
                    "/.supermachine/sm-checkpoint".to_string(),
                    "/bin/sh".to_string(),
                    "/.supermachine/run-workload".to_string(),
                ];
                if pool.warm(wrapped.iter().cloned()).is_ok() {
                    if let Ok(wpid) = pool.acquire_running() {
                        let run_dir = parts.rootfs.join("run");
                        let _ = std::fs::create_dir_all(&run_dir);
                        let _ = std::fs::write(
                            run_dir.join("supermachine-workload.pid"),
                            format!("{wpid}\n"),
                        );
                    }
                }
            }
            (None, Some(Arc::new(pool)))
        } else {
            let server = sandbox
                .serve_exec(&exec_path, parts.has_workload)
                .map_err(|e| Error::vm_msg(format!("sentry serve_exec: {e}")))?;
            (Some(server), None)
        };
        Ok(Vm {
            running: None,
            sentry_exec,
            // The cells run against the image's rootfs; `Vm::snapshot` copies it
            // to capture the warm filesystem state.
            sentry_src_rootfs: Some(parts.rootfs.clone()),
            // The sentry has no TSI mux; point the mux path at the exec socket so
            // `vsock_path()` returns something valid and cleanup unlinks one file.
            vsock_mux_path: exec_path.clone(),
            vsock_exec_path: exec_path,
            own_vsock_mux_dir: own_dir,
            skip_cleanup: false,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            _sentry_mem_admission: Some(mem_admission),
            sentry_warm_pool: None,
            sentry_unified_pool,
            runsc: None,
            kboxlike: None,
        })
    }

    /// Start the experimental external no-KVM **runsc** backend. This first
    /// product slice is a cold detached runsc container plus `runsc exec` for
    /// `ExecBuilder::output`; checkpoint/restore-backed pools are layered on top
    /// of this lifecycle.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn start_runsc(image: &Image, config: &VmConfig) -> Result<Vm, Error> {
        let parts = image
            .runsc
            .as_ref()
            .expect("start_runsc called on a non-runsc image");
        let runsc_bin = std::env::var_os("SUPERMACHINE_RUNSC_BIN")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("runsc"));
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        std::fs::create_dir_all(&dir).map_err(Error::Io)?;
        let runtime_dir = dir.join(format!(
            "supermachine-runsc-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        let bundle_dir = runtime_dir.join("bundle");
        let private_rootfs = bundle_dir.join("rootfs");
        let runsc_root = runtime_dir.join("runsc-root");
        std::fs::create_dir_all(&runsc_root).map_err(Error::Io)?;
        let network = runsc_network_for_config(config).to_owned();
        let build_netns = if network == crate::exec::RUNSC_NETWORK_SANDBOX {
            Some(RunscBuildNetwork::create()?)
        } else {
            None
        };
        let netns_path = build_netns.as_ref().map(|net| net.path());
        prepare_runsc_bundle(
            &runsc_bin,
            parts,
            &bundle_dir,
            &private_rootfs,
            &network,
            netns_path.as_deref(),
        )?;
        let container_id = format!("sm-runsc-{}-{}", std::process::id(), unique_suffix());
        let pid_file = runtime_dir.join("container.pid");
        if let Some(checkpoint) = &parts.checkpoint {
            if let Err(e) = runsc_restore_detached(
                &runsc_bin,
                &runsc_root,
                &network,
                &bundle_dir,
                checkpoint,
                &pid_file,
                &container_id,
            ) {
                let _ = std::fs::remove_dir_all(&runtime_dir);
                return Err(e);
            }
        } else {
            let mut run = Command::new(&runsc_bin);
            crate::exec::add_runsc_global_flags_with_network(&mut run, &runsc_root, &network);
            let run_out = run
                .arg("run")
                .arg("-detach")
                .arg("-bundle")
                .arg(&bundle_dir)
                .arg("-pid-file")
                .arg(&pid_file)
                .arg(&container_id)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .map_err(|e| Error::vm_msg(format!("runsc run {container_id}: {e}")))?;
            if !run_out.success() {
                let _ = std::fs::remove_dir_all(&runtime_dir);
                return Err(Error::vm_msg(format!(
                    "runsc run failed with status {:?}",
                    run_out.code()
                )));
            }
        }

        Ok(Vm {
            running: None,
            sentry_exec: None,
            sentry_src_rootfs: None,
            vsock_mux_path: runtime_dir.join("runsc-unwired.sock"),
            vsock_exec_path: runtime_dir.join("runsc-exec-unwired.sock"),
            own_vsock_mux_dir: None,
            skip_cleanup: false,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            _sentry_mem_admission: None,
            sentry_warm_pool: None,
            sentry_unified_pool: None,
            runsc: Some(RunscRuntime {
                runsc_bin,
                runsc_root,
                network,
                build_netns,
                container_id,
                bundle_dir,
                rootfs: private_rootfs,
                parts: parts.clone(),
                file_agent_exec: false,
            }),
            kboxlike: None,
        })
    }

    /// Start the native kbox-inspired no-KVM backend. This first product slice
    /// launches the baked workload under the extracted rootfs, captures the live
    /// tree at a stopped boundary, restores it into replacement host processes,
    /// then owns those restored processes as the VM lifetime.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn start_kboxlike(image: &Image, config: &VmConfig) -> Result<Vm, Error> {
        let parts = image
            .kboxlike
            .as_ref()
            .expect("start_kboxlike called on a non-kboxlike image");
        Self::start_kboxlike_parts(parts, config)
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_mounts_for_start(
        parts: &KboxlikeImageParts,
        config: &VmConfig,
    ) -> Result<Vec<(PathBuf, String)>, Error> {
        let mut mounts = Vec::new();
        let mut covered_guest_paths = std::collections::BTreeSet::new();

        // Runtime config wins, matching the KVM cold-boot path: callers can
        // override a baked mapping by reusing the same guest path.
        for m in &config.virtiofs {
            covered_guest_paths.insert(m.guest_path.clone());
            mounts.push((PathBuf::from(&m.host_path), m.guest_path.clone()));
        }
        for m in &parts.mounts {
            if covered_guest_paths.insert(m.guest_path.clone()) {
                mounts.push((PathBuf::from(&m.host_path), m.guest_path.clone()));
            }
        }

        // No-virt volumes are directory-backed bind mounts. Append them after
        // regular mounts so nested volumes overlay parent workspace mounts.
        for v in &config.volumes {
            let host_dir = PathBuf::from(&v.host_path);
            std::fs::create_dir_all(&host_dir).map_err(Error::Io)?;
            covered_guest_paths.insert(v.guest_path.clone());
            mounts.push((host_dir, v.guest_path.clone()));
        }
        for (host_dir, guest_path, _size, _pristine) in &parts.volumes {
            if !covered_guest_paths.insert(guest_path.clone()) {
                continue;
            }
            std::fs::create_dir_all(host_dir).map_err(Error::Io)?;
            mounts.push((host_dir.clone(), guest_path.clone()));
        }

        Ok(mounts)
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn start_kboxlike_parts(parts: &KboxlikeImageParts, config: &VmConfig) -> Result<Vm, Error> {
        if parts.warm_daemon {
            return Err(Error::vm_msg(
                "kboxlike warm-daemon images are not implemented yet".to_owned(),
            ));
        }

        let workload = parts.rootfs.join(".supermachine/run-workload");
        let argv = if parts.has_workload && workload.is_file() {
            vec![
                "/bin/sh".to_owned(),
                "/.supermachine/run-workload".to_owned(),
            ]
        } else if !parts.cmd.is_empty() {
            parts.cmd.clone()
        } else {
            return Err(Error::vm_msg(
                "kboxlike image has no staged workload or recorded cmd".to_owned(),
            ));
        };
        let model_exe = kboxlike_host_exe_path(parts, argv.first().map(String::as_str));

        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        std::fs::create_dir_all(&dir).map_err(Error::Io)?;
        let runtime_dir = dir.join(format!(
            "supermachine-kboxlike-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        let shadow_root = runtime_dir.join("shadow");
        std::fs::create_dir_all(&shadow_root).map_err(Error::Io)?;

        let settle_ms = std::env::var("SUPERMACHINE_KBOXLIKE_CAPTURE_SETTLE_MS")
            .ok()
            .and_then(|raw| raw.parse::<u64>().ok())
            .unwrap_or(750);
        let min_tracees = std::env::var("SUPERMACHINE_KBOXLIKE_MIN_TRACEES")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(1);
        let max_stops = std::env::var("SUPERMACHINE_KBOXLIKE_MAX_STOPS")
            .ok()
            .and_then(|raw| raw.parse::<usize>().ok())
            .unwrap_or(200000);
        let runtime_mounts = Self::kboxlike_mounts_for_start(parts, config)?;

        let captured =
            crate::kboxlike::capture_live_ptrace_rootfs_exec_snapshot_after_sigstop_request(
                &crate::kboxlike::KboxlikeRootfsExecConfig {
                    rootfs: parts.rootfs.clone(),
                    argv,
                    env: parts.image_env.clone(),
                    cwd: "/".to_owned(),
                    user: parts.user,
                    mounts: runtime_mounts.clone(),
                },
                min_tracees,
                max_stops,
                std::time::Duration::from_millis(settle_ms),
            )
            .map_err(|e| {
                let _ = std::fs::remove_dir_all(&runtime_dir);
                Error::vm_msg(format!("kboxlike capture workload: {e:?}"))
            })?;

        let mut source_root_host_pid = Some(captured.root_host_pid);
        let mut replacement_factory =
            if let Some(path) = std::env::var_os("SUPERMACHINE_KBOXLIKE_REPLACEMENT_PATH") {
                crate::kboxlike::LinuxStoppedTraceeReplacementFactory::with_static_replacement_path(
                    PathBuf::from(path),
                )
            } else if Path::new("/bin/busybox").is_file() {
                crate::kboxlike::LinuxStoppedTraceeReplacementFactory::with_static_replacement_path(
                    "/bin/busybox",
                )
            } else {
                crate::kboxlike::LinuxStoppedTraceeReplacementFactory::default()
            };
        let mut resumer = crate::kboxlike::PtraceDetachRestoredTraceeResumer;
        let trace_label =
            std::env::var_os("SUPERMACHINE_KBOXLIKE_TRACE_VM_START").map(|_| "KBOXLIVE_VM_START");
        let restore = crate::kboxlike::restore_runtime_snapshot_with_replacements(
            &captured.snapshot,
            &model_exe,
            crate::kboxlike::KboxlikeRuntimeRestoreOptions {
                shadow_root: shadow_root.clone(),
                trace_label,
                ..Default::default()
            },
            &mut replacement_factory,
            &mut resumer,
        )
        .map_err(|e| {
            if let Some(pid) = source_root_host_pid.take() {
                crate::kboxlike::kill_and_reap_live_process_group(pid);
            }
            replacement_factory.kill_created_tracees();
            let _ = std::fs::remove_dir_all(&runtime_dir);
            Error::vm_msg(format!("kboxlike restore workload: {e:?}"))
        })?;

        if let Some(pid) = source_root_host_pid.take() {
            crate::kboxlike::kill_and_reap_live_process_group(pid);
        }
        let restored_host_pids = restore
            .restore
            .replacement_host_pids
            .values()
            .copied()
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .collect::<Vec<_>>();

        Ok(Vm {
            running: None,
            sentry_exec: None,
            sentry_src_rootfs: None,
            vsock_mux_path: runtime_dir.join("kboxlike-unwired.sock"),
            vsock_exec_path: runtime_dir.join("kboxlike-exec-unwired.sock"),
            own_vsock_mux_dir: None,
            skip_cleanup: false,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            _sentry_mem_admission: None,
            sentry_warm_pool: None,
            sentry_unified_pool: None,
            runsc: None,
            kboxlike: Some(KboxlikeRuntime {
                runtime_dir,
                source_root_host_pid,
                restored_host_pids,
                rootfs: parts.rootfs.clone(),
                parts: parts.clone(),
                mounts: runtime_mounts,
            }),
        })
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn start_kboxlike_build_root(
        parts: &KboxlikeImageParts,
        config: &VmConfig,
    ) -> Result<Vm, Error> {
        let dir = match &config.vsock_mux_dir {
            Some(d) => d.clone(),
            None => std::env::temp_dir(),
        };
        std::fs::create_dir_all(&dir).map_err(Error::Io)?;
        let runtime_dir = dir.join(format!(
            "supermachine-kboxlike-build-vm-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        std::fs::create_dir_all(&runtime_dir).map_err(Error::Io)?;
        let runtime_mounts = Self::kboxlike_mounts_for_start(parts, config)?;

        Ok(Vm {
            running: None,
            sentry_exec: None,
            sentry_src_rootfs: None,
            vsock_mux_path: runtime_dir.join("kboxlike-build-unwired.sock"),
            vsock_exec_path: runtime_dir.join("kboxlike-build-exec-unwired.sock"),
            own_vsock_mux_dir: None,
            skip_cleanup: false,
            time_sync_stop: Arc::new(AtomicBool::new(false)),
            _sentry_mem_admission: None,
            sentry_warm_pool: None,
            sentry_unified_pool: None,
            runsc: None,
            kboxlike: Some(KboxlikeRuntime {
                runtime_dir,
                source_root_host_pid: None,
                restored_host_pids: Vec::new(),
                rootfs: parts.rootfs.clone(),
                parts: parts.clone(),
                mounts: runtime_mounts,
            }),
        })
    }

    /// Path to the host-side unix socket that proxies bytes to /
    /// from the first TSI listener inside the guest. Connect to it
    /// with [`UnixStream::connect`] (or via [`Vm::connect`]).
    pub fn vsock_path(&self) -> &Path {
        &self.vsock_mux_path
    }

    /// Path to the host-side unix socket that bridges to the
    /// in-guest exec agent (native AF_VSOCK on the guest side).
    /// Reachable once the agent lands in the initramfs and is
    /// running guest-side; until then dialing it returns an
    /// immediate EOF.
    pub fn exec_path(&self) -> &Path {
        &self.vsock_exec_path
    }

    /// Opaque token for language bindings that need to reconstruct an
    /// [`crate::exec::ExecBuilder`] later. For socket-backed backends this is
    /// just the exec socket path. For runsc it encodes the host-control-plane
    /// target needed by `runsc exec`.
    #[doc(hidden)]
    pub fn exec_binding_token(&self) -> String {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            let target = crate::exec::RunscExecTarget {
                runsc_bin: runsc.runsc_bin.clone(),
                runsc_root: runsc.runsc_root.clone(),
                network: Some(runsc.network.clone()),
                container_id: runsc.container_id.clone(),
                image_env: runsc.parts.image_env.clone(),
                agent_path: Some(runsc.parts.agent_path.clone()),
                file_agent_rootfs: runsc.file_agent_exec.then(|| runsc.rootfs.clone()),
            };
            if let Ok(bytes) = serde_json::to_vec(&target) {
                return format!(
                    "{}{}",
                    crate::exec::RUNSC_EXEC_TOKEN_PREFIX,
                    b64_encode(&bytes)
                );
            }
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            let target = crate::exec::KboxlikeExecTarget {
                rootfs: kboxlike.rootfs.clone(),
                image_env: kboxlike.parts.image_env.clone(),
                user: kboxlike.parts.user,
                mounts: kboxlike.mounts.clone(),
            };
            if let Ok(bytes) = serde_json::to_vec(&target) {
                return format!(
                    "{}{}",
                    crate::exec::KBOXLIKE_EXEC_TOKEN_PREFIX,
                    b64_encode(&bytes)
                );
            }
        }
        self.vsock_exec_path.to_string_lossy().to_string()
    }

    /// Spawn a process inside the running guest. Equivalent to
    /// `docker exec`. Returns an [`crate::exec::ExecChild`] handle
    /// you can read stdout/stderr from, write stdin to, and
    /// `wait()` for an exit status.
    ///
    /// ```no_run
    /// # use std::io::Read;
    /// # use supermachine::{Image, Vm, VmConfig};
    /// let image = Image::from_snapshot("path/to/snapshot")?;
    /// let vm = Vm::start(&image, &VmConfig::new())?;
    /// let mut child = vm.exec(["sh", "-c", "echo hi"])?;
    /// let mut buf = String::new();
    /// child.stdout().unwrap().read_to_string(&mut buf)?;
    /// assert_eq!(buf, "hi\n");
    /// child.wait()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn exec<I, S>(&self, argv: I) -> std::io::Result<crate::exec::ExecChild>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let argv: Vec<String> = argv.into_iter().map(|s| s.into()).collect();
        let _span = tracing::info_span!(
            "supermachine.exec",
            argv0 = argv.first().map(|s| s.as_str()).unwrap_or(""),
            argc = argv.len(),
        )
        .entered();
        self.exec_builder().argv(argv).spawn()
    }

    /// Configurable exec — TTY, env vars, cwd, initial winsize,
    /// timeout, and the [`crate::exec::ExecBuilder::output`]
    /// convenience that drains stdio + collects exit status into
    /// one [`crate::exec::ExecOutcome`].
    pub fn exec_builder(&self) -> crate::exec::ExecBuilder {
        let b = crate::exec::ExecBuilder::new(self.vsock_exec_path.clone());
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return b.with_runsc_exec(crate::exec::RunscExecTarget {
                runsc_bin: runsc.runsc_bin.clone(),
                runsc_root: runsc.runsc_root.clone(),
                network: Some(runsc.network.clone()),
                container_id: runsc.container_id.clone(),
                image_env: runsc.parts.image_env.clone(),
                agent_path: Some(runsc.parts.agent_path.clone()),
                file_agent_rootfs: runsc.file_agent_exec.then(|| runsc.rootfs.clone()),
            });
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return b.with_kboxlike_exec(crate::exec::KboxlikeExecTarget {
                rootfs: kboxlike.rootfs.clone(),
                image_env: kboxlike.parts.image_env.clone(),
                user: kboxlike.parts.user,
                mounts: kboxlike.mounts.clone(),
            });
        }
        // WarmDaemon pooled Vm: route `.output()` through the warm Pool
        // (Pool::exec_capture over the owned loopback) — a warm-daemon pooled Vm has
        // no exec socket. `Vm::exec` (streaming spawn) stays socket-only; the
        // request/response daemon-client model uses `.output()`.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(pool) = &self.sentry_warm_pool {
            return b.with_warm_pool(Arc::clone(pool));
        }
        b
    }

    /// Write `bytes` to `path` inside the guest, atomically.
    /// Native vsock RPC — no exec, no shell. Roughly ~100 µs per
    /// call regardless of file size (up to the 12 MiB raw limit
    /// imposed by the agent's frame cap).
    ///
    /// The guest agent stages to a sibling tmp file then renames
    /// for atomicity, so partial writes don't leave a half-baked
    /// file at `path`.
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// let image = Image::from_snapshot("path/to/snapshot")?;
    /// let vm = image.start(&VmConfig::new())?;
    /// vm.write_file("/tmp/main.rs", b"fn main() { println!(\"hi\"); }")?;
    /// let out = vm.exec_builder()
    ///     .argv(["rustc", "/tmp/main.rs", "-o", "/tmp/main"])
    ///     .output()?;
    /// assert!(out.success());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn write_file(&self, path: &str, bytes: &[u8]) -> std::io::Result<()> {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return runsc_write_file(runsc, path, bytes);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return kboxlike_write_file(kboxlike, path, bytes);
        }
        let body = serde_json::json!({
            "action": "write_file",
            "path": path,
            "data_b64": b64_encode(bytes),
        });
        crate::exec::send_control(&self.vsock_exec_path, &body)
    }

    /// Read `path` from inside the guest. Default cap is 32 MiB
    /// (raised in 0.5.0 from the prior 4 MiB to accommodate
    /// Playwright trace.zip artifacts and similar mid-sized blobs).
    /// For larger files use [`Vm::read_file_with_max_bytes`] with
    /// an explicit cap, or stream via [`Vm::exec`] (`cat`).
    pub fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
        self.read_file_with_max_bytes(path, 32 * 1024 * 1024)
    }

    /// Like [`Vm::read_file`] but with an explicit byte cap. Returns
    /// an error if the file exceeds `max_bytes` so the caller never
    /// gets a partial result silently. Cap is enforced inside the
    /// guest before any bytes leave it.
    pub fn read_file_with_max_bytes(&self, path: &str, max_bytes: u64) -> std::io::Result<Vec<u8>> {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return runsc_read_file(runsc, path, max_bytes);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return kboxlike_read_file(kboxlike, path, max_bytes);
        }
        let body = serde_json::json!({
            "action": "read_file",
            "path": path,
            "max_bytes": max_bytes,
        });
        // Generous read timeout for large reads — file IO inside
        // the VM is fast, but we want to tolerate cold-cache cases.
        let ack = crate::exec::send_control_with_ack(
            &self.vsock_exec_path,
            &body,
            Some(std::time::Duration::from_secs(30)),
        )?;
        let data_b64 = ack
            .get("data_b64")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "read_file: agent ack missing data_b64",
                )
            })?;
        b64_decode(data_b64).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    /// Send a Unix signal to the guest's main workload process.
    /// Use this for `docker stop`-style graceful shutdown:
    ///
    /// ```no_run
    /// # use supermachine::{Image, Vm, VmConfig};
    /// # let image = Image::from_snapshot("path")?;
    /// # let vm = Vm::start(&image, &VmConfig::new())?;
    /// vm.workload_signal(libc::SIGTERM)?;
    /// // ...wait for the workload to clean up...
    /// vm.stop()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// Implementation: dials the in-guest exec agent on a fresh
    /// connection with a CONTROL frame; the agent reads
    /// `/run/supermachine-workload.pid` (written by init-oci's
    /// PID-1 supervisor) and `kill(pid, signum)` it. Returns
    /// `Err(NotFound)` if the workload hasn't been spawned yet
    /// (only happens during the bake-time window).
    pub fn workload_signal(&self, signum: i32) -> std::io::Result<()> {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return runsc_workload_signal(runsc, signum);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return kboxlike_workload_signal(kboxlike, signum);
        }
        let body = serde_json::json!({
            "action": "signal",
            "signum": signum,
        });
        crate::exec::send_control(&self.vsock_exec_path, &body)
    }

    /// Connect to the guest's first TSI listener. The returned
    /// `UnixStream` is byte-equivalent to a `TcpStream` to the
    /// guest's `:80` (or whatever port it bound).
    ///
    /// For HTTP, just write a request and read the response:
    /// supermachine's vsock-mux is a transparent proxy.
    ///
    /// On the sentry backend the persistent supervisor provides the equivalent
    /// first-listener route through its owned LoopNet.
    pub fn connect(&self) -> std::io::Result<UnixStream> {
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return runsc_connect_port(runsc, 0);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return kboxlike_connect_port(kboxlike, 0);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if self.running.is_none() {
            return connect_port_sentry(&self.vsock_exec_path, 0);
        }
        UnixStream::connect(&self.vsock_mux_path)
    }

    /// Connect to the guest workload's listener on `port`, returning a
    /// [`UnixStream`] that is byte-equivalent to a `TcpStream` to the
    /// guest's `:port` — write a request and read the response.
    ///
    /// This is [`connect`](Vm::connect) with an explicit destination
    /// port. On the KVM/HVF backend it dials the vsock-mux and prefixes
    /// the connection with the `SMUX-PORT-V1` routing header (the same
    /// header [`expose_tcp`](Vm::expose_tcp) writes), so the mux routes
    /// to the matching guest TSI listener rather than the first one;
    /// `port == 0` opts out of the header and keeps the legacy
    /// first-listener behavior.
    ///
    /// On the sentry backend this dials the persistent supervisor and asks it to
    /// connect to the workload's supervisor-owned LoopNet listener. `port == 0`
    /// preserves the legacy first-listener behavior.
    pub fn connect_port(&self, port: u16) -> std::io::Result<UnixStream> {
        // A sentry-backed `Vm` has no `RunningVm` handle. Its persistent
        // supervisor owns the LoopNet listener and supplies the bridge.
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return runsc_connect_port(runsc, port);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return kboxlike_connect_port(kboxlike, port);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if self.running.is_none() {
            return connect_port_sentry(&self.vsock_exec_path, port);
        }
        let unix = UnixStream::connect(&self.vsock_mux_path)?;
        if port != 0 {
            // 16-byte magic + 4-byte BE port — same routing header as
            // `splice_tcp_to_unix`. Keep in sync with
            // `vmm::vsock_mux::SMUX_PORT_MAGIC`.
            let mut hdr = [0u8; 20];
            hdr[..16].copy_from_slice(b"SMUX-PORT-V1\0\0\0\0");
            hdr[16..].copy_from_slice(&(port as u32).to_be_bytes());
            (&unix).write_all(&hdr)?;
        }
        Ok(unix)
    }

    /// Reclaim guest memory via virtio-balloon: ask the guest to release `pages`
    /// 4 KiB pages, which the device then `madvise(MADV_FREE)`s on the host RAM
    /// map (the kernel can drop them under pressure). Requires the VM to have been
    /// started with [`VmConfig::with_balloon(true)`](VmConfig::with_balloon) on a
    /// cold boot; returns `false` if no balloon device is attached. Asynchronous —
    /// the guest's balloon driver frees pages in the background.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn request_balloon_inflate(&self, pages: u32) -> bool {
        self.running
            .as_ref()
            .map(|r| r.request_balloon_inflate(pages))
            .unwrap_or(false)
    }

    /// Bind a TCP listener on `127.0.0.1:host_port` that forwards
    /// each accepted connection to the guest's TSI listener (the
    /// same destination as [`Vm::connect`]). Returns a
    /// [`TcpForwarder`] that owns the accept-loop thread; drop it
    /// (or call [`TcpForwarder::stop`]) to stop accepting new
    /// connections. In-flight connections continue until they close
    /// naturally.
    ///
    /// `host_port = 0` lets the OS pick a free port; read the actual
    /// address back via [`TcpForwarder::local_addr`].
    ///
    /// `guest_port` pins the host-port → guest-port mapping. The
    /// host writes a small per-connection routing header (`SMUX-PORT
    /// -V1\0\0\0\0` + u32 BE port) before piping bytes, and the
    /// vsock-mux peeks (`MSG_PEEK`) that header and routes to the
    /// matching TSI listener instead of falling back to "first
    /// AF_INET listener." Pass `guest_port = 0` to opt out of the
    /// header and keep the legacy first-listener behavior — useful
    /// when the guest only binds one port and you want a router-
    /// style any-port forward.
    ///
    /// Use this when you want the embedded VM to look like a normal
    /// localhost service (e.g. `http://127.0.0.1:9090/`) rather than
    /// having every caller go through `vm.connect()`.
    ///
    /// ```no_run
    /// # use supermachine::{Image, Vm, VmConfig};
    /// let image = Image::from_snapshot("path/to/snapshot")?;
    /// let vm = Vm::start(&image, &VmConfig::new())?;
    /// let fwd = vm.expose_tcp(9090, 80)?;
    /// println!("nginx is on {}", fwd.local_addr());
    /// // ... do work ...
    /// drop(fwd); // stop forwarding
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    pub fn expose_tcp(&self, host_port: u16, guest_port: u16) -> std::io::Result<TcpForwarder> {
        // Sentry has no vsock/TSI mux. Its persistent supervisor owns the
        // in-process LoopNet, so ingress must be handed back to that supervisor.
        // A sentry-backed `Vm` has no `RunningVm` (`running.is_none()`).
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(runsc) = &self.runsc {
            return self.expose_tcp_runsc(host_port, guest_port, runsc);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if let Some(kboxlike) = &self.kboxlike {
            return self.expose_tcp_kboxlike(host_port, guest_port, kboxlike);
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        if self.running.is_none() {
            return self.expose_tcp_sentry(host_port, guest_port);
        }
        let listener = TcpListener::bind(("127.0.0.1", host_port))?;
        let bound = listener.local_addr()?;
        // Short accept timeout so the stop flag is responsive.
        listener.set_nonblocking(false)?;
        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = stop.clone();
        let vsock_path = self.vsock_mux_path.clone();
        let handle = std::thread::Builder::new()
            .name(format!("supermachine-tcp-{host_port}"))
            .spawn(move || {
                accept_loop(listener, vsock_path, stop_thread, guest_port);
            })
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
        // Best-effort: poke the listener to unblock its accept on
        // shutdown. We rely on `stop` flag + a self-connect during
        // drop. See TcpForwarder::drop.
        Ok(TcpForwarder {
            stop,
            handle: Some(handle),
            bound,
        })
    }

    /// Sentry backend variant of [`expose_tcp`](Vm::expose_tcp): a host-side TCP
    /// proxy into the persistent supervisor's owned LoopNet.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn expose_tcp_sentry(&self, host_port: u16, guest_port: u16) -> std::io::Result<TcpForwarder> {
        let listener = TcpListener::bind(("127.0.0.1", host_port))?;
        let bound = listener.local_addr()?;
        listener.set_nonblocking(false)?;
        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = stop.clone();
        let exec_path = self.vsock_exec_path.clone();
        let handle = std::thread::Builder::new()
            .name(format!("supermachine-tcp-{host_port}"))
            .spawn(move || sentry_accept_loop(listener, exec_path, guest_port, stop_thread))
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
        Ok(TcpForwarder {
            stop,
            handle: Some(handle),
            bound,
        })
    }

    /// Runsc backend variant of [`expose_tcp`](Vm::expose_tcp): a host-side TCP
    /// proxy that creates one `runsc exec` + `supermachine-agent --tcp-stdio`
    /// bridge per accepted connection.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn expose_tcp_runsc(
        &self,
        host_port: u16,
        guest_port: u16,
        runsc: &RunscRuntime,
    ) -> std::io::Result<TcpForwarder> {
        let listener = TcpListener::bind(("127.0.0.1", host_port))?;
        let bound = listener.local_addr()?;
        listener.set_nonblocking(false)?;
        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = stop.clone();
        let target = runsc_port_forward_target(runsc);
        let handle = std::thread::Builder::new()
            .name(format!("supermachine-tcp-{host_port}"))
            .spawn(move || runsc_accept_loop(listener, target, guest_port, stop_thread))
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
        Ok(TcpForwarder {
            stop,
            handle: Some(handle),
            bound,
        })
    }

    /// Kboxlike backend variant of [`expose_tcp`](Vm::expose_tcp): while the
    /// backend still restores into the host network namespace, ingress is a
    /// host-side TCP proxy into the restored workload's loopback listener.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn expose_tcp_kboxlike(
        &self,
        host_port: u16,
        guest_port: u16,
        kboxlike: &KboxlikeRuntime,
    ) -> std::io::Result<TcpForwarder> {
        let listener = TcpListener::bind(("127.0.0.1", host_port))?;
        let bound = listener.local_addr()?;
        listener.set_nonblocking(false)?;
        let stop = Arc::new(AtomicBool::new(false));
        let stop_thread = stop.clone();
        let target = kboxlike_port_forward_target(kboxlike);
        let handle = std::thread::Builder::new()
            .name(format!("supermachine-tcp-{host_port}"))
            .spawn(move || kboxlike_accept_loop(listener, target, guest_port, stop_thread))
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
        Ok(TcpForwarder {
            stop,
            handle: Some(handle),
            bound,
        })
    }

    /// (Linux/KVM) Start a host-side TLS terminator for this VM: accept HTTPS on
    /// `cfg.listen_addr`, terminate with rustls, and bridge decrypted plaintext
    /// to the guest's TSI listener — the guest serves plain HTTP, no TLS code in
    /// the guest. This is the in-process counterpart of the macOS/HVF worker's
    /// `--tls-*` flags (feature parity). Fire-and-forget: the acceptor runs for
    /// the VM's lifetime. Requires vsock enabled.
    ///
    /// On the sentry backend (`running.is_none()`) there is no vsock/TSI mux. The
    /// persistent supervisor owns the workload LoopNet, so the same rustls
    /// terminator bridges decrypted plaintext through the supervisor's bridge to
    /// `127.0.0.1:guest_port`. The guest TCP port is taken from `cfg.vm_port`,
    /// which must be `Some(p)` with `p` a non-zero value that fits a `u16` (the
    /// sentry has no "first TSI listener" fallback to route a 0 against, mirroring
    /// [`expose_tcp`](Vm::expose_tcp)'s `guest_port` rule).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn expose_tls(
        &self,
        cfg: crate::vmm::tls::TlsConfig,
    ) -> std::io::Result<std::net::SocketAddr> {
        // Sentry backend: no RunningVm handle, no vsock mux. Terminate TLS and
        // splice plaintext through the persistent supervisor's LoopNet bridge.
        if self.runsc.is_some() {
            let runsc = self.runsc.as_ref().ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::NotConnected, "runsc VM is not running")
            })?;
            let guest_port = match cfg.vm_port {
                Some(p) if p != 0 && p <= u16::MAX as u32 => p as u16,
                _ => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "expose_tls on the runsc backend requires cfg.vm_port = Some(non-zero u16 guest port)",
                    ))
                }
            };
            let target = runsc_port_forward_target(runsc);
            return crate::vmm::tls::start_to_unix_stream(
                cfg,
                format!("runsc bridge guest 127.0.0.1:{guest_port}"),
                move || runsc_connect_port_target(&target, guest_port),
            )
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()));
        }
        if let Some(kboxlike) = &self.kboxlike {
            let guest_port = match cfg.vm_port {
                Some(p) if p != 0 && p <= u16::MAX as u32 => p as u16,
                _ => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "expose_tls on the kboxlike backend requires cfg.vm_port = Some(non-zero u16 guest port)",
                    ))
                }
            };
            let target = kboxlike_port_forward_target(kboxlike);
            return crate::vmm::tls::start_to_unix_stream(
                cfg,
                format!("kboxlike bridge guest 127.0.0.1:{guest_port}"),
                move || kboxlike_connect_port_target(&target, guest_port),
            )
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()));
        }
        if self.running.is_none() {
            return self.expose_tls_sentry(cfg);
        }
        let running = self.running.as_ref().ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotConnected, "VM is not running")
        })?;
        running
            .expose_tls(cfg)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
    }

    /// Sentry backend variant of [`expose_tls`](Vm::expose_tls): terminate TLS on
    /// `cfg.listen_addr` with the backend-agnostic rustls terminator
    /// ([`crate::vmm::tls::start_to_addr`]) and bridge decrypted plaintext to the
    /// guest workload's LoopNet listener through the persistent supervisor bridge.
    /// The guest TCP port comes from `cfg.vm_port`, which must be `Some(p)` with
    /// `p != 0` and `p <= u16::MAX` (no first-listener fallback to route a
    /// 0/oversized vm_port against — same contract as [`expose_tcp`](Vm::expose_tcp)'s
    /// `guest_port`).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn expose_tls_sentry(
        &self,
        cfg: crate::vmm::tls::TlsConfig,
    ) -> std::io::Result<std::net::SocketAddr> {
        let guest_port = match cfg.vm_port {
            Some(p) if p != 0 && p <= u16::MAX as u32 => p as u16,
            _ => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "expose_tls on the sentry backend requires cfg.vm_port = Some(non-zero u16 guest port)",
                ))
            }
        };
        let exec_path = self.vsock_exec_path.clone();
        crate::vmm::tls::start_to_unix_stream(
            cfg,
            format!("sentry bridge guest 127.0.0.1:{guest_port}"),
            move || connect_port_sentry(&exec_path, guest_port),
        )
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
    }

    /// Stop the VM. Equivalent to dropping it, but returns errors
    /// rather than swallowing them.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn stop(mut self) -> Result<(), Error> {
        if let Some(pool) = self.pool.take() {
            let _ = pool.shutdown().map_err(Error::from)?;
        }
        self.cleanup_socket();
        Ok(())
    }

    /// Stop the VM (Linux/KVM): force-exit + join the vCPU threads via the
    /// [`RunningVm`](crate::kvm::run::RunningVm) handle, then unlink the sockets.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn stop(mut self) -> Result<(), Error> {
        if let Some(running) = self.running.take() {
            let _ = running.stop();
        }
        // Sentry backend: stop the exec server (kills the workload + unlinks).
        if let Some(srv) = self.sentry_exec.take() {
            srv.stop();
        }
        if let Some(pool) = self.sentry_unified_pool.take() {
            pool.stop();
        }
        if let Some(mut runtime) = self.kboxlike.take() {
            runtime.cleanup();
        }
        self.cleanup_socket();
        Ok(())
    }

    /// In-place reset this VM to its snapshot baseline (isolated warm-reuse) —
    /// see [`RunningVm::reset_to_snapshot`](crate::kvm::run::RunningVm::reset_to_snapshot).
    /// The pool calls this on release for the `restore_on_release=true`
    /// (isolated, default) path: it returns the guest byte-identical to the
    /// snapshot point — clean per-cycle isolation — without the full teardown +
    /// fresh-restore cost, since the KVM VM/vCPUs/threads/RAM all persist.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub(crate) fn reset_to_snapshot(&self) -> Result<(), Error> {
        self.running
            .as_ref()
            .ok_or_else(|| Error::vm_msg("reset_to_snapshot: VM has no running handle".to_owned()))?
            .reset_to_snapshot()
            .map_err(|e| Error::vm_msg(format!("reset_to_snapshot: {e}")))
    }

    /// Capture a snapshot of the running VM into `dest_dir`. The
    /// dir gets `restore.snap` (the captured VM state) and a
    /// `metadata.json` describing the layers/memory/vCPUs from
    /// the source [`Image`] — together they form a fresh
    /// snapshot loadable via [`Image::from_snapshot`].
    ///
    /// This is the **"rustc-warm snapshot" pattern** — boot a VM
    /// from a base image (e.g. `rust:1-slim`), populate
    /// expensive in-VM state (run `cargo build` to fill
    /// `target/` with cached deps), capture, then re-use the new
    /// snapshot via `Image::from_snapshot(...).acquire()` for
    /// fast subsequent iterations.
    ///
    /// ```no_run
    /// # use supermachine::{Image, VmConfig};
    /// let base = Image::from_snapshot("path/to/rust-slim")?;
    /// let vm = base.start(&VmConfig::new())?;
    /// // Pre-warm: populate target/ with cached deps.
    /// vm.exec_builder()
    ///     .argv(["sh", "-c", "cd /src && cargo build --release"])
    ///     .output()?;
    /// // Capture; vm is consumed (and stopped).
    /// let warm = vm.snapshot("/tmp/rust-warm")?;
    /// // Now `warm.acquire()` gets you a VM with target/
    /// // already populated — every subsequent compile re-uses
    /// // the cached deps.
    /// # Ok::<(), supermachine::Error>(())
    /// ```
    ///
    /// **Only works on a Vm produced by [`Image::start`]**.
    /// Pooled VMs (from [`Image::acquire`]) live in worker
    /// subprocesses and don't have host-side access to the
    /// snapshot machinery; snapshot them by re-starting the
    /// source image and snapshotting that.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn snapshot(mut self, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        let meta = self.image_meta.clone().ok_or_else(|| {
            Error::vm_msg(
                "Vm::snapshot requires an in-process Vm (use image.start, not image.acquire)"
                    .to_owned(),
            )
        })?;
        let pool = self.pool.as_ref().ok_or_else(|| {
            Error::vm_msg("Vm::snapshot: no pool to drive the capture".to_owned())
        })?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        let snap_path = dest_dir.join("restore.snap");
        // Flush guest dirty pages to host-persistent backing files
        // (virtio-blk volumes, writeback-cached virtio-fs) before
        // the capture — see `guest_sync_via_agent`.
        let _ = guest_sync_via_agent(&self.vsock_exec_path);
        // Trigger the capture via the pool RPC. Generous
        // timeout — capture is fast (~10s of ms) but disk
        // saving for big VMs can take a moment.
        let _result = pool
            .snapshot_timeout(
                snap_path.to_string_lossy().to_string(),
                Duration::from_secs(60),
            )
            .map_err(|e| Error::Vm {
                msg: format!("snapshot capture failed: {e:?}"),
                source: None,
            })?;
        // Write a metadata.json that mirrors what the bake step
        // emits, so Image::from_snapshot can load this dir.
        let metadata = serde_json::json!({
            "memory_mib": meta.memory_mib,
            "vcpus": meta.vcpus,
            "layers": meta
                .layers
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
            "delta_squashfs": meta
                .delta_squashfs
                .as_ref()
                .map(|p| p.to_string_lossy().to_string()),
            "snapshot_base": snap_path.to_string_lossy().to_string(),
            "baked_at": chrono_rfc3339_now(),
            "source": "Vm::snapshot",
        });
        std::fs::write(
            dest_dir.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::vm_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        // Cleanly shut down our worker — the snapshot is on disk.
        if let Some(pool) = self.pool.take() {
            let _ = pool.shutdown();
        }
        self.cleanup_socket();
        // Suppress the Drop, we already cleaned up.
        self.skip_cleanup = true;
        // Load the freshly-written dir as a new Image.
        Image::from_snapshot(&dest_dir)
    }

    /// Capture a snapshot (Linux/KVM) and return it as a loadable, snapshot-
    /// backed [`Image`] (`"backend":"kvm"`, `kvm_snapshot` → the saved file).
    /// Quiesces all vCPUs at a clean boundary, captures the full `VmSnapshot`,
    /// and writes `vm.snap` + `metadata.json` under `dest_dir`. Restoring the
    /// returned image via [`Vm::start`] is a CoW mmap (~ms) — this is what backs
    /// the warm pool and lets callers checkpoint a live guest.
    ///
    /// **Sentry backend:** there is no guest RAM/CPU to checkpoint; the warm
    /// state is the filesystem. This captures the live rootfs (e.g. a populated
    /// `node_modules`/`target` after a warming `exec`) into a new sentry image
    /// dir + re-emits `metadata.json`, so `Image::from_snapshot(dest).start()`
    /// boots a sandbox that already has that filesystem state. Capture at a
    /// quiescent point (after your warming exec has returned). Only works on a
    /// cold-start `Vm` from [`Image::start`] (pooled VMs return an error).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot(mut self, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        if let Some(runsc) = self.runsc.as_ref() {
            let image = write_runsc_snapshot_dir(runsc, &dest_dir, "Vm::snapshot", false)?;
            self.cleanup_socket();
            self.skip_cleanup = true;
            return Ok(image);
        }
        if self.kboxlike.is_some() {
            return Err(Error::vm_msg(
                "Vm::snapshot is not implemented for the kboxlike backend yet".to_owned(),
            ));
        }
        // Sentry backend (no `RunningVm`): capture the warm rootfs.
        if self.running.is_none() {
            return self.snapshot_sentry(dest_dir);
        }
        let running = self.running.take().ok_or_else(|| {
            Error::vm_msg("Vm::snapshot: this VM is not running (already stopped?)".to_owned())
        })?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        // Flush guest dirty pages to host-persistent backing files
        // (virtio-blk volumes, writeback-cached virtio-fs) before
        // the capture — see `guest_sync_via_agent`.
        let _ = guest_sync_via_agent(&self.vsock_exec_path);
        // Quiesce all vCPUs at a clean boundary + capture full VM state.
        let snap = running
            .snapshot(Some(&dest_dir.join("volumes")))
            .map_err(|e| Error::vm_msg(format!("capture snapshot: {e}")))?;
        let snap_path = dest_dir.join("vm.snap");
        snap.save(&snap_path)
            .map_err(|e| Error::vm_msg(format!("write snapshot {}: {e}", snap_path.display())))?;
        // metadata.json a `backend":"kvm"` restore-image points at the snapshot.
        let metadata = serde_json::json!({
            "backend": "kvm",
            "kvm_snapshot": snap_path.to_string_lossy(),
            "memory_mib": (snap.mem_size() >> 20) as u32,
            "vcpus": snap.num_cpus() as u32,
            "baked_at": chrono_rfc3339_now(),
            "source": "Vm::snapshot",
        });
        std::fs::write(
            dest_dir.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::vm_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        // The running VM was consumed by the capture; just unlink our sockets
        // and suppress the Drop's redundant cleanup.
        self.cleanup_socket();
        self.skip_cleanup = true;
        Image::from_snapshot(&dest_dir)
    }

    /// Sentry backend snapshot: copy the live rootfs (warm filesystem state) into
    /// a new sentry image dir + re-emit `metadata.json` (repointing
    /// `sentry_rootfs`, restamping `baked_at`/`source`, recomputing physical
    /// bytes, and preserving `sentry_has_workload`/`image_env`/`cmd`/… from the
    /// source). The result loads via [`Image::from_snapshot`].
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn snapshot_sentry(mut self, dest_dir: PathBuf) -> Result<Image, Error> {
        let src_rootfs = self.sentry_src_rootfs.clone().ok_or_else(|| {
            Error::vm_msg(
                "Vm::snapshot on the sentry backend requires an in-process Vm from \
                 Image::start (pooled VMs share a server and can't snapshot the rootfs)"
                    .to_owned(),
            )
        })?;
        // Copy the warm rootfs + re-emit metadata (shared with the pooled path).
        let image = write_sentry_snapshot_dir_inner(
            &src_rootfs,
            &dest_dir,
            "Vm::snapshot",
            false,
            None,
            None,
        )?;
        // Stop our exec server (kills the workload + unlinks), suppress Drop.
        if let Some(srv) = self.sentry_exec.take() {
            srv.stop();
        }
        self.cleanup_socket();
        self.skip_cleanup = true;
        Ok(image)
    }

    /// LIVE snapshot (Linux/KVM): capture a loadable [`Image`] WITHOUT stopping
    /// the guest — the VM keeps running and can be snapshotted again. Backs the
    /// builder's one-VM-per-layer snapshotting. `&self` (non-consuming).
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot_live(&self, dest_dir: impl Into<PathBuf>) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        let running = self
            .running
            .as_ref()
            .ok_or_else(|| Error::vm_msg("Vm::snapshot_live: VM not running".to_owned()))?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        // Flush guest dirty pages to host-persistent backing files
        // (virtio-blk volumes — incl. the builder's volume-backed
        // cache mounts) before the capture — see
        // `guest_sync_via_agent`.
        let _ = guest_sync_via_agent(&self.vsock_exec_path);
        let snap = running
            .snapshot_live(Some(&dest_dir.join("volumes")))
            .map_err(|e| Error::vm_msg(format!("capture live snapshot: {e}")))?;
        // `restore.snap` + a dir-RELATIVE `kvm_snapshot` is the builder's snapshot
        // -dir convention (is_snapshot_dir / clone_snapshot_dir): the relative
        // path resolves against the dir, so a cloned layer dir stays loadable.
        let snap_path = dest_dir.join("restore.snap");
        snap.save(&snap_path)
            .map_err(|e| Error::vm_msg(format!("write snapshot {}: {e}", snap_path.display())))?;
        write_kvm_snapshot_metadata(
            &dest_dir,
            "restore.snap",
            None,
            snap.mem_size(),
            snap.num_cpus(),
        )?;
        Image::from_snapshot(&dest_dir)
    }

    /// LIVE differential snapshot (Linux/KVM): like [`Vm::snapshot_live`] but
    /// stores only the guest-RAM pages changed vs `base_snap` (a full snapshot's
    /// `restore.snap`). Non-consuming — the VM keeps running. The builder chains
    /// these per layer off one VM.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot_diff_live(
        &self,
        dest_dir: impl Into<PathBuf>,
        base_snap: &Path,
    ) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        let running = self
            .running
            .as_ref()
            .ok_or_else(|| Error::vm_msg("Vm::snapshot_diff_live: VM not running".to_owned()))?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        // Same flush-before-capture as `Vm::snapshot_live`.
        let _ = guest_sync_via_agent(&self.vsock_exec_path);
        let snap = running
            .snapshot_live(Some(&dest_dir.join("volumes")))
            .map_err(|e| Error::vm_msg(format!("capture live snapshot: {e}")))?;
        let snap_path = dest_dir.join("restore.snap");
        snap.save_diff(&snap_path, base_snap).map_err(|e| {
            Error::vm_msg(format!("write diff snapshot {}: {e}", snap_path.display()))
        })?;
        write_kvm_snapshot_metadata(
            &dest_dir,
            "restore.snap",
            Some(base_snap),
            snap.mem_size(),
            snap.num_cpus(),
        )?;
        Image::from_snapshot(&dest_dir)
    }

    /// Differential snapshot (Linux/KVM): capture the running guest but store
    /// only the guest-RAM pages that changed vs `base` (another KVM-backed
    /// [`Image`], e.g. the previous layer) — the full vCPU/device state is always
    /// stored. Restoring the returned image transparently mmaps the base RAM
    /// copy-on-write and overlays the delta, so a chain of these (e.g. per-layer
    /// builder snapshots) each costs only its changed pages on disk.
    ///
    /// The base's snapshot file must remain in place (the diff references it by
    /// path). `base` must be a full (non-diff) KVM snapshot of the same memory
    /// size; pass an [`Image`] produced by [`Vm::snapshot`] / `bake_kvm_*`.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    pub fn snapshot_diff(
        mut self,
        dest_dir: impl Into<PathBuf>,
        base: &Image,
    ) -> Result<Image, Error> {
        let dest_dir = dest_dir.into();
        let base_snap = base
            .kvm
            .as_ref()
            .and_then(|k| k.snapshot.clone())
            .ok_or_else(|| {
                Error::vm_msg(
                    "Vm::snapshot_diff: base Image has no KVM snapshot to diff against".to_owned(),
                )
            })?;
        let running = self.running.take().ok_or_else(|| {
            Error::vm_msg("Vm::snapshot_diff: this VM is not running (already stopped?)".to_owned())
        })?;
        std::fs::create_dir_all(&dest_dir).map_err(Error::Io)?;
        // Same flush-before-capture as `Vm::snapshot_live`.
        let _ = guest_sync_via_agent(&self.vsock_exec_path);
        let snap = running
            .snapshot(Some(&dest_dir.join("volumes")))
            .map_err(|e| Error::vm_msg(format!("capture snapshot: {e}")))?;
        let snap_path = dest_dir.join("vm.snap");
        snap.save_diff(&snap_path, &base_snap).map_err(|e| {
            Error::vm_msg(format!("write diff snapshot {}: {e}", snap_path.display()))
        })?;
        let metadata = serde_json::json!({
            "backend": "kvm",
            "kvm_snapshot": snap_path.to_string_lossy(),
            "kvm_snapshot_base": base_snap.to_string_lossy(),
            "memory_mib": (snap.mem_size() >> 20) as u32,
            "vcpus": snap.num_cpus() as u32,
            "baked_at": chrono_rfc3339_now(),
            "source": "Vm::snapshot_diff",
        });
        std::fs::write(
            dest_dir.join("metadata.json"),
            serde_json::to_string_pretty(&metadata)
                .map_err(|e| Error::vm_msg(format!("metadata serialize: {e}")))?,
        )
        .map_err(Error::Io)?;
        self.cleanup_socket();
        self.skip_cleanup = true;
        Image::from_snapshot(&dest_dir)
    }

    fn cleanup_socket(&self) {
        let _ = std::fs::remove_file(&self.vsock_mux_path);
        let _ = std::fs::remove_file(&self.vsock_exec_path);
        if let Some(dir) = &self.own_vsock_mux_dir {
            // Only unlink the dir if it's still empty (best-effort).
            let _ = std::fs::remove_dir(dir);
        }
    }
}

// ---------- minimal base64 (RFC 4648, mirror of agent's) ----------
//
// Inlined to keep deps minimal. Round-trip-tested against the
// agent's implementation; identical alphabet + padding rules.

const B64_ALPHA: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Public so the napi binding can encode bytes for the agent's
/// `write_file` action JSON without re-implementing this. The
/// shape is internal — embedders outside this workspace should
/// stick to [`crate::Vm::write_file`] / [`crate::Vm::read_file`]
/// which call into this for you.
pub fn b64_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity((bytes.len() + 2) / 3 * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let b0 = bytes[i] as u32;
        let b1 = bytes[i + 1] as u32;
        let b2 = bytes[i + 2] as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(B64_ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[((n >> 12) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[((n >> 6) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[(n & 0x3f) as usize] as char);
        i += 3;
    }
    let rem = bytes.len() - i;
    if rem == 1 {
        let b0 = bytes[i] as u32;
        let n = b0 << 16;
        out.push(B64_ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[((n >> 12) & 0x3f) as usize] as char);
        out.push('=');
        out.push('=');
    } else if rem == 2 {
        let b0 = bytes[i] as u32;
        let b1 = bytes[i + 1] as u32;
        let n = (b0 << 16) | (b1 << 8);
        out.push(B64_ALPHA[((n >> 18) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[((n >> 12) & 0x3f) as usize] as char);
        out.push(B64_ALPHA[((n >> 6) & 0x3f) as usize] as char);
        out.push('=');
    }
    out
}

/// Public counterpart to [`b64_encode`]. Same shape, same caveat.
pub fn b64_decode(s: &str) -> Result<Vec<u8>, String> {
    let mut tbl = [255u8; 256];
    for (i, &b) in B64_ALPHA.iter().enumerate() {
        tbl[b as usize] = i as u8;
    }
    let bytes: Vec<u8> = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    if bytes.len() % 4 != 0 {
        return Err(format!(
            "base64 length {} is not a multiple of 4",
            bytes.len()
        ));
    }
    let nchunks = bytes.len() / 4;
    let mut out = Vec::with_capacity(nchunks * 3);
    for (ci, chunk) in bytes.chunks_exact(4).enumerate() {
        let v: [u8; 4] = chunk.try_into().unwrap();
        // `=` padding is only valid as the 1 or 2 TRAILING characters of
        // the FINAL chunk. Reject everything else — leading/embedded `=`
        // ("=AAA"), a padded non-final chunk ("AA==AAAA"), or 3-4 pads
        // ("A===", "===="). The previous code counted `=` anywhere and
        // emitted a spurious byte instead of erroring, so a hostile/buggy
        // in-guest agent could make read_file silently return wrong bytes.
        let pad = v.iter().filter(|&&b| b == b'=').count();
        if pad > 0 {
            let last_chunk = ci == nchunks - 1;
            let trailing_only = match pad {
                1 => v[3] == b'=',
                2 => v[2] == b'=' && v[3] == b'=',
                _ => false,
            };
            if !last_chunk || !trailing_only {
                return Err(format!("base64 misplaced or excess padding in chunk {ci}"));
            }
        }
        let mut acc: u32 = 0;
        for &b in &v {
            let d = if b == b'=' {
                0
            } else {
                let d = tbl[b as usize];
                if d == 255 {
                    return Err(format!("invalid base64 character {:#x}", b));
                }
                d
            };
            acc = (acc << 6) | (d as u32);
        }
        out.push(((acc >> 16) & 0xff) as u8);
        if pad < 2 {
            out.push(((acc >> 8) & 0xff) as u8);
        }
        if pad < 1 {
            out.push((acc & 0xff) as u8);
        }
    }
    Ok(out)
}

#[cfg(any(
    all(target_os = "macos", target_arch = "aarch64"),
    all(target_os = "linux", target_arch = "x86_64")
))]
impl Drop for Vm {
    fn drop(&mut self) {
        // PooledVm sets skip_cleanup so its inner Vm doesn't
        // shut down the shared pool or unlink sockets the
        // HiddenPool keeps alive.
        if self.skip_cleanup {
            return;
        }
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        if let Some(pool) = self.pool.take() {
            let _ = pool.shutdown();
        }
        #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
        {
            // Stop the background clock-resync thread so it doesn't keep
            // retrying (and leaking) for 30 s against a VM that's going away.
            self.time_sync_stop.store(true, Ordering::SeqCst);
            if let Some(running) = self.running.take() {
                let _ = running.stop();
            }
            // Sentry backend: stop the exec server (kills the workload + unlinks
            // its socket) BEFORE cleanup_socket removes the path.
            if let Some(srv) = self.sentry_exec.take() {
                srv.stop();
            }
            if let Some(pool) = self.sentry_unified_pool.take() {
                pool.stop();
            }
            if let Some(mut runtime) = self.kboxlike.take() {
                runtime.cleanup();
            }
        }
        self.cleanup_socket();
    }
}

/// Owns the accept-loop thread for a [`Vm::expose_tcp`] forwarder.
///
/// Drop this to stop accepting new connections. In-flight
/// connections continue until they close naturally — they're owned
/// by their own splice threads, not by the forwarder.
pub struct TcpForwarder {
    stop: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
    bound: SocketAddr,
}

impl TcpForwarder {
    /// The address the forwarder is listening on. Useful when you
    /// asked for `host_port = 0` and want to know the OS-assigned
    /// port.
    pub fn local_addr(&self) -> SocketAddr {
        self.bound
    }

    /// Stop accepting new connections. Equivalent to dropping the
    /// forwarder, but returns when the accept thread has actually
    /// exited.
    pub fn stop(mut self) {
        self.shutdown();
    }

    fn shutdown(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        // Self-connect to unblock the listener's accept(). We don't
        // care about the result — the connection just exists to wake
        // the loop, which then sees `stop` set and exits.
        let _ = TcpStream::connect_timeout(&self.bound, Duration::from_millis(200));
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

impl Drop for TcpForwarder {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// Accept loop for `Vm::expose_tcp`. Spawns a per-connection splice
/// thread for each accepted TCP stream; the splice threads live
/// independently of the forwarder so in-flight requests survive
/// `TcpForwarder::drop`.
fn accept_loop(listener: TcpListener, vsock_path: PathBuf, stop: Arc<AtomicBool>, guest_port: u16) {
    for incoming in listener.incoming() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        let tcp = match incoming {
            Ok(s) => s,
            Err(_) => continue,
        };
        // Linux: request/response traffic stalls ~40 ms per round-trip
        // without NODELAY (Nagle + delayed-ACK interaction): measured
        // 778 req/s with a flat 41 ms latency through this forwarder;
        // with NODELAY, 5.8k req/s at 5.6 ms (wrk -t4 -c32, nginx 1
        // vCPU). macOS is the OPPOSITE: its delayed-ACK behavior never
        // produces the stall, and Nagle usefully coalesces the
        // vsock-chunked response writes — NODELAY there measured a
        // consistent ~20% THROUGHPUT LOSS (23.5–25k → 18.4–19.9k
        // req/s, same harness, back-to-back A/B). Hence the cfg gate;
        // a write-coalescing splice would let both platforms run
        // NODELAY (future work).
        #[cfg(target_os = "linux")]
        let _ = tcp.set_nodelay(true);
        let vsock = vsock_path.clone();
        std::thread::Builder::new()
            .name("supermachine-tcp-conn".into())
            .spawn(move || {
                if let Err(e) = splice_tcp_to_unix(tcp, &vsock, guest_port) {
                    // Log to stderr — this is best-effort; the
                    // embedder's preferred logging is out of scope.
                    eprintln!("supermachine: tcp forward: {e}");
                }
            })
            .ok();
    }
}

/// Bridge a single TCP connection to the vsock-mux unix socket.
/// Two threads per connection: one shovels TCP→Unix, the other
/// Unix→TCP. Either side closing tears the bridge down.
///
/// If `guest_port != 0`, writes a 20-byte routing header
/// (`SMUX-PORT-V1\0\0\0\0` + u32 BE port) at the front of the unix
/// connection so the worker's vsock-mux accept handler routes this
/// stream to the matching guest TSI listener. With `guest_port == 0`
/// (or for any unix client that doesn't write the header), the mux
/// falls back to "first AF_INET TSI listener" — the legacy behavior.
fn splice_tcp_to_unix(tcp: TcpStream, vsock_path: &Path, guest_port: u16) -> std::io::Result<()> {
    let mut unix = UnixStream::connect(vsock_path)?;
    if guest_port != 0 {
        // 16-byte magic + 4-byte BE port. Keep this constant in sync
        // with `vmm::vsock_mux::SMUX_PORT_MAGIC`.
        let mut hdr = [0u8; 20];
        hdr[..16].copy_from_slice(b"SMUX-PORT-V1\0\0\0\0");
        hdr[16..].copy_from_slice(&(guest_port as u32).to_be_bytes());
        unix.write_all(&hdr)?;
    }
    // try_clone so each direction owns its own handle.
    let tcp_w = tcp.try_clone()?;
    let unix_w = unix.try_clone()?;
    let t1 = std::thread::Builder::new()
        .name("supermachine-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(tcp, unix_w);
        })?;
    let t2 = std::thread::Builder::new()
        .name("supermachine-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(unix, tcp_w);
        })?;
    let _ = t1.join();
    let _ = t2.join();
    Ok(())
}

/// Accept loop for the sentry backend's [`Vm::expose_tcp`]. Each connection is
/// handed to the persistent supervisor, which connects it to owned LoopNet.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sentry_accept_loop(
    listener: TcpListener,
    exec_path: PathBuf,
    guest_port: u16,
    stop: Arc<AtomicBool>,
) {
    for incoming in listener.incoming() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        let tcp = match incoming {
            Ok(s) => s,
            Err(_) => continue,
        };
        // Same NODELAY rationale as `accept_loop` (Linux-only; the sentry backend
        // is Linux/x86_64-only anyway).
        let _ = tcp.set_nodelay(true);
        let exec_path = exec_path.clone();
        std::thread::Builder::new()
            .name("supermachine-tcp-conn".into())
            .spawn(move || {
                if let Err(e) = splice_tcp_to_sentry(tcp, &exec_path, guest_port) {
                    eprintln!("supermachine: sentry tcp forward: {e}");
                }
            })
            .ok();
    }
}

/// Accept loop for the runsc backend's [`Vm::expose_tcp`]. Each inbound host
/// TCP connection gets its own agent stdio bridge into the sandbox.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_accept_loop(
    listener: TcpListener,
    target: RunscPortForwardTarget,
    guest_port: u16,
    stop: Arc<AtomicBool>,
) {
    for incoming in listener.incoming() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        let tcp = match incoming {
            Ok(s) => s,
            Err(_) => continue,
        };
        let _ = tcp.set_nodelay(true);
        let target = target.clone();
        std::thread::Builder::new()
            .name("supermachine-tcp-conn".into())
            .spawn(move || {
                if let Err(e) = splice_tcp_to_runsc(tcp, &target, guest_port) {
                    eprintln!("supermachine: runsc tcp forward: {e}");
                }
            })
            .ok();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_accept_loop(
    listener: TcpListener,
    target: KboxlikePortForwardTarget,
    guest_port: u16,
    stop: Arc<AtomicBool>,
) {
    for incoming in listener.incoming() {
        if stop.load(Ordering::SeqCst) {
            break;
        }
        let tcp = match incoming {
            Ok(s) => s,
            Err(_) => continue,
        };
        let _ = tcp.set_nodelay(true);
        let target = target.clone();
        std::thread::Builder::new()
            .name("supermachine-tcp-conn".into())
            .spawn(move || {
                if let Err(e) = splice_tcp_to_kboxlike(tcp, &target, guest_port) {
                    eprintln!("supermachine: kboxlike tcp forward: {e}");
                }
            })
            .ok();
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn splice_tcp_to_runsc(
    client: TcpStream,
    target: &RunscPortForwardTarget,
    guest_port: u16,
) -> std::io::Result<()> {
    let upstream = runsc_connect_port_target(target, guest_port)?;
    let client_w = client.try_clone()?;
    let upstream_w = upstream.try_clone()?;
    let t1 = std::thread::Builder::new()
        .name("supermachine-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(client, upstream_w);
        })?;
    let t2 = std::thread::Builder::new()
        .name("supermachine-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(upstream, client_w);
        })?;
    let _ = t1.join();
    let _ = t2.join();
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn splice_tcp_to_kboxlike(
    client: TcpStream,
    target: &KboxlikePortForwardTarget,
    guest_port: u16,
) -> std::io::Result<()> {
    let upstream = kboxlike_connect_tcp_target(target, guest_port)?;
    let client_w = client.try_clone()?;
    let upstream_w = upstream.try_clone()?;
    let t1 = std::thread::Builder::new()
        .name("supermachine-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(client, upstream_w);
        })?;
    let t2 = std::thread::Builder::new()
        .name("supermachine-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(upstream, client_w);
        })?;
    let _ = t1.join();
    let _ = t2.join();
    Ok(())
}

/// Bridge one inbound TCP connection to a raw supervisor bridge stream.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn splice_tcp_to_sentry(
    client: TcpStream,
    exec_path: &Path,
    guest_port: u16,
) -> std::io::Result<()> {
    let upstream = connect_port_sentry(exec_path, guest_port)?;
    let client_w = client.try_clone()?;
    let upstream_w = upstream.try_clone()?;
    let t1 = std::thread::Builder::new()
        .name("supermachine-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(client, upstream_w);
        })?;
    let t2 = std::thread::Builder::new()
        .name("supermachine-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(upstream, client_w);
        })?;
    let _ = t1.join();
    let _ = t2.join();
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_port_forward_target(runtime: &RunscRuntime) -> RunscPortForwardTarget {
    RunscPortForwardTarget {
        runsc_bin: runtime.runsc_bin.clone(),
        runsc_root: runtime.runsc_root.clone(),
        network: runtime.network.clone(),
        container_id: runtime.container_id.clone(),
        agent_path: runtime.parts.agent_path.clone(),
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_port_forward_target(runtime: &KboxlikeRuntime) -> KboxlikePortForwardTarget {
    KboxlikePortForwardTarget {
        restored_host_pids: runtime.restored_host_pids.clone(),
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_connect_port(runtime: &RunscRuntime, guest_port: u16) -> std::io::Result<UnixStream> {
    let port = if guest_port == 0 {
        runsc_first_listening_port(runtime)?
    } else {
        guest_port
    };
    let target = runsc_port_forward_target(runtime);
    runsc_connect_port_target(&target, port)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_connect_port(
    runtime: &KboxlikeRuntime,
    guest_port: u16,
) -> std::io::Result<UnixStream> {
    let target = kboxlike_port_forward_target(runtime);
    kboxlike_connect_port_target(&target, guest_port)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_connect_port_target(
    target: &RunscPortForwardTarget,
    guest_port: u16,
) -> std::io::Result<UnixStream> {
    if guest_port == 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "runsc bridge requires a non-zero guest port",
        ));
    }
    let (client, bridge) = UnixStream::pair()?;
    let mut cmd = Command::new(&target.runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut cmd, &target.runsc_root, &target.network);
    cmd.arg("exec")
        .arg(&target.container_id)
        .arg(&target.agent_path)
        .arg("--tcp-stdio")
        .arg("127.0.0.1")
        .arg(guest_port.to_string())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().map_err(|e| {
        std::io::Error::new(
            e.kind(),
            format!(
                "runsc exec {} {} --tcp-stdio 127.0.0.1 {}: {e}",
                target.container_id, target.agent_path, guest_port
            ),
        )
    })?;
    let child_stdin = child.stdin.take().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "runsc tcp bridge stdin was not available",
        )
    })?;
    let child_stdout = child.stdout.take().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "runsc tcp bridge stdout was not available",
        )
    })?;

    let startup_deadline = Instant::now() + Duration::from_millis(200);
    while Instant::now() < startup_deadline {
        if let Some(status) = child.try_wait()? {
            let out = child.wait_with_output()?;
            let detail = String::from_utf8_lossy(&out.stderr).trim().to_owned();
            let msg = if detail.is_empty() {
                format!("runsc tcp bridge to guest port {guest_port} exited with status {status}")
            } else {
                format!(
                    "runsc tcp bridge to guest port {guest_port} exited with status {status}: {detail}"
                )
            };
            return Err(std::io::Error::new(
                std::io::ErrorKind::ConnectionRefused,
                msg,
            ));
        }
        std::thread::sleep(Duration::from_millis(10));
    }

    let bridge_to_child = bridge.try_clone()?;
    let child_to_bridge = bridge.try_clone()?;
    let to_child = std::thread::Builder::new()
        .name("supermachine-runsc-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(bridge_to_child, child_stdin);
        })?;
    let from_child = std::thread::Builder::new()
        .name("supermachine-runsc-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(child_stdout, child_to_bridge);
        })?;
    std::thread::Builder::new()
        .name("supermachine-runsc-tcp-bridge".into())
        .spawn(move || {
            let _ = to_child.join();
            let _ = from_child.join();
            match child.wait_with_output() {
                Ok(out) if !out.status.success() => {
                    let detail = String::from_utf8_lossy(&out.stderr).trim().to_owned();
                    if detail.is_empty() {
                        eprintln!(
                            "supermachine: runsc tcp bridge exited with status {}",
                            out.status
                        );
                    } else {
                        eprintln!(
                            "supermachine: runsc tcp bridge exited with status {}: {}",
                            out.status, detail
                        );
                    }
                }
                Ok(_) => {}
                Err(e) => eprintln!("supermachine: runsc tcp bridge wait failed: {e}"),
            }
            drop(bridge);
        })?;
    Ok(client)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_connect_port_target(
    target: &KboxlikePortForwardTarget,
    guest_port: u16,
) -> std::io::Result<UnixStream> {
    let upstream = kboxlike_connect_tcp_target(target, guest_port)?;
    let (client, bridge) = UnixStream::pair()?;
    let bridge_to_upstream = bridge.try_clone()?;
    let upstream_to_bridge = upstream.try_clone()?;
    let to_upstream = std::thread::Builder::new()
        .name("supermachine-kboxlike-tcp-c2g".into())
        .spawn(move || {
            let _ = pump(bridge_to_upstream, upstream);
        })?;
    let from_upstream = std::thread::Builder::new()
        .name("supermachine-kboxlike-tcp-g2c".into())
        .spawn(move || {
            let _ = pump(upstream_to_bridge, bridge);
        })?;
    std::thread::Builder::new()
        .name("supermachine-kboxlike-tcp-bridge".into())
        .spawn(move || {
            let _ = to_upstream.join();
            let _ = from_upstream.join();
        })?;
    Ok(client)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_connect_tcp_target(
    target: &KboxlikePortForwardTarget,
    guest_port: u16,
) -> std::io::Result<TcpStream> {
    let port = if guest_port == 0 {
        kboxlike_first_listening_port(target)?
    } else {
        guest_port
    };
    kboxlike_connect_loopback(port)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_connect_loopback(port: u16) -> std::io::Result<TcpStream> {
    let timeout = Duration::from_secs(5);
    let v4 = SocketAddr::from(([127, 0, 0, 1], port));
    match TcpStream::connect_timeout(&v4, timeout) {
        Ok(stream) => {
            let _ = stream.set_nodelay(true);
            Ok(stream)
        }
        Err(v4_err) => {
            let v6 = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], port));
            match TcpStream::connect_timeout(&v6, timeout) {
                Ok(stream) => {
                    let _ = stream.set_nodelay(true);
                    Ok(stream)
                }
                Err(v6_err) => Err(std::io::Error::new(
                    v6_err.kind(),
                    format!(
                        "kboxlike bridge: connect to loopback port {port} failed: IPv4={v4_err}; IPv6={v6_err}"
                    ),
                )),
            }
        }
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_first_listening_port(runtime: &RunscRuntime) -> std::io::Result<u16> {
    let out = runsc_exec_shell(
        runtime,
        "cat /proc/net/tcp /proc/net/tcp6 2>/dev/null || true",
        None,
    )?;
    if !out.status.success() {
        return Err(runsc_io_error("runsc list listening ports", out));
    }
    parse_first_listening_port(&out.stdout).ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "runsc bridge: no listening TCP port found in the guest",
        )
    })
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_first_listening_port(target: &KboxlikePortForwardTarget) -> std::io::Result<u16> {
    let socket_inodes = kboxlike_owned_socket_inodes(&target.restored_host_pids);
    if socket_inodes.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "kboxlike bridge: no socket fds owned by the restored workload",
        ));
    }
    for pid in &target.restored_host_pids {
        let mut proc_net_tcp = Vec::new();
        for name in ["tcp", "tcp6"] {
            let path = format!("/proc/{pid}/net/{name}");
            if let Ok(bytes) = std::fs::read(path) {
                proc_net_tcp.extend_from_slice(&bytes);
                proc_net_tcp.push(b'\n');
            }
        }
        if let Some(port) = parse_first_owned_listening_port(&proc_net_tcp, &socket_inodes) {
            return Ok(port);
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::ConnectionRefused,
        "kboxlike bridge: no listening TCP port owned by the restored workload",
    ))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_owned_socket_inodes(pids: &[i32]) -> std::collections::BTreeSet<u64> {
    let mut inodes = std::collections::BTreeSet::new();
    for pid in pids {
        let fd_dir = format!("/proc/{pid}/fd");
        let Ok(entries) = std::fs::read_dir(fd_dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let Ok(target) = std::fs::read_link(entry.path()) else {
                continue;
            };
            let Some(text) = target.to_str() else {
                continue;
            };
            let Some(inner) = text
                .strip_prefix("socket:[")
                .and_then(|rest| rest.strip_suffix(']'))
            else {
                continue;
            };
            if let Ok(inode) = inner.parse::<u64>() {
                inodes.insert(inode);
            }
        }
    }
    inodes
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn parse_first_owned_listening_port(
    proc_net_tcp: &[u8],
    socket_inodes: &std::collections::BTreeSet<u64>,
) -> Option<u16> {
    let text = String::from_utf8_lossy(proc_net_tcp);
    for line in text.lines() {
        let mut fields = line.split_whitespace();
        let _slot = fields.next()?;
        let local = fields.next()?;
        let _remote = fields.next()?;
        let state = fields.next()?;
        if state != "0A" {
            continue;
        }
        for _ in 0..5 {
            fields.next()?;
        }
        let inode = fields.next()?.parse::<u64>().ok()?;
        if !socket_inodes.contains(&inode) {
            continue;
        }
        let Some((_addr, port_hex)) = local.rsplit_once(':') else {
            continue;
        };
        let Ok(port) = u16::from_str_radix(port_hex, 16) else {
            continue;
        };
        if port != 0 {
            return Some(port);
        }
    }
    None
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn parse_first_listening_port(proc_net_tcp: &[u8]) -> Option<u16> {
    let text = String::from_utf8_lossy(proc_net_tcp);
    for line in text.lines() {
        let mut fields = line.split_whitespace();
        let _slot = fields.next()?;
        let local = fields.next()?;
        let _remote = fields.next()?;
        let state = fields.next()?;
        if state != "0A" {
            continue;
        }
        let Some((_addr, port_hex)) = local.rsplit_once(':') else {
            continue;
        };
        let Ok(port) = u16::from_str_radix(port_hex, 16) else {
            continue;
        };
        if port != 0 {
            return Some(port);
        }
    }
    None
}

/// Dial the persistent sentry supervisor's raw LoopNet bridge. The request starts
/// as one exec-wire frame; after the one-byte ack the same UnixStream carries raw
/// workload bytes in both directions.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn connect_port_sentry(exec_path: &Path, guest_port: u16) -> std::io::Result<UnixStream> {
    let mut stream = UnixStream::connect(exec_path)?;
    let mut frame = [0u8; 7];
    frame[0] = 0xfd; // EW_BRIDGE
    frame[1..5].copy_from_slice(&2u32.to_be_bytes());
    frame[5..7].copy_from_slice(&guest_port.to_be_bytes());
    stream.write_all(&frame)?;
    let mut ack = [0u8; 1];
    stream.read_exact(&mut ack)?;
    if ack[0] != 1 {
        let dst = if guest_port == 0 {
            "first listener".to_string()
        } else {
            format!("guest port {guest_port}")
        };
        return Err(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            format!("sentry bridge: no listener on {dst}"),
        ));
    }
    Ok(stream)
}

/// Generic byte pump from `r` → `w` until EOF or error. We use
/// `Read + Write` trait objects via concrete types so this works
/// for both TcpStream and UnixStream. Half-close on EOF: the writer
/// gets shutdown so the peer of `w` sees the FIN.
fn pump<R, W>(mut r: R, mut w: W) -> std::io::Result<()>
where
    R: Read,
    W: Write + Shutdownable,
{
    let mut buf = [0u8; 16 * 1024];
    loop {
        let n = match r.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(e),
        };
        w.write_all(&buf[..n])?
    }
    let _ = w.shutdown_write();
    Ok(())
}

/// Trait letting `pump` call `shutdown(Write)` on either a
/// `TcpStream` or a `UnixStream` without dynamic dispatch.
trait Shutdownable {
    fn shutdown_write(&mut self) -> std::io::Result<()>;
}

impl Shutdownable for TcpStream {
    fn shutdown_write(&mut self) -> std::io::Result<()> {
        TcpStream::shutdown(self, std::net::Shutdown::Write)
    }
}

impl Shutdownable for UnixStream {
    fn shutdown_write(&mut self) -> std::io::Result<()> {
        UnixStream::shutdown(self, std::net::Shutdown::Write)
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
impl Shutdownable for ChildStdin {
    fn shutdown_write(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

fn unique_suffix() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    nanos.wrapping_add(COUNTER.fetch_add(1, Ordering::Relaxed))
}

/// Tiny RFC 3339 timestamp formatter — used by [`Vm::snapshot`]'s
/// metadata. Avoids pulling in `chrono` for a single timestamp.
/// Recursive on-disk size of a directory tree (regular files only; best-effort,
/// errors skipped). Used for the sentry image's `snapshot_physical_bytes` so
/// `supermachine images` can show a SIZE without a backend-specific probe.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn dir_size_bytes(dir: &Path) -> u64 {
    let mut total = 0u64;
    let mut stack = vec![dir.to_path_buf()];
    while let Some(d) = stack.pop() {
        let Ok(rd) = std::fs::read_dir(&d) else {
            continue;
        };
        for entry in rd.flatten() {
            let Ok(ft) = entry.file_type() else { continue };
            if ft.is_dir() {
                stack.push(entry.path());
            } else if ft.is_file() {
                if let Ok(m) = entry.metadata() {
                    total += m.len();
                }
            }
        }
    }
    total
}

/// Parse an OCI `User` string into a numeric `(uid, gid)` for the sentry's
/// uid-drop. Accepts only the numeric forms — `"1000"` (gid := uid) and
/// `"1000:1000"` / `"1000:1000:1000"` (a trailing supplementary-group field, if
/// any, is ignored). Returns `None` for a username (no passwd lookup in the
/// sentry), an empty string, or `root`/`0` (a no-op drop the supervisor skips).
/// Whitespace is trimmed; a non-numeric component yields `None` (best-effort:
/// the guest just runs at the sentry's own uid).
fn parse_numeric_user(user: &str) -> Option<(u32, u32)> {
    let user = user.trim();
    if user.is_empty() || user == "root" {
        return None;
    }
    let mut parts = user.split(':');
    let uid: u32 = parts.next()?.trim().parse().ok()?;
    let gid: u32 = match parts.next() {
        Some(g) => g.trim().parse().ok()?,
        None => uid,
    };
    if uid == 0 {
        return None;
    }
    Some((uid, gid))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_bin_path() -> PathBuf {
    std::env::var_os("SUPERMACHINE_RUNSC_BIN")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("runsc"))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_warmup_checkpoint(
    image: &Image,
    dest: &Path,
    warmup: Box<dyn FnOnce(&Vm) -> Result<(), Error> + Send>,
) -> Result<(), Error> {
    let parts = image
        .runsc
        .as_ref()
        .ok_or_else(|| Error::vm_msg("runsc warmup image missing runsc metadata"))?;
    let runsc_bin = runsc_bin_path();
    let runtime_dir = std::env::temp_dir().join(format!(
        "supermachine-runsc-warmup-{}-{}",
        std::process::id(),
        unique_suffix()
    ));
    let bundle_dir = runtime_dir.join("bundle");
    let runsc_root = runtime_dir.join("runsc-root");
    let pid_file = runtime_dir.join("container.pid");
    let checkpoint_dir = dest.join("runsc-checkpoint");
    let container_id = format!("sm-runsc-warmup-{}-{}", std::process::id(), unique_suffix());
    std::fs::create_dir_all(&runsc_root).map_err(Error::Io)?;
    let cleanup_dir = |err: Error, runtime_dir: &Path| -> Error {
        let _ = std::fs::remove_dir_all(runtime_dir);
        err
    };
    let network = crate::exec::RUNSC_NETWORK_SANDBOX.to_owned();
    let build_netns = RunscBuildNetwork::create().map_err(|e| cleanup_dir(e, &runtime_dir))?;
    let netns_path = build_netns.path();
    write_runsc_bundle_config(
        &runsc_bin,
        parts,
        &bundle_dir,
        &parts.rootfs,
        &network,
        Some(&netns_path),
    )
    .map_err(|e| cleanup_dir(e, &runtime_dir))?;
    runsc_run_detached(
        &runsc_bin,
        &runsc_root,
        &network,
        &bundle_dir,
        &pid_file,
        &container_id,
    )
    .map_err(|e| cleanup_dir(e, &runtime_dir))?;

    let vm = Vm {
        running: None,
        sentry_exec: None,
        sentry_src_rootfs: None,
        vsock_mux_path: runtime_dir.join("runsc-unwired.sock"),
        vsock_exec_path: runtime_dir.join("runsc-exec-unwired.sock"),
        own_vsock_mux_dir: None,
        skip_cleanup: false,
        time_sync_stop: Arc::new(AtomicBool::new(false)),
        _sentry_mem_admission: None,
        sentry_warm_pool: None,
        sentry_unified_pool: None,
        runsc: Some(RunscRuntime {
            runsc_bin: runsc_bin.clone(),
            runsc_root: runsc_root.clone(),
            network: network.clone(),
            build_netns: Some(build_netns),
            container_id: container_id.clone(),
            bundle_dir: bundle_dir.clone(),
            rootfs: parts.rootfs.clone(),
            parts: parts.clone(),
            file_agent_exec: true,
        }),
        kboxlike: None,
    };

    let warmup_res = warmup(&vm);
    if warmup_res.is_ok() {
        let _ = std::fs::remove_dir_all(&checkpoint_dir);
        std::fs::create_dir_all(&checkpoint_dir).map_err(Error::Io)?;
        runsc_checkpoint(
            &runsc_bin,
            &runsc_root,
            &network,
            &checkpoint_dir,
            &container_id,
        )?;
    }
    drop(vm);
    warmup_res?;

    let meta_path = dest.join("metadata.json");
    let meta_text = std::fs::read_to_string(&meta_path)
        .map_err(|e| Error::bake_msg(format!("read {}: {e}", meta_path.display())))?;
    let mut meta: serde_json::Value = serde_json::from_str(&meta_text)
        .map_err(|e| Error::bake_msg(format!("parse {}: {e}", meta_path.display())))?;
    if let Some(obj) = meta.as_object_mut() {
        obj.insert(
            "runsc_checkpoint".to_owned(),
            serde_json::json!(checkpoint_dir.to_string_lossy()),
        );
    }
    let meta_out = serde_json::to_string_pretty(&meta)
        .map_err(|e| Error::bake_msg(format!("runsc metadata serialize: {e}")))?;
    std::fs::write(&meta_path, meta_out).map_err(Error::Io)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn prepare_runsc_bundle(
    runsc_bin: &Path,
    parts: &RunscImageParts,
    bundle_dir: &Path,
    rootfs: &Path,
    network: &str,
    netns_path: Option<&Path>,
) -> Result<(), Error> {
    std::fs::create_dir_all(bundle_dir).map_err(Error::Io)?;
    copy_dir_recursive(&parts.rootfs, rootfs)
        .map_err(|e| Error::vm_msg(format!("runsc rootfs clone: {e}")))?;
    write_runsc_bundle_config(runsc_bin, parts, bundle_dir, rootfs, network, netns_path)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn prepare_runsc_restore_rootfs(
    base_rootfs: &Path,
    runtime_dir: &Path,
    rootfs: &Path,
) -> Result<(), Error> {
    let upper = runtime_dir.join("overlay-upper");
    let work = runtime_dir.join("overlay-work");
    std::fs::create_dir_all(rootfs).map_err(Error::Io)?;
    std::fs::create_dir_all(&upper).map_err(Error::Io)?;
    std::fs::create_dir_all(&work).map_err(Error::Io)?;
    let opts = format!(
        "lowerdir={},upperdir={},workdir={}",
        base_rootfs.display(),
        upper.display(),
        work.display()
    );
    match Command::new("mount")
        .args(["-t", "overlay", "overlay", "-o", &opts])
        .arg(rootfs)
        .status()
    {
        Ok(status) if status.success() => Ok(()),
        Ok(status) => {
            eprintln!(
                "supermachine(runsc): overlay rootfs mount failed with status {:?}; \
                 falling back to full rootfs copy",
                status.code()
            );
            let _ = std::fs::remove_dir_all(rootfs);
            let _ = std::fs::remove_dir_all(&upper);
            let _ = std::fs::remove_dir_all(&work);
            copy_dir_recursive(base_rootfs, rootfs)
                .map_err(|e| Error::vm_msg(format!("runsc restore rootfs clone: {e}")))
        }
        Err(e) => {
            eprintln!(
                "supermachine(runsc): overlay rootfs mount failed ({e}); \
                 falling back to full rootfs copy"
            );
            let _ = std::fs::remove_dir_all(rootfs);
            let _ = std::fs::remove_dir_all(&upper);
            let _ = std::fs::remove_dir_all(&work);
            copy_dir_recursive(base_rootfs, rootfs)
                .map_err(|e| Error::vm_msg(format!("runsc restore rootfs clone: {e}")))
        }
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_runsc_bundle_config(
    runsc_bin: &Path,
    parts: &RunscImageParts,
    bundle_dir: &Path,
    rootfs: &Path,
    network: &str,
    netns_path: Option<&Path>,
) -> Result<(), Error> {
    std::fs::create_dir_all(bundle_dir).map_err(Error::Io)?;
    ensure_runsc_mountpoints(parts, rootfs)?;
    ensure_runsc_resolver(rootfs, network)?;
    ensure_runsc_file_agent(rootfs)?;
    let spec = Command::new(runsc_bin)
        .arg("spec")
        .current_dir(bundle_dir)
        .output()
        .map_err(|e| Error::vm_msg(format!("runsc spec: {e}")))?;
    if !spec.status.success() {
        return Err(Error::vm_msg(format!(
            "runsc spec failed with status {:?}: {}",
            spec.status.code(),
            String::from_utf8_lossy(&spec.stderr)
        )));
    }
    let config_path = bundle_dir.join("config.json");
    let config_text = std::fs::read_to_string(&config_path)
        .map_err(|e| Error::vm_msg(format!("read runsc config.json: {e}")))?;
    let mut spec_json: serde_json::Value = serde_json::from_str(&config_text)
        .map_err(|e| Error::vm_msg(format!("parse runsc config.json: {e}")))?;
    patch_runsc_spec(&mut spec_json, parts, rootfs, network, netns_path)?;
    let spec_out = serde_json::to_string_pretty(&spec_json)
        .map_err(|e| Error::vm_msg(format!("serialize runsc config.json: {e}")))?;
    std::fs::write(&config_path, spec_out)
        .map_err(|e| Error::vm_msg(format!("write runsc config.json: {e}")))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn ensure_runsc_file_agent(rootfs: &Path) -> Result<(), Error> {
    let dir = rootfs.join(".supermachine");
    std::fs::create_dir_all(dir.join("runsc-exec/requests")).map_err(|e| {
        Error::vm_msg(format!(
            "create runsc file-agent dir {}: {e}",
            dir.display()
        ))
    })?;
    let script_path = dir.join("runsc-file-agent.sh");
    let script = r#"#!/bin/sh
set +e
DIR=/.supermachine/runsc-exec
mkdir -p "$DIR/requests" /run
if [ -f /.supermachine/run-workload ]; then
  /bin/sh /.supermachine/run-workload &
  echo $! >/run/supermachine-workload.pid
fi
while :; do
  for req in "$DIR"/requests/*; do
    [ -d "$req" ] || continue
    [ -f "$req/ready" ] || continue
    [ ! -f "$req/done" ] || continue
    /bin/sh "$req/script" >"$req/stdout" 2>"$req/stderr"
    rc=$?
    echo "$rc" >"$req/status"
    echo 1 >"$req/done"
  done
  sleep 0.05
done
"#;
    std::fs::write(&script_path, script).map_err(|e| {
        Error::vm_msg(format!(
            "write runsc file-agent {}: {e}",
            script_path.display()
        ))
    })?;
    let mut perms = std::fs::metadata(&script_path)
        .map_err(Error::Io)?
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(&script_path, perms).map_err(Error::Io)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn ensure_runsc_mountpoints(parts: &RunscImageParts, rootfs: &Path) -> Result<(), Error> {
    for mount in &parts.mounts {
        let rel = mount.guest_path.trim_start_matches('/');
        let target = confined_rootfs_join(rootfs, rel).ok_or_else(|| {
            Error::vm_msg(format!(
                "runsc mount guest path escapes the rootfs: {:?}",
                mount.guest_path
            ))
        })?;
        std::fs::create_dir_all(&target).map_err(|e| {
            Error::vm_msg(format!("create runsc mountpoint {}: {e}", target.display()))
        })?;
    }
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn ensure_runsc_resolver(rootfs: &Path, network: &str) -> Result<(), Error> {
    if network != crate::exec::RUNSC_NETWORK_SANDBOX {
        return Ok(());
    }
    let Some(text) = host_resolv_conf_for_runsc() else {
        return Ok(());
    };
    let target = confined_rootfs_join(rootfs, "etc/resolv.conf")
        .ok_or_else(|| Error::vm_msg("runsc resolver path escaped rootfs".to_owned()))?;
    if let Some(parent) = target.parent() {
        std::fs::create_dir_all(parent).map_err(Error::Io)?;
    }
    std::fs::write(&target, text)
        .map_err(|e| Error::vm_msg(format!("write runsc resolver {}: {e}", target.display())))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn host_resolv_conf_for_runsc() -> Option<String> {
    for path in ["/run/systemd/resolve/resolv.conf", "/etc/resolv.conf"] {
        let Ok(text) = std::fs::read_to_string(path) else {
            continue;
        };
        if let Some(text) = sanitize_runsc_resolver(&text) {
            return Some(text);
        }
    }
    None
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sanitize_runsc_resolver(text: &str) -> Option<String> {
    let nameserver = text.lines().find_map(|line| {
        let mut fields = line.split_whitespace();
        if !matches!(fields.next(), Some("nameserver")) {
            return None;
        }
        let addr = fields.next()?;
        if addr.starts_with("127.") || addr == "::1" || addr.eq_ignore_ascii_case("localhost") {
            return None;
        }
        if addr.contains(':') {
            return None;
        }
        Some(addr.to_owned())
    })?;

    Some(format!(
        "# generated by supermachine for runsc build networking\nnameserver {nameserver}\noptions single-request no-aaaa\n"
    ))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn copy_runsc_bundle_config(
    base_bundle_dir: &Path,
    bundle_dir: &Path,
    parts: &RunscImageParts,
    rootfs: &Path,
    network: &str,
    netns_path: Option<&Path>,
) -> Result<(), Error> {
    std::fs::create_dir_all(bundle_dir).map_err(Error::Io)?;
    let config_path = base_bundle_dir.join("config.json");
    let config_text = std::fs::read_to_string(&config_path)
        .map_err(|e| Error::vm_msg(format!("read base runsc config.json: {e}")))?;
    let mut spec_json: serde_json::Value = serde_json::from_str(&config_text)
        .map_err(|e| Error::vm_msg(format!("parse base runsc config.json: {e}")))?;
    ensure_runsc_mountpoints(parts, rootfs)?;
    ensure_runsc_resolver(rootfs, network)?;
    patch_runsc_spec(&mut spec_json, parts, rootfs, network, netns_path)?;
    let spec_out = serde_json::to_string_pretty(&spec_json)
        .map_err(|e| Error::vm_msg(format!("serialize restore runsc config.json: {e}")))?;
    std::fs::write(bundle_dir.join("config.json"), spec_out)
        .map_err(|e| Error::vm_msg(format!("write restore runsc config.json: {e}")))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_run_detached(
    runsc_bin: &Path,
    runsc_root: &Path,
    network: &str,
    bundle_dir: &Path,
    pid_file: &Path,
    container_id: &str,
) -> Result<(), Error> {
    let mut run = Command::new(runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut run, runsc_root, network);
    let status = run
        .arg("run")
        .arg("-detach")
        .arg("-bundle")
        .arg(bundle_dir)
        .arg("-pid-file")
        .arg(pid_file)
        .arg(container_id)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|e| Error::vm_msg(format!("runsc run {container_id}: {e}")))?;
    if status.success() {
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "runsc run failed with status {:?}",
            status.code()
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_checkpoint(
    runsc_bin: &Path,
    runsc_root: &Path,
    network: &str,
    checkpoint_dir: &Path,
    container_id: &str,
) -> Result<(), Error> {
    runsc_checkpoint_with_options(
        runsc_bin,
        runsc_root,
        network,
        checkpoint_dir,
        container_id,
        false,
    )
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_checkpoint_with_options(
    runsc_bin: &Path,
    runsc_root: &Path,
    network: &str,
    checkpoint_dir: &Path,
    container_id: &str,
    leave_running: bool,
) -> Result<(), Error> {
    let mut cmd = Command::new(runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut cmd, runsc_root, network);
    cmd.arg("checkpoint").arg("-image-path").arg(checkpoint_dir);
    if leave_running {
        cmd.arg("-leave-running");
    }
    let out = cmd
        .arg(container_id)
        .output()
        .map_err(|e| Error::vm_msg(format!("runsc checkpoint {container_id}: {e}")))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "runsc checkpoint{} failed with status {:?}: {}",
            if leave_running { " -leave-running" } else { "" },
            out.status.code(),
            String::from_utf8_lossy(&out.stderr)
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_restore_detached(
    runsc_bin: &Path,
    runsc_root: &Path,
    network: &str,
    bundle_dir: &Path,
    checkpoint_dir: &Path,
    pid_file: &Path,
    container_id: &str,
) -> Result<(), Error> {
    let mut cmd = Command::new(runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut cmd, runsc_root, network);
    let status = cmd
        .arg("restore")
        .arg("-detach")
        .arg("-bundle")
        .arg(bundle_dir)
        .arg("-image-path")
        .arg(checkpoint_dir)
        .arg("-pid-file")
        .arg(pid_file)
        .arg(container_id)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|e| Error::vm_msg(format!("runsc restore {container_id}: {e}")))?;
    if status.success() {
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "runsc restore failed with status {:?}",
            status.code()
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_delete_force(
    runsc_bin: &Path,
    runsc_root: &Path,
    network: &str,
    container_id: &str,
) -> Result<(), Error> {
    let mut kill = Command::new(runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut kill, runsc_root, network);
    let _ = kill.arg("kill").arg(container_id).arg("KILL").status();

    let mut delete = Command::new(runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(&mut delete, runsc_root, network);
    let status = delete
        .arg("delete")
        .arg("-force")
        .arg(container_id)
        .status()
        .map_err(|e| Error::vm_msg(format!("runsc delete {container_id}: {e}")))?;
    if status.success() {
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "runsc delete failed with status {:?}",
            status.code()
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_exec_shell(
    runtime: &RunscRuntime,
    script: &str,
    stdin_bytes: Option<&[u8]>,
) -> std::io::Result<std::process::Output> {
    let mut cmd = Command::new(&runtime.runsc_bin);
    crate::exec::add_runsc_global_flags_with_network(
        &mut cmd,
        &runtime.runsc_root,
        &runtime.network,
    );
    cmd.arg("exec")
        .arg(&runtime.container_id)
        .arg("/bin/sh")
        .arg("-c")
        .arg(script)
        .stdin(if stdin_bytes.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().map_err(|e| {
        std::io::Error::new(
            e.kind(),
            format!("runsc exec {} for control RPC: {e}", runtime.container_id),
        )
    })?;
    if let Some(bytes) = stdin_bytes {
        let mut stdin = child.stdin.take().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "runsc exec stdin was not available",
            )
        })?;
        stdin.write_all(bytes)?;
    }
    child.wait_with_output()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_io_error(action: &str, out: std::process::Output) -> std::io::Error {
    let detail = String::from_utf8_lossy(&out.stderr).trim().to_owned();
    std::io::Error::new(
        std::io::ErrorKind::Other,
        if detail.is_empty() {
            format!("{action} failed with status {:?}", out.status.code())
        } else {
            format!(
                "{action} failed with status {:?}: {detail}",
                out.status.code()
            )
        },
    )
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_write_file(runtime: &RunscRuntime, path: &str, bytes: &[u8]) -> std::io::Result<()> {
    let q = sh_quote_runsc(path);
    let script = format!(
        r#"set -e
p={q}
d=$(dirname -- "$p")
b=$(basename -- "$p")
tmp="$d/.${{b}}.supermachine.$$"
rm -f "$tmp"
cat > "$tmp"
chmod 0644 "$tmp" 2>/dev/null || true
mv -f "$tmp" "$p"
"#
    );
    let out = runsc_exec_shell(runtime, &script, Some(bytes))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(runsc_io_error("runsc write_file", out))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_read_file(runtime: &RunscRuntime, path: &str, max_bytes: u64) -> std::io::Result<Vec<u8>> {
    let cap = max_bytes.saturating_add(1);
    let q = sh_quote_runsc(path);
    let script = format!(
        r#"set -e
p={q}
if [ ! -f "$p" ]; then
  echo "read_file: not a regular file: $p" >&2
  exit 1
fi
size=$(wc -c < "$p" | tr -d ' ')
if [ "$size" -gt "{max_bytes}" ]; then
  echo "read_file: file exceeds max_bytes ($size > {max_bytes})" >&2
  exit 1
fi
head -c {cap} -- "$p"
"#
    );
    let out = runsc_exec_shell(runtime, &script, None)?;
    if !out.status.success() {
        return Err(runsc_io_error("runsc read_file", out));
    }
    if out.stdout.len() as u64 > max_bytes {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "read_file: file exceeds max_bytes ({} > {max_bytes})",
                out.stdout.len()
            ),
        ));
    }
    Ok(out.stdout)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_rootfs_join_io(rootfs: &Path, guest_path: &str) -> std::io::Result<PathBuf> {
    let rel = guest_path.strip_prefix('/').unwrap_or(guest_path);
    let p = Path::new(rel);
    if rel.is_empty()
        || p.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir | std::path::Component::RootDir
            )
        })
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("guest path escapes rootfs: {guest_path}"),
        ));
    }
    Ok(rootfs.join(p))
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_write_file(runtime: &KboxlikeRuntime, path: &str, bytes: &[u8]) -> std::io::Result<()> {
    let target = kboxlike_rootfs_join_io(&runtime.rootfs, path)?;
    let parent = target.parent().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("write_file path has no parent: {path}"),
        )
    })?;
    std::fs::create_dir_all(parent)?;
    let name = target
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("write");
    let tmp = parent.join(format!(".supermachine-write-{}-{name}", std::process::id()));
    std::fs::write(&tmp, bytes)?;
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644))?;
    std::fs::rename(&tmp, target)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_read_file(
    runtime: &KboxlikeRuntime,
    path: &str,
    max_bytes: u64,
) -> std::io::Result<Vec<u8>> {
    let target = kboxlike_rootfs_join_io(&runtime.rootfs, path)?;
    let meta = std::fs::metadata(&target)?;
    if !meta.is_file() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("read_file: not a regular file: {path}"),
        ));
    }
    if meta.len() > max_bytes {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "read_file: file exceeds max_bytes ({} > {max_bytes})",
                meta.len()
            ),
        ));
    }
    std::fs::read(target)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_workload_signal(runtime: &RunscRuntime, signum: i32) -> std::io::Result<()> {
    let script = format!(
        r#"set -e
pid=$(cat /run/supermachine-workload.pid)
kill -s {signum} "$pid"
"#
    );
    let out = runsc_exec_shell(runtime, &script, None)?;
    if out.status.success() {
        Ok(())
    } else {
        Err(runsc_io_error("runsc workload_signal", out))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn kboxlike_workload_signal(runtime: &KboxlikeRuntime, signum: i32) -> std::io::Result<()> {
    let Some(pid) = runtime.restored_host_pids.first().copied() else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "kboxlike workload has no restored host pid",
        ));
    };
    let ret = unsafe { libc::kill(pid, signum) };
    if ret == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn sh_quote_runsc(s: &str) -> String {
    let mut out = String::from("'");
    for ch in s.chars() {
        if ch == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(ch);
        }
    }
    out.push('\'');
    out
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn patch_runsc_spec(
    spec: &mut serde_json::Value,
    parts: &RunscImageParts,
    rootfs: &Path,
    network: &str,
    netns_path: Option<&Path>,
) -> Result<(), Error> {
    let root = spec
        .get_mut("root")
        .and_then(|v| v.as_object_mut())
        .ok_or_else(|| Error::vm_msg("runsc config.json missing root object".to_owned()))?;
    root.insert(
        "path".to_owned(),
        serde_json::json!(rootfs.to_string_lossy().to_string()),
    );
    root.insert("readonly".to_owned(), serde_json::json!(false));

    let process = spec
        .get_mut("process")
        .and_then(|v| v.as_object_mut())
        .ok_or_else(|| Error::vm_msg("runsc config.json missing process object".to_owned()))?;
    let mut env: Vec<String> = parts
        .image_env
        .iter()
        .map(|(k, v)| format!("{k}={v}"))
        .collect();
    if !parts.image_env.iter().any(|(k, _)| k == "PATH") {
        env.push("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_owned());
    }
    process.insert("env".to_owned(), serde_json::json!(env));
    process.insert("cwd".to_owned(), serde_json::json!("/"));
    process.insert(
        "args".to_owned(),
        serde_json::json!(["/bin/sh", "/.supermachine/runsc-file-agent.sh"]),
    );
    if let Some((uid, gid)) = parts.user {
        process.insert(
            "user".to_owned(),
            serde_json::json!({
                "uid": uid,
                "gid": gid,
            }),
        );
    }
    let caps = serde_json::json!([
        "CAP_AUDIT_WRITE",
        "CAP_CHOWN",
        "CAP_DAC_OVERRIDE",
        "CAP_FOWNER",
        "CAP_KILL",
        "CAP_NET_BIND_SERVICE",
        "CAP_SETGID",
        "CAP_SETUID"
    ]);
    process.insert(
        "capabilities".to_owned(),
        serde_json::json!({
            "bounding": caps,
            "effective": caps,
            "inheritable": caps,
            "permitted": caps,
        }),
    );
    process.insert("terminal".to_owned(), serde_json::json!(false));

    if network == crate::exec::RUNSC_NETWORK_SANDBOX {
        patch_runsc_network_namespace(spec, netns_path)?;
    }

    if !parts.mounts.is_empty() {
        let mounts = spec
            .get_mut("mounts")
            .and_then(|v| v.as_array_mut())
            .ok_or_else(|| Error::vm_msg("runsc config.json missing mounts array".to_owned()))?;
        for mount in &parts.mounts {
            // runsc has no virtio-fs symlink-policy hook. The backend-level
            // parity here is the host-dir-at-guest-path mapping; policy-specific
            // enforcement needs a later runsc file-access adapter.
            let opts = if mount.read_only {
                vec!["rbind", "ro"]
            } else {
                vec!["rbind", "rw"]
            };
            mounts.push(serde_json::json!({
                "destination": mount.guest_path,
                "type": "bind",
                "source": mount.host_path,
                "options": opts,
            }));
        }
    }
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn patch_runsc_network_namespace(
    spec: &mut serde_json::Value,
    netns_path: Option<&Path>,
) -> Result<(), Error> {
    let Some(namespaces) = spec
        .get_mut("linux")
        .and_then(|v| v.get_mut("namespaces"))
        .and_then(|v| v.as_array_mut())
    else {
        return Ok(());
    };
    let Some(netns_path) = netns_path else {
        return Ok(());
    };
    for ns in namespaces {
        if ns
            .get("type")
            .and_then(|v| v.as_str())
            .map(|ty| ty == "network")
            .unwrap_or(false)
        {
            ns["path"] = serde_json::json!(netns_path.to_string_lossy().to_string());
            return Ok(());
        }
    }
    Ok(())
}

/// Recursively copy `src` → `dst`, preserving directories (+ perms), symlinks
/// (not followed), regular files (+ perms), and **hardlinks** (same `(dev,ino)`
/// → a single `hard_link`, so busybox's ~hundreds of applet links don't bloat
/// the copy). Regular files try a reflink (`clonefile_one`) first and fall back
/// to a byte copy. Non-regular/non-symlink entries (sockets, fifos, devices) are
/// skipped — a sentry rootfs doesn't ship them. Backs the sentry `Vm::snapshot`.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
    use std::collections::HashMap;
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::MetadataExt;
    fn set_owner(path: &Path, uid: u32, gid: u32, follow: bool) -> std::io::Result<()> {
        let c = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
            std::io::Error::new(std::io::ErrorKind::InvalidInput, "path contains NUL")
        })?;
        let r = unsafe {
            if follow {
                libc::chown(c.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
            } else {
                libc::lchown(c.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
            }
        };
        if r == 0 {
            Ok(())
        } else {
            Err(std::io::Error::last_os_error())
        }
    }
    std::fs::create_dir_all(dst)?;
    let root_md = std::fs::symlink_metadata(src)?;
    let _ = std::fs::set_permissions(dst, root_md.permissions());
    set_owner(dst, root_md.uid(), root_md.gid(), true)?;
    let mut hardlinks: HashMap<(u64, u64), PathBuf> = HashMap::new();
    let mut stack = vec![(src.to_path_buf(), dst.to_path_buf())];
    while let Some((s, d)) = stack.pop() {
        for entry in std::fs::read_dir(&s)? {
            let entry = entry?;
            let sp = entry.path();
            let dp = d.join(entry.file_name());
            let md = std::fs::symlink_metadata(&sp)?;
            let ft = md.file_type();
            if ft.is_dir() {
                std::fs::create_dir_all(&dp)?;
                let _ = std::fs::set_permissions(&dp, md.permissions());
                set_owner(&dp, md.uid(), md.gid(), true)?;
                stack.push((sp, dp));
            } else if ft.is_symlink() {
                let target = std::fs::read_link(&sp)?;
                let _ = std::fs::remove_file(&dp);
                std::os::unix::fs::symlink(&target, &dp)?;
                set_owner(&dp, md.uid(), md.gid(), false)?;
            } else if ft.is_file() {
                // Preserve hardlinks: re-link to the first copy of this inode.
                if md.nlink() > 1 {
                    let key = (md.dev(), md.ino());
                    if let Some(first) = hardlinks.get(&key) {
                        let _ = std::fs::remove_file(&dp);
                        std::fs::hard_link(first, &dp)?;
                        set_owner(&dp, md.uid(), md.gid(), true)?;
                        continue;
                    }
                    hardlinks.insert(key, dp.clone());
                }
                if crate::bake::clonefile_one(&sp, &dp).is_err() {
                    let _ = std::fs::remove_file(&dp);
                    std::fs::copy(&sp, &dp)?;
                }
                set_owner(&dp, md.uid(), md.gid(), true)?;
            }
            // else: socket/fifo/device — skip (not present in a sentry rootfs).
        }
    }
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn commit_staged_snapshot_dir(staging: &Path, dest_dir: &Path) -> Result<(), Error> {
    use std::os::unix::ffi::OsStrExt;

    let staging_c = std::ffi::CString::new(staging.as_os_str().as_bytes())
        .map_err(|_| Error::vm_msg("snapshot: staging path has NUL".to_owned()))?;
    let dest_c = std::ffi::CString::new(dest_dir.as_os_str().as_bytes())
        .map_err(|_| Error::vm_msg("snapshot: dest path has NUL".to_owned()))?;
    const RENAME_EXCHANGE: libc::c_uint = 1 << 1;
    let exch = unsafe {
        libc::renameat2(
            libc::AT_FDCWD,
            staging_c.as_ptr(),
            libc::AT_FDCWD,
            dest_c.as_ptr(),
            RENAME_EXCHANGE,
        )
    };
    if exch == 0 {
        let _ = std::fs::remove_dir_all(staging);
        return Ok(());
    }

    let err = std::io::Error::last_os_error();
    if err.raw_os_error() == Some(libc::ENOENT) || !dest_dir.exists() {
        std::fs::rename(staging, dest_dir).map_err(|e| {
            Error::vm_msg(format!(
                "snapshot: atomic commit rename {} -> {}: {e}",
                staging.display(),
                dest_dir.display()
            ))
        })?;
        Ok(())
    } else {
        Err(Error::vm_msg(format!(
            "snapshot: gap-free directory exchange {} <-> {} failed: {err}",
            staging.display(),
            dest_dir.display()
        )))
    }
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn runsc_mounts_metadata(mounts: &[crate::vmm::resources::MountSpec]) -> Vec<serde_json::Value> {
    mounts
        .iter()
        .map(|m| {
            let mut obj = serde_json::Map::new();
            obj.insert("host_path".to_owned(), serde_json::json!(&m.host_path));
            obj.insert("guest_tag".to_owned(), serde_json::json!(&m.guest_tag));
            obj.insert("guest_path".to_owned(), serde_json::json!(&m.guest_path));
            if m.read_only {
                obj.insert("read_only".to_owned(), serde_json::json!(true));
            }
            match m.symlinks {
                crate::vmm::resources::SymlinkPolicy::Opaque => {}
                crate::vmm::resources::SymlinkPolicy::Deny => {
                    obj.insert("symlinks".to_owned(), serde_json::json!("deny"));
                }
                crate::vmm::resources::SymlinkPolicy::Follow => {
                    obj.insert("symlinks".to_owned(), serde_json::json!("follow"));
                }
            }
            serde_json::Value::Object(obj)
        })
        .collect()
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_runsc_snapshot_dir(
    runtime: &RunscRuntime,
    dest_dir: &Path,
    source: &str,
    leave_running: bool,
) -> Result<Image, Error> {
    if dest_dir == runtime.rootfs || dest_dir.starts_with(&runtime.rootfs) {
        return Err(Error::vm_msg(
            "snapshot: dest_dir must be outside the source rootfs".to_owned(),
        ));
    }
    let parent = dest_dir
        .parent()
        .ok_or_else(|| Error::vm_msg("snapshot: dest_dir must have a parent dir".to_owned()))?;
    std::fs::create_dir_all(parent).map_err(Error::Io)?;
    let staging = parent.join(format!(
        ".{}.tmp-{}-{}",
        dest_dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "snap".to_owned()),
        std::process::id(),
        unique_suffix(),
    ));
    let _ = std::fs::remove_dir_all(&staging);
    let cleanup = |e: Error, staging: &Path| -> Error {
        let _ = std::fs::remove_dir_all(staging);
        e
    };

    let staging_rootfs = staging.join("rootfs");
    let staging_checkpoint = staging.join("runsc-checkpoint");
    let checkpointed = runtime.network != crate::exec::RUNSC_NETWORK_SANDBOX;
    if checkpointed {
        std::fs::create_dir_all(&staging_checkpoint)
            .map_err(|e| cleanup(Error::Io(e), &staging))?;
        runsc_checkpoint_with_options(
            &runtime.runsc_bin,
            &runtime.runsc_root,
            &runtime.network,
            &staging_checkpoint,
            &runtime.container_id,
            leave_running,
        )
        .map_err(|e| cleanup(e, &staging))?;
    }
    copy_dir_recursive(&runtime.rootfs, &staging_rootfs).map_err(|e| {
        cleanup(
            Error::vm_msg(format!("snapshot: copy rootfs: {e}")),
            &staging,
        )
    })?;

    let mut env_obj = serde_json::Map::new();
    for (k, v) in &runtime.parts.image_env {
        env_obj.insert(k.clone(), serde_json::json!(v));
    }
    let user = runtime.parts.user.map(|(uid, gid)| format!("{uid}:{gid}"));
    let final_rootfs = dest_dir.join("rootfs");
    let final_checkpoint = dest_dir.join("runsc-checkpoint");
    let mut metadata = serde_json::json!({
        "backend": "runsc",
        "runsc_rootfs": final_rootfs.to_string_lossy(),
        "runsc_has_workload": runtime.parts.has_workload,
        "runsc_agent_path": &runtime.parts.agent_path,
        "runsc_agent_unix_env": &runtime.parts.agent_unix_env,
        "memory_mib": runtime.parts.memory_mib,
        "vcpus": runtime.parts.vcpus,
        "image_env": serde_json::Value::Object(env_obj),
        "cmd": &runtime.parts.cmd,
        "user": user,
        "warm_daemon": runtime.parts.warm_daemon,
        "mounts": runsc_mounts_metadata(&runtime.parts.mounts),
        "baked_by_version": env!("CARGO_PKG_VERSION"),
        "baked_at": chrono_rfc3339_now(),
        "source": source,
        "snapshot_physical_bytes": dir_size_bytes(&staging_rootfs) + if checkpointed { dir_size_bytes(&staging_checkpoint) } else { 0 },
    });
    if checkpointed {
        metadata["runsc_checkpoint"] = serde_json::json!(final_checkpoint.to_string_lossy());
    }
    let meta_text = serde_json::to_string_pretty(&metadata)
        .map_err(|e| cleanup(Error::vm_msg(format!("metadata serialize: {e}")), &staging))?;
    std::fs::write(staging.join("metadata.json"), meta_text)
        .map_err(|e| cleanup(Error::Io(e), &staging))?;
    std::fs::write(staging.join("restore.snap"), b"runsc-checkpoint\n")
        .map_err(|e| cleanup(Error::Io(e), &staging))?;

    commit_staged_snapshot_dir(&staging, dest_dir).map_err(|e| cleanup(e, &staging))?;
    Image::from_snapshot(dest_dir)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_kboxlike_snapshot_dir(
    runtime: &KboxlikeRuntime,
    dest_dir: &Path,
    source: &str,
) -> Result<Image, Error> {
    if dest_dir == runtime.rootfs || dest_dir.starts_with(&runtime.rootfs) {
        return Err(Error::vm_msg(
            "snapshot: dest_dir must be outside the source rootfs".to_owned(),
        ));
    }
    let parent = dest_dir
        .parent()
        .ok_or_else(|| Error::vm_msg("snapshot: dest_dir must have a parent dir".to_owned()))?;
    std::fs::create_dir_all(parent).map_err(Error::Io)?;
    let staging = parent.join(format!(
        ".{}.tmp-{}-{}",
        dest_dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "snap".to_owned()),
        std::process::id(),
        unique_suffix(),
    ));
    let _ = std::fs::remove_dir_all(&staging);
    let cleanup = |e: Error, staging: &Path| -> Error {
        let _ = std::fs::remove_dir_all(staging);
        e
    };

    let staging_rootfs = staging.join("rootfs");
    std::fs::create_dir_all(&staging).map_err(|e| cleanup(Error::Io(e), &staging))?;
    copy_dir_recursive(&runtime.rootfs, &staging_rootfs).map_err(|e| {
        cleanup(
            Error::vm_msg(format!("snapshot: copy rootfs: {e}")),
            &staging,
        )
    })?;

    let final_rootfs = dest_dir.join("rootfs");
    let mut meta = runtime
        .rootfs
        .parent()
        .map(|p| p.join("metadata.json"))
        .and_then(|p| std::fs::read(p).ok())
        .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        .unwrap_or_else(|| serde_json::json!({ "backend": "kboxlike" }));
    if let Some(obj) = meta.as_object_mut() {
        obj.insert("backend".to_owned(), serde_json::json!("kboxlike"));
        obj.insert(
            "kboxlike_rootfs".to_owned(),
            serde_json::json!(final_rootfs.to_string_lossy()),
        );
        obj.insert(
            "kboxlike_has_workload".to_owned(),
            serde_json::json!(runtime.parts.has_workload),
        );
        obj.insert(
            "memory_mib".to_owned(),
            serde_json::json!(runtime.parts.memory_mib),
        );
        obj.insert("vcpus".to_owned(), serde_json::json!(runtime.parts.vcpus));
        obj.insert(
            "baked_by_version".to_owned(),
            serde_json::json!(env!("CARGO_PKG_VERSION")),
        );
        obj.insert(
            "baked_at".to_owned(),
            serde_json::json!(chrono_rfc3339_now()),
        );
        obj.insert("source".to_owned(), serde_json::json!(source));
        obj.insert(
            "snapshot_physical_bytes".to_owned(),
            serde_json::json!(dir_size_bytes(&staging_rootfs)),
        );
    }
    let meta_text = serde_json::to_string_pretty(&meta)
        .map_err(|e| cleanup(Error::vm_msg(format!("metadata serialize: {e}")), &staging))?;
    std::fs::write(staging.join("metadata.json"), meta_text)
        .map_err(|e| cleanup(Error::Io(e), &staging))?;
    std::fs::write(staging.join("restore.snap"), b"kboxlike-rootfs\n")
        .map_err(|e| cleanup(Error::Io(e), &staging))?;

    commit_staged_snapshot_dir(&staging, dest_dir).map_err(|e| cleanup(e, &staging))?;
    Image::from_snapshot(dest_dir)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn remove_dir_contents(dir: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dir)?;
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        let md = std::fs::symlink_metadata(&path)?;
        if md.file_type().is_dir() {
            std::fs::remove_dir_all(&path)?;
        } else {
            std::fs::remove_file(&path)?;
        }
    }
    Ok(())
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn replace_dir_contents_from_staging(staging: &Path, dst: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dst)?;
    remove_dir_contents(dst)?;
    for entry in std::fs::read_dir(staging)? {
        let entry = entry?;
        std::fs::rename(entry.path(), dst.join(entry.file_name()))?;
    }
    std::fs::remove_dir_all(staging)?;
    Ok(())
}

/// Capture a sentry warm rootfs into a self-contained snapshot image dir:
/// recursively copy `src_rootfs` → `dest_dir/rootfs` and re-emit a
/// `"backend":"sentry"` `metadata.json` (repointing `sentry_rootfs` to the copy,
/// restamping `baked_at`/`source`/`baked_by_version`, recomputing
/// `snapshot_physical_bytes`, and preserving
/// `sentry_has_workload`/`image_env`/`cmd`/… from the SOURCE's metadata, which is
/// the sibling of `src_rootfs`). Returns the loaded [`Image`].
///
/// Non-consuming + side-effect-free w.r.t. the caller's `Vm`/pool: it neither
/// stops the exec server nor unlinks sockets, so both the consuming cold-path
/// [`Vm::snapshot`] and the non-consuming pooled [`PooledVm::snapshot`] can share
/// it. The source rootfs is left intact (the live VM / pool keeps running).
///
/// The sentry writes straight to the host rootfs dir (no guest-kernel page
/// cache), so no fsync is needed; this is a point-in-time copy — call it after
/// your warming exec has returned.
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_sentry_snapshot_dir(
    src_rootfs: &Path,
    dest_dir: &Path,
    source: &str,
) -> Result<Image, Error> {
    write_sentry_snapshot_dir_inner(src_rootfs, dest_dir, source, false, None, None)
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn write_sentry_snapshot_dir_inner(
    src_rootfs: &Path,
    dest_dir: &Path,
    source: &str,
    allow_warm_daemon: bool,
    memory_mib: Option<u32>,
    vcpus: Option<u32>,
) -> Result<Image, Error> {
    if dest_dir == src_rootfs || dest_dir.starts_with(src_rootfs) {
        return Err(Error::vm_msg(
            "snapshot: dest_dir must be outside the source rootfs".to_owned(),
        ));
    }
    // Defense-in-depth gate (metadata-driven; covers the cold Vm::start ->
    // Vm::snapshot path that bypasses the typed SentryPool.warm_daemon check): a
    // warm-daemon image's warm state is a LIVE parked cell, not the rootfs dir, so a
    // cold rootfs copy would silently emit an un-warm image. Refuse UP FRONT (before
    // copying the whole rootfs). The bare {"backend":"sentry"} fallback has no
    // warm_daemon key, so cold/derived images stay snapshottable.
    if !allow_warm_daemon
        && src_rootfs
            .parent()
            .map(|p| p.join("metadata.json"))
            .and_then(|p| std::fs::read(p).ok())
            .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
            .and_then(|m| m.get("warm_daemon").and_then(|v| v.as_bool()))
            == Some(true)
    {
        return Err(Error::vm_msg(
            "snapshot: source image is a warm-daemon image; cold rootfs capture would \
             drop the live warm cell (unsupported)"
                .to_owned(),
        ));
    }
    // ATOMIC COMMIT (concurrent-build rootfs race, task_96ba9a6d): a sentry
    // layer-cache dir is read LOCK-FREE by the builder's longest-prefix scan
    // (`builder::executor::build_stage` step 2: `is_snapshot_dir` +
    // `Image::from_snapshot`), while a concurrent producer holds only the
    // per-key `CacheLock`. If we wrote `rootfs/` then `metadata.json` IN PLACE,
    // a reader could observe the torn middle — a half-copied `rootfs/` (or stale
    // metadata) that `is_snapshot_dir` accepts → the verify-exec then fails with
    // code 127 (missing /bin/sh) / code 1 (cannot open root). Instead, build the
    // WHOLE image (rootfs + metadata) in a uniquely-named sibling staging dir,
    // then `rename(2)` it onto `dest_dir` in one step. POSIX directory rename on
    // the same filesystem is atomic, so a concurrent reader sees `dest_dir` as
    // either entirely absent/old (→ a safe cache MISS that rebuilds) or fully
    // complete — never a partial tree. Per-build isolation is unchanged: the
    // per-build PRIVATE clone (`SentryPool::build`) and this capture are
    // independent.
    let parent = dest_dir
        .parent()
        .ok_or_else(|| Error::vm_msg("snapshot: dest_dir must have a parent dir".to_owned()))?;
    std::fs::create_dir_all(parent).map_err(Error::Io)?;
    let staging = parent.join(format!(
        ".{}.tmp-{}-{}",
        dest_dir
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "snap".to_owned()),
        std::process::id(),
        unique_suffix(),
    ));
    // A failed earlier attempt may have left a same-named staging dir behind.
    let _ = std::fs::remove_dir_all(&staging);
    // Helper so every fallible step below tears the staging dir down (never leak
    // a partial sibling next to the cache dir).
    let cleanup = |e: Error, staging: &Path| -> Error {
        let _ = std::fs::remove_dir_all(staging);
        e
    };
    let staging_rootfs = staging.join("rootfs");
    std::fs::create_dir_all(&staging).map_err(|e| cleanup(Error::Io(e), &staging))?;
    copy_dir_recursive(src_rootfs, &staging_rootfs).map_err(|e| {
        cleanup(
            Error::vm_msg(format!("snapshot: copy rootfs: {e}")),
            &staging,
        )
    })?;
    // `sentry_rootfs` records the FINAL location (`dest_dir/rootfs`), not the
    // staging path — after the rename below that is where the bytes live, and
    // `Image::from_snapshot` resolves it post-commit.
    let final_rootfs = dest_dir.join("rootfs");
    // Re-emit metadata from the SOURCE (sibling of the source rootfs),
    // repointing the rootfs and restamping. Falls back to a minimal doc if the
    // source metadata is missing/unreadable.
    let mut meta = src_rootfs
        .parent()
        .map(|p| p.join("metadata.json"))
        .and_then(|p| std::fs::read(p).ok())
        .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
        .unwrap_or_else(|| serde_json::json!({ "backend": "sentry" }));
    if let Some(obj) = meta.as_object_mut() {
        obj.insert("backend".to_owned(), serde_json::json!("sentry"));
        obj.insert(
            "sentry_rootfs".to_owned(),
            serde_json::json!(final_rootfs.to_string_lossy()),
        );
        let inherited_memory_mib = obj
            .get("memory_mib")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32);
        let effective_memory_mib = memory_mib.or(inherited_memory_mib).unwrap_or(512);
        let inherited_vcpus = obj.get("vcpus").and_then(|v| v.as_u64()).map(|v| v as u32);
        let effective_vcpus = vcpus.or(inherited_vcpus).unwrap_or(1).max(1);
        obj.insert(
            "memory_mib".to_owned(),
            serde_json::json!(effective_memory_mib),
        );
        obj.insert("vcpus".to_owned(), serde_json::json!(effective_vcpus));
        // Stamp the CURRENT binary version — the rootfs we just copied was
        // materialized by these binaries, so the snapshot must declare them.
        // `Image::from_snapshot`'s backend-agnostic version gate
        // (`snapshot_baked_under_other_version`) HARD-refuses a sentry dir
        // restored under a different version, mirroring the KVM gate; without
        // this stamp the gate stays permanently permissive for sentry captures
        // (and a stale version carried over from the source would mislabel a
        // freshly-baked snapshot).
        obj.insert(
            "baked_by_version".to_owned(),
            serde_json::json!(env!("CARGO_PKG_VERSION")),
        );
        obj.insert(
            "baked_at".to_owned(),
            serde_json::json!(chrono_rfc3339_now()),
        );
        obj.insert("source".to_owned(), serde_json::json!(source));
        obj.insert(
            "snapshot_physical_bytes".to_owned(),
            serde_json::json!(dir_size_bytes(&staging_rootfs)),
        );
    }
    let meta_text = serde_json::to_string_pretty(&meta)
        .map_err(|e| cleanup(Error::vm_msg(format!("metadata serialize: {e}")), &staging))?;
    std::fs::write(staging.join("metadata.json"), meta_text)
        .map_err(|e| cleanup(Error::Io(e), &staging))?;
    // Write a uniform `restore.snap` so the on-disk layout matches the KVM/HVF
    // snapshot dirs (metadata.json + restore.snap + filesystem artifact) and
    // `snapshot_path()` resolves to a REAL file on every backend. A sentry
    // exec-server snapshot's durable state IS the filesystem (the rootfs copied
    // above) — captured at a quiescent point there is no live process/memory to
    // checkpoint — so the state container honestly records the host CPU-feature
    // baseline with empty memory/proctree/netstack/fd/cwd sections. The sentry
    // restore path serves from `sentry_rootfs`; this file makes the snapshot
    // format self-consistent and version-stamped (read_from HARD-refuses a skew).
    {
        use crate::sentry::state_snap::{
            CpuFeatures, FdTableSnapshot, MemImage, ProcTreeSnapshot, SnapshotEntryKind,
            StateSnapshot, CURRENT_VERSION,
        };
        let state = StateSnapshot {
            version: CURRENT_VERSION,
            cpu_feature_baseline: CpuFeatures::current(),
            entry_kind: SnapshotEntryKind::WarmZygote,
            mem: MemImage::default(),
            proctree: ProcTreeSnapshot::default(),
            netstack: crate::sentry::netstack::LoopSnapshot::default(),
            fdtable: FdTableSnapshot::default(),
            cwds: Vec::new(),
            cmdlines: Vec::new(),
            exes: Vec::new(),
        };
        let mut snap_buf = Vec::new();
        state.write_to(&mut snap_buf).map_err(|e| {
            cleanup(
                Error::vm_msg(format!("snapshot: state container serialize: {e}")),
                &staging,
            )
        })?;
        std::fs::write(staging.join("restore.snap"), &snap_buf)
            .map_err(|e| cleanup(Error::Io(e), &staging))?;
    }
    // Commit. `rename(2)` requires the target to be absent or an EMPTY dir, so
    // clear any prior (stale/partial) `dest_dir` first. The producer holds the
    // per-key `CacheLock` across this call, so no peer is mid-rename on the same
    // key; a lock-free READER landing in the tiny remove→rename gap simply sees
    // `dest_dir` absent (a safe cache miss → rebuild), never a torn tree.
    // GAP-FREE publish. A `remove_dir_all(dest)` + `rename(staging, dest)` leaves a
    // window where `dest` is absent/half-removed — and `dest` is read LOCK-FREE by the
    // builder's longest-prefix scan AND cloned (as a resume base) by concurrent stages,
    // so a reader landing in that window sees a torn/missing tree (the
    // sentry_concurrent_layer_cache_no_torn_tree flake: "metadata.json EOF", "cannot
    // read ld.so", "No such file or directory"). Instead, atomically EXCHANGE our
    // complete staging tree with `dest` via renameat2(RENAME_EXCHANGE): `dest` is at
    // every instant a COMPLETE tree (old or new), never absent. Then drop the
    // swapped-out old tree (now at `staging`). If `dest` doesn't exist yet, EXCHANGE
    // fails with ENOENT and a plain `rename` is already atomic (create-in-place).
    {
        use std::os::unix::ffi::OsStrExt;
        let staging_c = std::ffi::CString::new(staging.as_os_str().as_bytes()).map_err(|_| {
            cleanup(
                Error::vm_msg("snapshot: staging path has NUL".to_owned()),
                &staging,
            )
        })?;
        let dest_c = std::ffi::CString::new(dest_dir.as_os_str().as_bytes()).map_err(|_| {
            cleanup(
                Error::vm_msg("snapshot: dest path has NUL".to_owned()),
                &staging,
            )
        })?;
        const RENAME_EXCHANGE: libc::c_uint = 1 << 1; // (RENAME_NOREPLACE=1, EXCHANGE=2)
        let exch = unsafe {
            libc::renameat2(
                libc::AT_FDCWD,
                staging_c.as_ptr(),
                libc::AT_FDCWD,
                dest_c.as_ptr(),
                RENAME_EXCHANGE,
            )
        };
        if exch == 0 {
            // dest now holds the new tree; staging holds the prior one — drop it.
            let _ = std::fs::remove_dir_all(&staging);
        } else {
            let err = std::io::Error::last_os_error();
            // ENOENT: dest didn't exist → a plain rename is an atomic create. If the
            // destination exists and RENAME_EXCHANGE is unsupported, there is no
            // lock-free-reader-safe fallback for replacing a non-empty directory; do
            // not reintroduce the remove→rename gap that this path exists to avoid.
            if err.raw_os_error() == Some(libc::ENOENT) || !dest_dir.exists() {
                std::fs::rename(&staging, dest_dir).map_err(|e| {
                    cleanup(
                        Error::vm_msg(format!(
                            "snapshot: atomic commit rename {} -> {}: {e}",
                            staging.display(),
                            dest_dir.display()
                        )),
                        &staging,
                    )
                })?;
            } else {
                return Err(cleanup(
                    Error::vm_msg(format!(
                        "snapshot: gap-free directory exchange {} <-> {} failed: {err}",
                        staging.display(),
                        dest_dir.display()
                    )),
                    &staging,
                ));
            }
        }
    }
    Image::from_snapshot(dest_dir)
}

fn chrono_rfc3339_now() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    // Days since 1970-01-01 / seconds within day.
    let days = secs.div_euclid(86_400);
    let sod = secs.rem_euclid(86_400);
    let hh = sod / 3600;
    let mm = (sod % 3600) / 60;
    let ss = sod % 60;
    // Civil-from-days (Howard Hinnant's algorithm).
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}

#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
fn set_executable(path: &Path) -> std::io::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)?.permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms)
}

#[cfg(test)]
mod version_skew_tests {
    //! `Image::from_snapshot` must HARD-refuse snapshots baked under a
    //! different binary version — a field report had a 0.7.74 layer
    //! snapshot restore under 0.7.80 binaries into a VM with zero egress,
    //! with only a warning printed. Cache-or-bake callers treat this
    //! error as a miss and rebake; direct callers get an actionable error
    //! instead of a silently broken VM.
    use super::Image;
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    use super::{Error, SentryBakeConfig, VmConfig};
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    use std::io::{Read as _, Write as _};

    fn snap_dir(meta: serde_json::Value) -> std::path::PathBuf {
        // Unique per call even across parallel tests — SystemTime nanos
        // can collide between threads.
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let dir = std::env::temp_dir().join(format!(
            "sm-verskew-{}-{}",
            std::process::id(),
            SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("metadata.json"),
            serde_json::to_string_pretty(&meta).unwrap(),
        )
        .unwrap();
        dir
    }

    #[test]
    fn from_snapshot_refuses_version_skewed_snapshot() {
        // backend=kvm sidesteps the restore.snap existence check, so the
        // version gate is what fires (the gate itself is backend-agnostic).
        let dir = snap_dir(serde_json::json!({
            "backend": "kvm",
            "kvm_snapshot": "vm.snap",
            "memory_mib": 256,
            "vcpus": 1,
            "baked_by_version": "0.0.1",
        }));
        let err = Image::from_snapshot(&dir).expect_err("must refuse version skew");
        let msg = format!("{err:?}");
        assert!(
            msg.contains("0.0.1") && msg.contains("Re-bake"),
            "error must name the baked version and tell the user to rebake: {msg}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn from_snapshot_refuses_version_skewed_sentry_snapshot() {
        // The no-virt sentry backend also stamps `baked_by_version` at bake and
        // (like kvm) skips the restore.snap existence check, so the backend-agnostic
        // version gate must fire for a sentry dir too — a skewed sentry snapshot can
        // carry an incompatible pinned init/agent. Errors at the gate BEFORE any
        // sentry_rootfs handling, so no real rootfs is needed here. Explicit
        // coverage guards against a future sentry-branch bypass of the gate.
        let dir = snap_dir(serde_json::json!({
            "backend": "sentry",
            "sentry_rootfs": "rootfs",
            "memory_mib": 256,
            "baked_by_version": "0.0.1",
        }));
        let err = Image::from_snapshot(&dir).expect_err("must refuse sentry version skew");
        let msg = format!("{err:?}");
        assert!(
            msg.contains("0.0.1") && msg.contains("Re-bake"),
            "sentry skew error must name the baked version and tell the user to rebake: {msg}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn from_snapshot_allows_current_version_and_indeterminate() {
        for meta in [
            serde_json::json!({
                "backend": "kvm",
                "kvm_snapshot": "vm.snap",
                "baked_by_version": env!("CARGO_PKG_VERSION"),
            }),
            // No version info at all (bundles, custom kernels): permissive.
            serde_json::json!({
                "backend": "kvm",
                "kvm_snapshot": "vm.snap",
            }),
        ] {
            let dir = snap_dir(meta);
            match Image::from_snapshot(&dir) {
                Ok(_) => {}
                Err(e) => {
                    let msg = format!("{e:?}");
                    assert!(
                        !msg.contains("Re-bake"),
                        "version gate must not fire here: {msg}"
                    );
                }
            }
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    #[test]
    fn from_snapshot_loads_runsc_rootfs_metadata() {
        let dir = snap_dir(serde_json::json!({
            "backend": "runsc",
            "runsc_rootfs": "rootfs",
            "runsc_has_workload": true,
            "memory_mib": 384,
            "vcpus": 2,
            "image_env": {"PATH": "/usr/bin"},
            "cmd": ["/bin/sh", "-lc", "echo hi"],
            "runsc_agent_path": "/.supermachine/supermachine-agent",
            "runsc_agent_unix_env": "SUPERMACHINE_AGENT_UNIX_SOCKET",
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        std::fs::create_dir_all(dir.join("rootfs")).unwrap();
        let image = Image::from_snapshot(&dir).expect("runsc snapshot loads");
        assert!(image.is_runsc());
        assert!(!image.is_sentry());
        assert_eq!(image.memory_mib, 384);
        assert_eq!(image.vcpus, 2);
        let parts = image.runsc.as_ref().expect("runsc parts");
        assert!(parts.has_workload);
        assert_eq!(parts.cmd, ["/bin/sh", "-lc", "echo hi"]);
        assert_eq!(parts.agent_path, "/.supermachine/supermachine-agent");
        assert_eq!(parts.agent_unix_env, "SUPERMACHINE_AGENT_UNIX_SOCKET");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn from_snapshot_loads_kboxlike_rootfs_metadata() {
        let volume_host = std::env::temp_dir().join(format!(
            "sm-kboxlike-metadata-volume-{}",
            std::process::id()
        ));
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "rootfs",
            "kboxlike_has_workload": true,
            "memory_mib": 512,
            "vcpus": 3,
            "user": "1000:1001",
            "image_env": {"PATH": "/usr/local/bin"},
            "cmd": ["/bin/sh", "-lc", "echo kboxlike"],
            "volumes": [{"host_file": volume_host.to_string_lossy(), "guest_path": "/var/lib/data", "size_bytes": 12345}],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        std::fs::create_dir_all(dir.join("rootfs")).unwrap();
        let image = Image::from_snapshot(&dir).expect("kboxlike snapshot loads");
        assert!(image.is_kboxlike());
        assert!(!image.is_runsc());
        assert!(!image.is_sentry());
        assert_eq!(image.memory_mib, 512);
        assert_eq!(image.vcpus, 3);
        let parts = image.kboxlike.as_ref().expect("kboxlike parts");
        assert!(parts.has_workload);
        assert_eq!(parts.user, Some((1000, 1001)));
        assert_eq!(
            parts.image_env,
            [("PATH".to_string(), "/usr/local/bin".to_string())]
        );
        assert_eq!(parts.cmd, ["/bin/sh", "-lc", "echo kboxlike"]);
        assert_eq!(parts.volumes.len(), 1);
        assert_eq!(parts.volumes[0].0, volume_host);
        assert_eq!(parts.volumes[0].1, "/var/lib/data");
        assert_eq!(parts.volumes[0].2, 12345);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions and live ptrace restore"]
    fn kboxlike_vm_start_restores_host_root_sleep_smoke() {
        let workload_uid_path = format!(
            "/tmp/sm-kboxlike-workload-user-{}-{}",
            std::process::id(),
            1
        );
        let host_mount = std::env::temp_dir().join(format!(
            "sm-kboxlike-host-mount-{}-{}",
            std::process::id(),
            1
        ));
        std::fs::create_dir_all(&host_mount).unwrap();
        std::fs::write(host_mount.join("input.txt"), b"kboxlike-mounted\n").unwrap();
        let guest_mount = format!("/tmp/sm-kboxlike-guest-mount-{}-{}", std::process::id(), 1);
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "/",
            "kboxlike_has_workload": false,
            "memory_mib": 64,
            "vcpus": 1,
            "user": "65534:65534",
            "image_env": {"PATH": "/usr/bin:/bin"},
            "cmd": ["/bin/sh", "-lc", format!("id -u > {workload_uid_path}; id -g >> {workload_uid_path}; sleep 30")],
            "mounts": [{"host_path": host_mount.to_string_lossy(), "guest_tag": "mnt", "guest_path": guest_mount}],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        let image = Image::from_snapshot(&dir).expect("kboxlike host-root snapshot loads");
        let vm = image
            .start(&super::VmConfig::new())
            .expect("kboxlike vm starts");
        let mut workload_user = Vec::new();
        for _ in 0..20 {
            if let Ok(bytes) = vm.read_file(&workload_uid_path) {
                workload_user = bytes;
                if String::from_utf8_lossy(&workload_user).contains("65534\n65534") {
                    break;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        assert_eq!(
            String::from_utf8_lossy(&workload_user),
            "65534\n65534\n",
            "kboxlike workload did not run as metadata user"
        );
        let path = format!("/tmp/sm-kboxlike-file-{}-{}", std::process::id(), 1);
        vm.write_file(&path, b"kboxlike-file\n")
            .expect("kboxlike write_file");
        assert_eq!(
            vm.read_file(&path).expect("kboxlike read_file"),
            b"kboxlike-file\n"
        );
        let staged = format!("/tmp/sm-kboxlike-stage-{}-{}", std::process::id(), 1);
        let out = vm
            .exec_builder()
            .argv([
                "/bin/sh",
                "-lc",
                "id -u; id -g; pwd; cat \"$SM_FILE\"; cat \"$SM_STAGE\"; cat \"$SM_MOUNT/input.txt\"",
            ])
            .cwd("/tmp")
            .env("SM_FILE", &path)
            .env("SM_STAGE", &staged)
            .env("SM_MOUNT", &guest_mount)
            .stage_file(&staged, b"staged\n")
            .output()
            .expect("kboxlike exec output");
        assert!(out.success(), "kboxlike exec failed: {out:?}");
        assert_eq!(
            out.stdout,
            b"65534\n65534\n/tmp\nkboxlike-file\nstaged\nkboxlike-mounted\n"
        );
        let mut child = vm
            .exec_builder()
            .argv([
                "/bin/sh",
                "-lc",
                "cat; printf 'kboxlike-stream-err\\n' >&2; exit 7",
            ])
            .spawn()
            .expect("kboxlike streaming exec spawn");
        let mut stdin = child.stdin().expect("kboxlike streaming stdin");
        stdin
            .write_all(b"kboxlike-stream-out\n")
            .expect("kboxlike streaming stdin write");
        stdin.close().expect("kboxlike streaming stdin close");
        let mut stream_stdout = String::new();
        child
            .stdout()
            .expect("kboxlike streaming stdout")
            .read_to_string(&mut stream_stdout)
            .expect("kboxlike streaming stdout read");
        let mut stream_stderr = String::new();
        child
            .stderr()
            .expect("kboxlike streaming stderr")
            .read_to_string(&mut stream_stderr)
            .expect("kboxlike streaming stderr read");
        let status = child.wait().expect("kboxlike streaming wait");
        assert_eq!(status.code(), Some(7));
        assert_eq!(stream_stdout, "kboxlike-stream-out\n");
        assert_eq!(stream_stderr, "kboxlike-stream-err\n");
        vm.workload_signal(libc::SIGTERM)
            .expect("kboxlike workload_signal");
        vm.stop().expect("kboxlike vm stops");

        let pool = image
            .pool()
            .min(1)
            .max(1)
            .restore_on_release(false)
            .build()
            .expect("kboxlike pool builds");
        let pooled_path = format!("/tmp/sm-kboxlike-pooled-{}-{}", std::process::id(), 1);
        {
            let pooled = pool.acquire().expect("kboxlike pool acquire");
            let stats = pool.stats();
            assert_eq!(stats.alive, 1);
            assert_eq!(stats.in_use, 1);
            assert_eq!(stats.max, 1);
            let out = pooled
                .exec_builder()
                .argv(["/bin/sh", "-lc", "id -u; id -g; echo pooled > \"$P\""])
                .env("P", &pooled_path)
                .output()
                .expect("kboxlike pooled exec output");
            assert!(out.success(), "kboxlike pooled exec failed: {out:?}");
            assert_eq!(out.stdout, b"65534\n65534\n");
        }
        let stats = pool.stats();
        assert_eq!(stats.alive, 1);
        assert_eq!(stats.idle, 1);
        assert_eq!(
            std::fs::read_to_string(&pooled_path).unwrap_or_default(),
            "pooled\n"
        );
        pool.shutdown();

        let _ = std::fs::remove_file(path);
        let _ = std::fs::remove_file(staged);
        let _ = std::fs::remove_file(pooled_path);
        let _ = std::fs::remove_dir_all(host_mount);
        let _ = std::fs::remove_dir_all(guest_mount);
        let _ = std::fs::remove_file(workload_uid_path);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions and live ptrace restore"]
    fn kboxlike_vm_start_honors_runtime_virtiofs_mount() {
        let host_mount = std::env::temp_dir().join(format!(
            "sm-kboxlike-runtime-mount-{}-{}",
            std::process::id(),
            1
        ));
        std::fs::create_dir_all(&host_mount).unwrap();
        std::fs::write(host_mount.join("input.txt"), b"runtime-mounted\n").unwrap();
        let guest_mount = format!(
            "/tmp/sm-kboxlike-runtime-guest-mount-{}-{}",
            std::process::id(),
            1
        );
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "/",
            "kboxlike_has_workload": false,
            "memory_mib": 64,
            "vcpus": 1,
            "image_env": {"PATH": "/usr/bin:/bin"},
            "cmd": ["/bin/sh", "-lc", "sleep 30"],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        let image = Image::from_snapshot(&dir).expect("kboxlike runtime-mount snapshot loads");
        let cfg = VmConfig::new().with_virtiofs(crate::vmm::resources::MountSpec::new(
            host_mount.to_string_lossy().to_string(),
            "runtime",
            guest_mount.clone(),
        ));
        let vm = image
            .start(&cfg)
            .expect("kboxlike vm starts with runtime mount");
        let out = vm
            .exec_builder()
            .argv(["/bin/sh", "-lc", "cat \"$SM_MOUNT/input.txt\""])
            .env("SM_MOUNT", &guest_mount)
            .timeout(std::time::Duration::from_secs(10))
            .output()
            .expect("kboxlike exec reads runtime mount");
        assert!(out.success(), "kboxlike runtime mount exec failed: {out:?}");
        assert_eq!(out.stdout, b"runtime-mounted\n");
        vm.stop().expect("kboxlike runtime-mount vm stops");

        let _ = std::fs::remove_dir_all(host_mount);
        let _ = std::fs::remove_dir_all(guest_mount);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions and live ptrace restore"]
    fn kboxlike_vm_start_honors_runtime_volume_mount() {
        let host_volume = std::env::temp_dir().join(format!(
            "sm-kboxlike-runtime-volume-{}-{}",
            std::process::id(),
            1
        ));
        let guest_volume = format!(
            "/tmp/sm-kboxlike-runtime-guest-volume-{}-{}",
            std::process::id(),
            1
        );
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "/",
            "kboxlike_has_workload": false,
            "memory_mib": 64,
            "vcpus": 1,
            "image_env": {"PATH": "/usr/bin:/bin"},
            "cmd": ["/bin/sh", "-lc", "sleep 30"],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        let image = Image::from_snapshot(&dir).expect("kboxlike runtime-volume snapshot loads");
        let cfg = VmConfig::new().with_volume(crate::vmm::resources::VolumeSpec::new(
            host_volume.to_string_lossy().to_string(),
            guest_volume.clone(),
        ));
        let vm = image
            .start(&cfg)
            .expect("kboxlike vm starts with runtime volume");
        let out = vm
            .exec_builder()
            .argv([
                "/bin/sh",
                "-lc",
                "echo runtime-volume > \"$SM_VOLUME/marker\" && cat \"$SM_VOLUME/marker\"",
            ])
            .env("SM_VOLUME", &guest_volume)
            .timeout(std::time::Duration::from_secs(10))
            .output()
            .expect("kboxlike exec writes runtime volume");
        assert!(
            out.success(),
            "kboxlike runtime volume exec failed: {out:?}"
        );
        assert_eq!(out.stdout, b"runtime-volume\n");
        assert_eq!(
            std::fs::read_to_string(host_volume.join("marker")).unwrap_or_default(),
            "runtime-volume\n"
        );
        vm.stop().expect("kboxlike runtime-volume vm stops");

        let _ = std::fs::remove_dir_all(host_volume);
        let _ = std::fs::remove_dir_all(guest_volume);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions, OCI pull, and live ptrace restore"]
    fn kboxlike_bake_warmup_mount_exec_smoke() {
        let host_mount = std::env::temp_dir().join(format!(
            "sm-kboxlike-bake-host-mount-{}-{}",
            std::process::id(),
            1
        ));
        std::fs::create_dir_all(&host_mount).unwrap();
        std::fs::write(host_mount.join("input.txt"), b"mounted-from-host\n").unwrap();
        let dir = std::env::temp_dir().join(format!(
            "sm-kboxlike-bake-snap-{}-{}",
            std::process::id(),
            1
        ));
        let _ = std::fs::remove_dir_all(&dir);

        let mut cfg = SentryBakeConfig {
            memory_mib: Some(128),
            vcpus: Some(1),
            cmd: Some(vec![
                "/bin/sh".to_owned(),
                "-lc".to_owned(),
                "sleep 30".to_owned(),
            ]),
            warmup_tag: Some("kboxlike-bake-warmup-mount-smoke-v1".to_owned()),
            ..Default::default()
        };
        cfg.mounts.push((
            host_mount.clone(),
            "workspace".to_owned(),
            crate::vmm::resources::SymlinkPolicy::Opaque,
            "/workspace".to_owned(),
        ));
        cfg.warmup = Some(Box::new(|vm| {
            let out = vm
                .exec_builder()
                .argv([
                    "/bin/sh",
                    "-lc",
                    "cat /workspace/input.txt > /warmup-mounted.txt && echo warmed > /warmup-created.txt",
                ])
                .timeout(std::time::Duration::from_secs(30))
                .output()?;
            if !out.success() {
                return Err(Error::vm_msg(format!("warmup failed: {out:?}")));
            }
            Ok(())
        }));

        let image = Image::bake_kboxlike_with_config("alpine:3.20", &dir, cfg)
            .expect("kboxlike bake with warmup and mount");
        assert!(image.is_kboxlike());
        let vm = image
            .start(&VmConfig::new())
            .expect("kboxlike baked vm starts");
        let out = vm
            .exec_builder()
            .argv([
                "/bin/sh",
                "-lc",
                "cat /warmup-mounted.txt; cat /warmup-created.txt; cat /workspace/input.txt",
            ])
            .timeout(std::time::Duration::from_secs(30))
            .output()
            .expect("kboxlike baked exec");
        assert!(out.success(), "kboxlike baked exec failed: {out:?}");
        assert_eq!(
            out.stdout,
            b"mounted-from-host\nwarmed\nmounted-from-host\n"
        );
        vm.stop().expect("kboxlike baked vm stops");
        let _ = std::fs::remove_dir_all(host_mount);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions, live ptrace restore, and python3"]
    fn kboxlike_vm_start_exposes_restored_tcp_listener_smoke() {
        let python = if std::path::Path::new("/usr/bin/python3").is_file() {
            "/usr/bin/python3"
        } else {
            "/bin/python3"
        };
        assert!(
            std::path::Path::new(python).is_file(),
            "python3 binary not found at /usr/bin/python3 or /bin/python3"
        );
        let port = kboxlike_free_host_port();
        let server_code = format!(
            r#"import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", {port}))
s.listen(16)
body = b"kboxlike-http\n"
resp = b"HTTP/1.0 200 OK\r\nContent-Length: " + str(len(body)).encode() + b"\r\nConnection: close\r\n\r\n" + body
while True:
    conn, _addr = s.accept()
    try:
        conn.recv(4096)
        conn.sendall(resp)
    finally:
        conn.close()
"#
        );
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "/",
            "kboxlike_has_workload": false,
            "memory_mib": 128,
            "vcpus": 1,
            "image_env": {"PATH": "/usr/bin:/bin"},
            "cmd": [
                python,
                "-u",
                "-c",
                server_code
            ],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));
        let cert = dir.join("cert.pem");
        let key = dir.join("key.pem");
        let openssl_ok = std::process::Command::new("openssl")
            .args([
                "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1",
            ])
            .arg("-keyout")
            .arg(&key)
            .arg("-out")
            .arg(&cert)
            .args(["-subj", "/CN=localhost"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);
        let curl_ok = std::process::Command::new("curl")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false);

        let result = (|| {
            let image = Image::from_snapshot(&dir).expect("kboxlike HTTP snapshot loads");
            let vm = image
                .start(&super::VmConfig::new())
                .expect("kboxlike HTTP vm starts");

            let direct_addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
            let direct = kboxlike_http_get_tcp_until(direct_addr, "/payload.txt")
                .expect("direct TCP reaches restored HTTP listener");
            eprintln!("KBOXLIVE_VM_START_HTTP_DIRECT ok=true");
            assert!(
                direct.contains("kboxlike-http"),
                "unexpected direct TCP response: {direct:?}"
            );

            let explicit = kboxlike_http_get_unix_until(|| vm.connect_port(port), "/payload.txt")
                .expect("connect_port reaches restored HTTP listener");
            eprintln!("KBOXLIVE_VM_START_HTTP_CONNECT_PORT ok=true");
            assert!(
                explicit.contains("kboxlike-http"),
                "unexpected connect_port response: {explicit:?}"
            );

            let first = kboxlike_http_get_unix_until(|| vm.connect(), "/payload.txt")
                .expect("connect reaches first restored HTTP listener");
            eprintln!("KBOXLIVE_VM_START_HTTP_CONNECT ok=true");
            assert!(
                first.contains("kboxlike-http"),
                "unexpected connect response: {first:?}"
            );

            let fwd = vm.expose_tcp(0, port).expect("kboxlike expose_tcp starts");
            let exposed = kboxlike_http_get_tcp_until(fwd.local_addr(), "/payload.txt")
                .expect("expose_tcp reaches restored HTTP listener");
            eprintln!("KBOXLIVE_VM_START_HTTP_EXPOSE_TCP ok=true");
            assert!(
                exposed.contains("kboxlike-http"),
                "unexpected expose_tcp response: {exposed:?}"
            );
            drop(fwd);

            if openssl_ok && curl_ok {
                let addr = vm
                    .expose_tls(crate::vmm::tls::TlsConfig {
                        listen_addr: "127.0.0.1:0".into(),
                        vm_port: Some(port as u32),
                        cert_path: cert.to_string_lossy().into_owned(),
                        key_path: key.to_string_lossy().into_owned(),
                    })
                    .expect("kboxlike expose_tls starts");
                let mut tls_body = String::new();
                for _ in 0..20 {
                    tls_body = std::process::Command::new("curl")
                        .args(["-sk", "--max-time", "8"])
                        .arg(format!("https://{addr}/payload.txt"))
                        .output()
                        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
                        .unwrap_or_default();
                    if tls_body.contains("kboxlike-http") {
                        break;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(300));
                }
                eprintln!("KBOXLIVE_VM_START_HTTP_EXPOSE_TLS ok=true");
                assert!(
                    tls_body.contains("kboxlike-http"),
                    "unexpected expose_tls response: {tls_body:?}"
                );
            } else {
                eprintln!(
                    "KBOXLIVE_VM_START_HTTP_EXPOSE_TLS skipped openssl_ok={openssl_ok} curl_ok={curl_ok}"
                );
            }

            vm.stop().expect("kboxlike HTTP vm stops");
        })();

        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    #[ignore = "requires Linux root/chroot permissions, live ptrace restore, and Chromium"]
    fn kboxlike_vm_start_restores_host_root_chromium_devtools_smoke() {
        let chrome = std::env::var("SUPERMACHINE_KBOXLIVE_CHROME").unwrap_or_else(|_| {
            "/root/.cache/ms-playwright/chromium-1217/chrome-linux64/chrome".to_owned()
        });
        assert!(
            std::path::Path::new(&chrome).is_file(),
            "Chromium binary not found at {chrome}; set SUPERMACHINE_KBOXLIVE_CHROME"
        );
        let profile_dir = std::env::temp_dir().join(format!(
            "kboxlike-vm-chromium-profile-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&profile_dir).unwrap();
        let user_data_dir = format!("--user-data-dir={}", profile_dir.display());
        let image_env = std::env::vars()
            .map(|(key, value)| (key, serde_json::json!(value)))
            .collect::<serde_json::Map<_, _>>();
        let dir = snap_dir(serde_json::json!({
            "backend": "kboxlike",
            "kboxlike_rootfs": "/",
            "kboxlike_has_workload": false,
            "memory_mib": 512,
            "vcpus": 2,
            "image_env": image_env,
            "cmd": [
                chrome,
                "--headless=new",
                "--disable-gpu",
                "--disable-dev-shm-usage",
                "--no-sandbox",
                "--remote-debugging-port=0",
                user_data_dir,
                "about:blank"
            ],
            "warm_daemon": false,
            "baked_by_version": env!("CARGO_PKG_VERSION"),
        }));

        let result = (|| {
            let image = Image::from_snapshot(&dir).expect("kboxlike Chromium snapshot loads");
            let vm = image
                .start(&super::VmConfig::new())
                .expect("kboxlike Chromium vm starts");
            let port = kboxlike_read_devtools_active_port_until(
                &profile_dir,
                std::time::Duration::from_secs(3),
            )
            .expect("restored Chromium DevTools active port");
            let status =
                kboxlike_probe_devtools_version_until(port, std::time::Duration::from_secs(3))
                    .expect("restored Chromium DevTools /json/version response");
            eprintln!("KBOXLIVE_VM_START_CHROMIUM_DEVTOOLS port={port} ok=true {status}");
            vm.stop().expect("kboxlike Chromium vm stops");
        })();

        let _ = std::fs::remove_dir_all(&profile_dir);
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_free_host_port() -> u16 {
        std::net::TcpListener::bind(("127.0.0.1", 0))
            .unwrap()
            .local_addr()
            .unwrap()
            .port()
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_http_get_unix_until<F>(mut connect: F, path: &str) -> std::io::Result<String>
    where
        F: FnMut() -> std::io::Result<std::os::unix::net::UnixStream>,
    {
        use std::io::Write as _;

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            match connect() {
                Ok(mut stream) => {
                    stream.set_read_timeout(Some(std::time::Duration::from_secs(2)))?;
                    stream.write_all(
                        format!("GET {path} HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n").as_bytes(),
                    )?;
                    let _ = stream.shutdown(std::net::Shutdown::Write);
                    let response = kboxlike_read_http_response_chunks(&mut stream)?;
                    if response.contains("200 OK") && response.contains("kboxlike-http") {
                        return Ok(response);
                    }
                    if std::time::Instant::now() >= deadline {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            format!("HTTP response was not 200: {response:?}"),
                        ));
                    }
                }
                Err(err) if std::time::Instant::now() >= deadline => return Err(err),
                Err(_) => {}
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_http_get_tcp_until(
        addr: std::net::SocketAddr,
        path: &str,
    ) -> std::io::Result<String> {
        use std::io::Write as _;

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            match std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(200))
            {
                Ok(mut stream) => {
                    stream.set_read_timeout(Some(std::time::Duration::from_secs(2)))?;
                    stream.write_all(
                        format!("GET {path} HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n").as_bytes(),
                    )?;
                    let _ = stream.shutdown(std::net::Shutdown::Write);
                    let response = kboxlike_read_http_response_chunks(&mut stream)?;
                    if response.contains("200 OK") && response.contains("kboxlike-http") {
                        return Ok(response);
                    }
                    if std::time::Instant::now() >= deadline {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            format!("HTTP response was not 200: {response:?}"),
                        ));
                    }
                }
                Err(err) if std::time::Instant::now() >= deadline => return Err(err),
                Err(_) => {}
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_read_http_response_chunks<R: std::io::Read>(
        reader: &mut R,
    ) -> std::io::Result<String> {
        let mut response = Vec::new();
        let mut chunk = [0u8; 1024];
        loop {
            match reader.read(&mut chunk) {
                Ok(0) => break,
                Ok(n) => {
                    response.extend_from_slice(&chunk[..n]);
                    if let Ok(text) = std::str::from_utf8(&response) {
                        if text.contains("200 OK") && text.contains("kboxlike-http") {
                            return Ok(text.to_owned());
                        }
                    }
                }
                Err(err)
                    if matches!(
                        err.kind(),
                        std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                    ) =>
                {
                    break;
                }
                Err(err) => return Err(err),
            }
        }
        Ok(String::from_utf8_lossy(&response).into_owned())
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_read_devtools_active_port_until(
        profile_dir: &std::path::Path,
        timeout: std::time::Duration,
    ) -> std::io::Result<u16> {
        let path = profile_dir.join("DevToolsActivePort");
        let deadline = std::time::Instant::now() + timeout;
        loop {
            match std::fs::read_to_string(&path) {
                Ok(text) => {
                    if let Some(first) = text.lines().next() {
                        if let Ok(port) = first.trim().parse::<u16>() {
                            return Ok(port);
                        }
                    }
                }
                Err(err)
                    if err.kind() != std::io::ErrorKind::NotFound
                        && std::time::Instant::now() >= deadline =>
                {
                    return Err(err);
                }
                Err(_) => {}
            }
            if std::time::Instant::now() >= deadline {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    format!("{} did not appear", path.display()),
                ));
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    fn kboxlike_probe_devtools_version_until(
        port: u16,
        timeout: std::time::Duration,
    ) -> std::io::Result<String> {
        use std::io::{Read as _, Write as _};

        let deadline = std::time::Instant::now() + timeout;
        let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
        loop {
            match std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(200))
            {
                Ok(mut stream) => {
                    stream.set_read_timeout(Some(std::time::Duration::from_millis(500)))?;
                    stream.write_all(b"GET /json/version HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")?;
                    let mut response = Vec::new();
                    let mut chunk = [0u8; 1024];
                    loop {
                        match stream.read(&mut chunk) {
                            Ok(0) => break,
                            Ok(n) => {
                                response.extend_from_slice(&chunk[..n]);
                                if let Ok(text) = std::str::from_utf8(&response) {
                                    if let Some(status) = text.lines().next() {
                                        if status.contains("200") {
                                            return Ok(status.to_owned());
                                        }
                                    }
                                }
                            }
                            Err(err)
                                if matches!(
                                    err.kind(),
                                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                                ) =>
                            {
                                break;
                            }
                            Err(err) => return Err(err),
                        }
                    }
                    if let Ok(text) = std::str::from_utf8(&response) {
                        if let Some(status) = text.lines().next() {
                            if status.contains("200") {
                                return Ok(status.to_owned());
                            }
                        }
                    }
                }
                Err(err) if std::time::Instant::now() >= deadline => return Err(err),
                Err(_) => {}
            }
            if std::time::Instant::now() >= deadline {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::TimedOut,
                    format!("DevTools on 127.0.0.1:{port} did not answer"),
                ));
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    }
}

#[cfg(test)]
mod oci_image_builder_mount_tests {
    //! Coverage for the `OciImageBuilder` mount setters: every
    //! mount carries a `guest_path` (required field), policy is
    //! orthogonal, and multiple mounts compose in insertion order.
    use super::OciImageBuilder;
    use crate::vmm::resources::SymlinkPolicy;
    use std::path::PathBuf;

    #[test]
    fn with_mount_stores_all_four_fields() {
        let b = OciImageBuilder::new("alpine").with_mount("/host/x", "tag", "/workspace");
        assert_eq!(b.mounts.len(), 1);
        let (h, t, p, gp) = &b.mounts[0];
        assert_eq!(h, &PathBuf::from("/host/x"));
        assert_eq!(t, "tag");
        assert_eq!(p, &SymlinkPolicy::Opaque);
        assert_eq!(gp, "/workspace");
    }

    #[test]
    fn with_mount_symlinks_combines_policy_and_guest_path() {
        let b = OciImageBuilder::new("alpine").with_mount_symlinks(
            "/host/x",
            "ws",
            "/workspace",
            SymlinkPolicy::Follow,
        );
        let (h, t, p, gp) = &b.mounts[0];
        assert_eq!(h, &PathBuf::from("/host/x"));
        assert_eq!(t, "ws");
        assert_eq!(p, &SymlinkPolicy::Follow);
        assert_eq!(gp, "/workspace");
    }

    #[test]
    fn with_mount_symlinks_deny_policy_round_trips() {
        let b = OciImageBuilder::new("alpine").with_mount_symlinks(
            "/h",
            "t",
            "/g",
            SymlinkPolicy::Deny,
        );
        assert_eq!(b.mounts[0].2, SymlinkPolicy::Deny);
    }

    #[test]
    fn multiple_mounts_compose_independently() {
        // The auth-flow shape: one virtio-fs bind for source, one
        // for a sibling cache share, one with a non-default policy.
        let b = OciImageBuilder::new("alpine")
            .with_mount("/host/src", "workspace", "/workspace")
            .with_mount("/host/cache", "ro-cache", "/cache")
            .with_mount_symlinks("/host/strict", "strict", "/strict", SymlinkPolicy::Deny);
        assert_eq!(b.mounts.len(), 3);
        assert_eq!(b.mounts[0].3, "/workspace");
        assert_eq!(b.mounts[1].3, "/cache");
        assert_eq!(b.mounts[2].3, "/strict");
        assert_eq!(b.mounts[2].2, SymlinkPolicy::Deny);
    }

    #[test]
    fn mounts_preserve_insertion_order() {
        // Order matters for init-oci auto-mount sequencing: when
        // two binds nest (e.g. /a then /a/b), the parent must come
        // first or the child's mkdir + mount sequence misses.
        let b = OciImageBuilder::new("alpine")
            .with_mount("/h1", "first", "/a/b")
            .with_mount("/h2", "second", "/a")
            .with_mount("/h3", "third", "/a/c");
        let tags: Vec<&str> = b.mounts.iter().map(|m| m.1.as_str()).collect();
        assert_eq!(tags, vec!["first", "second", "third"]);
    }
}

#[cfg(test)]
mod map_bake_error_tests {
    use super::{map_bake_error, Error};

    #[test]
    fn decodes_kernel_panic_sentinel() {
        let msg = "KERNEL_PANIC|Kernel panic - not syncing: oops|frame_a\x1Fframe_b\x1Fframe_c"
            .to_string();
        let err = map_bake_error("nginx:alpine", msg);
        match err {
            Error::KernelPanic { first_line, stack } => {
                assert!(first_line.contains("Kernel panic"));
                assert_eq!(stack, vec!["frame_a", "frame_b", "frame_c"]);
            }
            other => panic!("expected KernelPanic, got {other:?}"),
        }
    }

    #[test]
    fn kernel_panic_with_empty_stack() {
        let msg = "KERNEL_PANIC|Internal error: Oops|".to_owned();
        match map_bake_error("img", msg) {
            Error::KernelPanic { first_line, stack } => {
                assert_eq!(first_line, "Internal error: Oops");
                // splitn(2) with empty-string second half yields one empty
                // stack frame; consumer sees a single empty line which is
                // fine — `Display` skips printing meaningfully.
                assert!(stack.len() <= 1);
            }
            other => panic!("expected KernelPanic, got {other:?}"),
        }
    }

    #[test]
    fn non_panic_messages_unchanged() {
        let err = map_bake_error(
            "img",
            "supermachine snapshot timeout; see bake.log".to_owned(),
        );
        match err {
            Error::Bake { msg, .. } => assert!(msg.contains("timeout")),
            other => panic!("expected Bake, got {other:?}"),
        }
    }
}

#[cfg(test)]
mod base64_tests {
    //! The `wire` base64 codec carries read_file payloads as
    //! agent-controlled `data_b64`. Decoding must round-trip what we
    //! encode and REJECT malformed input rather than emit spurious bytes.
    use super::{b64_decode, b64_encode};
    use proptest::prelude::*;

    #[test]
    fn known_vectors_round_trip() {
        // RFC 4648 §10 test vectors.
        let cases: &[(&[u8], &str)] = &[
            (b"", ""),
            (b"f", "Zg=="),
            (b"fo", "Zm8="),
            (b"foo", "Zm9v"),
            (b"foob", "Zm9vYg=="),
            (b"fooba", "Zm9vYmE="),
            (b"foobar", "Zm9vYmFy"),
        ];
        for (raw, enc) in cases {
            assert_eq!(b64_encode(raw), *enc, "encode {raw:?}");
            assert_eq!(b64_decode(enc).unwrap(), *raw, "decode {enc:?}");
        }
    }

    #[test]
    fn decode_rejects_malformed_padding() {
        // The bug this fix closes: misplaced / excess padding must error,
        // not decode to spurious bytes.
        for bad in ["====", "A===", "=AAA", "AA==AAAA", "Zm==Zm9v", "=Zm9"] {
            assert!(
                b64_decode(bad).is_err(),
                "{bad:?} must be rejected as malformed padding"
            );
        }
    }

    #[test]
    fn decode_rejects_bad_length_and_chars() {
        assert!(b64_decode("ABC").is_err(), "length not a multiple of 4");
        assert!(b64_decode("Zm9").is_err());
        assert!(b64_decode("Zm$v").is_err(), "invalid character");
        assert!(b64_decode("Zm9*").is_err());
    }

    #[test]
    fn decode_tolerates_whitespace() {
        // The codec strips ASCII whitespace before decoding (wrapped
        // base64 from agents / PEM-style line breaks).
        assert_eq!(b64_decode("Zm9v YmFy").unwrap(), b"foobar");
        assert_eq!(b64_decode("Zm9v\nYmFy\n").unwrap(), b"foobar");
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(1024))]

        /// decode(encode(x)) == x for ALL byte strings, and the encoding
        /// is always a clean multiple of 4 with no interior padding.
        #[test]
        fn round_trips_for_all_bytes(data in proptest::collection::vec(any::<u8>(), 0..512)) {
            let enc = b64_encode(&data);
            prop_assert_eq!(enc.len() % 4, 0);
            prop_assert_eq!(b64_decode(&enc).unwrap(), data);
        }
    }
}