supermachine 0.4.4

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.
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
use std::cell::RefCell;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};

pub struct BakeRequest {
    pub image: String,
    pub name: Option<String>,
    pub runtime: String,
    pub guest_port: u16,
    pub memory_mib: u32,
    /// Number of vCPUs in the guest. Default 1. Multi-vCPU is
    /// gated on a per-bake basis because snapshot-with-multiple-
    /// vCPUs hit an HVF `ICH_LR_EL2` round-trip bug; see
    /// docs/design/multi-vcpu-snapshot-intermittency-2026-04-27.md.
    /// Listener-mode bakes (today's default for non-volume runs)
    /// snapshot only after secondaries are quiescent in WFI, so
    /// that should be safe — but the matrix is wide. Treat
    /// `vcpus > 1` as opt-in for HTTP-throughput-sensitive
    /// workloads.
    pub vcpus: u32,
    pub pull_policy: String,
    pub snapshots_dir: PathBuf,
    pub cmd_override: Option<String>,
    pub extra_args: Vec<String>,
}

trait ImageSource {
    fn local_arch(&self, image: &str) -> Option<String>;
    fn pull_arm64(&self, image: &str, force_refresh: bool) -> Result<(), String>;
    fn inspect(&self, image: &str) -> Result<serde_json::Value, String>;
    fn save_arm64(&self, image: &str, work_dir: &Path) -> Result<PathBuf, String>;
}

struct DockerImageSource;

impl ImageSource for DockerImageSource {
    fn local_arch(&self, image: &str) -> Option<String> {
        let mut cmd = Command::new("docker");
        cmd.arg("image")
            .arg("inspect")
            .arg("--format")
            .arg("{{.Architecture}}")
            .arg(image)
            .stderr(Stdio::null());
        command_output(cmd, "docker image inspect architecture")
            .ok()
            .map(|s| s.trim().to_owned())
            .filter(|s| !s.is_empty() && s != "<no value>")
    }

    fn pull_arm64(&self, image: &str, _force_refresh: bool) -> Result<(), String> {
        let mut cmd = Command::new("docker");
        cmd.arg("pull")
            .arg("--platform=linux/arm64")
            .arg(image)
            .stdout(Stdio::null());
        run_status(cmd, "docker pull")
    }

    fn inspect(&self, image: &str) -> Result<serde_json::Value, String> {
        let mut inspect_cmd = Command::new("docker");
        inspect_cmd.arg("image").arg("inspect").arg(image);
        let inspect = command_output(inspect_cmd, "docker image inspect")?;
        let inspect_json: serde_json::Value = serde_json::from_str(&inspect)
            .map_err(|e| format!("docker image inspect JSON: {e}"))?;
        inspect_json
            .as_array()
            .and_then(|a| a.first())
            .cloned()
            .ok_or_else(|| format!("docker image inspect returned no records for {image}"))
    }

    fn save_arm64(&self, image: &str, work_dir: &Path) -> Result<PathBuf, String> {
        let save_tar = work_dir.join("image.tar");
        let mut save = Command::new("docker");
        save.arg("save")
            .arg("--platform=linux/arm64")
            .arg(image)
            .arg("-o")
            .arg(&save_tar)
            .stderr(Stdio::null());
        run_status(save, "docker save")?;

        let save_dir = work_dir.join("_save");
        std::fs::create_dir_all(&save_dir)
            .map_err(|e| format!("create save dir {}: {e}", save_dir.display()))?;
        let mut tar = Command::new("tar");
        tar.arg("-xf").arg(&save_tar).arg("-C").arg(&save_dir);
        run_status(tar, "tar extract docker save")?;
        let _ = std::fs::remove_file(&save_tar);

        Ok(save_dir)
    }
}

#[derive(Clone)]
struct RegistryImageRef {
    registry: String,
    repository: String,
    reference: String,
}

/// Username + password resolved from `~/.docker/config.json`'s
/// `auths.<registry>.auth` field (or `--registry-auth USER:PASS`).
/// Sent as HTTP Basic auth on the registry's token endpoint —
/// the token returned then carries the user's pull permissions.
#[derive(Clone)]
struct RegistryCreds {
    user: String,
    pass: String,
}

impl RegistryCreds {
    fn basic_header_value(&self) -> String {
        let mut joined = String::with_capacity(self.user.len() + self.pass.len() + 1);
        joined.push_str(&self.user);
        joined.push(':');
        joined.push_str(&self.pass);
        format!("Basic {}", b64_encode(joined.as_bytes()))
    }
}

/// Look up credentials for `registry` host in `~/.docker/config.json`.
/// Honors `$DOCKER_CONFIG` if set. Tries common key shapes so
/// existing config files (typed via `docker login`) Just Work:
///   - `registry` (e.g. `ghcr.io`)
///   - `https://registry/v1/` (legacy docker hub style)
///   - `https://registry`
fn docker_config_auth(registry: &str) -> Option<RegistryCreds> {
    let config_path = std::env::var_os("DOCKER_CONFIG")
        .map(|d| PathBuf::from(d).join("config.json"))
        .unwrap_or_else(|| home_join(".docker/config.json"));
    let text = std::fs::read_to_string(&config_path).ok()?;
    let json: serde_json::Value = serde_json::from_str(&text).ok()?;
    let auths = json.get("auths")?.as_object()?;
    // Docker Hub special-case: `index.docker.io` is the v2 host;
    // legacy `docker login` still writes its key as
    // `https://index.docker.io/v1/`.
    let docker_hub_aliases = ["docker.io", "index.docker.io", "registry-1.docker.io"];
    let is_docker_hub = docker_hub_aliases.contains(&registry);
    let mut keys: Vec<String> = vec![
        registry.to_string(),
        format!("https://{registry}"),
        format!("https://{registry}/"),
        format!("https://{registry}/v1/"),
        format!("https://{registry}/v2/"),
    ];
    if is_docker_hub {
        for alias in &docker_hub_aliases {
            keys.push(format!("https://{alias}/v1/"));
            keys.push(format!("https://{alias}/v2/"));
            keys.push(format!("https://{alias}"));
            keys.push((*alias).to_string());
        }
    }
    for key in &keys {
        let entry = match auths.get(key) {
            Some(e) => e,
            None => continue,
        };
        let auth_b64 = entry.get("auth").and_then(|v| v.as_str())?;
        let decoded = b64_decode(auth_b64.trim())?;
        let s = String::from_utf8(decoded).ok()?;
        let (user, pass) = s.split_once(':')?;
        return Some(RegistryCreds {
            user: user.to_owned(),
            pass: pass.to_owned(),
        });
    }
    None
}

/// Tiny no-deps base64 decoder. Used only for `auth` strings out
/// of `~/.docker/config.json`, which are short and well-formed.
fn b64_decode(s: &str) -> Option<Vec<u8>> {
    let mut lookup = [255u8; 256];
    let table = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i, &b) in table.iter().enumerate() {
        lookup[b as usize] = i as u8;
    }
    let mut out = Vec::new();
    let mut buf: u32 = 0;
    let mut bits: u32 = 0;
    for &b in s.as_bytes() {
        if b == b'=' {
            break;
        }
        if matches!(b, b'\n' | b'\r' | b' ' | b'\t') {
            continue;
        }
        let v = lookup[b as usize];
        if v == 255 {
            return None;
        }
        buf = (buf << 6) | u32::from(v);
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((buf >> bits) as u8);
            buf &= (1u32 << bits).wrapping_sub(1);
        }
    }
    Some(out)
}

/// Tiny base64 encoder. Used to format the `Basic` auth header.
fn b64_encode(bytes: &[u8]) -> String {
    let table = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(((bytes.len() + 2) / 3) * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
        out.push(table[((n >> 18) & 0x3f) as usize] as char);
        out.push(table[((n >> 12) & 0x3f) as usize] as char);
        out.push(table[((n >> 6) & 0x3f) as usize] as char);
        out.push(table[(n & 0x3f) as usize] as char);
        i += 3;
    }
    let rem = bytes.len() - i;
    if rem == 1 {
        let n = (bytes[i] as u32) << 16;
        out.push(table[((n >> 18) & 0x3f) as usize] as char);
        out.push(table[((n >> 12) & 0x3f) as usize] as char);
        out.push('=');
        out.push('=');
    } else if rem == 2 {
        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
        out.push(table[((n >> 18) & 0x3f) as usize] as char);
        out.push(table[((n >> 12) & 0x3f) as usize] as char);
        out.push(table[((n >> 6) & 0x3f) as usize] as char);
        out.push('=');
    }
    out
}

struct RegistryImageSource {
    image: RegistryImageRef,
    cached_layout: RefCell<Option<RegistryLayoutCache>>,
}

struct RegistryLayoutCache {
    work_dir: PathBuf,
    layout: PathBuf,
}

impl RegistryImageSource {
    fn cached_layout(&self, force_refresh: bool) -> Result<PathBuf, String> {
        if let Some(cache) = self.cached_layout.borrow().as_ref() {
            return Ok(cache.layout.clone());
        }
        let work_dir = temp_work_dir("supermachine-registry-layout")?;
        let layout = work_dir.join("_oci");
        let result = fetch_registry_to_oci_layout(&self.image, &layout, force_refresh);
        if let Err(err) = result {
            let _ = std::fs::remove_dir_all(work_dir);
            return Err(err);
        }
        *self.cached_layout.borrow_mut() = Some(RegistryLayoutCache {
            work_dir,
            layout: layout.clone(),
        });
        Ok(layout)
    }
}

impl Drop for RegistryImageSource {
    fn drop(&mut self) {
        if let Some(cache) = self.cached_layout.get_mut().take() {
            let _ = std::fs::remove_dir_all(cache.work_dir);
        }
    }
}

impl ImageSource for RegistryImageSource {
    fn local_arch(&self, _image: &str) -> Option<String> {
        None
    }

    fn pull_arm64(&self, _image: &str, force_refresh: bool) -> Result<(), String> {
        self.cached_layout(force_refresh).map(|_| ())
    }

    fn inspect(&self, image: &str) -> Result<serde_json::Value, String> {
        let layout = self.cached_layout(false)?;
        inspect_oci_layout(image, &layout)
    }

    fn save_arm64(&self, _image: &str, work_dir: &Path) -> Result<PathBuf, String> {
        if let Some(cache) = self.cached_layout.borrow().as_ref() {
            return Ok(cache.layout.clone());
        }
        let layout = work_dir.join("_oci");
        fetch_registry_to_oci_layout(&self.image, &layout, false)?;
        Ok(layout)
    }
}

struct HttpResponse {
    status: u16,
    headers: String,
    body: Vec<u8>,
}

struct RegistryManifest {
    manifest_digest: String,
    manifest_bytes: Vec<u8>,
    manifest: serde_json::Value,
    config_digest: String,
    config_bytes: Vec<u8>,
    blob_cache_hits: usize,
    blob_downloads: usize,
    ref_cache_hit: bool,
    ref_cache_age_ms: Option<u128>,
    ref_cache_ttl_ms: u128,
}

struct OciLayoutImageSource {
    path: PathBuf,
}

impl ImageSource for OciLayoutImageSource {
    fn local_arch(&self, _image: &str) -> Option<String> {
        Some("arm64".to_owned())
    }

    fn pull_arm64(&self, _image: &str, _force_refresh: bool) -> Result<(), String> {
        Ok(())
    }

    fn inspect(&self, image: &str) -> Result<serde_json::Value, String> {
        inspect_oci_layout(image, &self.path)
    }

    fn save_arm64(&self, _image: &str, _work_dir: &Path) -> Result<PathBuf, String> {
        Ok(self.path.clone())
    }
}

struct OciArchiveImageSource {
    path: PathBuf,
}

impl ImageSource for OciArchiveImageSource {
    fn local_arch(&self, _image: &str) -> Option<String> {
        Some("arm64".to_owned())
    }

    fn pull_arm64(&self, _image: &str, _force_refresh: bool) -> Result<(), String> {
        Ok(())
    }

    fn inspect(&self, image: &str) -> Result<serde_json::Value, String> {
        let work_dir = temp_work_dir("supermachine-oci-archive-inspect")?;
        let result = (|| {
            let layout = extract_oci_archive(&self.path, &work_dir)?;
            inspect_oci_layout(image, &layout)
        })();
        let _ = std::fs::remove_dir_all(work_dir);
        result
    }

    fn save_arm64(&self, _image: &str, work_dir: &Path) -> Result<PathBuf, String> {
        extract_oci_archive(&self.path, work_dir)
    }
}

/// Path to the VMM worker binary. Tried in order:
///   - $SUPERMACHINE_WORKER_BIN (explicit override)
///   - sibling of the running binary (`cargo install` layout —
///     `~/.cargo/bin/supermachine-worker` next to
///     `~/.cargo/bin/supermachine`)
///   - dev-tree:        `<root>/target/release/supermachine-worker`
///   - tarball install: `<root>/bin/supermachine-worker`
///
/// Returns the dev-tree path as a last-resort default so error
/// messages from the caller point somewhere actionable.
pub(crate) fn supermachine_worker_bin(root: &Path) -> PathBuf {
    // Delegate to the single canonical locator so this and the
    // `Image::acquire` pool-spawn path can't drift apart. The
    // unified locator handles env-var override, sibling-of-exe,
    // canonicalize-fallback for symlinked installs, $CARGO_HOME,
    // and $PATH walk. Falls through to `root.join(...)` only if
    // none of those work, and emits the dev-tree fallback as a
    // last resort so error messages from the caller still point
    // at a well-known location instead of a bogus default.
    if let Some(p) = crate::codesign::locate_worker_bin() {
        #[cfg(target_os = "macos")]
        {
            let _ = crate::codesign::ensure_worker_signed(&p);
        }
        return p;
    }
    for candidate in [
        "target/release/supermachine-worker",
        "bin/supermachine-worker",
    ] {
        let p = root.join(candidate);
        if p.is_file() {
            return p;
        }
    }
    root.join("target/release/supermachine-worker")
}

/// Path to the Linux kernel image used by every microVM. Tried in
/// order:
///   - dev-tree:        `<root>/crates/supermachine-kernel/kernel`
///   - tarball install: `<root>/share/supermachine/kernel`
///   - bundled extract: `$XDG_DATA_HOME/supermachine/v{VERSION}/kernel`
///     auto-extracted from the linked-in `supermachine-kernel` crate
///     on first call (the cargo-install path)
///
/// Returns the dev-tree path as a last-resort default so error
/// messages from the caller point somewhere actionable.
pub(crate) fn supermachine_kernel(root: &Path) -> PathBuf {
    for candidate in [
        "crates/supermachine-kernel/kernel",
        "share/supermachine/kernel",
    ] {
        let p = root.join(candidate);
        if p.is_file() {
            return p;
        }
    }
    if let Some(p) = crate::assets::AssetPaths::discover().kernel {
        return p;
    }
    root.join("crates/supermachine-kernel/kernel")
}

fn select_image_source(image: &str) -> Result<Box<dyn ImageSource>, String> {
    if let Some(path) = image.strip_prefix("oci-layout:") {
        let path = PathBuf::from(path);
        if !path.join("index.json").is_file() {
            return Err(format!("OCI layout missing index.json: {}", path.display()));
        }
        return Ok(Box::new(OciLayoutImageSource { path }));
    }
    if let Some(path) = image.strip_prefix("oci-archive:") {
        let path = PathBuf::from(path);
        if !path.is_file() {
            return Err(format!("OCI archive not found: {}", path.display()));
        }
        return Ok(Box::new(OciArchiveImageSource { path }));
    }
    if std::env::var("SUPERMACHINE_IMAGE_SOURCE")
        .map(|v| v == "docker")
        .unwrap_or(false)
    {
        return Ok(Box::new(DockerImageSource));
    }
    Ok(Box::new(RegistryImageSource {
        image: parse_registry_image_ref(image)?,
        cached_layout: RefCell::new(None),
    }))
}

fn parse_registry_image_ref(image: &str) -> Result<RegistryImageRef, String> {
    let (name, reference) = if let Some((name, digest)) = image.rsplit_once('@') {
        (name, digest.to_owned())
    } else {
        let slash = image.rfind('/');
        let colon = image.rfind(':');
        if let Some(colon) = colon.filter(|colon| slash.map(|slash| *colon > slash).unwrap_or(true))
        {
            (&image[..colon], image[colon + 1..].to_owned())
        } else {
            (image, "latest".to_owned())
        }
    };
    let first = name.split('/').next().unwrap_or_default();
    let has_registry = first.contains('.') || first.contains(':') || first == "localhost";
    let (registry, repository) = if has_registry {
        let Some((registry, repository)) = name.split_once('/') else {
            return Err(format!("invalid registry image reference: {image}"));
        };
        (registry.to_owned(), repository.to_owned())
    } else {
        let repository = if name.contains('/') {
            name.to_owned()
        } else {
            format!("library/{name}")
        };
        ("registry-1.docker.io".to_owned(), repository)
    };
    if repository.is_empty() || reference.is_empty() {
        return Err(format!("invalid image reference: {image}"));
    }
    Ok(RegistryImageRef {
        registry,
        repository,
        reference,
    })
}

fn registry_accept_header() -> &'static str {
    "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json"
}

/// Authorization choice for a single registry request.
#[derive(Default)]
enum RegistryAuth<'a> {
    #[default]
    None,
    Bearer(&'a str),
    /// `Basic <base64>` — used for the registry token endpoint
    /// when the user has creds in `~/.docker/config.json`. We
    /// also use this directly against repositories on registries
    /// that don't issue a bearer challenge (e.g. Harbor in some
    /// configurations).
    Basic(&'a RegistryCreds),
}

fn curl_request(
    url: &str,
    accept: Option<&str>,
    auth: RegistryAuth<'_>,
    output_path: Option<&Path>,
) -> Result<HttpResponse, String> {
    let work_dir = temp_work_dir("supermachine-curl")?;
    let headers_path = work_dir.join("headers");
    let body_path = output_path
        .map(PathBuf::from)
        .unwrap_or_else(|| work_dir.join("body"));
    let result = (|| {
        let mut cmd = Command::new("curl");
        cmd.arg("-sS")
            .arg("-L")
            .arg("-w")
            .arg("%{http_code}")
            .arg("-D")
            .arg(&headers_path)
            .arg("-o")
            .arg(&body_path);
        if let Some(accept) = accept {
            cmd.arg("-H").arg(format!("Accept: {accept}"));
        }
        match auth {
            RegistryAuth::None => {}
            RegistryAuth::Bearer(token) => {
                cmd.arg("-H").arg(format!("Authorization: Bearer {token}"));
            }
            RegistryAuth::Basic(creds) => {
                cmd.arg("-H")
                    .arg(format!("Authorization: {}", creds.basic_header_value()));
            }
        }
        cmd.arg(url);
        let out = command_output(cmd, "curl")?;
        let status = out
            .trim()
            .parse::<u16>()
            .map_err(|e| format!("parse curl status for {url}: {e}; output={out:?}"))?;
        let headers = std::fs::read_to_string(&headers_path)
            .map_err(|e| format!("read curl headers: {e}"))?;
        let body = if output_path.is_some() {
            Vec::new()
        } else {
            std::fs::read(&body_path).map_err(|e| format!("read curl body: {e}"))?
        };
        Ok(HttpResponse {
            status,
            headers,
            body,
        })
    })();
    let _ = std::fs::remove_dir_all(work_dir);
    result
}

fn parse_bearer_challenge(headers: &str) -> Option<(String, String, String)> {
    let line = headers
        .lines()
        .find(|line| line.to_ascii_lowercase().starts_with("www-authenticate:"))?;
    let value = line.split_once(':')?.1.trim();
    let params = value.strip_prefix("Bearer ")?;
    let mut realm = None;
    let mut service = None;
    let mut scope = None;
    for part in params.split(',') {
        let (k, v) = part.trim().split_once('=')?;
        let v = v.trim().trim_matches('"').to_owned();
        match k {
            "realm" => realm = Some(v),
            "service" => service = Some(v),
            "scope" => scope = Some(v),
            _ => {}
        }
    }
    Some((
        realm?,
        service.unwrap_or_default(),
        scope.unwrap_or_default(),
    ))
}

fn url_encode_query(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

fn registry_token(
    realm: &str,
    service: &str,
    scope: &str,
    creds: Option<&RegistryCreds>,
) -> Result<String, String> {
    let mut url = format!("{realm}?service={}", url_encode_query(service));
    if !scope.is_empty() {
        url.push_str("&scope=");
        url.push_str(&url_encode_query(scope));
    }
    // Anonymous tokens still get issued for public images even
    // when creds are present; we send Basic only when we have it
    // so private repos work, while public repos stay zero-conf.
    let auth = match creds {
        Some(c) => RegistryAuth::Basic(c),
        None => RegistryAuth::None,
    };
    let resp = curl_request(&url, None, auth, None)?;
    if resp.status >= 400 {
        return Err(format!(
            "registry token request failed with HTTP {} (creds={})",
            resp.status,
            if creds.is_some() { "yes" } else { "no" },
        ));
    }
    let json: serde_json::Value =
        serde_json::from_slice(&resp.body).map_err(|e| format!("registry token JSON: {e}"))?;
    json.get("token")
        .or_else(|| json.get("access_token"))
        .and_then(|v| v.as_str())
        .map(ToOwned::to_owned)
        .ok_or_else(|| "registry token response missing token".to_owned())
}

fn registry_request(
    image: &RegistryImageRef,
    path: &str,
    accept: Option<&str>,
    output_path: Option<&Path>,
) -> Result<HttpResponse, String> {
    let url = format!(
        "https://{}/v2/{}/{}",
        image.registry, image.repository, path
    );
    let creds = docker_config_auth(&image.registry);
    // First attempt: unauth. Most public repos answer 200 here;
    // private repos answer 401 with a bearer challenge.
    let first = curl_request(&url, accept, RegistryAuth::None, output_path)?;
    if first.status != 401 {
        return Ok(first);
    }
    let (realm, service, scope) = parse_bearer_challenge(&first.headers)
        .ok_or_else(|| format!("registry auth challenge missing/unsupported for {url}"))?;
    let token = registry_token(&realm, &service, &scope, creds.as_ref())?;
    curl_request(&url, accept, RegistryAuth::Bearer(&token), output_path)
}

fn read_registry_manifest(
    image: &RegistryImageRef,
    force_refresh: bool,
) -> Result<RegistryManifest, String> {
    let ref_cache_ttl_ms = registry_ref_cache_ttl_ms();
    if !force_refresh {
        if let Some(cached) = read_registry_ref_cache(image, ref_cache_ttl_ms)? {
            return Ok(cached);
        }
    }

    let mut blob_cache_hits = 0usize;
    let mut blob_downloads = 0usize;
    let resp = registry_request(
        image,
        &format!("manifests/{}", image.reference),
        Some(registry_accept_header()),
        None,
    )?;
    if resp.status >= 400 {
        return Err(format!(
            "registry manifest request failed for {}/{}:{} with HTTP {}",
            image.registry, image.repository, image.reference, resp.status
        ));
    }
    let root: serde_json::Value =
        serde_json::from_slice(&resp.body).map_err(|e| format!("registry manifest JSON: {e}"))?;
    let manifest_bytes = if root.get("manifests").is_some() {
        let desc = find_registry_manifest_descriptor(&root)?;
        let digest = desc
            .get("digest")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "registry arm64 descriptor missing digest".to_owned())?;
        let (bytes, cache_hit) = read_or_fetch_registry_blob_bytes(
            image,
            digest,
            &format!("manifests/{digest}"),
            Some(registry_accept_header()),
        )?;
        if cache_hit {
            blob_cache_hits += 1;
        } else {
            blob_downloads += 1;
        }
        bytes
    } else {
        let manifest_digest = sha256_bytes(&resp.body)?;
        store_registry_blob_bytes(&manifest_digest, &resp.body)?;
        blob_downloads += 1;
        resp.body
    };
    let manifest: serde_json::Value = serde_json::from_slice(&manifest_bytes)
        .map_err(|e| format!("registry arm64 manifest JSON: {e}"))?;
    let config_digest = manifest
        .get("config")
        .and_then(|v| v.get("digest"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| "registry manifest missing config digest".to_owned())?
        .to_owned();
    let manifest_digest = sha256_bytes(&manifest_bytes)?;
    let (config_bytes, cache_hit) = read_or_fetch_registry_blob_bytes(
        image,
        &config_digest,
        &format!("blobs/{config_digest}"),
        None,
    )?;
    if cache_hit {
        blob_cache_hits += 1;
    } else {
        blob_downloads += 1;
    }
    serde_json::from_slice::<serde_json::Value>(&config_bytes)
        .map_err(|e| format!("registry config JSON: {e}"))?;
    write_registry_ref_cache(image, &manifest_digest, &config_digest)?;
    Ok(RegistryManifest {
        manifest_digest,
        manifest_bytes,
        manifest,
        config_digest,
        config_bytes,
        blob_cache_hits,
        blob_downloads,
        ref_cache_hit: false,
        ref_cache_age_ms: None,
        ref_cache_ttl_ms,
    })
}

fn find_registry_manifest_descriptor(
    index: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let manifests = index
        .get("manifests")
        .and_then(|v| v.as_array())
        .ok_or_else(|| "registry index missing manifests".to_owned())?;
    manifests
        .iter()
        .find(|desc| {
            descriptor_platform_arch(desc) == Some("arm64")
                && desc
                    .get("platform")
                    .and_then(|p| p.get("os"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("linux")
                    == "linux"
        })
        .cloned()
        .ok_or_else(|| "registry image has no linux/arm64 manifest".to_owned())
}

fn sha256_bytes(bytes: &[u8]) -> Result<String, String> {
    let work_dir = temp_work_dir("supermachine-json-sha")?;
    let path = work_dir.join("blob");
    let result = (|| {
        std::fs::write(&path, bytes).map_err(|e| format!("write digest blob: {e}"))?;
        sha256_file(&path)
    })();
    let _ = std::fs::remove_dir_all(work_dir);
    result
}

fn epoch_ms() -> Result<u128, String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .map_err(|e| format!("system time before Unix epoch: {e}"))
}

fn registry_ref_cache_ttl_ms() -> u128 {
    std::env::var("SUPERMACHINE_REGISTRY_REF_CACHE_TTL_MS")
        .ok()
        .and_then(|s| s.parse::<u128>().ok())
        .unwrap_or(60_000)
}

fn registry_ref_cache_dir() -> PathBuf {
    layer_cache_dir().join("registry/refs")
}

fn registry_ref_cache_path(image: &RegistryImageRef) -> Result<PathBuf, String> {
    let key = sha256_text(&format!(
        "{}\n{}\n{}\nlinux/arm64\n",
        image.registry, image.repository, image.reference
    ))?;
    Ok(registry_ref_cache_dir().join(format!("{key}.json")))
}

fn read_registry_ref_cache(
    image: &RegistryImageRef,
    ttl_ms: u128,
) -> Result<Option<RegistryManifest>, String> {
    if ttl_ms == 0 {
        return Ok(None);
    }
    let path = registry_ref_cache_path(image)?;
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read registry ref cache {}: {e}", path.display())),
    };
    let json: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| format!("parse registry ref cache {}: {e}", path.display()))?;
    if json.get("version").and_then(|v| v.as_u64()) != Some(1) {
        return Ok(None);
    }
    let created_ms = json
        .get("created_ms")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| format!("registry ref cache {} missing created_ms", path.display()))?
        as u128;
    let age_ms = epoch_ms()?.saturating_sub(created_ms);
    if age_ms > ttl_ms {
        return Ok(None);
    }
    let manifest_digest = json
        .get("manifest_digest")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            format!(
                "registry ref cache {} missing manifest_digest",
                path.display()
            )
        })?
        .to_owned();
    let config_digest = json
        .get("config_digest")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            format!(
                "registry ref cache {} missing config_digest",
                path.display()
            )
        })?
        .to_owned();

    let manifest_path = registry_blob_cache_path(&manifest_digest)?;
    let config_path = registry_blob_cache_path(&config_digest)?;
    let manifest_bytes = match std::fs::read(&manifest_path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(format!(
                "read registry manifest cache {}: {e}",
                manifest_path.display()
            ))
        }
    };
    let config_bytes = match std::fs::read(&config_path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(format!(
                "read registry config cache {}: {e}",
                config_path.display()
            ))
        }
    };
    let manifest: serde_json::Value = serde_json::from_slice(&manifest_bytes)
        .map_err(|e| format!("registry cached manifest JSON: {e}"))?;
    let manifest_config_digest = manifest
        .get("config")
        .and_then(|v| v.get("digest"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| "registry cached manifest missing config digest".to_owned())?;
    if manifest_config_digest != config_digest {
        return Ok(None);
    }
    serde_json::from_slice::<serde_json::Value>(&config_bytes)
        .map_err(|e| format!("registry cached config JSON: {e}"))?;
    Ok(Some(RegistryManifest {
        manifest_digest,
        manifest_bytes,
        manifest,
        config_digest,
        config_bytes,
        blob_cache_hits: 2,
        blob_downloads: 0,
        ref_cache_hit: true,
        ref_cache_age_ms: Some(age_ms),
        ref_cache_ttl_ms: ttl_ms,
    }))
}

fn write_registry_ref_cache(
    image: &RegistryImageRef,
    manifest_digest: &str,
    config_digest: &str,
) -> Result<(), String> {
    let path = registry_ref_cache_path(image)?;
    let dir = path
        .parent()
        .ok_or_else(|| format!("registry ref cache path has no parent: {}", path.display()))?;
    std::fs::create_dir_all(dir).map_err(|e| format!("create registry ref cache: {e}"))?;
    let json = serde_json::json!({
        "version": 1,
        "created_ms": epoch_ms()?,
        "registry": image.registry,
        "repository": image.repository,
        "reference": image.reference,
        "platform": {"os": "linux", "architecture": "arm64"},
        "manifest_digest": manifest_digest,
        "config_digest": config_digest,
    });
    let tmp = path.with_extension(format!(
        "json.{}.{}.tmp",
        std::process::id(),
        TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    std::fs::write(
        &tmp,
        serde_json::to_vec_pretty(&json).map_err(|e| format!("encode registry ref cache: {e}"))?,
    )
    .map_err(|e| format!("write registry ref cache {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, &path).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        format!(
            "install registry ref cache {} -> {}: {e}",
            tmp.display(),
            path.display()
        )
    })
}

fn registry_blob_cache_dir() -> PathBuf {
    layer_cache_dir().join("registry/blobs/sha256")
}

fn registry_blob_cache_path(digest: &str) -> Result<PathBuf, String> {
    let sha = strip_sha256(digest);
    if sha.is_empty() || sha.contains('/') {
        return Err(format!("unsupported registry blob digest: {digest}"));
    }
    Ok(registry_blob_cache_dir().join(sha))
}

fn registry_blob_tmp_path(sha: &str) -> PathBuf {
    let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    registry_blob_cache_dir().join(format!(".{sha}.{}.{}.tmp", std::process::id(), unique))
}

fn store_registry_blob_bytes(sha: &str, bytes: &[u8]) -> Result<(), String> {
    let cache = registry_blob_cache_path(sha)?;
    if cache.is_file() {
        return Ok(());
    }
    let actual = sha256_bytes(bytes)?;
    if actual != strip_sha256(sha) {
        return Err(format!(
            "registry blob digest mismatch: expected {}, got {actual}",
            strip_sha256(sha)
        ));
    }
    std::fs::create_dir_all(registry_blob_cache_dir())
        .map_err(|e| format!("create registry blob cache: {e}"))?;
    let tmp = registry_blob_tmp_path(&strip_sha256(sha));
    std::fs::write(&tmp, bytes)
        .map_err(|e| format!("write registry cache {}: {e}", tmp.display()))?;
    match std::fs::rename(&tmp, &cache) {
        Ok(()) => Ok(()),
        Err(e) if cache.is_file() => {
            let _ = std::fs::remove_file(&tmp);
            let _ = e;
            Ok(())
        }
        Err(e) => {
            let _ = std::fs::remove_file(&tmp);
            Err(format!(
                "install registry cache {} -> {}: {e}",
                tmp.display(),
                cache.display()
            ))
        }
    }
}

fn read_or_fetch_registry_blob_bytes(
    image: &RegistryImageRef,
    digest: &str,
    registry_path: &str,
    accept: Option<&str>,
) -> Result<(Vec<u8>, bool), String> {
    let cache = registry_blob_cache_path(digest)?;
    if cache.is_file() {
        let bytes = std::fs::read(&cache)
            .map_err(|e| format!("read registry cache {}: {e}", cache.display()))?;
        return Ok((bytes, true));
    }
    let resp = registry_request(image, registry_path, accept, None)?;
    if resp.status >= 400 {
        return Err(format!("registry blob {digest} HTTP {}", resp.status));
    }
    store_registry_blob_bytes(digest, &resp.body)?;
    Ok((resp.body, false))
}

fn copy_or_fetch_registry_blob_to_layout(
    image: &RegistryImageRef,
    digest: &str,
    out: &Path,
) -> Result<bool, String> {
    if out.is_file() {
        return Ok(true);
    }
    let cache = registry_blob_cache_path(digest)?;
    if cache.is_file() {
        std::fs::copy(&cache, out).map_err(|e| {
            format!(
                "copy registry cache {} -> {}: {e}",
                cache.display(),
                out.display()
            )
        })?;
        return Ok(true);
    }

    std::fs::create_dir_all(registry_blob_cache_dir())
        .map_err(|e| format!("create registry blob cache: {e}"))?;
    let sha = strip_sha256(digest);
    let tmp = registry_blob_tmp_path(&sha);
    let resp = registry_request(image, &format!("blobs/{digest}"), None, Some(&tmp))?;
    if resp.status >= 400 {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!("registry layer blob {digest} HTTP {}", resp.status));
    }
    let actual = sha256_file(&tmp)?;
    if actual != sha {
        let _ = std::fs::remove_file(&tmp);
        return Err(format!(
            "registry blob digest mismatch: expected {sha}, got {actual}"
        ));
    }
    match std::fs::rename(&tmp, &cache) {
        Ok(()) => {}
        Err(e) if cache.is_file() => {
            let _ = std::fs::remove_file(&tmp);
            let _ = e;
        }
        Err(e) => {
            let _ = std::fs::remove_file(&tmp);
            return Err(format!(
                "install registry cache {} -> {}: {e}",
                tmp.display(),
                cache.display()
            ));
        }
    }
    std::fs::copy(&cache, out).map_err(|e| {
        format!(
            "copy registry cache {} -> {}: {e}",
            cache.display(),
            out.display()
        )
    })?;
    Ok(false)
}

fn fetch_registry_to_oci_layout(
    image: &RegistryImageRef,
    layout: &Path,
    force_refresh: bool,
) -> Result<(), String> {
    let _ = std::fs::remove_dir_all(layout);
    std::fs::create_dir_all(layout.join("blobs/sha256"))
        .map_err(|e| format!("create registry OCI layout {}: {e}", layout.display()))?;
    std::fs::write(
        layout.join("oci-layout"),
        r#"{"imageLayoutVersion":"1.0.0"}"#,
    )
    .map_err(|e| format!("write OCI layout marker: {e}"))?;
    let rm = read_registry_manifest(image, force_refresh)?;
    let mut blob_cache_hits = rm.blob_cache_hits;
    let mut blob_downloads = rm.blob_downloads;
    if trace_enabled() {
        eprintln!(
            "supermachine: registry ref cache_hit={} age_ms={} ttl_ms={} cache={}",
            rm.ref_cache_hit,
            rm.ref_cache_age_ms
                .map(|age| age.to_string())
                .unwrap_or_default(),
            rm.ref_cache_ttl_ms,
            registry_ref_cache_dir().display()
        );
    }
    write_oci_blob_bytes(layout, &rm.manifest_digest, &rm.manifest_bytes)?;
    write_oci_blob_bytes(layout, &strip_sha256(&rm.config_digest), &rm.config_bytes)?;
    let layers = rm
        .manifest
        .get("layers")
        .and_then(|v| v.as_array())
        .ok_or_else(|| "registry manifest missing layers".to_owned())?;
    for layer in layers {
        let digest = layer
            .get("digest")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "registry layer missing digest".to_owned())?;
        let sha = strip_sha256(digest);
        let out = layout.join("blobs/sha256").join(&sha);
        if out.is_file() {
            blob_cache_hits += 1;
            continue;
        }
        if copy_or_fetch_registry_blob_to_layout(image, digest, &out)? {
            blob_cache_hits += 1;
        } else {
            blob_downloads += 1;
        }
    }
    let index = serde_json::json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.index.v1+json",
        "manifests": [{
            "mediaType": "application/vnd.oci.image.manifest.v1+json",
            "digest": format!("sha256:{}", rm.manifest_digest),
            "platform": {"architecture": "arm64", "os": "linux"}
        }]
    });
    std::fs::write(
        layout.join("index.json"),
        serde_json::to_vec_pretty(&index).map_err(|e| format!("encode OCI index: {e}"))?,
    )
    .map_err(|e| format!("write OCI index: {e}"))?;
    if trace_enabled() {
        eprintln!(
            "supermachine: registry blobs cache_hits={} downloads={} cache={}",
            blob_cache_hits,
            blob_downloads,
            registry_blob_cache_dir().display()
        );
    }
    Ok(())
}

fn write_oci_blob_bytes(layout: &Path, sha: &str, bytes: &[u8]) -> Result<(), String> {
    let path = layout.join("blobs/sha256").join(sha);
    if path.is_file() {
        return Ok(());
    }
    std::fs::write(&path, bytes).map_err(|e| format!("write OCI blob {}: {e}", path.display()))
}

fn extract_oci_archive(archive: &Path, work_dir: &Path) -> Result<PathBuf, String> {
    let layout = work_dir.join("_oci");
    let _ = std::fs::remove_dir_all(&layout);
    std::fs::create_dir_all(&layout)
        .map_err(|e| format!("create OCI archive extract dir {}: {e}", layout.display()))?;
    let mut tar = Command::new("tar");
    tar.arg("-xf").arg(archive).arg("-C").arg(&layout);
    run_status(tar, "extract OCI archive")?;
    if !layout.join("index.json").is_file() {
        return Err(format!(
            "OCI archive {} did not contain index.json at archive root",
            archive.display()
        ));
    }
    Ok(layout)
}

fn blob_path(layout: &Path, digest: &str) -> Result<PathBuf, String> {
    let sha = strip_sha256(digest);
    if sha.is_empty() || sha.contains('/') {
        return Err(format!("unsupported OCI digest: {digest}"));
    }
    Ok(layout.join("blobs/sha256").join(sha))
}

fn read_oci_json_blob(
    layout: &Path,
    digest: &str,
    label: &str,
) -> Result<serde_json::Value, String> {
    let path = blob_path(layout, digest)?;
    let text = std::fs::read_to_string(&path)
        .map_err(|e| format!("read OCI {label} {}: {e}", path.display()))?;
    serde_json::from_str(&text).map_err(|e| format!("parse OCI {label} {}: {e}", path.display()))
}

fn descriptor_platform_arch(desc: &serde_json::Value) -> Option<&str> {
    desc.get("platform")
        .and_then(|p| p.get("architecture"))
        .and_then(|v| v.as_str())
}

fn find_oci_manifest_descriptor(
    layout: &Path,
    index: &serde_json::Value,
    depth: usize,
) -> Result<serde_json::Value, String> {
    if depth > 4 {
        return Err("nested OCI image index too deep".to_owned());
    }
    let manifests = index
        .get("manifests")
        .and_then(|v| v.as_array())
        .ok_or_else(|| "OCI index missing manifests".to_owned())?;

    for desc in manifests {
        if descriptor_platform_arch(desc) == Some("arm64") {
            let media_type = desc
                .get("mediaType")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            if media_type.contains("image.index") || media_type.contains("manifest.list") {
                let digest = desc
                    .get("digest")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| "nested OCI index descriptor missing digest".to_owned())?;
                let nested = read_oci_json_blob(layout, digest, "nested index")?;
                return find_oci_manifest_descriptor(layout, &nested, depth + 1);
            }
            return Ok(desc.clone());
        }
    }
    Err("OCI layout has no linux/arm64 image manifest".to_owned())
}

fn inspect_oci_layout(image: &str, layout: &Path) -> Result<serde_json::Value, String> {
    let index_text = std::fs::read_to_string(layout.join("index.json")).map_err(|e| {
        format!(
            "read OCI layout index {}: {e}",
            layout.join("index.json").display()
        )
    })?;
    let index: serde_json::Value =
        serde_json::from_str(&index_text).map_err(|e| format!("parse OCI layout index: {e}"))?;
    let manifest_desc = find_oci_manifest_descriptor(layout, &index, 0)?;
    let manifest_digest = manifest_desc
        .get("digest")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "OCI manifest descriptor missing digest".to_owned())?;
    let manifest = read_oci_json_blob(layout, manifest_digest, "manifest")?;
    let config_digest = manifest
        .get("config")
        .and_then(|v| v.get("digest"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| "OCI manifest missing config digest".to_owned())?;
    let config = read_oci_json_blob(layout, config_digest, "config")?;
    let cfg = config
        .get("config")
        .cloned()
        .unwrap_or_else(|| serde_json::json!({}));
    let arch = config
        .get("architecture")
        .and_then(|v| v.as_str())
        .or_else(|| descriptor_platform_arch(&manifest_desc))
        .unwrap_or("arm64");
    Ok(serde_json::json!({
        "Id": format!("sha256:{}", strip_sha256(config_digest)),
        "Architecture": arch,
        "RepoTags": [image],
        "Config": {
            "Env": cfg.get("Env").cloned().unwrap_or(serde_json::Value::Null),
            "Entrypoint": cfg.get("Entrypoint").cloned().unwrap_or(serde_json::Value::Null),
            "Cmd": cfg.get("Cmd").cloned().unwrap_or(serde_json::Value::Null),
            "WorkingDir": cfg.get("WorkingDir").cloned().unwrap_or(serde_json::Value::Null),
            "User": cfg.get("User").cloned().unwrap_or(serde_json::Value::Null),
        }
    }))
}

struct BakePlan<'a> {
    image: &'a str,
    name: Option<&'a str>,
    runtime: &'a str,
    guest_port: u16,
    memory_mib: u32,
    vcpus: u32,
    pull_policy: &'a str,
    snapshots_dir: &'a Path,
    cmd_override: Option<&'a str>,
    extra_args: &'a [String],
}

impl<'a> BakePlan<'a> {
    fn from_request(request: &'a BakeRequest) -> Self {
        Self {
            image: &request.image,
            name: request.name.as_deref(),
            runtime: &request.runtime,
            guest_port: request.guest_port,
            memory_mib: request.memory_mib,
            vcpus: request.vcpus,
            pull_policy: &request.pull_policy,
            snapshots_dir: &request.snapshots_dir,
            cmd_override: request.cmd_override.as_deref(),
            extra_args: &request.extra_args,
        }
    }

    fn snapshot_name(&self) -> String {
        self.name
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| sanitized_snapshot_name(self.image))
    }

    fn metadata_path(&self) -> PathBuf {
        self.snapshots_dir
            .join(self.snapshot_name())
            .join("metadata.json")
    }

    fn command(&self, root: &Path) -> Result<Command, String> {
        let push = root.join("tools/supermachine-push");
        if !push.is_file() {
            return Err(format!("missing image bake tool: {}", push.display()));
        }
        let mut cmd = Command::new(push);
        cmd.arg(self.image)
            .arg("--runtime")
            .arg(self.runtime)
            .arg("--port")
            .arg(self.guest_port.to_string())
            .arg("--memory")
            .arg(self.memory_mib.to_string())
            .arg("--pull")
            .arg("never")
            .env("SUPERMACHINE_SNAPSHOTS", self.snapshots_dir);
        if let Some(name) = self.name {
            cmd.arg("--name").arg(name);
        }
        cmd.args(self.extra_args);
        Ok(cmd)
    }
}

struct ImageResolution {
    local_arch: Option<String>,
    architecture: Option<String>,
    image_id: Option<String>,
    effective_cmd: Vec<String>,
    working_dir: Option<String>,
    user: Option<String>,
    env: Vec<String>,
    env_count: usize,
    pull_action: String,
    inspect_ms: u128,
}

struct LayerPlan {
    cache_dir: PathBuf,
    index_path: Option<PathBuf>,
    layer_shas: Vec<String>,
    save_work_dir: Option<PathBuf>,
    save_dir: Option<PathBuf>,
    cached_layers: usize,
    missing_layers: usize,
    manifest_cache_hit: bool,
    plan_ms: u128,
}

struct LayerMaterialization {
    materialize_ms: u128,
    built_layers: usize,
    reused_layers: usize,
}

struct DeltaMaterialization {
    prepare_ms: u128,
    materialize_ms: u128,
    cache_hit: bool,
    skipped: Option<String>,
    key: Option<String>,
    cache_path: Option<PathBuf>,
}

struct NativeBakeResult {
    total_ms: u128,
    timings: serde_json::Value,
    reused: bool,
}

static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

fn emit_image_resolution_trace(resolution: &ImageResolution) {
    let cmd_json =
        serde_json::to_string(&resolution.effective_cmd).unwrap_or_else(|_| "[]".to_owned());
    eprintln!(
        "supermachine: image resolved inspect_ms={} pull={} local_arch={} arch={} image_id={} env_count={} cmd={}",
        resolution.inspect_ms,
        resolution.pull_action,
        resolution.local_arch.as_deref().unwrap_or(""),
        resolution.architecture.as_deref().unwrap_or(""),
        resolution
            .image_id
            .as_deref()
            .map(|s| &s[..s.len().min(16)])
            .unwrap_or(""),
        resolution.env_count,
        cmd_json
    );
}

pub fn run_push(request: &BakeRequest, run_t0: Instant, root: &Path) -> Result<(), String> {
    let plan = BakePlan::from_request(request);
    if trace_enabled() {
        eprintln!(
            "supermachine: bake plan image={} name={} runtime={} port={} memory={}MiB snapshots={} pull={}",
            plan.image,
            plan.snapshot_name(),
            plan.runtime,
            plan.guest_port,
            plan.memory_mib,
            plan.snapshots_dir.display(),
            plan.pull_policy
        );
    }

    // Fast cache-hit check: if the snapshot's stored bake inputs
    // already match the cheap subset of inputs we can compute
    // without hitting the registry, return immediately. Skips
    // `select_image_source` + `resolve_image` (the slow path for
    // a fresh process — manifest fetch / `docker inspect`). User
    // can force the full resolve via `--pull always`.
    if plan.runtime == "supermachine"
        && std::env::var("SUPERMACHINE_NATIVE_BAKE_TAIL")
            .map(|v| v != "0" && v != "false")
            .unwrap_or(true)
    {
        if let Some(result) = try_fast_cache_hit(&plan, root, run_t0)? {
            if trace_enabled() {
                eprintln!(
                    "supermachine: fast cache-hit after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
                eprintln!("supermachine: bake timings {}", result.timings);
            }
            return Ok(());
        }
    }

    let source = select_image_source(plan.image)?;
    let resolution = resolve_image(&plan, source.as_ref())?;
    if trace_enabled() {
        emit_image_resolution_trace(&resolution);
    }
    if plan.runtime == "supermachine"
        && std::env::var("SUPERMACHINE_NATIVE_BAKE_TAIL")
            .map(|v| v != "0" && v != "false")
            .unwrap_or(true)
    {
        if let Some(result) = native_supermachine_early_reuse_snapshot(&plan, &resolution, root, run_t0)?
        {
            if trace_enabled() {
                eprintln!(
                    "supermachine: native bake reused snapshot after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
                eprintln!("supermachine: bake timings {}", result.timings);
                eprintln!(
                    "supermachine: push finished after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
            }
            return Ok(());
        }
    }
    let layer_plan = plan_layers(&plan, &resolution, source.as_ref())?;
    let layer_materialization_result = match layer_plan.as_ref() {
        Some(layer_plan) => {
            materialize_missing_layers(plan.image, layer_plan, source.as_ref()).map(Some)
        }
        None => Ok(None),
    };
    if let Some(work_dir) = layer_plan
        .as_ref()
        .and_then(|layer_plan| layer_plan.save_work_dir.as_deref())
    {
        let _ = std::fs::remove_dir_all(work_dir);
    }
    let layer_materialization = layer_materialization_result?;
    let delta_materialization = materialize_delta_cache(&plan, &resolution, root)?;

    if trace_enabled() {
        if let Some(layer_plan) = layer_plan.as_ref() {
            let first_layer = layer_plan
                .layer_shas
                .first()
                .map(|s| &s[..s.len().min(16)])
                .unwrap_or("");
            eprintln!(
                "supermachine: layer plan plan_ms={} layers={} cached={} missing={} manifest_cache_hit={} cache={} index={} first_layer={}",
                layer_plan.plan_ms,
                layer_plan.layer_shas.len(),
                layer_plan.cached_layers,
                layer_plan.missing_layers,
                layer_plan.manifest_cache_hit,
                layer_plan.cache_dir.display(),
                layer_plan
                    .index_path
                    .as_deref()
                    .map(|p| p.display().to_string())
                    .unwrap_or_default(),
                first_layer
            );
        }
        if let Some(materialization) = layer_materialization.as_ref() {
            eprintln!(
                "supermachine: layer materialize materialize_ms={} built={} reused={}",
                materialization.materialize_ms,
                materialization.built_layers,
                materialization.reused_layers
            );
        }
        if let Some(delta) = delta_materialization.as_ref() {
            eprintln!(
                "supermachine: delta materialize prepare_ms={} materialize_ms={} cache_hit={} skipped={} key={} cache={}",
                delta.prepare_ms,
                delta.materialize_ms,
                delta.cache_hit,
                delta.skipped.as_deref().unwrap_or(""),
                delta
                    .key
                    .as_deref()
                    .map(|key| &key[..key.len().min(16)])
                    .unwrap_or(""),
                delta
                    .cache_path
                    .as_deref()
                    .map(|path| path.display().to_string())
                    .unwrap_or_default()
            );
        }
    }

    if plan.runtime == "supermachine"
        && std::env::var("SUPERMACHINE_NATIVE_BAKE_TAIL")
            .map(|v| v != "0" && v != "false")
            .unwrap_or(true)
    {
        let layer_plan = layer_plan
            .as_ref()
            .ok_or_else(|| "missing layer plan".to_owned())?;
        let delta = delta_materialization
            .as_ref()
            .ok_or_else(|| "missing delta cache".to_owned())?;
        let (native_bake_key, native_bake_inputs) =
            native_supermachine_bake_key(&plan, &resolution, layer_plan, delta, root)?;
        if let Some(result) = native_supermachine_reuse_snapshot(&plan, &native_bake_key, run_t0)? {
            if trace_enabled() {
                eprintln!(
                    "supermachine: native bake reused snapshot after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
                eprintln!("supermachine: bake timings {}", result.timings);
                eprintln!(
                    "supermachine: push finished after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
            }
            return Ok(());
        }
        let native_t0 = Instant::now();
        let result = run_native_supermachine_bake(
            &plan,
            &resolution,
            layer_plan,
            delta,
            root,
            &native_bake_key,
            &native_bake_inputs,
        )?;
        if trace_enabled() {
            if result.reused {
                eprintln!(
                    "supermachine: native bake reused snapshot after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
            } else {
                eprintln!(
                    "supermachine: native bake finished after {}ms total={}ms",
                    result.total_ms,
                    elapsed_ms(run_t0)
                );
            }
            eprintln!("supermachine: bake timings {}", result.timings);
        }
        if trace_enabled() {
            eprintln!(
                "supermachine: push finished after {}ms total={}ms",
                elapsed_ms(native_t0),
                elapsed_ms(run_t0)
            );
        }
        return Ok(());
    }

    let mut cmd = plan.command(root)?;
    let push_t0 = Instant::now();
    let status = cmd
        .status()
        .map_err(|e| format!("supermachine-push: {e}"))?;
    let push_ms = elapsed_ms(push_t0);
    if trace_enabled() {
        eprintln!(
            "supermachine: push finished after {}ms total={}ms",
            push_ms,
            elapsed_ms(run_t0)
        );
    }
    if status.success() {
        emit_bake_timing_metadata(&plan);
        Ok(())
    } else {
        Err(format!(
            "supermachine-push failed with exit code {}",
            status.code().unwrap_or(1)
        ))
    }
}

fn home_join(path: &str) -> PathBuf {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(path)
}

fn layer_cache_dir() -> PathBuf {
    std::env::var_os("SUPERMACHINE_LAYER_CACHE")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine-layer-cache"))
}

fn volumes_dir() -> PathBuf {
    std::env::var_os("SUPERMACHINE_VOLUMES")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_join(".local/supermachine/volumes"))
}

/// One entry from the user's `--volume HOST:GUEST` flag.
///
/// HOST can be either:
/// - a name (no `/`, no `.` prefix): resolved to
///   `~/.local/supermachine/volumes/<name>.img`
/// - an absolute path / relative-with-slashes: used as-is
///
/// GUEST is the absolute mount path inside the guest.
#[derive(Debug, Clone)]
pub(crate) struct VolumeMapping {
    /// Resolved host file path.
    pub host_file: PathBuf,
    /// Mount point inside the guest, must start with `/`.
    pub guest_path: String,
}

/// Parse all `--volume HOST:GUEST` entries from `extra_args` and
/// return them in the order they were specified. Validates that
/// HOST and GUEST are well-formed; does not yet create the host
/// file.
pub(crate) fn parse_volume_args(extra_args: &[String]) -> Result<Vec<VolumeMapping>, String> {
    let mut out = Vec::new();
    for raw in arg_values(extra_args, "--volume") {
        let (host, guest) = raw
            .split_once(':')
            .ok_or_else(|| format!("--volume expects HOST:GUEST, got {raw:?}"))?;
        if host.is_empty() || guest.is_empty() {
            return Err(format!("--volume HOST:GUEST has empty side: {raw:?}"));
        }
        if !guest.starts_with('/') {
            return Err(format!("--volume guest path must be absolute: {guest:?}"));
        }
        if guest.contains('\n') || guest.contains('\r') {
            return Err(format!("--volume guest path contains newline: {guest:?}"));
        }
        let host_file = if host.contains('/') || host.starts_with('.') {
            PathBuf::from(host)
        } else {
            // Sanitize the name so it's safe as a filename.
            if host.chars().any(|c| matches!(c, '/' | '\\' | ':' | '\0')) {
                return Err(format!("--volume name {host:?} contains forbidden chars"));
            }
            volumes_dir().join(format!("{host}.img"))
        };
        out.push(VolumeMapping {
            host_file,
            guest_path: guest.to_owned(),
        });
    }
    Ok(out)
}

/// Locate `mke2fs` (or `mkfs.ext4`) on PATH. Returned path is
/// suitable to pass to `Command::new`.
fn locate_mke2fs() -> Option<PathBuf> {
    for candidate in ["mkfs.ext4", "mke2fs", "/usr/sbin/mkfs.ext4"] {
        if let Ok(out) = Command::new("which").arg(candidate).output() {
            if out.status.success() {
                let p = String::from_utf8_lossy(&out.stdout).trim().to_owned();
                if !p.is_empty() {
                    return Some(PathBuf::from(p));
                }
            }
        }
    }
    // Android SDK ships mke2fs at a known path on macOS dev boxes.
    let android = std::env::var_os("HOME")
        .map(|h| {
            PathBuf::from(h).join("Library/Android/sdk/platform-tools/mke2fs")
        })
        .filter(|p| p.is_file());
    if android.is_some() {
        return android;
    }
    None
}

/// Ensure the host file backing this volume exists and is
/// formatted ext4. Idempotent: if the file already exists at
/// `>= size_bytes`, leave it alone.
pub(crate) fn ensure_volume_host_file(
    mapping: &VolumeMapping,
    size_bytes: u64,
) -> Result<(), String> {
    let path = &mapping.host_file;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("create volume dir {}: {e}", parent.display()))?;
    }
    let already_existed = path.is_file();
    if already_existed {
        let len = std::fs::metadata(path)
            .map_err(|e| format!("stat {}: {e}", path.display()))?
            .len();
        if len >= size_bytes {
            return Ok(());
        }
        // Existing-but-too-small: don't grow silently — that
        // requires an in-place resize2fs which we don't ship.
        // Surface the mismatch so the user can pick a larger
        // size or rm the file.
        return Err(format!(
            "volume {} exists at {len} bytes, smaller than requested {size_bytes}; \
             remove it or pass a smaller size",
            path.display()
        ));
    }

    // Create sparse file at requested size.
    let f = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(path)
        .map_err(|e| format!("create {}: {e}", path.display()))?;
    f.set_len(size_bytes)
        .map_err(|e| format!("truncate {}: {e}", path.display()))?;
    drop(f);

    // Format ext4. Try the host's mke2fs / mkfs.ext4. If neither
    // is on PATH, surface a clear error: the user can install
    // e2fsprogs (Homebrew) or point us at one with $PATH.
    let mke2fs = locate_mke2fs().ok_or_else(|| {
        format!(
            "no `mke2fs` / `mkfs.ext4` on PATH; install e2fsprogs (\
             `brew install e2fsprogs`) so volume {} can be formatted",
            path.display()
        )
    })?;
    let mut cmd = Command::new(&mke2fs);
    // -t ext4: force ext4 (mke2fs default depends on conf file).
    // -F: force on a regular file (no /dev/disk*).
    // -L: label so blkid recognizes it.
    cmd.arg("-t")
        .arg("ext4")
        .arg("-F")
        .arg("-L")
        .arg("supermachine-vol")
        .arg(path)
        .stdout(Stdio::null())
        .stderr(Stdio::piped());
    let out = cmd
        .output()
        .map_err(|e| format!("spawn {}: {e}", mke2fs.display()))?;
    if !out.status.success() {
        // Cleanup the half-formatted file so retry doesn't hit
        // the "already exists" branch above.
        let _ = std::fs::remove_file(path);
        return Err(format!(
            "{} {}: exit {:?}: {}",
            mke2fs.display(),
            path.display(),
            out.status.code(),
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(())
}

fn trace_enabled() -> bool {
    std::env::var_os("SUPERMACHINE_RUN_TRACE").is_some()
}

fn elapsed_ms(t0: Instant) -> u128 {
    t0.elapsed().as_millis()
}

/// Public version of `sanitized_snapshot_name` for callers that
/// need to predict the snapshot directory layout before/after a
/// bake (e.g. `Image::from_oci`'s cache lookup).
pub fn snapshot_name_for_image(image: &str) -> String {
    sanitized_snapshot_name(image)
}

fn sanitized_snapshot_name(image: &str) -> String {
    image
        .chars()
        .map(|c| if matches!(c, ':' | '/' | '.') { '_' } else { c })
        .take(60)
        .collect()
}

fn emit_bake_timing_metadata(plan: &BakePlan<'_>) {
    if !trace_enabled() {
        return;
    }
    let meta_path = plan.metadata_path();
    let Ok(text) = std::fs::read_to_string(&meta_path) else {
        return;
    };
    let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
        return;
    };
    if let Some(timings) = json.get("timings") {
        eprintln!("supermachine: bake timings {timings}");
    }
}

fn command_output(mut cmd: Command, label: &str) -> Result<String, String> {
    let output = cmd.output().map_err(|e| format!("{label}: {e}"))?;
    if output.status.success() {
        return String::from_utf8(output.stdout)
            .map_err(|e| format!("{label}: non-utf8 stdout: {e}"));
    }
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let detail = stderr
        .lines()
        .find(|line| !line.trim().is_empty())
        .or_else(|| stdout.lines().find(|line| !line.trim().is_empty()))
        .unwrap_or("command failed");
    Err(format!("{label}: {detail}"))
}

fn run_status(mut cmd: Command, label: &str) -> Result<(), String> {
    let status = cmd.status().map_err(|e| format!("{label}: {e}"))?;
    if status.success() {
        Ok(())
    } else {
        Err(format!(
            "{label} failed with exit code {}",
            status.code().unwrap_or(1)
        ))
    }
}

fn spawn_status(mut cmd: Command, label: &str) -> Result<std::process::ExitStatus, String> {
    cmd.status().map_err(|e| format!("{label}: {e}"))
}

fn value_string_array(value: Option<&serde_json::Value>) -> Vec<String> {
    match value {
        Some(serde_json::Value::Array(items)) => items
            .iter()
            .filter_map(|v| v.as_str().map(ToOwned::to_owned))
            .collect(),
        Some(serde_json::Value::String(s)) if !s.is_empty() => vec![s.to_owned()],
        _ => Vec::new(),
    }
}

fn temp_work_dir(prefix: &str) -> Result<PathBuf, String> {
    let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let path = std::env::temp_dir().join(format!("{prefix}-{}-{n}", std::process::id()));
    std::fs::create_dir_all(&path)
        .map_err(|e| format!("create temp dir {}: {e}", path.display()))?;
    Ok(path)
}

fn strip_sha256(s: &str) -> String {
    s.strip_prefix("sha256:").unwrap_or(s).to_owned()
}

fn read_layer_index(path: &Path, cache_dir: &Path) -> Result<Option<Vec<String>>, String> {
    let text = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read layer index {}: {e}", path.display())),
    };
    let shas: Vec<String> = text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect();
    if shas.is_empty() {
        return Ok(None);
    }
    let complete = shas
        .iter()
        .all(|sha| cache_dir.join(format!("{sha}.squashfs")).is_file());
    Ok(complete.then_some(shas))
}

fn layer_shas_from_save_dir(image: &str, save_dir: &Path) -> Result<Vec<String>, String> {
    let index_text = std::fs::read_to_string(save_dir.join("index.json"))
        .map_err(|e| format!("read image save index.json: {e}"))?;
    let index: serde_json::Value =
        serde_json::from_str(&index_text).map_err(|e| format!("image save index JSON: {e}"))?;
    let manifest_digest = index
        .get("manifests")
        .and_then(|v| v.as_array())
        .and_then(|items| {
            items.iter().find_map(|item| {
                let arch = item
                    .get("platform")
                    .and_then(|p| p.get("architecture"))
                    .and_then(|v| v.as_str());
                if arch == Some("arm64") {
                    item.get("digest")
                        .and_then(|v| v.as_str())
                        .map(strip_sha256)
                } else {
                    None
                }
            })
        })
        .ok_or_else(|| format!("no arm64 manifest in image {image}"))?;
    let manifest_path = save_dir.join("blobs/sha256").join(&manifest_digest);
    let manifest_text = std::fs::read_to_string(&manifest_path)
        .map_err(|e| format!("read image save manifest {}: {e}", manifest_path.display()))?;
    let manifest: serde_json::Value = serde_json::from_str(&manifest_text)
        .map_err(|e| format!("image save manifest JSON: {e}"))?;
    let shas: Vec<String> = manifest
        .get("layers")
        .and_then(|v| v.as_array())
        .ok_or_else(|| "image save manifest missing layers".to_owned())?
        .iter()
        .filter_map(|layer| {
            layer
                .get("digest")
                .and_then(|v| v.as_str())
                .map(strip_sha256)
        })
        .collect();
    if shas.is_empty() {
        return Err(format!("image {image} has no arm64 layers"));
    }
    Ok(shas)
}

fn plan_layers(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    source: &dyn ImageSource,
) -> Result<Option<LayerPlan>, String> {
    if plan.runtime != "supermachine" {
        return Ok(None);
    }
    let t0 = Instant::now();
    let cache_dir = layer_cache_dir();
    let index_dir = cache_dir.join("images");
    std::fs::create_dir_all(&index_dir)
        .map_err(|e| format!("create layer index dir {}: {e}", index_dir.display()))?;
    std::fs::create_dir_all(cache_dir.join("deltas"))
        .map_err(|e| format!("create layer delta cache dir: {e}"))?;

    let index_path = resolution
        .image_id
        .as_deref()
        .map(|id| index_dir.join(format!("{id}.arm64.layers")));
    let mut manifest_cache_hit = false;
    let mut save_work_dir = None;
    let mut save_dir = None;
    let layer_shas = if let Some(path) = index_path.as_deref() {
        if let Some(shas) = read_layer_index(path, &cache_dir)? {
            manifest_cache_hit = true;
            shas
        } else {
            let work_dir = temp_work_dir("supermachine-layer-plan")?;
            let saved_dir = source.save_arm64(plan.image, &work_dir)?;
            let shas = layer_shas_from_save_dir(plan.image, &saved_dir)?;
            std::fs::write(path, format!("{}\n", shas.join("\n")))
                .map_err(|e| format!("write layer index {}: {e}", path.display()))?;
            save_work_dir = Some(work_dir);
            save_dir = Some(saved_dir);
            shas
        }
    } else {
        let work_dir = temp_work_dir("supermachine-layer-plan")?;
        let saved_dir = source.save_arm64(plan.image, &work_dir)?;
        let shas = layer_shas_from_save_dir(plan.image, &saved_dir)?;
        save_work_dir = Some(work_dir);
        save_dir = Some(saved_dir);
        shas
    };
    let cached_layers = layer_shas
        .iter()
        .filter(|sha| cache_dir.join(format!("{sha}.squashfs")).is_file())
        .count();
    let missing_layers = layer_shas.len().saturating_sub(cached_layers);
    Ok(Some(LayerPlan {
        cache_dir,
        index_path,
        layer_shas,
        save_work_dir,
        save_dir,
        cached_layers,
        missing_layers,
        manifest_cache_hit,
        plan_ms: elapsed_ms(t0),
    }))
}

fn remove_oci_whiteouts(root: &Path) -> Result<(), String> {
    let entries =
        std::fs::read_dir(root).map_err(|e| format!("read layer dir {}: {e}", root.display()))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("read layer dir entry {}: {e}", root.display()))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|e| format!("stat layer path {}: {e}", path.display()))?;
        if file_type.is_dir() {
            remove_oci_whiteouts(&path)?;
        }
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if !name.starts_with(".wh.") {
            continue;
        }
        if name != ".wh..wh..opq" {
            let target = path.with_file_name(name.trim_start_matches(".wh."));
            match std::fs::remove_dir_all(&target) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(dir_err) => {
                    std::fs::remove_file(&target).map_err(|e2| {
                        format!(
                            "remove whiteout target {}: {dir_err}; {e2}",
                            target.display()
                        )
                    })?;
                }
            }
        }
        std::fs::remove_file(&path)
            .map_err(|e| format!("remove OCI whiteout {}: {e}", path.display()))?;
    }
    Ok(())
}

fn materialize_missing_layers(
    image: &str,
    layer_plan: &LayerPlan,
    source: &dyn ImageSource,
) -> Result<LayerMaterialization, String> {
    let t0 = Instant::now();
    if layer_plan.missing_layers == 0 {
        return Ok(LayerMaterialization {
            materialize_ms: elapsed_ms(t0),
            built_layers: 0,
            reused_layers: layer_plan.cached_layers,
        });
    }

    let mut owned_work_dir = None;
    let save_dir = if let Some(save_dir) = layer_plan.save_dir.as_deref() {
        save_dir.to_path_buf()
    } else {
        let work_dir = temp_work_dir("supermachine-layer-materialize")?;
        let save_dir = source.save_arm64(image, &work_dir)?;
        owned_work_dir = Some(work_dir);
        save_dir
    };
    let result = (|| {
        let saved_shas = layer_shas_from_save_dir(image, &save_dir)?;
        if saved_shas != layer_plan.layer_shas {
            return Err(format!(
                "image layer set changed while materializing {image}; retry the command"
            ));
        }

        let mut built_layers = 0usize;
        let mut reused_layers = 0usize;
        for sha in &layer_plan.layer_shas {
            let layer_squashfs = layer_plan.cache_dir.join(format!("{sha}.squashfs"));
            if layer_squashfs.is_file() {
                reused_layers += 1;
                continue;
            }

            let blob = save_dir.join("blobs/sha256").join(sha);
            if !blob.is_file() {
                return Err(format!("layer blob {} missing from image save", sha));
            }

            let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
            let layer_extract = layer_plan.cache_dir.join(format!(
                "{sha}.extract.{}.{}",
                std::process::id(),
                unique
            ));
            let tmp_squashfs = layer_plan.cache_dir.join(format!(
                ".{sha}.squashfs.{}.{}.tmp",
                std::process::id(),
                unique
            ));
            let _ = std::fs::remove_dir_all(&layer_extract);
            let _ = std::fs::remove_file(&tmp_squashfs);
            std::fs::create_dir_all(&layer_extract)
                .map_err(|e| format!("create layer extract {}: {e}", layer_extract.display()))?;

            let built: Result<bool, String> = (|| {
                let mut tar = Command::new("tar");
                tar.arg("-xf")
                    .arg(&blob)
                    .arg("-C")
                    .arg(&layer_extract)
                    .stdout(Stdio::null())
                    .stderr(Stdio::null());
                let _ = spawn_status(tar, "tar extract OCI layer")?;
                remove_oci_whiteouts(&layer_extract)?;

                if layer_squashfs.is_file() {
                    return Ok(false);
                }

                let mut squash = Command::new("mksquashfs");
                squash
                    .arg(&layer_extract)
                    .arg(&tmp_squashfs)
                    .arg("-comp")
                    .arg("zstd")
                    .arg("-no-xattrs")
                    .arg("-noappend")
                    .arg("-quiet")
                    .stdout(Stdio::null())
                    .stderr(Stdio::null());
                run_status(squash, "mksquashfs layer")?;

                if layer_squashfs.is_file() {
                    let _ = std::fs::remove_file(&tmp_squashfs);
                    return Ok(false);
                }
                std::fs::rename(&tmp_squashfs, &layer_squashfs).map_err(|e| {
                    format!(
                        "install layer squashfs {} -> {}: {e}",
                        tmp_squashfs.display(),
                        layer_squashfs.display()
                    )
                })?;
                Ok(true)
            })();
            let _ = std::fs::remove_dir_all(&layer_extract);
            if built.is_err() {
                let _ = std::fs::remove_file(&tmp_squashfs);
            }
            if built? {
                built_layers += 1;
            } else {
                reused_layers += 1;
            }
        }

        Ok(LayerMaterialization {
            materialize_ms: elapsed_ms(t0),
            built_layers,
            reused_layers,
        })
    })();
    if let Some(work_dir) = owned_work_dir {
        let _ = std::fs::remove_dir_all(work_dir);
    }
    result
}

fn arg_values<'a>(args: &'a [String], flag: &str) -> Vec<&'a str> {
    let mut values = Vec::new();
    let mut i = 0;
    while i < args.len() {
        if args[i] == flag && i + 1 < args.len() {
            values.push(args[i + 1].as_str());
            i += 2;
        } else {
            i += 1;
        }
    }
    values
}

fn arg_present(args: &[String], flag: &str) -> bool {
    args.iter().any(|arg| arg == flag)
}

fn arg_value<'a>(args: &'a [String], flag: &str) -> Option<&'a str> {
    arg_values(args, flag).into_iter().last()
}

fn sha256_file(path: &Path) -> Result<String, String> {
    let mut cmd = Command::new("shasum");
    cmd.arg("-a").arg("256").arg(path);
    let out = command_output(cmd, "shasum file")?;
    out.split_whitespace()
        .next()
        .map(ToOwned::to_owned)
        .ok_or_else(|| format!("shasum produced no digest for {}", path.display()))
}

fn sha256_text(text: &str) -> Result<String, String> {
    let work_dir = temp_work_dir("supermachine-sha")?;
    let path = work_dir.join("input");
    let result = (|| {
        std::fs::write(&path, text).map_err(|e| format!("write {}: {e}", path.display()))?;
        sha256_file(&path)
    })();
    let _ = std::fs::remove_dir_all(&work_dir);
    result
}

fn file_mode_octal(path: &Path) -> Result<String, String> {
    let mode = std::fs::metadata(path)
        .map_err(|e| format!("stat {}: {e}", path.display()))?
        .permissions()
        .mode()
        & 0o7777;
    Ok(format!("{mode:o}"))
}

fn file_size_mtime(path: &Path) -> Result<String, String> {
    let meta = std::fs::metadata(path).map_err(|e| format!("stat {}: {e}", path.display()))?;
    let mtime = meta
        .modified()
        .map_err(|e| format!("mtime {}: {e}", path.display()))?
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("mtime before epoch {}: {e}", path.display()))?
        .as_secs();
    Ok(format!("{}:{mtime}", meta.len()))
}

fn set_mode(path: &Path, mode: u32) -> Result<(), String> {
    let mut permissions = std::fs::metadata(path)
        .map_err(|e| format!("stat {}: {e}", path.display()))?
        .permissions();
    permissions.set_mode(mode);
    std::fs::set_permissions(path, permissions)
        .map_err(|e| format!("chmod {:o} {}: {e}", mode, path.display()))
}

fn write_lines(path: &Path, lines: &[String]) -> Result<(), String> {
    let mut text = String::new();
    for line in lines {
        text.push_str(line);
        text.push('\n');
    }
    std::fs::write(path, text).map_err(|e| format!("write {}: {e}", path.display()))
}

fn ensure_init_oci(root: &Path) -> Result<PathBuf, String> {
    // Resolve the oci/ dir, in order:
    //   - dev-tree:        crates/supermachine/oci/
    //   - installed-tree:  share/supermachine/oci/  (from release tarball)
    //   - legacy dev-tree: crates/supermachine/oci/
    let dir = [
        root.join("crates/supermachine/oci"),
        root.join("share/supermachine/oci"),
        root.join("crates/supermachine/oci"),
    ]
    .into_iter()
    .find(|p| p.is_dir())
    .unwrap_or_else(|| root.join("crates/supermachine/oci"));
    let src = dir.join("init-oci.c");
    let bin = dir.join("init-oci");
    // Fast path: dev-tree or release-tarball already has the binary.
    if bin.is_file() {
        let executable = std::fs::metadata(&bin)
            .ok()
            .map(|m| m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false);
        let src_meta = std::fs::metadata(&src).ok();
        let up_to_date = match src_meta {
            Some(s) => std::fs::metadata(&bin)
                .ok()
                .and_then(|b| Some((b.modified().ok()?, s.modified().ok()?)))
                .map(|(b, s)| b >= s)
                .unwrap_or(false),
            None => true, // No source file means we trust whatever binary is here
        };
        if executable && up_to_date {
            return Ok(bin);
        }
    }
    // Cargo-install path: no dev tree, no source. Use the bundled
    // binary that supermachine-kernel ships, auto-extracted to
    // $XDG_DATA_HOME/supermachine/v{VERSION}/ on first call.
    if !src.is_file() {
        let assets = crate::assets::AssetPaths::discover();
        if let Some(p) = assets.init_oci_bin {
            return Ok(p);
        }
    }
    // Last resort: compile from source via zig (dev-tree workflow
    // when a maintainer is editing init-oci.c).
    if src.is_file() {
        let mut cmd = Command::new("zig");
        cmd.current_dir(&dir)
            .arg("cc")
            .arg("--target=aarch64-linux-musl")
            .arg("-static")
            .arg("-O2")
            .arg("-o")
            .arg("init-oci")
            .arg("init-oci.c")
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        run_status(cmd, "build init-oci")?;
        if bin.is_file() {
            return Ok(bin);
        }
    }
    Err(format!(
        "missing init-oci: not found in dev tree ({}), bundled assets, or via zig build",
        bin.display()
    ))
}

/// Locate (and build, if missing) the `supermachine-agent` binary
/// that ships inside the guest. Mirrors `ensure_init_oci`'s shape:
///
///   - dev-tree:        `crates/supermachine-guest-agent/target/aarch64-unknown-linux-musl/release/supermachine-agent`
///   - installed-tree:  `share/supermachine/supermachine-agent`
///
/// On dev hosts, builds via `cargo build --release` from the agent
/// crate dir. The crate's `.cargo/config.toml` already pins the
/// musl target and the zig-cc linker shim; we just need PATH to
/// include the crate dir so the shim resolves.
fn ensure_supermachine_agent(root: &Path) -> Result<PathBuf, String> {
    // Installed-tree fast path: tarball ships the prebuilt binary.
    let installed = root.join("share/supermachine/supermachine-agent");
    if installed.is_file() {
        return Ok(installed);
    }

    // Dev-tree fast path: the agent crate's prebuilt aarch64-musl
    // binary, if it exists.
    let crate_dir = root.join("crates/supermachine-guest-agent");
    let dev_bin = crate_dir
        .join("target/aarch64-unknown-linux-musl/release/supermachine-agent");
    if dev_bin.is_file() {
        // If we have source, only use the binary if it's newer.
        let src = crate_dir.join("src/main.rs");
        let up_to_date = match (
            std::fs::metadata(&dev_bin).ok(),
            std::fs::metadata(&src).ok(),
        ) {
            (Some(b), Some(s)) => b.modified().ok() >= s.modified().ok(),
            (Some(_), None) => true,
            _ => false,
        };
        if up_to_date {
            return Ok(dev_bin);
        }
    }

    // Cargo-install path: no dev tree, no installed tree. Use the
    // bundled binary that supermachine-kernel ships, auto-extracted
    // to $XDG_DATA_HOME/supermachine/v{VERSION}/ on first call.
    if !crate_dir.is_dir() {
        let assets = crate::assets::AssetPaths::discover();
        if let Some(p) = assets.supermachine_agent {
            return Ok(p);
        }
        return Err(format!(
            "supermachine-agent: not found at {} (release tarball), \
             {} (dev tree), or in the bundled assets from supermachine-kernel",
            installed.display(),
            dev_bin.display()
        ));
    }

    // Last resort: rebuild the dev-tree binary via cargo. The
    // crate's .cargo/config.toml pins the musl target and the
    // linker shim; PATH must include the shim's location.
    let path = std::env::var("PATH").unwrap_or_default();
    let new_path = format!("{}:{}", crate_dir.display(), path);
    let mut cmd = Command::new("cargo");
    cmd.current_dir(&crate_dir)
        .arg("build")
        .arg("--release")
        .env("PATH", new_path)
        .stdout(Stdio::null())
        .stderr(Stdio::piped());
    run_status(cmd, "build supermachine-agent")?;
    if !dev_bin.is_file() {
        return Err(format!(
            "supermachine-agent build did not produce {}",
            dev_bin.display()
        ));
    }
    Ok(dev_bin)
}

fn build_initramfs(root: &Path, out_dir: &Path) -> Result<(PathBuf, u128), String> {
    let t0 = Instant::now();
    let init = ensure_init_oci(root)?;
    // The cpio cache lives next to init-oci itself, which already
    // resolves to either the new (crates/supermachine/oci) or
    // legacy (crates/supermachine/oci) location.
    let init_dir = init
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| root.join("crates/supermachine/oci"));
    let cache = init_dir.join("init-oci.cpio.gz");
    let rebuild = match (std::fs::metadata(&cache), std::fs::metadata(&init)) {
        (Ok(cache_meta), Ok(init_meta)) => cache_meta.modified().ok() < init_meta.modified().ok(),
        _ => true,
    };
    if rebuild {
        let stage = temp_work_dir("supermachine-initramfs-stage")?;
        let result: Result<(), String> = (|| {
            std::fs::copy(&init, stage.join("init"))
                .map_err(|e| format!("copy init into initramfs stage: {e}"))?;
            set_mode(&stage.join("init"), 0o755)?;
            for dir in ["proc", "sys", "dev", "newroot"] {
                std::fs::create_dir_all(stage.join(dir))
                    .map_err(|e| format!("create initramfs dir {dir}: {e}"))?;
            }
            let script =
                "cd \"$1\" && find . -mindepth 1 -print | sed 's|^\\./||' | cpio -o -H newc 2>/dev/null | gzip > \"$2\"";
            let mut cmd = Command::new("sh");
            cmd.arg("-c")
                .arg(script)
                .arg("sh")
                .arg(&stage)
                .arg(&cache)
                .stdout(Stdio::null());
            run_status(cmd, "build initramfs cpio")?;
            Ok(())
        })();
        let _ = std::fs::remove_dir_all(&stage);
        result?;
    }
    let out = out_dir.join("init.cpio.gz");
    std::fs::copy(&cache, &out).map_err(|e| {
        format!(
            "copy initramfs cache {} -> {}: {e}",
            cache.display(),
            out.display()
        )
    })?;
    Ok((out, elapsed_ms(t0)))
}

fn write_env_json(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    out_dir: &Path,
) -> Result<PathBuf, String> {
    let json = env_json_value(plan, resolution);
    let path = out_dir.join("env.json");
    std::fs::write(
        &path,
        serde_json::to_vec_pretty(&json).map_err(|e| format!("encode env.json: {e}"))?,
    )
    .map_err(|e| format!("write {}: {e}", path.display()))?;
    Ok(path)
}

fn env_json_value(plan: &BakePlan<'_>, resolution: &ImageResolution) -> serde_json::Value {
    let mut env = serde_json::Map::new();
    for line in &resolution.env {
        if let Some((k, v)) = line.split_once('=') {
            env.insert(k.to_owned(), serde_json::Value::String(v.to_owned()));
        }
    }
    for line in arg_values(plan.extra_args, "--env") {
        if let Some((k, v)) = line.split_once('=') {
            env.insert(k.to_owned(), serde_json::Value::String(v.to_owned()));
        }
    }
    serde_json::json!({ "env": env, "secrets": {} })
}

fn read_to_string_lossy(path: &Path) -> String {
    std::fs::read(path)
        .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
        .unwrap_or_default()
}

fn log_has(path: &Path, needle: &str) -> bool {
    read_to_string_lossy(path).contains(needle)
}

fn log_has_failure(path: &Path) -> bool {
    let text = read_to_string_lossy(path);
    text.lines().any(|line| {
        line.starts_with("FATAL:")
            || line.starts_with("error:")
            || line.contains("panic")
            || line.contains("snapshot") && line.contains("ERR")
    })
}

fn last_line_containing(path: &Path, needle: &str) -> Option<String> {
    read_to_string_lossy(path)
        .lines()
        .filter(|line| line.contains(needle))
        .last()
        .map(ToOwned::to_owned)
}

fn parse_snapshot_reason(line: &str) -> Option<String> {
    let start = line.find("snapshot (")? + "snapshot (".len();
    let end = line[start..].find("):")? + start;
    Some(line[start..end].to_owned())
}

fn parse_capture_save_us(line: &str) -> (Option<u64>, Option<u64>) {
    let capture = line
        .split("capture ")
        .nth(1)
        .and_then(|s| s.split(" us").next())
        .and_then(|s| s.trim().parse().ok());
    let save = line
        .split("save ")
        .nth(1)
        .and_then(|s| s.split(" us").next())
        .and_then(|s| s.trim().parse().ok());
    (capture, save)
}

fn parse_ram_mib(line: &str) -> (Option<u64>, Option<u64>) {
    let Some(after_data) = line.split("data ").nth(1) else {
        return (None, None);
    };
    let data = after_data
        .split(" MiB")
        .next()
        .and_then(|s| s.trim().parse().ok());
    let zero = line
        .split("zero ")
        .nth(1)
        .and_then(|s| s.split(" MiB").next())
        .and_then(|s| s.trim().parse().ok());
    (data, zero)
}

fn file_physical_bytes(path: &Path) -> Option<u64> {
    let mut cmd = Command::new("du");
    cmd.arg("-sk").arg(path);
    command_output(cmd, "du -sk")
        .ok()
        .and_then(|out| {
            out.split_whitespace()
                .next()
                .and_then(|s| s.parse::<u64>().ok())
        })
        .map(|kib| kib * 1024)
}

fn now_utc_iso() -> Result<String, String> {
    let mut cmd = Command::new("date");
    cmd.arg("-u").arg("+%Y-%m-%dT%H:%M:%SZ");
    Ok(command_output(cmd, "date utc")?.trim().to_owned())
}

fn native_listener_settle_ms(plan: &BakePlan<'_>) -> u64 {
    arg_value(plan.extra_args, "--supermachine-listener-settle-ms")
        .and_then(|s| s.parse::<u64>().ok())
        .or_else(|| {
            std::env::var("SUPERMACHINE_LISTENER_SETTLE_MS")
                .ok()
                .and_then(|s| s.parse::<u64>().ok())
        })
        .unwrap_or(50)
}

fn native_snapshot_after_ms(plan: &BakePlan<'_>) -> u64 {
    arg_value(plan.extra_args, "--supermachine-snapshot-after-ms")
        .and_then(|s| s.parse::<u64>().ok())
        .or_else(|| {
            std::env::var("SUPERMACHINE_SNAPSHOT_AFTER_MS")
                .ok()
                .and_then(|s| s.parse::<u64>().ok())
        })
        .unwrap_or(7000)
}

fn native_supermachine_base_inputs(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    root: &Path,
) -> Result<serde_json::Value, String> {
    let sm22_bin = supermachine_worker_bin(root);
    let kernel = supermachine_kernel(root);
    let init = ensure_init_oci(root)?;
    let agent = ensure_supermachine_agent(root)?;
    let snapshot_hash_mode =
        std::env::var("SUPERMACHINE_SNAPSHOT_HASH_MODE").unwrap_or_else(|_| "fast".to_owned());
    Ok(serde_json::json!({
        "version": 1,
        "runtime": "supermachine",
        "image": plan.image,
        "image_id": resolution.image_id,
        "architecture": resolution.architecture,
        "guest_port": plan.guest_port,
        "memory_mib": plan.memory_mib,
        "cmd": resolution.effective_cmd,
        "working_dir": resolution.working_dir,
        "user": resolution.user,
        "env": env_json_value(plan, resolution),
        "extra_args": plan.extra_args,
        "egress_policy": arg_value(plan.extra_args, "--egress-policy").unwrap_or(""),
        "listener_settle_ms": native_listener_settle_ms(plan),
        "snapshot_after_ms": native_snapshot_after_ms(plan),
        "runtime_bin": file_size_mtime(&sm22_bin)?,
        "kernel": file_size_mtime(&kernel)?,
        "init_oci": file_size_mtime(&init)?,
        "agent": file_size_mtime(&agent)?,
        "snapshot_hash_mode": snapshot_hash_mode,
    }))
}

/// Subset of [`native_supermachine_base_inputs`] that doesn't
/// require an [`ImageResolution`] — i.e. the keys whose values
/// don't depend on hitting the registry / running `inspect` on
/// the image. Used for the early cache-hit check that skips
/// `select_image_source` + `resolve_image` entirely when the
/// snapshot's stored bake key already matches on these.
///
/// **Cache semantics:** if the user re-pushed a floating tag
/// (e.g. `rust:1-slim` got rebuilt upstream), this fast path
/// won't notice — the snapshot's `image_id` could be stale and
/// we'd serve the cached snapshot anyway. That's the same
/// trade-off `docker run` makes when `--pull missing` and the
/// image is locally cached. Users who need freshness pass
/// `--pull always`, which short-circuits the fast path back to
/// the full resolve-and-rebuild flow.
fn native_supermachine_cheap_input_keys() -> &'static [&'static str] {
    &[
        "version",
        "runtime",
        "image",
        "guest_port",
        "memory_mib",
        "extra_args",
        "egress_policy",
        "listener_settle_ms",
        "snapshot_after_ms",
        "runtime_bin",
        "kernel",
        "init_oci",
        // The in-guest agent is baked into the delta layer; its
        // fingerprint MUST be part of the cheap cache key. Without
        // this, shipping a new agent (e.g. adding stage_file or
        // chain support) doesn't invalidate existing snapshots,
        // and embedders silently keep using the stale agent —
        // which makes new ExecRequest fields look like no-ops.
        "agent",
        "snapshot_hash_mode",
    ]
}

fn native_supermachine_cheap_inputs(
    plan: &BakePlan<'_>,
    root: &Path,
) -> Result<serde_json::Value, String> {
    let sm22_bin = supermachine_worker_bin(root);
    let kernel = supermachine_kernel(root);
    let init = ensure_init_oci(root)?;
    let agent = ensure_supermachine_agent(root)?;
    let snapshot_hash_mode =
        std::env::var("SUPERMACHINE_SNAPSHOT_HASH_MODE").unwrap_or_else(|_| "fast".to_owned());
    Ok(serde_json::json!({
        "version": 1,
        "runtime": "supermachine",
        "image": plan.image,
        "guest_port": plan.guest_port,
        "memory_mib": plan.memory_mib,
        "extra_args": plan.extra_args,
        "egress_policy": arg_value(plan.extra_args, "--egress-policy").unwrap_or(""),
        "listener_settle_ms": native_listener_settle_ms(plan),
        "snapshot_after_ms": native_snapshot_after_ms(plan),
        "runtime_bin": file_size_mtime(&sm22_bin)?,
        "kernel": file_size_mtime(&kernel)?,
        "init_oci": file_size_mtime(&init)?,
        "agent": file_size_mtime(&agent)?,
        "snapshot_hash_mode": snapshot_hash_mode,
    }))
}

/// Pre-resolution cache-hit check. Reads `metadata.json`,
/// compares the stored `native_bake_inputs` against the cheap
/// subset of inputs we can compute without calling
/// `resolve_image` (which is the slow path that runs `docker
/// inspect` / parses an OCI manifest). Returns `Some` if the
/// snapshot is reusable, `None` if we need the full resolve.
///
/// Skipped when `pull_policy = "always"` (user explicitly opted
/// into per-call upstream verification).
fn try_fast_cache_hit(
    plan: &BakePlan<'_>,
    root: &Path,
    run_t0: Instant,
) -> Result<Option<NativeBakeResult>, String> {
    if plan.pull_policy == "always" {
        return Ok(None);
    }
    if snapshot_reuse_disabled() || !native_supermachine_early_reuse_supported(plan) {
        return Ok(None);
    }
    let meta_path = plan.metadata_path();
    let text = match std::fs::read_to_string(&meta_path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read metadata {}: {e}", meta_path.display())),
    };
    let meta: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| format!("parse metadata {}: {e}", meta_path.display()))?;
    if meta.get("supermachine_version").and_then(|v| v.as_str()) != Some("supermachine") {
        return Ok(None);
    }
    let Some(meta_inputs) = meta.get("native_bake_inputs").and_then(|v| v.as_object()) else {
        return Ok(None);
    };
    let cheap = native_supermachine_cheap_inputs(plan, root)?;
    let cheap_obj = cheap
        .as_object()
        .ok_or_else(|| "cheap bake inputs was not an object".to_owned())?;
    for &key in native_supermachine_cheap_input_keys() {
        if meta_inputs.get(key) != cheap_obj.get(key) {
            return Ok(None);
        }
    }
    if !metadata_snapshot_files_exist(&meta) {
        return Ok(None);
    }
    let timings = serde_json::json!({
        "total_ms": 0,
        "snapshot_reused": true,
        "fast_snapshot_reused": true,
        "reuse_check_total_ms": elapsed_ms(run_t0),
    });
    Ok(Some(NativeBakeResult {
        total_ms: 0,
        timings,
        reused: true,
    }))
}

fn native_supermachine_bake_key(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    layer_plan: &LayerPlan,
    delta: &DeltaMaterialization,
    root: &Path,
) -> Result<(String, serde_json::Value), String> {
    let delta_key = delta
        .key
        .as_deref()
        .ok_or_else(|| "native supermachine bake needs delta key".to_owned())?;
    let mut inputs = native_supermachine_base_inputs(plan, resolution, root)?;
    let obj = inputs
        .as_object_mut()
        .ok_or_else(|| "native bake inputs was not an object".to_owned())?;
    obj.insert(
        "layers".to_owned(),
        serde_json::json!(layer_plan.layer_shas),
    );
    obj.insert("delta_key".to_owned(), serde_json::json!(delta_key));
    let encoded =
        serde_json::to_string(&inputs).map_err(|e| format!("encode native bake key: {e}"))?;
    let key = sha256_text(&format!("{encoded}\n"))?;
    Ok((key, inputs))
}

fn metadata_string(value: &serde_json::Value, key: &str) -> Option<String> {
    value.get(key)?.as_str().map(ToOwned::to_owned)
}

fn metadata_path_value(meta: &serde_json::Value, key: &str) -> Option<PathBuf> {
    metadata_string(meta, key).map(PathBuf::from)
}

fn metadata_path_exists(meta: &serde_json::Value, key: &str) -> bool {
    metadata_path_value(meta, key)
        .as_deref()
        .map(Path::exists)
        .unwrap_or(false)
}

fn snapshot_reuse_disabled() -> bool {
    std::env::var("SUPERMACHINE_SNAPSHOT_REUSE")
        .map(|v| v == "0" || v == "false")
        .unwrap_or(false)
}

/// Look up the cmd (argv) from a previous bake's metadata.json so
/// re-running without `--cmd` keeps the user's last-known intent.
/// Returns None if the metadata doesn't exist, doesn't have `cmd`,
/// or its image differs from the requested one.
fn previous_metadata_cmd(plan: &BakePlan<'_>) -> Option<Vec<String>> {
    let meta_path = plan.metadata_path();
    let text = std::fs::read_to_string(&meta_path).ok()?;
    let meta: serde_json::Value = serde_json::from_str(&text).ok()?;
    if meta.get("image").and_then(|v| v.as_str()) != Some(plan.image) {
        return None;
    }
    let arr = meta.get("cmd")?.as_array()?;
    let mut out = Vec::with_capacity(arr.len());
    for v in arr {
        out.push(v.as_str()?.to_owned());
    }
    if out.is_empty() { None } else { Some(out) }
}

fn metadata_snapshot_files_exist(meta: &serde_json::Value) -> bool {
    if !metadata_path_exists(meta, "snapshot_base")
        || !metadata_path_exists(meta, "delta_squashfs")
        || !metadata_path_exists(meta, "init_cpio")
    {
        return false;
    }
    meta.get("layers")
        .and_then(|v| v.as_array())
        .map(|layers| {
            !layers.is_empty()
                && layers.iter().all(|layer| {
                    layer
                        .as_str()
                        .map(Path::new)
                        .map(Path::exists)
                        .unwrap_or(false)
                })
        })
        .unwrap_or(false)
}

fn native_supermachine_early_reuse_supported(plan: &BakePlan<'_>) -> bool {
    !arg_present(plan.extra_args, "--extra-file")
        && !arg_present(plan.extra_args, "--inbound-tls-autogen")
        && arg_value(plan.extra_args, "--inbound-tls-cert").is_none()
        && arg_value(plan.extra_args, "--inbound-tls-key").is_none()
}

fn native_supermachine_early_reuse_snapshot(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    root: &Path,
    run_t0: Instant,
) -> Result<Option<NativeBakeResult>, String> {
    if snapshot_reuse_disabled() || !native_supermachine_early_reuse_supported(plan) {
        return Ok(None);
    }
    let meta_path = plan.metadata_path();
    let text = match std::fs::read_to_string(&meta_path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read metadata {}: {e}", meta_path.display())),
    };
    let meta: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| format!("parse metadata {}: {e}", meta_path.display()))?;
    if meta.get("supermachine_version").and_then(|v| v.as_str()) != Some("supermachine") {
        return Ok(None);
    }
    let Some(meta_inputs) = meta.get("native_bake_inputs").and_then(|v| v.as_object()) else {
        return Ok(None);
    };
    let current_inputs = native_supermachine_base_inputs(plan, resolution, root)?;
    let current_obj = current_inputs
        .as_object()
        .ok_or_else(|| "native base inputs was not an object".to_owned())?;
    for (key, value) in current_obj {
        if meta_inputs.get(key) != Some(value) {
            return Ok(None);
        }
    }
    if !metadata_snapshot_files_exist(&meta) {
        return Ok(None);
    }
    let timings = serde_json::json!({
        "total_ms": 0,
        "snapshot_reused": true,
        "early_snapshot_reused": true,
        "reuse_check_total_ms": elapsed_ms(run_t0),
    });
    Ok(Some(NativeBakeResult {
        total_ms: 0,
        timings,
        reused: true,
    }))
}

fn native_supermachine_reuse_snapshot(
    plan: &BakePlan<'_>,
    expected_bake_key: &str,
    run_t0: Instant,
) -> Result<Option<NativeBakeResult>, String> {
    if snapshot_reuse_disabled() {
        return Ok(None);
    }
    let meta_path = plan.metadata_path();
    let text = match std::fs::read_to_string(&meta_path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read metadata {}: {e}", meta_path.display())),
    };
    let meta: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| format!("parse metadata {}: {e}", meta_path.display()))?;
    if meta.get("supermachine_version").and_then(|v| v.as_str()) != Some("supermachine") {
        return Ok(None);
    }
    if meta.get("native_bake_key").and_then(|v| v.as_str()) != Some(expected_bake_key) {
        return Ok(None);
    }
    if !metadata_snapshot_files_exist(&meta) {
        return Ok(None);
    }
    let total_ms = 0;
    let timings = serde_json::json!({
        "total_ms": total_ms,
        "snapshot_reused": true,
        "reuse_check_total_ms": elapsed_ms(run_t0),
    });
    Ok(Some(NativeBakeResult {
        total_ms,
        timings,
        reused: true,
    }))
}

fn run_native_supermachine_bake(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    layer_plan: &LayerPlan,
    delta: &DeltaMaterialization,
    root: &Path,
    native_bake_key: &str,
    native_bake_inputs: &serde_json::Value,
) -> Result<NativeBakeResult, String> {
    let total_t0 = Instant::now();
    let out_dir = plan.snapshots_dir.join(plan.snapshot_name());
    std::fs::create_dir_all(&out_dir)
        .map_err(|e| format!("create snapshot dir {}: {e}", out_dir.display()))?;

    let delta_cache = delta
        .cache_path
        .as_ref()
        .filter(|p| p.is_file())
        .ok_or_else(|| "native supermachine bake needs materialized delta cache".to_owned())?;
    let squash_t0 = Instant::now();
    let delta_squashfs = out_dir.join("delta.squashfs");
    std::fs::copy(delta_cache, &delta_squashfs).map_err(|e| {
        format!(
            "copy delta cache {} -> {}: {e}",
            delta_cache.display(),
            delta_squashfs.display()
        )
    })?;
    let squashfs_ms = elapsed_ms(squash_t0);

    let env_json = write_env_json(plan, resolution, &out_dir)?;
    let (init_cpio, initramfs_ms) = build_initramfs(root, &out_dir)?;

    let sm22_bin = supermachine_worker_bin(root);
    let kernel = supermachine_kernel(root);
    let snap_base = out_dir.join("restore.snap");
    let log = out_dir.join("bake.log");
    let _ = std::fs::remove_file(&snap_base);
    let log_file = std::fs::File::create(&log)
        .map_err(|e| format!("create bake log {}: {e}", log.display()))?;
    let log_err = log_file
        .try_clone()
        .map_err(|e| format!("clone bake log fd: {e}"))?;
    let listener_settle_ms = native_listener_settle_ms(plan);
    let snapshot_after_ms = native_snapshot_after_ms(plan);
    let host_time = std::time::SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("host time before epoch: {e}"))?
        .as_secs();

    let bake_t0 = Instant::now();
    let mut cmd = Command::new(&sm22_bin);
    cmd.arg("--kernel")
        .arg(&kernel)
        .arg("--initramfs")
        .arg(&init_cpio);
    let layer_paths: Vec<PathBuf> = layer_plan
        .layer_shas
        .iter()
        .map(|sha| layer_plan.cache_dir.join(format!("{sha}.squashfs")))
        .collect();
    for layer in &layer_paths {
        cmd.arg("--virtio-blk").arg(layer);
    }
    cmd.arg("--virtio-blk")
        .arg(&delta_squashfs);
    // Writable volumes — pass each as `--volume HOST_FILE:GUEST_PATH`
    // so the worker's CLI parser turns them into VmResources::volumes.
    // Volume order matches /.supermachine-volumes (written into the
    // delta squashfs at delta-stage time) so init-oci can map
    // /dev/vd<letter> → guest mount point.
    let volumes = parse_volume_args(plan.extra_args)?;
    for vol in &volumes {
        ensure_volume_host_file(vol, crate::vmm::resources::VolumeSpec::DEFAULT_SIZE_BYTES)?;
        cmd.arg("--volume").arg(format!(
            "{}:{}",
            vol.host_file.display(),
            vol.guest_path
        ));
    }
    cmd.arg("--memory")
        .arg(plan.memory_mib.to_string())
        .arg("--vcpus")
        .arg(plan.vcpus.to_string())
        .arg("--cmdline")
        .arg(format!(
            "earlycon=pl011,mmio32,0x09000000 console=ttyAMA0 tsi_hijack supermachine.host_time={host_time}"
        ));
    // Snapshot trigger:
    //   - Without volumes: --snapshot-on-listener — fastest path,
    //     captures the workload mid-run with its listener bound.
    //     If no listener appears within --snapshot-after-ms, the
    //     worker falls back to capturing whatever state the guest
    //     is in (typically init-oci parked after a non-service
    //     workload exited — rust:1-slim, python:slim, etc.).
    //   - With volumes: --snapshot-at 1 — captures init-oci's
    //     pre-mount state at the heartbeat marker. Each restore
    //     re-runs mount_volumes() against the *current* host file
    //     contents, dodging the page-cache vs. on-disk drift that
    //     would otherwise corrupt the FS across runs. The
    //     trade-off is a slower restore (must complete workload
    //     init post-restore) — acceptable for stateful workloads.
    if volumes.is_empty() {
        cmd.arg("--snapshot-on-listener")
            .arg("--snapshot-after-ms")
            .arg(snapshot_after_ms.to_string())
            .arg("--quiesce-ms")
            .arg(listener_settle_ms.to_string());
    } else {
        cmd.arg("--snapshot-at")
            .arg("1");
    }
    cmd.arg("--snapshot-out")
        .arg(&snap_base)
        .arg("--env-file")
        .arg(&env_json)
        .stdout(Stdio::from(log_file))
        .stderr(Stdio::from(log_err));
    let mut child = cmd
        .spawn()
        .map_err(|e| format!("spawn supermachine bake: {e}"))?;

    let mut listener_ready_ms = None;
    let mut snapshot_trigger_ms = None;
    let mut snapshot_line_ms = None;
    let deadline = Instant::now() + std::time::Duration::from_secs(240);
    while Instant::now() < deadline {
        if listener_ready_ms.is_none() && log_has(&log, "listener readiness") {
            listener_ready_ms = Some(elapsed_ms(bake_t0));
        }
        if snapshot_trigger_ms.is_none() && log_has(&log, "snapshot trigger (") {
            snapshot_trigger_ms = Some(elapsed_ms(bake_t0));
        }
        if snapshot_line_ms.is_none() && log_has(&log, "snapshot (") {
            snapshot_line_ms = Some(elapsed_ms(bake_t0));
        }
        if snap_base.is_file() {
            let _ = child.wait();
            break;
        }
        if child
            .try_wait()
            .map_err(|e| format!("poll supermachine bake: {e}"))?
            .is_some()
        {
            break;
        }
        if log_has_failure(&log) {
            let _ = child.kill();
            let _ = child.wait();
            return Err(format!("supermachine bake failed; see {}", log.display()));
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    let vmm_bake_ms = elapsed_ms(bake_t0);
    if !snap_base.is_file() {
        let _ = child.kill();
        let _ = child.wait();
        return Err(format!("supermachine snapshot timeout; see {}", log.display()));
    }
    if listener_ready_ms.is_none() && log_has(&log, "listener readiness") {
        listener_ready_ms = Some(elapsed_ms(bake_t0));
    }
    if snapshot_trigger_ms.is_none() && log_has(&log, "snapshot trigger (") {
        snapshot_trigger_ms = Some(elapsed_ms(bake_t0));
    }
    if snapshot_line_ms.is_none() && log_has(&log, "snapshot (") {
        snapshot_line_ms = Some(elapsed_ms(bake_t0));
    }

    let snapshot_line = last_line_containing(&log, "snapshot (").unwrap_or_default();
    let snapshot_reason = parse_snapshot_reason(&snapshot_line).unwrap_or_default();
    let (snapshot_capture_us, snapshot_save_us) = parse_capture_save_us(&snapshot_line);
    let (snapshot_ram_data_mib, snapshot_ram_zero_mib) = parse_ram_mib(&snapshot_line);
    let snapshot_logical_bytes = std::fs::metadata(&snap_base).ok().map(|m| m.len());
    let snapshot_physical_bytes = file_physical_bytes(&snap_base);
    let listener_to_trigger_ms = listener_ready_ms
        .zip(snapshot_trigger_ms)
        .map(|(a, b)| b.saturating_sub(a));
    let listener_to_snapshot_ms = listener_ready_ms
        .zip(snapshot_line_ms)
        .map(|(a, b)| b.saturating_sub(a));

    let metadata_t0 = Instant::now();
    let runtime_sha = sha256_file(&sm22_bin)?;
    let runtime_sha16 = &runtime_sha[..runtime_sha.len().min(16)];
    let hash_mode =
        std::env::var("SUPERMACHINE_SNAPSHOT_HASH_MODE").unwrap_or_else(|_| "fast".to_owned());
    let snapshot_id = if hash_mode == "content" {
        let h = sha256_file(&snap_base)?;
        h[..h.len().min(16)].to_owned()
    } else if hash_mode == "fast" {
        let meta = std::fs::metadata(&snap_base)
            .map_err(|e| format!("stat snapshot {}: {e}", snap_base.display()))?;
        let mtime_ns = meta
            .modified()
            .map_err(|e| format!("snapshot mtime: {e}"))?
            .duration_since(UNIX_EPOCH)
            .map_err(|e| format!("snapshot mtime before epoch: {e}"))?
            .as_nanos();
        let material = format!(
            "{}\0{}\0{}\0{}\0{}",
            plan.snapshot_name(),
            plan.image,
            runtime_sha16,
            meta.len(),
            mtime_ns
        );
        let h = sha256_text(&material)?;
        h[..h.len().min(16)].to_owned()
    } else {
        return Err("SUPERMACHINE_SNAPSHOT_HASH_MODE must be fast or content".to_owned());
    };
    let baked_at = now_utc_iso()?;
    let egress_policy = arg_value(plan.extra_args, "--egress-policy").unwrap_or("");
    let balloon_target_pages = plan.memory_mib as u64 * 256 * 70 / 100;
    let metadata_prepare_ms = elapsed_ms(metadata_t0);
    let total_ms = elapsed_ms(total_t0);
    let timings = serde_json::json!({
        "total_ms": total_ms,
        "pull_inspect_ms": resolution.inspect_ms,
        "rootfs_prepare_ms": layer_plan.plan_ms,
        "rootfs_customize_ms": delta.prepare_ms,
        "init_oci_build_ms": 0,
        "squashfs_ms": squashfs_ms,
        "initramfs_ms": initramfs_ms,
        "vmm_bake_ms": vmm_bake_ms,
        "metadata_prepare_ms": metadata_prepare_ms,
        "guest_boot_to_listener_ms": listener_ready_ms,
        "listener_settle_config_ms": listener_settle_ms,
        "listener_to_snapshot_trigger_ms": listener_to_trigger_ms,
        "listener_to_snapshot_ms": listener_to_snapshot_ms,
        "snapshot_capture_us": snapshot_capture_us,
        "snapshot_save_us": snapshot_save_us,
        "snapshot_reason": snapshot_reason,
    });
    // Volumes: writable virtio-blk attachments. Host file path and
    // guest mount point are both runtime — restore needs both to
    // re-attach. We store the resolved host_file (so the router
    // doesn't need to recompute the name → path mapping) and the
    // bake-fingerprinted guest_path.
    let volumes_meta: Vec<serde_json::Value> = parse_volume_args(plan.extra_args)?
        .into_iter()
        .map(|v| {
            serde_json::json!({
                "host_file": v.host_file.to_string_lossy(),
                "guest_path": v.guest_path,
            })
        })
        .collect();

    // Restart policy. Default `no` (docker default) — watchdog
    // doesn't auto-respawn unless the user opted in. Accepted:
    // `no`, `on-failure`, `always`. CLI normalizes
    // `unless-stopped` → `always` since our daemon goes away on
    // `--stop`.
    let restart_policy = arg_value(plan.extra_args, "--restart").unwrap_or("no");

    // Health check command + interval. The router's per-snapshot
    // health thread runs the command via the in-guest exec agent
    // every `health_interval` seconds and tracks pass/fail.
    // Empty cmd → no health check (default).
    let health_cmd = arg_value(plan.extra_args, "--health-cmd").unwrap_or("");
    let health_interval_secs: u32 = arg_value(plan.extra_args, "--health-interval")
        .and_then(|s| s.parse().ok())
        .unwrap_or(if health_cmd.is_empty() { 0 } else { 30 });

    let metadata = serde_json::json!({
        "name": plan.snapshot_name(),
        "image": plan.image,
        "port": plan.guest_port,
        "memory_mib": plan.memory_mib,
        "cmd": resolution.effective_cmd,
        "snapshot_sha16": snapshot_id,
        "snapshot_id16": snapshot_id,
        "snapshot_hash_mode": hash_mode,
        "runtime_sha16": runtime_sha16,
        "layers": layer_paths,
        "volumes": volumes_meta,
        "restart_policy": restart_policy,
        "health_cmd": health_cmd,
        "health_interval_secs": health_interval_secs,
        "delta_squashfs": delta_squashfs,
        "rootfs_squashfs": serde_json::Value::Null,
        "snapshot_base": snap_base,
        "snapshot_logical_bytes": snapshot_logical_bytes,
        "snapshot_physical_bytes": snapshot_physical_bytes,
        "snapshot_ram_data_mib": snapshot_ram_data_mib,
        "snapshot_ram_zero_mib": snapshot_ram_zero_mib,
        "init_cpio": init_cpio,
        "kernel": kernel,
        "egress_policy": egress_policy,
        "vcpus": plan.vcpus,
        "ttl_seconds": serde_json::Value::Null,
        "egress_bps": serde_json::Value::Null,
        "cpu_nice": serde_json::Value::Null,
        "cpu_affinity": serde_json::Value::Null,
        "cpu_qos": serde_json::Value::Null,
        "balloon_target_pages": balloon_target_pages,
        "auth": {"type": "none"},
        "native_bake_key": native_bake_key,
        "native_bake_inputs": native_bake_inputs,
        "timings": timings,
        "baked_at": baked_at,
        "supermachine_version": "supermachine",
    });
    let meta_path = out_dir.join("metadata.json");
    std::fs::write(
        &meta_path,
        serde_json::to_vec_pretty(&metadata).map_err(|e| format!("encode metadata: {e}"))?,
    )
    .map_err(|e| format!("write metadata {}: {e}", meta_path.display()))?;

    Ok(NativeBakeResult {
        total_ms,
        timings,
        reused: false,
    })
}

fn materialize_delta_cache(
    plan: &BakePlan<'_>,
    resolution: &ImageResolution,
    root: &Path,
) -> Result<Option<DeltaMaterialization>, String> {
    if plan.runtime != "supermachine" {
        return Ok(None);
    }
    let prepare_t0 = Instant::now();
    let mut result = DeltaMaterialization {
        prepare_ms: 0,
        materialize_ms: 0,
        cache_hit: false,
        skipped: None,
        key: None,
        cache_path: None,
    };
    if arg_present(plan.extra_args, "--inbound-tls-autogen") {
        result.prepare_ms = elapsed_ms(prepare_t0);
        result.skipped = Some("inbound-tls-autogen".to_owned());
        return Ok(Some(result));
    }

    let cmd_json = plan.cmd_override.map(ToOwned::to_owned).unwrap_or_else(|| {
        serde_json::to_string(&resolution.effective_cmd).unwrap_or_else(|_| "[]".to_owned())
    });
    let mut key_material = format!("cmd={cmd_json}");
    let stage = temp_work_dir("supermachine-delta-stage")?;
    let materialize_t0 = Instant::now();
    let materialized = (|| {
        write_lines(&stage.join(".supermachine-cmd"), &resolution.effective_cmd)?;

        if let Some(cwd) = resolution
            .working_dir
            .as_deref()
            .filter(|cwd| !cwd.is_empty() && *cwd != "/")
        {
            std::fs::write(stage.join(".supermachine-workdir"), format!("{cwd}\n"))
                .map_err(|e| format!("write .supermachine-workdir: {e}"))?;
            key_material.push_str(&format!("\ncwd={cwd}"));
        }
        if let Some(user) = resolution.user.as_deref().filter(|user| !user.is_empty()) {
            std::fs::write(stage.join(".supermachine-user"), format!("{user}\n"))
                .map_err(|e| format!("write .supermachine-user: {e}"))?;
            key_material.push_str(&format!("\nuser={user}"));
        }

        // `--hostname HOSTNAME`: init-oci sets the kernel's
        // hostname before exec'ing the workload. Limit to 63
        // bytes (POSIX HOST_NAME_MAX-ish) and reject newlines so
        // the file is one trustable line.
        if let Some(hostname) = arg_value(plan.extra_args, "--hostname") {
            if hostname.is_empty()
                || hostname.len() > 63
                || hostname.contains(|c: char| c.is_whitespace() || c == '\0')
            {
                return Err(format!("--hostname {hostname:?} invalid (1..=63 chars, no whitespace)"));
            }
            std::fs::write(stage.join(".supermachine-hostname"), format!("{hostname}\n"))
                .map_err(|e| format!("write .supermachine-hostname: {e}"))?;
            key_material.push_str(&format!("\nhostname={hostname}"));
        }

        for extra in arg_values(plan.extra_args, "--extra-file") {
            let Some((host, guest)) = extra.split_once(':') else {
                return Err(format!("bad --extra-file '{extra}' (want host:guest)"));
            };
            let host_path = PathBuf::from(host);
            let guest_path = guest.trim_start_matches('/');
            let dst = stage.join(guest_path);
            if let Some(parent) = dst.parent() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| format!("create extra parent {}: {e}", parent.display()))?;
            }
            std::fs::copy(&host_path, &dst).map_err(|e| {
                format!(
                    "copy extra {} -> {}: {e}",
                    host_path.display(),
                    dst.display()
                )
            })?;
            let mode = file_mode_octal(&host_path)?;
            let sum = sha256_file(&host_path)?;
            key_material.push_str(&format!("\nextra={guest}:{mode}:{sum}"));
        }

        let tls_cert = arg_value(plan.extra_args, "--inbound-tls-cert");
        let tls_key = arg_value(plan.extra_args, "--inbound-tls-key");
        if tls_cert.is_some() || tls_key.is_some() {
            let cert = tls_cert
                .ok_or_else(|| "need both --inbound-tls-cert and --inbound-tls-key".to_owned())?;
            let key = tls_key
                .ok_or_else(|| "need both --inbound-tls-cert and --inbound-tls-key".to_owned())?;
            let tls_dir = stage.join("etc/supermachine");
            std::fs::create_dir_all(&tls_dir)
                .map_err(|e| format!("create TLS dir {}: {e}", tls_dir.display()))?;
            let cert_path = PathBuf::from(cert);
            let key_path = PathBuf::from(key);
            std::fs::copy(&cert_path, tls_dir.join("cert.pem"))
                .map_err(|e| format!("copy TLS cert {}: {e}", cert_path.display()))?;
            std::fs::copy(&key_path, tls_dir.join("key.pem"))
                .map_err(|e| format!("copy TLS key {}: {e}", key_path.display()))?;
            set_mode(&tls_dir.join("cert.pem"), 0o644)?;
            set_mode(&tls_dir.join("key.pem"), 0o600)?;
            let cert_sum = sha256_file(&cert_path)?;
            let key_sum = sha256_file(&key_path)?;
            key_material.push_str(&format!("\ntls=provided:{cert_sum}:{key_sum}"));
        }

        for dir in ["proc", "sys", "dev", "dev/shm", "tmp", "run"] {
            std::fs::create_dir_all(stage.join(dir))
                .map_err(|e| format!("create delta dir {dir}: {e}"))?;
        }

        let init = ensure_init_oci(root)?;
        let init_dst = stage.join("init");
        std::fs::copy(&init, &init_dst)
            .map_err(|e| format!("copy init-oci {}: {e}", init.display()))?;
        set_mode(&init_dst, 0o755)?;
        key_material.push_str(&format!("\ninit={}", file_size_mtime(&init)?));

        // Volumes: drop a `/.supermachine-volumes` file with one
        // GUEST_PATH per line. init-oci reads this post-pivot,
        // matches each line to /dev/vd<letter> by index (volumes
        // come after the layer block-devices), and mounts them as
        // ext4. Bake fingerprint includes the guest paths so adding
        // / removing / renaming a mount re-bakes; the host file's
        // current contents are runtime-only and never contribute.
        let volumes = parse_volume_args(plan.extra_args)?;
        if !volumes.is_empty() {
            let body: String = volumes
                .iter()
                .map(|v| format!("{}\n", v.guest_path))
                .collect();
            std::fs::write(stage.join(".supermachine-volumes"), &body)
                .map_err(|e| format!("write .supermachine-volumes: {e}"))?;
            for v in &volumes {
                key_material.push_str(&format!("\nvolume={}", v.guest_path));
            }
        }

        // Drop the in-guest exec agent into the delta layer at
        // /supermachine-agent. init-oci forks + execs it post-pivot.
        // The agent is statically-linked aarch64 musl so it runs
        // unconditionally regardless of the workload's libc.
        let agent = ensure_supermachine_agent(root)?;
        let agent_dst = stage.join("supermachine-agent");
        std::fs::copy(&agent, &agent_dst)
            .map_err(|e| format!("copy supermachine-agent {}: {e}", agent.display()))?;
        set_mode(&agent_dst, 0o755)?;
        key_material.push_str(&format!("\nagent={}", file_size_mtime(&agent)?));

        let key = sha256_text(&format!("{key_material}\n"))?;
        let delta_cache_dir = layer_cache_dir().join("deltas");
        std::fs::create_dir_all(&delta_cache_dir)
            .map_err(|e| format!("create delta cache dir {}: {e}", delta_cache_dir.display()))?;
        let cache_path = delta_cache_dir.join(format!("{key}.squashfs"));
        result.prepare_ms = elapsed_ms(prepare_t0);
        result.key = Some(key);
        result.cache_path = Some(cache_path.clone());
        if cache_path.is_file() {
            result.cache_hit = true;
            return Ok(());
        }

        let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let tmp = delta_cache_dir.join(format!(
            ".delta.{}.{}.squashfs.tmp",
            std::process::id(),
            unique
        ));
        let _ = std::fs::remove_file(&tmp);
        let mut squash = Command::new("mksquashfs");
        squash
            .arg(&stage)
            .arg(&tmp)
            .arg("-noappend")
            .arg("-comp")
            .arg("zstd")
            .arg("-Xcompression-level")
            .arg("3")
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        run_status(squash, "mksquashfs delta cache")?;
        if cache_path.is_file() {
            let _ = std::fs::remove_file(&tmp);
            result.cache_hit = true;
        } else {
            std::fs::rename(&tmp, &cache_path).map_err(|e| {
                format!(
                    "install delta cache {} -> {}: {e}",
                    tmp.display(),
                    cache_path.display()
                )
            })?;
            result.cache_hit = false;
        }
        Ok(())
    })();
    result.materialize_ms = elapsed_ms(materialize_t0);
    let _ = std::fs::remove_dir_all(&stage);
    materialized?;
    Ok(Some(result))
}

fn resolve_image(plan: &BakePlan<'_>, source: &dyn ImageSource) -> Result<ImageResolution, String> {
    let t0 = Instant::now();
    let local_arch = source.local_arch(plan.image);
    let pull_action = match plan.pull_policy {
        "always" => {
            source.pull_arm64(plan.image, true)?;
            "always".to_owned()
        }
        "missing" => {
            if local_arch.as_deref() == Some("arm64") {
                "skipped-local-arm64".to_owned()
            } else {
                source.pull_arm64(plan.image, false)?;
                "missing-pulled-arm64".to_owned()
            }
        }
        "never" => {
            if local_arch.is_none() {
                return Err(format!(
                    "image {} not present locally and --pull never was set",
                    plan.image
                ));
            }
            "never".to_owned()
        }
        other => return Err(format!("unknown --pull policy: {other}")),
    };

    let image_obj = source.inspect(plan.image)?;
    let cfg = image_obj
        .get("Config")
        .ok_or_else(|| "image inspect missing Config".to_owned())?;
    let image_id = image_obj
        .get("Id")
        .and_then(|v| v.as_str())
        .map(|s| s.strip_prefix("sha256:").unwrap_or(s).to_owned());
    let architecture = image_obj
        .get("Architecture")
        .and_then(|v| v.as_str())
        .map(ToOwned::to_owned);
    let env_count = cfg
        .get("Env")
        .and_then(|v| v.as_array())
        .map(|v| v.len())
        .unwrap_or(0);
    let env = value_string_array(cfg.get("Env"));
    // docker-style runtime overrides. `--workdir` / `--user`
    // replace the image's WorkingDir / User. Empty string is
    // explicitly allowed (means "no chdir / run as root") so
    // customers can override-to-default.
    let workdir_override = arg_value(plan.extra_args, "--workdir").map(ToOwned::to_owned);
    let user_override = arg_value(plan.extra_args, "--user").map(ToOwned::to_owned);
    let working_dir = workdir_override.or_else(|| {
        cfg.get("WorkingDir")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(ToOwned::to_owned)
    });
    let user = user_override.or_else(|| {
        cfg.get("User")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
            .map(ToOwned::to_owned)
    });

    // `--entrypoint`: replaces the image's ENTRYPOINT. Combined
    // with the image's CMD (or `--cmd` override) the final argv
    // becomes [entrypoint, ...cmd-args]. Mirrors
    // `docker run --entrypoint X my-image arg1 arg2`.
    let entrypoint_override = arg_value(plan.extra_args, "--entrypoint").map(ToOwned::to_owned);

    let effective_cmd = if let Some(cmd_override) = plan.cmd_override {
        let cmd_argv = serde_json::from_str::<Vec<String>>(cmd_override)
            .map_err(|e| format!("--cmd must be a JSON string array: {e}"))?;
        match &entrypoint_override {
            Some(ep) if !ep.is_empty() => {
                let mut argv = vec![ep.clone()];
                argv.extend(cmd_argv);
                argv
            }
            _ => cmd_argv,
        }
    } else if let Some(ep) = &entrypoint_override {
        // Entrypoint without --cmd: keep the image's CMD as args
        // (docker semantics) and replace ENTRYPOINT with the override.
        let mut argv = vec![ep.clone()];
        argv.extend(value_string_array(cfg.get("Cmd")));
        if argv.len() == 1 && ep.is_empty() {
            return Err("--entrypoint cannot be empty without --cmd".to_owned());
        }
        argv
    } else {
        // Reuse a previous bake's `cmd` when the user didn't override.
        // Without this, re-running `supermachine run X` after a custom
        // first-run with `--cmd Y` falls back to the image's default
        // CMD, mismatches the cached snapshot inputs, and forces a
        // re-bake (often failing if the default CMD doesn't open a
        // listener — e.g. python:3.x's CMD is the REPL, not a server).
        if let Some(prev_cmd) = previous_metadata_cmd(plan) {
            prev_cmd
        } else {
            let mut argv = value_string_array(cfg.get("Entrypoint"));
            argv.extend(value_string_array(cfg.get("Cmd")));
            if argv.is_empty() {
                return Err(format!(
                    "image {} has no CMD/ENTRYPOINT; pass --cmd '<argv json>'",
                    plan.image
                ));
            }
            argv
        }
    };

    Ok(ImageResolution {
        local_arch,
        architecture,
        image_id,
        effective_cmd,
        working_dir,
        user,
        env,
        env_count,
        pull_action,
        inspect_ms: elapsed_ms(t0),
    })
}