mvm-cli 0.11.0

CLI commands, UI, and bootstrap for mvm
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use serde::Serialize;
use std::sync::{Arc, Mutex};

use crate::bootstrap;
use crate::fleet;
use crate::logging::{self, LogFormat};
use crate::shell_init;
use crate::template_cmd;
use crate::ui;
use crate::update;

use mvm_core::naming::{validate_flake_ref, validate_template_name, validate_vm_name};
use mvm_core::util::parse_human_size;
use mvm_core::vm_backend::VmId;
use mvm_runtime::config;
use mvm_runtime::shell;
use mvm_runtime::vm::backend::AnyBackend;
use mvm_runtime::vm::{firecracker, image, lima, microvm};

/// Parameters for building a `VmStartConfig` from runtime-specific types.
struct VmStartParams<'a> {
    name: String,
    rootfs_path: String,
    vmlinux_path: String,
    initrd_path: Option<String>,
    revision_hash: String,
    flake_ref: String,
    profile: Option<String>,
    cpus: u32,
    memory_mib: u32,
    volumes: &'a [image::RuntimeVolume],
    config_files: &'a [microvm::DriveFile],
    secret_files: &'a [microvm::DriveFile],
    port_mappings: &'a [config::PortMapping],
}

impl VmStartParams<'_> {
    fn into_start_config(self) -> mvm_core::vm_backend::VmStartConfig {
        mvm_core::vm_backend::VmStartConfig {
            name: self.name,
            rootfs_path: self.rootfs_path,
            kernel_path: Some(self.vmlinux_path),
            initrd_path: self.initrd_path,
            revision_hash: self.revision_hash,
            flake_ref: self.flake_ref,
            profile: self.profile,
            cpus: self.cpus,
            memory_mib: self.memory_mib,
            ports: self
                .port_mappings
                .iter()
                .map(|p| mvm_core::vm_backend::VmPortMapping {
                    host: p.host,
                    guest: p.guest,
                })
                .collect(),
            volumes: self
                .volumes
                .iter()
                .map(|v| mvm_core::vm_backend::VmVolume {
                    host: v.host.clone(),
                    guest: v.guest.clone(),
                    size: v.size.clone(),
                })
                .collect(),
            config_files: self
                .config_files
                .iter()
                .map(|f| mvm_core::vm_backend::VmFile {
                    name: f.name.clone(),
                    content: f.content.clone(),
                    mode: f.mode,
                })
                .collect(),
            secret_files: self
                .secret_files
                .iter()
                .map(|f| mvm_core::vm_backend::VmFile {
                    name: f.name.clone(),
                    content: f.content.clone(),
                    mode: f.mode,
                })
                .collect(),
            runner_dir: None,
        }
    }
}

/// Global registry of spawned child PIDs so the signal handler can clean them up.
static CHILD_PIDS: std::sync::LazyLock<Arc<Mutex<Vec<u32>>>> =
    std::sync::LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));

/// When true, the Ctrl-C handler does nothing — console mode forwards
/// raw bytes to the guest instead.
static IN_CONSOLE_MODE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

#[derive(Parser)]
#[command(name = "mvmctl", version, about = "Lightweight VM development tool")]
struct Cli {
    /// Log format: human (default) or json (structured)
    #[arg(long, global = true)]
    log_format: Option<String>,

    /// Override Firecracker version (e.g., v1.14.0)
    #[arg(long, global = true)]
    fc_version: Option<String>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)] // Up variant has many CLI fields; boxing breaks Clap derive
enum Commands {
    /// Full environment setup from scratch
    Bootstrap {
        /// Production mode (skip Homebrew, assume Linux with apt)
        #[arg(long)]
        production: bool,
    },
    /// Create Lima VM, install Firecracker, download kernel/rootfs (requires limactl)
    Setup {
        /// Delete the existing rootfs and rebuild it from scratch
        #[arg(long)]
        recreate: bool,
        /// Re-run all setup steps even if already complete
        #[arg(long)]
        force: bool,
        /// Number of vCPUs for the Lima VM
        #[arg(long, default_value = "8")]
        lima_cpus: u32,
        /// Memory (GiB) for the Lima VM
        #[arg(long, default_value = "16")]
        lima_mem: u32,
    },
    /// Manage the Lima development environment (up, down, shell, status)
    Dev {
        #[command(subcommand)]
        action: Option<DevCmd>,
    },
    /// Remove old dev-build artifacts and run Nix garbage collection
    Cleanup {
        /// Number of newest build revisions to keep
        #[arg(long)]
        keep: Option<usize>,
        /// Remove all cached build revisions
        #[arg(long)]
        all: bool,
        /// Print each cached build path that gets removed
        #[arg(long)]
        verbose: bool,
    },
    /// Show console logs from a running microVM
    Logs {
        /// Name of the VM
        #[arg(value_parser = clap_vm_name)]
        name: String,
        /// Follow log output (like tail -f)
        #[arg(long, short = 'f')]
        follow: bool,
        /// Number of lines to show (default 50)
        #[arg(long, short = 'n', default_value = "50")]
        lines: u32,
        /// Show Firecracker hypervisor logs instead of guest console output
        #[arg(long)]
        hypervisor: bool,
    },
    /// Forward a port from a running microVM to localhost
    Forward {
        /// Name of the VM
        #[arg(value_parser = clap_vm_name)]
        name: String,
        /// Port mapping(s): GUEST_PORT or LOCAL_PORT:GUEST_PORT
        #[arg(short, long, value_name = "PORT", value_parser = clap_port_spec)]
        port: Vec<String>,
        /// Port mapping(s) (positional, same as --port)
        #[arg(trailing_var_arg = true, hide = true)]
        ports: Vec<String>,
    },
    /// List running VMs
    #[command(alias = "ls", alias = "status")]
    Ps {
        /// Show all VMs (including stopped)
        #[arg(long, short = 'a')]
        all: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Check for and install the latest version of mvmctl
    Update {
        /// Only check for updates, don't install
        #[arg(long)]
        check: bool,
        /// Force reinstall even if already up to date
        #[arg(long)]
        force: bool,
        /// Skip cosign signature verification even if cosign is installed
        #[arg(long)]
        skip_verify: bool,
    },
    /// System diagnostics and dependency checks
    Doctor {
        /// Output results as JSON
        #[arg(long)]
        json: bool,
    },
    /// Manage global templates (shared base images)
    Template {
        #[command(subcommand)]
        action: TemplateCmd,
    },
    /// Build a microVM image from a Mvmfile.toml config or Nix flake
    Build {
        /// Image name (built-in like "openclaw") or path to directory with Mvmfile.toml
        #[arg(default_value = ".")]
        path: String,
        /// Output path for the built .elf image
        #[arg(long, short = 'o')]
        output: Option<String>,
        /// Nix flake reference (enables flake build mode)
        #[arg(long, value_parser = clap_flake_ref)]
        flake: Option<String>,
        /// Flake package variant (e.g. worker, gateway). Omit to use flake default.
        #[arg(long)]
        profile: Option<String>,
        /// Watch flake.lock and rebuild on change (flake mode)
        #[arg(long)]
        watch: bool,
        /// Output structured JSON events instead of human-readable output
        #[arg(long)]
        json: bool,
    },
    /// Build and run a VM from a Nix flake or template
    #[command(alias = "start", alias = "run", group(clap::ArgGroup::new("source").required(true)))]
    Up {
        /// Nix flake reference (local path or remote URI)
        #[arg(long, group = "source", value_parser = clap_flake_ref)]
        flake: Option<String>,
        /// Run from a pre-built template (skip build)
        #[arg(long, group = "source")]
        template: Option<String>,
        /// VM name (auto-generated if omitted)
        #[arg(long, value_parser = clap_vm_name)]
        name: Option<String>,
        /// Flake package variant (e.g. worker, gateway). Omit to use flake default.
        #[arg(long)]
        profile: Option<String>,
        /// vCPU cores
        #[arg(long)]
        cpus: Option<u32>,
        /// Memory (supports human-readable sizes: 512M, 4G, 1024K, or plain MB)
        #[arg(long)]
        memory: Option<String>,
        /// Runtime config (TOML) for persistent resources/volumes
        #[arg(long)]
        config: Option<String>,
        /// Volume (host_dir:/guest/path or host:/guest/path:size). Repeatable.
        #[arg(long, short = 'v', value_parser = clap_volume_spec)]
        volume: Vec<String>,
        /// Hypervisor backend (firecracker, qemu, apple-container, docker). Default: auto-detect.
        #[arg(long, default_value = "firecracker")]
        hypervisor: String,
        /// Port mapping (format: HOST:GUEST or PORT). Repeatable.
        #[arg(long, short = 'p', value_parser = clap_port_spec)]
        port: Vec<String>,
        /// Environment variable to inject (format: KEY=VALUE). Repeatable.
        #[arg(long, short = 'e')]
        env: Vec<String>,
        /// Auto-forward declared ports after boot (blocks until Ctrl-C)
        #[arg(long)]
        forward: bool,
        /// Bind a Prometheus metrics endpoint on this port (0 = disabled)
        #[arg(long, default_value = "0")]
        metrics_port: u16,
        /// Reload ~/.mvm/config.toml automatically when it changes
        #[arg(long)]
        watch_config: bool,
        /// Watch the flake for changes and auto-rebuild + reboot (requires local --flake)
        #[arg(long)]
        watch: bool,
        /// Run in background (detached mode, like docker run -d)
        #[arg(long, short = 'd')]
        detach: bool,
        /// Network preset (unrestricted, none, registries, dev)
        #[arg(long)]
        network_preset: Option<String>,
        /// Network allowlist entry (format: HOST:PORT). Repeatable.
        #[arg(long)]
        network_allow: Vec<String>,
        /// Seccomp profile tier (essential, minimal, standard, network, unrestricted)
        #[arg(long, default_value = "unrestricted")]
        seccomp: String,
        /// Secret binding (format: KEY:host, KEY:host:header, or KEY=value:host). Repeatable.
        #[arg(long, short = 's')]
        secret: Vec<String>,
        /// Named dev network to attach VM to (default: "default")
        #[arg(long, default_value = "default")]
        network: String,
    },
    /// Stop microVMs (from mvm.toml, by name, or all)
    Down {
        /// VM name to stop (or all VMs if omitted)
        name: Option<String>,
        /// Path to fleet config (stops only VMs defined in config)
        #[arg(long, short = 'f')]
        config: Option<String>,
    },
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Print shell configuration (completions + dev aliases) to stdout
    ShellInit,
    /// Show runtime metrics (Prometheus text format by default)
    Metrics {
        /// Output as JSON instead of Prometheus exposition format
        #[arg(long)]
        json: bool,
    },
    /// Read or write global operator config (~/.mvm/config.toml)
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Remove Lima VM, Firecracker binary, and all mvm state (clean uninstall)
    Uninstall {
        /// Skip confirmation prompt
        #[arg(long, short = 'y')]
        yes: bool,
        /// Also remove ~/.mvm/ config dir and /usr/local/bin/mvmctl binary
        #[arg(long)]
        all: bool,
        /// Print what would be removed without actually removing anything
        #[arg(long)]
        dry_run: bool,
    },
    /// View the local audit log (~/.mvm/log/audit.jsonl)
    Audit {
        #[command(subcommand)]
        action: AuditCmd,
    },
    /// Validate a Nix flake before building
    Flake {
        #[command(subcommand)]
        action: FlakeCmd,
    },
    /// Show filesystem changes in a running VM (files created/modified/deleted since boot)
    Diff {
        /// VM name
        name: String,
        /// Output as JSON instead of human-readable
        #[arg(long)]
        json: bool,
    },
    /// Manage named dev networks
    Network {
        #[command(subcommand)]
        action: NetworkCmd,
    },
    /// Browse and fetch images from the Nix-based image catalog
    Image {
        #[command(subcommand)]
        action: ImageCmd,
    },
    /// Interactive console (PTY-over-vsock) to a running VM
    Console {
        /// VM name
        #[arg(value_parser = clap_vm_name)]
        name: String,
        /// Run a single command instead of opening an interactive shell
        #[arg(long)]
        command: Option<String>,
    },
    /// Manage the XDG cache directory (~/.cache/mvm)
    Cache {
        #[command(subcommand)]
        action: CacheCmd,
    },
    /// First-time setup wizard — installs deps, creates Lima VM, sets up default network
    Init {
        /// Skip interactive prompts, use defaults
        #[arg(long)]
        non_interactive: bool,
        /// Number of vCPUs for the Lima VM
        #[arg(long, default_value = "8")]
        lima_cpus: u32,
        /// Memory (GiB) for the Lima VM
        #[arg(long, default_value = "16")]
        lima_mem: u32,
    },
    /// Show security posture and status
    Security {
        #[command(subcommand)]
        action: SecurityCmd,
    },
}

#[derive(Subcommand)]
enum AuditCmd {
    /// Show the last N audit events (default: 20)
    Tail {
        /// Number of lines to show
        #[arg(long, short = 'n', default_value = "20")]
        lines: usize,
        /// Follow log output (poll every 500 ms until Ctrl-C)
        #[arg(long, short = 'f')]
        follow: bool,
    },
}

#[derive(Subcommand)]
enum DevCmd {
    /// Bootstrap and start the dev environment
    Up {
        /// Number of vCPUs for the Lima VM
        #[arg(long, default_value = "8")]
        lima_cpus: u32,
        /// Memory (GiB) for the Lima VM
        #[arg(long, default_value = "16")]
        lima_mem: u32,
        /// Project directory to cd into inside the VM
        #[arg(long)]
        project: Option<String>,
        /// Bind a Prometheus metrics endpoint on this port (0 = disabled)
        #[arg(long, default_value = "0")]
        metrics_port: u16,
        /// Reload ~/.mvm/config.toml automatically when it changes
        #[arg(long)]
        watch_config: bool,
        /// Force Lima backend even on macOS 26+ (where Apple Container is default)
        #[arg(long)]
        lima: bool,
        /// Open an interactive shell after starting
        #[arg(long, short = 's')]
        shell: bool,
    },
    /// Stop the Lima development VM
    Down,
    /// Open a shell in the running Lima VM
    Shell {
        /// Project directory to cd into inside the VM (Lima maps ~ → ~)
        #[arg(long)]
        project: Option<String>,
    },
    /// Show dev environment status (Lima VM, Firecracker, Nix)
    Status,
    /// Rebuild the dev environment (down + clear cache + up)
    Rebuild {
        /// Number of vCPUs for the Lima VM
        #[arg(long, default_value = "8")]
        lima_cpus: u32,
        /// Memory (GiB) for the Lima VM
        #[arg(long, default_value = "16")]
        lima_mem: u32,
        /// Force Lima backend even on macOS 26+
        #[arg(long)]
        lima: bool,
        /// Open an interactive shell after rebuilding
        #[arg(long, short = 's')]
        shell: bool,
    },
}

#[derive(Subcommand)]
enum FlakeCmd {
    /// Run `nix flake check` to validate a flake before building
    Check {
        /// Flake path or reference (default: current directory)
        #[arg(long, default_value = ".")]
        flake: String,
        /// Output structured JSON instead of human-readable output
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum NetworkCmd {
    /// Create a named dev network with its own bridge and subnet
    #[command(alias = "new")]
    Create {
        /// Network name (lowercase alphanumeric + hyphens)
        name: String,
        /// Subnet CIDR (auto-assigned if omitted)
        #[arg(long)]
        subnet: Option<String>,
    },
    /// List all dev networks
    #[command(alias = "ls")]
    List,
    /// Show details of a named network
    Inspect {
        /// Network name
        name: String,
    },
    /// Remove a named network
    #[command(alias = "rm")]
    Remove {
        /// Network name
        name: String,
    },
}

#[derive(Subcommand)]
enum ImageCmd {
    /// List available images in the catalog
    #[command(alias = "ls")]
    List,
    /// Search images by name or tag
    Search {
        /// Search query
        query: String,
    },
    /// Fetch (build) an image from the catalog
    Fetch {
        /// Image name from the catalog
        name: String,
    },
    /// Show details of a catalog image
    Info {
        /// Image name from the catalog
        name: String,
    },
}

#[derive(Subcommand)]
enum SecurityCmd {
    /// Show security posture evaluation for the current environment
    Status {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum CacheCmd {
    /// Remove stale items from the cache directory
    Prune {
        /// Print what would be removed without actually removing anything
        #[arg(long)]
        dry_run: bool,
    },
    /// Show cache directory path and disk usage
    Info,
}

#[derive(Subcommand)]
enum TemplateCmd {
    /// Create a new template (single role/profile)
    #[command(alias = "new")]
    Create {
        /// Template name (e.g. "base", "openclaw")
        name: String,
        /// Nix flake reference for the template source
        #[arg(long, default_value = ".", value_parser = clap_flake_ref)]
        flake: String,
        /// Flake package variant
        #[arg(long, default_value = "default")]
        profile: String,
        /// VM role (worker or gateway)
        #[arg(long, default_value = "worker")]
        role: String,
        /// Default vCPU count for VMs using this template
        #[arg(long, default_value = "2")]
        cpus: u8,
        /// Default memory (supports human-readable sizes: 512M, 4G, or plain MB)
        #[arg(long, default_value = "1024")]
        mem: String,
        /// Data disk size (supports human-readable sizes: 10G, 512M, or plain MB; 0 = no disk)
        #[arg(long, default_value = "0")]
        data_disk: String,
    },
    /// Create multiple role-specific templates (name-role)
    CreateMulti {
        /// Base template name (each role becomes <base>-<role>)
        base: String,
        /// Nix flake reference for the template source
        #[arg(long, default_value = ".", value_parser = clap_flake_ref)]
        flake: String,
        /// Flake package variant
        #[arg(long, default_value = "default")]
        profile: String,
        /// Comma-separated roles, e.g. gateway,agent
        #[arg(long)]
        roles: String,
        /// Default vCPU count for VMs using this template
        #[arg(long, default_value = "2")]
        cpus: u8,
        /// Default memory (supports human-readable sizes: 512M, 4G, or plain MB)
        #[arg(long, default_value = "1024")]
        mem: String,
        /// Data disk size (supports human-readable sizes: 10G, 512M, or plain MB; 0 = no disk)
        #[arg(long, default_value = "0")]
        data_disk: String,
    },
    /// Build a template (shared image via nix build)
    Build {
        /// Template name to build
        name: String,
        /// Rebuild even if a cached revision exists
        #[arg(long)]
        force: bool,
        /// After build, boot VM, wait for healthy, and create a snapshot for instant starts
        #[arg(long)]
        snapshot: bool,
        /// Optional template config TOML to build multiple variants
        #[arg(long)]
        config: Option<String>,
        /// Recompute the Nix fixed-output derivation hash (use after version bump)
        #[arg(long)]
        update_hash: bool,
    },
    /// Push a built template revision to the object storage registry
    Push {
        /// Template name to push
        name: String,
        /// Revision hash to push (defaults to current)
        #[arg(long)]
        revision: Option<String>,
    },
    /// Pull a template revision from the object storage registry
    Pull {
        /// Template name to pull
        name: String,
        /// Revision hash to pull (defaults to registry current)
        #[arg(long)]
        revision: Option<String>,
    },
    /// Verify a locally installed template revision against checksums.json
    Verify {
        /// Template name to verify
        name: String,
        /// Revision hash to verify (defaults to current)
        #[arg(long)]
        revision: Option<String>,
    },
    /// List all templates
    List {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show template details (spec, revisions, cache key)
    Info {
        /// Template name
        name: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Edit an existing template's configuration
    Edit {
        /// Template name to edit
        name: String,
        /// Update Nix flake reference
        #[arg(long)]
        flake: Option<String>,
        /// Update flake package variant
        #[arg(long)]
        profile: Option<String>,
        /// Update VM role
        #[arg(long)]
        role: Option<String>,
        /// Update vCPU count
        #[arg(long)]
        cpus: Option<u8>,
        /// Update memory (supports human-readable sizes: 512M, 4G, or plain MB)
        #[arg(long)]
        mem: Option<String>,
        /// Update data disk size (supports human-readable sizes: 10G, 512M, or plain MB)
        #[arg(long)]
        data_disk: Option<String>,
    },
    /// Delete a template and its artifacts
    Delete {
        /// Template name to delete
        name: String,
        /// Skip confirmation prompt
        #[arg(long)]
        force: bool,
    },
    /// Initialize on-disk template layout (idempotent)
    Init {
        /// Template name to initialize
        name: String,
        /// Create locally instead of in ~/.mvm/templates
        #[arg(long)]
        local: bool,
        /// Create inside the Lima VM (overrides --local)
        #[arg(long)]
        vm: bool,
        /// Base directory for local init (default: current dir)
        #[arg(long, default_value = ".")]
        dir: String,
        /// Scaffold preset: minimal, http, postgres, worker, python (default: minimal)
        #[arg(long)]
        preset: Option<String>,
        /// Natural-language prompt used to generate a local scaffold and metadata (uses OpenAI when OPENAI_API_KEY is set)
        #[arg(long)]
        prompt: Option<String>,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Print current config as TOML
    Show,
    /// Open the config file in $EDITOR (falls back to nano)
    Edit,
    /// Set a single config key
    Set {
        /// Config key (e.g. lima_cpus)
        key: String,
        /// New value
        value: String,
    },
}

// ============================================================================
// Structured JSON event output for --json mode
// ============================================================================

/// Structured event emitted during sync/build operations in --json mode.
#[derive(Debug, Serialize)]
struct PhaseEvent {
    timestamp: String,
    command: &'static str,
    phase: String,
    status: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

impl PhaseEvent {
    fn new(command: &'static str, phase: &str, status: &'static str) -> Self {
        Self {
            timestamp: chrono::Utc::now().to_rfc3339(),
            command,
            phase: phase.to_string(),
            status,
            message: None,
            error: None,
        }
    }

    fn with_message(mut self, msg: &str) -> Self {
        self.message = Some(msg.to_string());
        self
    }

    fn with_error(mut self, err: &str) -> Self {
        self.error = Some(err.to_string());
        self
    }

    fn emit(&self) {
        if let Ok(json) = serde_json::to_string(self) {
            println!("{}", json);
        }
    }
}

// ============================================================================
// Entry point
// ============================================================================

/// Return the Clap `Command` tree for `mvmctl`.
///
/// Used by the `xtask` crate to generate man pages without duplicating the
/// command definition.
pub fn cli_command() -> clap::Command {
    use clap::CommandFactory;
    Cli::command()
}

pub fn run() -> Result<()> {
    let cli = Cli::parse();

    // Apply FC version override before anything reads it.
    // SAFETY: called once at startup before any threads are spawned.
    if let Some(ref version) = cli.fc_version {
        unsafe { std::env::set_var("MVM_FC_VERSION", version) };
    }

    // Initialize logging
    let log_format = match cli.log_format.as_deref() {
        Some("json") => LogFormat::Json,
        Some("human") => LogFormat::Human,
        Some(other) => {
            eprintln!(
                "Unknown --log-format '{}', using 'human'. Valid: human, json",
                other
            );
            LogFormat::Human
        }
        None => LogFormat::Human,
    };
    logging::init(log_format);

    // Install Ctrl-C / SIGTERM handler for graceful shutdown.
    let pids = Arc::clone(&CHILD_PIDS);
    if let Err(e) = ctrlc::set_handler(move || {
        // In console mode, Ctrl-C is forwarded as a raw byte to the guest.
        if IN_CONSOLE_MODE.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        eprintln!("\nInterrupted, cleaning up...");
        // Kill any tracked child processes (e.g., socat port-forwarders).
        if let Ok(pids) = pids.lock() {
            for &pid in pids.iter() {
                unsafe {
                    libc::kill(pid as libc::pid_t, libc::SIGTERM);
                }
            }
        }
        std::process::exit(130);
    }) {
        tracing::warn!("failed to install signal handler: {e}");
    }

    // Load operator config once; used as fallback for lima_cpus, lima_mem, cpus, memory.
    let cfg = mvm_core::user_config::load(None);

    let result = match cli.command {
        Commands::Bootstrap { production } => cmd_bootstrap(production),
        Commands::Setup {
            recreate,
            force,
            lima_cpus,
            lima_mem,
        } => {
            let effective_cpus = if lima_cpus == 8 {
                cfg.lima_cpus
            } else {
                lima_cpus
            };
            let effective_mem = if lima_mem == 16 {
                cfg.lima_mem_gib
            } else {
                lima_mem
            };
            cmd_setup(recreate, force, effective_cpus, effective_mem)
        }
        Commands::Dev { action } => {
            let action = action.unwrap_or(DevCmd::Up {
                lima_cpus: 8,
                lima_mem: 16,
                project: None,
                metrics_port: 0,
                watch_config: false,
                lima: false,
                shell: false,
            });
            match action {
                DevCmd::Up {
                    lima_cpus,
                    lima_mem,
                    project,
                    metrics_port,
                    watch_config,
                    lima,
                    shell,
                } => {
                    let effective_cpus = if lima_cpus == 8 {
                        cfg.lima_cpus
                    } else {
                        lima_cpus
                    };
                    let effective_mem = if lima_mem == 16 {
                        cfg.lima_mem_gib
                    } else {
                        lima_mem
                    };

                    let use_apple_container =
                        !lima && mvm_core::platform::current().has_apple_containers();

                    if use_apple_container {
                        cmd_dev_apple_container(effective_cpus, effective_mem, shell)
                    } else {
                        cmd_dev(
                            effective_cpus,
                            effective_mem,
                            project.as_deref(),
                            metrics_port,
                            watch_config,
                        )
                    }
                }
                DevCmd::Down => {
                    if mvm_core::platform::current().has_apple_containers() {
                        cmd_dev_apple_container_down()
                    } else {
                        cmd_dev_down()
                    }
                }
                DevCmd::Shell { project } => {
                    if mvm_core::platform::current().has_apple_containers() {
                        if !is_apple_container_dev_running() {
                            anyhow::bail!("Dev VM is not running. Start it with: mvmctl dev up");
                        }
                        // Try connecting — the VM may be in another process
                        match console_interactive("mvm-dev") {
                            Ok(()) => Ok(()),
                            Err(_) => {
                                anyhow::bail!(
                                    "Dev VM is running but owned by another process.\n\
                                     Use the terminal where you ran 'mvmctl dev up',\n\
                                     or restart with: mvmctl dev down && mvmctl dev up --shell"
                                )
                            }
                        }
                    } else {
                        cmd_shell(project.as_deref())
                    }
                }
                DevCmd::Status => {
                    if mvm_core::platform::current().has_apple_containers() {
                        cmd_dev_apple_container_status()
                    } else {
                        cmd_dev_status()
                    }
                }
                DevCmd::Rebuild {
                    lima_cpus,
                    lima_mem,
                    lima,
                    shell,
                } => {
                    // Down
                    if mvm_core::platform::current().has_apple_containers() {
                        let _ = cmd_dev_apple_container_down();
                    } else {
                        let _ = cmd_dev_down();
                    }

                    // Clear cached dev image
                    let cache_dir = format!("{}/dev", mvm_core::config::mvm_cache_dir());
                    let _ = std::fs::remove_dir_all(&cache_dir);

                    // Up
                    let effective_cpus = if lima_cpus == 8 {
                        cfg.lima_cpus
                    } else {
                        lima_cpus
                    };
                    let effective_mem = if lima_mem == 16 {
                        cfg.lima_mem_gib
                    } else {
                        lima_mem
                    };
                    let use_apple_container =
                        !lima && mvm_core::platform::current().has_apple_containers();
                    if use_apple_container {
                        cmd_dev_apple_container(effective_cpus, effective_mem, shell)
                    } else {
                        cmd_dev(effective_cpus, effective_mem, None, 0, false)
                    }
                }
            }
        }
        Commands::Cleanup { keep, all, verbose } => cmd_cleanup(keep, all, verbose),
        Commands::Logs {
            name,
            follow,
            lines,
            hypervisor,
        } => cmd_logs(&name, follow, lines, hypervisor),
        Commands::Forward { name, port, ports } => {
            let mut all_ports = port;
            all_ports.extend(ports);
            cmd_forward(&name, &all_ports)
        }

        Commands::Ps { all, json } => cmd_ls(all, json),
        Commands::Update {
            check,
            force,
            skip_verify,
        } => cmd_update(check, force, skip_verify),
        Commands::Doctor { json } => cmd_doctor(json),
        Commands::Build {
            path,
            output,
            flake,
            profile,
            watch,
            json,
        } => {
            if let Some(flake_ref) = flake {
                cmd_build_flake(&flake_ref, profile.as_deref(), watch, json)
            } else {
                cmd_build(&path, output.as_deref())
            }
        }
        Commands::Up {
            flake,
            template,
            name,
            profile,
            cpus,
            memory,
            config,
            volume,
            hypervisor,
            port,
            env,
            forward,
            metrics_port,
            watch_config,
            watch,
            detach,
            network_preset,
            network_allow,
            seccomp,
            secret,
            network,
        } => {
            let memory_mb = memory
                .as_ref()
                .map(|s| parse_human_size(s))
                .transpose()
                .context("Invalid memory size")?;
            // CLI flag takes precedence; fall back to per-user config defaults.
            let effective_cpus = cpus.or(Some(cfg.default_cpus));
            let effective_memory = memory_mb.or(Some(cfg.default_memory_mib));

            let network_policy = resolve_network_policy(network_preset.as_deref(), &network_allow)?;
            let seccomp_tier: mvm_security::seccomp::SeccompTier =
                seccomp.parse().context("Invalid --seccomp value")?;
            let secret_bindings: Vec<mvm_core::secret_binding::SecretBinding> = secret
                .iter()
                .map(|s| s.parse())
                .collect::<Result<Vec<_>>>()
                .context("Invalid --secret value")?;

            cmd_run(RunParams {
                flake_ref: flake.as_deref(),
                template_name: template.as_deref(),
                name: name.as_deref(),
                profile: profile.as_deref(),
                cpus: effective_cpus,
                memory: effective_memory,
                config_path: config.as_deref(),
                volumes: &volume,
                hypervisor: &hypervisor,
                ports: &port,
                env_vars: &env,
                forward,
                metrics_port,
                watch_config,
                watch,
                detach,
                network_policy,
                network_name: &network,
                seccomp_tier,
                secret_bindings,
            })
        }
        Commands::Down { name, config } => cmd_down(name.as_deref(), config.as_deref()),
        Commands::Completions { shell } => cmd_completions(shell),
        Commands::ShellInit => shell_init::print_shell_init(),
        Commands::Metrics { json } => cmd_metrics(json),
        Commands::Template { action } => cmd_template(action),
        Commands::Config { action } => cmd_config(action),
        Commands::Uninstall { yes, all, dry_run } => cmd_uninstall(yes, all, dry_run),
        Commands::Audit { action } => cmd_audit(action),
        Commands::Diff { name, json } => cmd_diff(&name, json),
        Commands::Flake { action } => cmd_flake(action),
        Commands::Network { action } => cmd_network(action),
        Commands::Image { action } => cmd_image(action),
        Commands::Console { name, command } => cmd_console(&name, command.as_deref()),
        Commands::Cache { action } => cmd_cache(action),
        Commands::Init {
            non_interactive,
            lima_cpus,
            lima_mem,
        } => cmd_init(non_interactive, lima_cpus, lima_mem),
        Commands::Security { action } => cmd_security(action),
    };

    with_hints(result)
}

// ============================================================================
// Clap value parsers — run at argument-parse time for early validation
// ============================================================================

/// Validate a VM name at Clap parse time.
fn clap_vm_name(s: &str) -> Result<String, String> {
    mvm_core::naming::validate_vm_name(s).map_err(|e| e.to_string())?;
    Ok(s.to_owned())
}

/// Validate a Nix flake reference at Clap parse time.
fn clap_flake_ref(s: &str) -> Result<String, String> {
    mvm_core::naming::validate_flake_ref(s).map_err(|e| e.to_string())?;
    Ok(s.to_owned())
}

/// Validate a port spec (`PORT` or `HOST:GUEST`) at Clap parse time.
fn clap_port_spec(s: &str) -> Result<String, String> {
    if s.is_empty() {
        return Err("port spec must not be empty".to_owned());
    }
    if let Some((host_part, guest_part)) = s.split_once(':') {
        host_part
            .parse::<u16>()
            .map_err(|_| format!("invalid host port {:?} in {:?}", host_part, s))?;
        guest_part
            .parse::<u16>()
            .map_err(|_| format!("invalid guest port {:?} in {:?}", guest_part, s))?;
    } else {
        s.parse::<u16>()
            .map_err(|_| format!("invalid port {:?} — expected PORT or HOST:GUEST", s))?;
    }
    Ok(s.to_owned())
}

/// Validate a volume spec (`host:/guest` or `host:/guest:size`) at Clap parse time.
fn clap_volume_spec(s: &str) -> Result<String, String> {
    if s.is_empty() {
        return Err("volume spec must not be empty".to_owned());
    }
    let parts: Vec<&str> = s.splitn(3, ':').collect();
    if parts.len() < 2 || parts[0].is_empty() || parts[1].is_empty() {
        return Err(format!(
            "invalid volume {:?} — expected host:/guest or host:/guest:size",
            s
        ));
    }
    Ok(s.to_owned())
}

// ============================================================================
// Dev mode handlers
// ============================================================================

fn cmd_bootstrap(production: bool) -> Result<()> {
    ui::info("Bootstrapping full environment...\n");

    if !production {
        bootstrap::check_package_manager()?;
    }

    ui::info("\nInstalling prerequisites...");
    bootstrap::ensure_lima()?;

    // Bootstrap uses default Lima resources (8 vCPUs, 16 GiB), never forces
    run_setup_steps(false, 8, 16)?;

    ui::success("\nBootstrap complete! Run 'mvmctl dev' to enter the development environment.");
    Ok(())
}

fn cmd_setup(recreate: bool, force: bool, lima_cpus: u32, lima_mem: u32) -> Result<()> {
    if recreate {
        recreate_rootfs()?;
        ui::success("\nRootfs recreated! Run 'mvmctl start' or 'mvmctl dev' to launch.");
        return Ok(());
    }

    if !bootstrap::is_lima_required() {
        // Native Linux — just install FC directly
        run_setup_steps(force, lima_cpus, lima_mem)?;
        ui::success("\nSetup complete! Run 'mvmctl start' to launch a microVM.");
        return Ok(());
    }

    which::which("limactl").map_err(|_| {
        anyhow::anyhow!(
            "'limactl' not found. Install Lima first: brew install lima\n\
             Or run 'mvmctl bootstrap' for full automatic setup."
        )
    })?;

    run_setup_steps(force, lima_cpus, lima_mem)?;

    ui::success("\nSetup complete! Run 'mvmctl start' to launch a microVM.");
    Ok(())
}

/// Stop the running microVM and rebuild the rootfs from the upstream squashfs.
fn recreate_rootfs() -> Result<()> {
    if bootstrap::is_lima_required() {
        lima::require_running()?;
    }

    // Stop Firecracker if running
    if firecracker::is_running()? {
        ui::info("Stopping running microVM...");
        microvm::stop()?;
    }

    ui::info("Removing existing rootfs...");
    shell::run_in_vm(&format!(
        "rm -f {dir}/ubuntu-*.ext4",
        dir = config::MICROVM_DIR,
    ))?;

    ui::info("Rebuilding rootfs...");
    firecracker::prepare_rootfs()?;
    firecracker::write_state()?;

    Ok(())
}

fn cmd_dev(
    lima_cpus: u32,
    lima_mem: u32,
    project: Option<&str>,
    metrics_port: u16,
    watch_config: bool,
) -> Result<()> {
    let _metrics_server = if metrics_port > 0 {
        Some(crate::metrics_server::MetricsServer::start(metrics_port)?)
    } else {
        None
    };

    // Start config watcher before setup so any reload during bootstrap is captured.
    let _config_watcher = if watch_config {
        let config_path = {
            let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
            std::path::PathBuf::from(home)
                .join(".mvm")
                .join("config.toml")
        };
        if config_path.exists() {
            match crate::config_watcher::ConfigWatcher::start(&config_path) {
                Ok(w) => {
                    tracing::info!("Watching ~/.mvm/config.toml for changes");
                    Some(w)
                }
                Err(e) => {
                    tracing::warn!("Could not start config watcher: {e}");
                    None
                }
            }
        } else {
            None
        }
    } else {
        None
    };

    ui::info("Launching development environment...\n");

    if bootstrap::is_lima_required() {
        // macOS or Linux without KVM — need Lima
        if which::which("limactl").is_err() {
            ui::info("Lima not found. Running bootstrap...\n");
            cmd_bootstrap(false)?;
        } else {
            let lima_status = lima::get_status()?;
            match lima_status {
                lima::LimaStatus::NotFound => {
                    ui::info("Lima VM not found. Running setup...\n");
                    run_setup_steps(false, lima_cpus, lima_mem)?;
                }
                lima::LimaStatus::Stopped => {
                    ui::info("Lima VM is stopped. Starting...");
                    lima::start()?;
                }
                lima::LimaStatus::Running => {}
            }
        }
    }

    // Install Firecracker binary if not present
    if !firecracker::is_installed()? {
        ui::info("Firecracker not installed. Installing...\n");
        firecracker::install()?;
    }

    // Download kernel + squashfs only if missing
    if !firecracker::has_base_assets()? {
        ui::info("Downloading kernel and rootfs...\n");
        firecracker::download_assets()?;
        firecracker::prepare_rootfs()?;
        firecracker::write_state()?;
    }

    // Ensure shell completions and dev aliases are in ~/.zshrc
    shell_init::ensure_shell_init()?;

    // Drop into the Lima VM shell (the development environment)
    cmd_shell(project)
}

fn cmd_dev_down() -> Result<()> {
    if !bootstrap::is_lima_required() {
        ui::info("Lima is not required on this platform (native KVM available).");
        return Ok(());
    }

    if which::which("limactl").is_err() {
        anyhow::bail!("Lima is not installed. Run 'mvmctl dev up' to bootstrap first.");
    }

    let status = lima::get_status()?;
    match status {
        lima::LimaStatus::Running => {
            ui::info("Stopping Lima development VM...");
            lima::stop()?;
            ui::success("Development VM stopped.");
            Ok(())
        }
        lima::LimaStatus::Stopped => {
            ui::info("Development VM is already stopped.");
            Ok(())
        }
        lima::LimaStatus::NotFound => {
            anyhow::bail!(
                "Lima VM '{}' does not exist. Run 'mvmctl dev up' first.",
                config::VM_NAME
            );
        }
    }
}

fn cmd_dev_status() -> Result<()> {
    if !bootstrap::is_lima_required() {
        ui::info("Lima is not required on this platform (native KVM available).");
        return Ok(());
    }

    if which::which("limactl").is_err() {
        ui::warn("Lima is not installed. Run 'mvmctl dev up' to bootstrap.");
        return Ok(());
    }

    let status = lima::get_status()?;
    let status_str = match status {
        lima::LimaStatus::Running => "Running",
        lima::LimaStatus::Stopped => "Stopped",
        lima::LimaStatus::NotFound => "Not found",
    };

    ui::info(&format!("Lima VM '{}': {status_str}", config::VM_NAME));

    if matches!(status, lima::LimaStatus::Running) {
        let fc_ver = shell::run_in_vm_stdout("firecracker --version 2>/dev/null | head -1")
            .unwrap_or_default();
        let nix_ver = shell::run_in_vm_stdout("nix --version 2>/dev/null").unwrap_or_default();

        ui::info(&format!(
            "  Firecracker: {}",
            if fc_ver.trim().is_empty() {
                "not installed"
            } else {
                fc_ver.trim()
            }
        ));
        ui::info(&format!(
            "  Nix:         {}",
            if nix_ver.trim().is_empty() {
                "not installed"
            } else {
                nix_ver.trim()
            }
        ));

        let mvm_in_vm =
            shell::run_in_vm_stdout("test -f /usr/local/bin/mvmctl && echo yes || echo no")
                .unwrap_or_default();
        if mvm_in_vm.trim() == "yes" {
            let mvm_ver = shell::run_in_vm_stdout("/usr/local/bin/mvmctl --version 2>/dev/null")
                .unwrap_or_default();
            ui::info(&format!(
                "  mvmctl:      {}",
                if mvm_ver.trim().is_empty() {
                    "installed"
                } else {
                    mvm_ver.trim()
                }
            ));
        } else {
            ui::warn("  mvmctl not installed in VM. Run 'mvmctl sync' to build and install it.");
        }
    }

    Ok(())
}

// ============================================================================
// Apple Container dev environment
// ============================================================================

const DEV_VM_NAME: &str = "mvm-dev";

/// Check if the Apple Container dev VM is running.
/// Checks both in-process VM tracking (PID file) and launchd agent.
fn is_apple_container_dev_running() -> bool {
    // Check persisted PID file (also checks if process is alive)
    let pid_running = mvm_apple_container::list_ids()
        .iter()
        .any(|id| id == DEV_VM_NAME);
    if pid_running {
        return true;
    }
    // Check if launchd agent is installed and loaded
    if dev_launchd_plist_path().exists() {
        let output = std::process::Command::new("launchctl")
            .args(["list", DEV_LAUNCHD_LABEL])
            .output();
        if let Ok(o) = output
            && o.status.success()
        {
            return true;
        }
    }
    false
}

/// Boot the Apple Container dev VM, optionally opening an interactive console.
fn cmd_dev_apple_container(cpus: u32, memory_gib: u32, open_shell: bool) -> Result<()> {
    let is_daemon = std::env::var("MVM_DEV_DAEMON").as_deref() == Ok("1");

    // When running as the daemon process, do the actual VM boot.
    if is_daemon {
        return cmd_dev_apple_container_daemon(cpus, memory_gib);
    }

    ui::info("Starting dev environment via Apple Container...\n");

    if is_apple_container_dev_running() {
        if open_shell {
            ui::info("Dev VM already running. Opening shell...");
            return console_interactive(DEV_VM_NAME);
        }
        ui::info("Dev VM already running.");
        return Ok(());
    }

    // Clean up stale state from a previous process that died.
    cleanup_stale_dev_vm();

    // Ensure dev image exists (build if needed — this runs in the CLI process)
    let (kernel, rootfs) = ensure_dev_image()?;

    // Launch a background daemon process that keeps the VM alive.
    let exe = std::env::current_exe().context("cannot find current executable")?;
    let log_dir = format!("{}/dev", mvm_core::config::mvm_cache_dir());
    std::fs::create_dir_all(&log_dir)?;

    // Sign the binary BEFORE launching via launchd. The daemon runs with
    // MVM_SIGNED=1 so it won't re-exec (which would lose launchd context).
    mvm_apple_container::ensure_signed();

    ui::info(&format!(
        "Booting dev VM ({} vCPUs, {} GiB memory)...",
        cpus, memory_gib
    ));

    // Install a launchd agent to run the daemon. This is a proper macOS
    // service that is cleanly unloaded by `dev down`.
    install_dev_launchd_agent(&exe, &kernel, &rootfs, cpus, memory_gib, &log_dir)?;

    // Wait for the VM to become ready (vsock proxy socket + guest agent reachable)
    let proxy_path = dev_vsock_proxy_path();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
    loop {
        if std::time::Instant::now() > deadline {
            anyhow::bail!(
                "Dev VM did not start within 60 seconds.\n\
                           Check logs: {log_dir}/daemon-stderr.log"
            );
        }
        if std::path::Path::new(&proxy_path).exists()
            && vsock_proxy_connect(&proxy_path, mvm_guest::vsock::GUEST_AGENT_PORT).is_ok()
        {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }

    ui::success("Dev VM ready.");
    ui::info("  Shell:      mvmctl dev shell");
    ui::info("  Stop VM:    mvmctl dev down");

    if open_shell {
        ui::info("");
        let _ = console_interactive(DEV_VM_NAME);
    }

    Ok(())
}

/// Path for the vsock proxy Unix socket.
fn dev_vsock_proxy_path() -> String {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    format!("{home}/.mvm/vms/{DEV_VM_NAME}/vsock.sock")
}

/// Daemon mode: boot the VM, expose a vsock proxy socket, and block forever.
fn cmd_dev_apple_container_daemon(cpus: u32, memory_gib: u32) -> Result<()> {
    let kernel = std::env::var("MVM_DEV_KERNEL")
        .unwrap_or_else(|_| format!("{}/dev/vmlinux", mvm_core::config::mvm_cache_dir()));
    let rootfs = std::env::var("MVM_DEV_ROOTFS")
        .unwrap_or_else(|_| format!("{}/dev/rootfs.ext4", mvm_core::config::mvm_cache_dir()));

    let memory_mib = (memory_gib as u64) * 1024;
    mvm_apple_container::start(DEV_VM_NAME, &kernel, &rootfs, cpus, memory_mib)
        .map_err(|e| anyhow::anyhow!("Failed to start dev VM: {e}"))?;

    // Start a vsock proxy: listen on a Unix socket and proxy each
    // connection to the guest agent's vsock port. This lets `dev shell`
    // from another process connect to the VM.
    let proxy_path = dev_vsock_proxy_path();
    let _ = std::fs::remove_file(&proxy_path);
    start_vsock_proxy(&proxy_path);

    // Block forever — the VM lives in this process.
    loop {
        std::thread::park();
    }
}

const DEV_LAUNCHD_LABEL: &str = "com.mvm.dev";

fn dev_launchd_plist_path() -> std::path::PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    std::path::PathBuf::from(format!(
        "{home}/Library/LaunchAgents/{DEV_LAUNCHD_LABEL}.plist"
    ))
}

fn install_dev_launchd_agent(
    exe: &std::path::Path,
    kernel: &str,
    rootfs: &str,
    cpus: u32,
    memory_gib: u32,
    log_dir: &str,
) -> Result<()> {
    // Unload any previous agent first
    unload_dev_launchd_agent();

    let plist = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{DEV_LAUNCHD_LABEL}</string>
    <key>ProgramArguments</key>
    <array>
        <string>{exe}</string>
        <string>dev</string>
        <string>up</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>MVM_DEV_DAEMON</key>
        <string>1</string>
        <key>MVM_DEV_KERNEL</key>
        <string>{kernel}</string>
        <key>MVM_DEV_ROOTFS</key>
        <string>{rootfs}</string>
        <key>MVM_DEV_CPUS</key>
        <string>{cpus}</string>
        <key>MVM_DEV_MEM_GIB</key>
        <string>{memory_gib}</string>
        <key>MVM_SIGNED</key>
        <string>0</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
    <key>StandardOutPath</key>
    <string>{log_dir}/daemon-stdout.log</string>
    <key>StandardErrorPath</key>
    <string>{log_dir}/daemon-stderr.log</string>
</dict>
</plist>"#,
        exe = exe.display(),
    );

    let plist_path = dev_launchd_plist_path();
    let agents_dir = plist_path.parent().expect("plist path must have parent");
    std::fs::create_dir_all(agents_dir)?;
    std::fs::write(&plist_path, &plist)?;

    let output = std::process::Command::new("launchctl")
        .args(["load", plist_path.to_str().unwrap_or("")])
        .output()
        .context("Failed to run launchctl")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("launchctl load failed: {stderr}");
    }

    Ok(())
}

fn unload_dev_launchd_agent() {
    let plist_path = dev_launchd_plist_path();
    if plist_path.exists() {
        let _ = std::process::Command::new("launchctl")
            .args(["unload", plist_path.to_str().unwrap_or("")])
            .output();
        let _ = std::fs::remove_file(&plist_path);
    }
}

/// Listen on a Unix socket and proxy each connection to the VM's vsock.
fn start_vsock_proxy(socket_path: &str) {
    use std::os::unix::net::UnixListener;

    let listener = match UnixListener::bind(socket_path) {
        Ok(l) => l,
        Err(e) => {
            tracing::warn!("Failed to start vsock proxy: {e}");
            return;
        }
    };

    std::thread::spawn(move || {
        for stream in listener.incoming().flatten() {
            // Each connection: read the target vsock port from the first 4 bytes,
            // then proxy bidirectionally to that vsock port.
            std::thread::spawn(move || {
                use std::io::Read;
                let mut client = stream;
                let mut port_buf = [0u8; 4];
                if client.read_exact(&mut port_buf).is_err() {
                    return;
                }
                let port = u32::from_le_bytes(port_buf);

                let vsock = match mvm_apple_container::vsock_connect(DEV_VM_NAME, port) {
                    Ok(s) => s,
                    Err(_) => return,
                };

                // Bidirectional proxy
                let mut vsock_read = match vsock.try_clone() {
                    Ok(s) => s,
                    Err(_) => return,
                };
                let mut client_write = match client.try_clone() {
                    Ok(s) => s,
                    Err(_) => return,
                };

                let h = std::thread::spawn(move || {
                    let _ = std::io::copy(&mut vsock_read, &mut client_write);
                });
                let mut vsock_write = vsock;
                let _ = std::io::copy(&mut client, &mut vsock_write);
                let _ = h.join();
            });
        }
    });
}

/// Kill the process that owns the dev VM and clean up its state.
fn stop_dev_vm_owner() {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let vm_dir = std::path::PathBuf::from(format!("{home}/.mvm/vms/{DEV_VM_NAME}"));
    let pid_file = vm_dir.join("pid");

    if let Ok(pid_str) = std::fs::read_to_string(&pid_file)
        && let Ok(pid) = pid_str.trim().parse::<i32>()
    {
        // Don't kill ourselves
        if pid as u32 != std::process::id() {
            unsafe {
                libc::kill(pid, libc::SIGTERM);
            }
            // Wait briefly for it to exit
            for _ in 0..20 {
                if unsafe { libc::kill(pid, 0) } != 0 {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
        }
    }

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

/// Clean up stale persisted state from a dead dev VM process.
fn cleanup_stale_dev_vm() {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let vm_dir = std::path::PathBuf::from(format!("{home}/.mvm/vms/{DEV_VM_NAME}"));
    let pid_file = vm_dir.join("pid");

    if !pid_file.exists() {
        return;
    }

    let pid_str = match std::fs::read_to_string(&pid_file) {
        Ok(s) => s.trim().to_string(),
        Err(_) => return,
    };
    let pid: i32 = match pid_str.parse() {
        Ok(p) => p,
        Err(_) => return,
    };

    // Check if the process is still alive (signal 0 = existence check)
    let alive = unsafe { libc::kill(pid, 0) } == 0;
    if alive {
        return; // process still running, not stale
    }

    ui::info("Cleaning up stale dev VM state from a previous session...");
    let _ = std::fs::remove_dir_all(&vm_dir);
}

/// Stop the Apple Container dev VM.
fn cmd_dev_apple_container_down() -> Result<()> {
    let was_running = is_apple_container_dev_running() || dev_launchd_plist_path().exists();

    // Unload the launchd agent (stops the daemon process)
    unload_dev_launchd_agent();
    // Kill any lingering daemon process
    stop_dev_vm_owner();
    // Clean up state files
    cleanup_stale_dev_vm();
    let _ = std::fs::remove_file(dev_vsock_proxy_path());

    if was_running {
        ui::success("Dev VM stopped.");
    } else {
        ui::info("Dev VM is not running.");
    }
    Ok(())
}

/// Show Apple Container dev VM status.
fn cmd_dev_apple_container_status() -> Result<()> {
    let running = is_apple_container_dev_running();
    ui::info("Backend:  Apple Container (Virtualization.framework)");
    ui::info(&format!("Dev VM:   {DEV_VM_NAME}"));
    ui::info(&format!(
        "Status:   {}",
        if running { "running" } else { "stopped" }
    ));

    if running
        && let Ok(mut stream) =
            mvm_apple_container::vsock_connect(DEV_VM_NAME, mvm_guest::vsock::GUEST_AGENT_PORT)
        && let Ok(mvm_guest::vsock::GuestResponse::ExecResult { stdout, .. }) =
            mvm_guest::vsock::send_request(
                &mut stream,
                &mvm_guest::vsock::GuestRequest::Exec {
                    command: "uname -r".to_string(),
                    stdin: None,
                    timeout_secs: Some(5),
                },
            )
    {
        ui::info(&format!("  Kernel:  {}", stdout.trim()));
    }

    // Show dev image info
    let cache_dir = format!("{}/dev", mvm_core::config::mvm_cache_dir());
    let kernel_path = format!("{cache_dir}/vmlinux");
    let rootfs_path = format!("{cache_dir}/rootfs.ext4");
    ui::info(&format!(
        "  Image:   {}",
        if std::path::Path::new(&rootfs_path).exists() {
            "cached"
        } else {
            "not built"
        }
    ));
    if std::path::Path::new(&kernel_path).exists() {
        ui::info(&format!("  Kernel:  {kernel_path}"));
    }
    if std::path::Path::new(&rootfs_path).exists() {
        ui::info(&format!("  Rootfs:  {rootfs_path}"));
    }

    Ok(())
}

/// Ensure the Nix linux-builder VM is running, SSH is configured, and
/// nix-daemon knows about it.
///
/// `nix run 'nixpkgs#darwin.linux-builder'` starts a QEMU VM on port 31022
/// and writes `/etc/nix/builder_ed25519`, but does NOT create the SSH config
/// that maps `linux-builder` → `localhost:31022`. It also does not add the
/// `builders` line to nix.conf. This function handles all three pieces:
/// 1. Start the builder VM in the background if not already running
/// 2. Write the SSH host alias so nix-daemon can connect
/// 3. Add the `builders` line to nix.custom.conf
///
/// Returns `true` if the builder appears reachable after any fixup.
fn ensure_linux_builder_ssh_config() -> bool {
    #[cfg(not(target_os = "macos"))]
    {
        false
    }

    #[cfg(target_os = "macos")]
    {
        use std::io::Write;
        use std::net::TcpStream;
        use std::time::Duration;

        let key_path = "/etc/nix/builder_ed25519";
        let builder_port: u16 = 31022;

        let builder_listening = || {
            TcpStream::connect_timeout(
                &format!("127.0.0.1:{builder_port}")
                    .parse()
                    .expect("valid socket address literal"),
                Duration::from_secs(2),
            )
            .is_ok()
        };

        // If builder is not listening, try to start it automatically
        if !builder_listening() {
            let nix_bin = find_nix_binary();
            ui::info("  Starting Nix linux-builder VM in the background...");

            // Launch as a background process. The builder writes
            // /etc/nix/builder_ed25519 on first run (needs sudo).
            // Redirect output to a log file so it doesn't clutter the terminal.
            let log_path = format!("{}/linux-builder.log", mvm_core::config::mvm_cache_dir());
            let log_file = std::fs::File::create(&log_path)
                .or_else(|_| std::fs::File::create("/dev/null"))
                .expect("failed to open /dev/null");
            let stderr_file = log_file
                .try_clone()
                .or_else(|_| std::fs::File::create("/dev/null"))
                .expect("failed to open /dev/null");

            let child = std::process::Command::new(&nix_bin)
                .args(["run", "nixpkgs#darwin.linux-builder"])
                .stdout(log_file)
                .stderr(stderr_file)
                .stdin(std::process::Stdio::null())
                .spawn();

            if child.is_err() {
                return false;
            }

            // Wait for the builder to become ready (port 31022 + key file).
            // First boot can take a while as it downloads the builder VM.
            ui::info(
                "  Waiting for linux-builder to become ready (this may take a minute on first run)...",
            );
            let deadline = std::time::Instant::now() + Duration::from_secs(120);
            loop {
                if std::time::Instant::now() > deadline {
                    ui::warn("  Timed out waiting for linux-builder to start.");
                    return false;
                }
                if std::path::Path::new(key_path).exists() && builder_listening() {
                    break;
                }
                std::thread::sleep(Duration::from_secs(2));
            }
        }

        // Key must exist (created by the linux-builder on first run)
        if !std::path::Path::new(key_path).exists() {
            return false;
        }

        // --- SSH config ---
        // Check that the SSH config exists AND uses the correct user ("builder",
        // not "root"). Older versions wrote "User root" which doesn't work.
        let ssh_config_dir = std::path::Path::new("/etc/ssh/ssh_config.d");
        let config_path = ssh_config_dir.join("200-linux-builder.conf");

        let expected_config = format!(
            "Host linux-builder\n\
             \x20 HostName localhost\n\
             \x20 Port {builder_port}\n\
             \x20 User builder\n\
             \x20 IdentityFile {key_path}\n\
             \x20 IdentitiesOnly yes\n\
             \x20 StrictHostKeyChecking no\n\
             \x20 UserKnownHostsFile /dev/null\n\
             \x20 LogLevel ERROR\n"
        );

        let ssh_needs_write = if config_path.exists() {
            // Re-write if the existing config has wrong user
            std::fs::read_to_string(&config_path)
                .map(|c| !c.contains("User builder"))
                .unwrap_or(true)
        } else {
            // Also check via ssh -G whether some other config provides
            // a correct mapping (e.g. user's own ~/.ssh/config)
            let ssh_check = std::process::Command::new("ssh")
                .args(["-G", "linux-builder"])
                .output();
            if let Ok(out) = ssh_check {
                let cfg = String::from_utf8_lossy(&out.stdout);
                let has_host = cfg.lines().any(|l| {
                    l.strip_prefix("hostname ")
                        .is_some_and(|h| h.trim() != "linux-builder")
                });
                let has_user = cfg.lines().any(|l| {
                    l.strip_prefix("user ")
                        .is_some_and(|u| u.trim() == "builder")
                });
                !has_host || !has_user
            } else {
                true
            }
        };

        let mut ssh_ok = !ssh_needs_write;
        if ssh_needs_write {
            let tmp_path = "/tmp/mvm-linux-builder-ssh.conf";
            if let Ok(mut f) = std::fs::File::create(tmp_path)
                && f.write_all(expected_config.as_bytes()).is_ok()
            {
                let status = std::process::Command::new("sudo")
                    .args(["cp", tmp_path, config_path.to_str().unwrap_or_default()])
                    .status();
                let _ = std::fs::remove_file(tmp_path);
                ssh_ok = matches!(status, Ok(s) if s.success());
            }
        }

        if !ssh_ok {
            return false;
        }

        // --- nix.conf builders line ---
        // nix-daemon needs a `builders` entry pointing at the linux-builder.
        // Determinate Nix uses nix.custom.conf (included from nix.conf).
        // Also fix stale configs that used the wrong SSH user.
        let builders_line = format!(
            "builders = ssh-ng://builder@linux-builder aarch64-linux {key_path} 4 1 kvm,big-parallel - -"
        );

        let nix_custom = std::path::Path::new("/etc/nix/nix.custom.conf");
        let nix_conf = std::path::Path::new("/etc/nix/nix.conf");

        let nix_needs_write = {
            let has_correct = [nix_custom, nix_conf].iter().any(|path| {
                std::fs::read_to_string(path)
                    .map(|c| {
                        c.lines().any(|l| {
                            l.trim_start().starts_with("builders")
                                && l.contains("builder@linux-builder")
                        })
                    })
                    .unwrap_or(false)
            });
            !has_correct
        };

        if nix_needs_write {
            ui::info("  Configuring nix-daemon to use the linux-builder...");

            // Read existing content, strip any old mvmctl builder block, append fresh one
            let existing = std::fs::read_to_string(nix_custom).unwrap_or_default();
            let cleaned: String = {
                let mut skip = false;
                let mut lines = Vec::new();
                for line in existing.lines() {
                    if line.contains("Added by mvmctl for darwin.linux-builder") {
                        skip = true;
                        continue;
                    }
                    if skip {
                        // Skip the builders and builders-use-substitutes lines
                        if line.trim_start().starts_with("builders") {
                            continue;
                        }
                        // Blank line after the block — skip it too, then stop skipping
                        if line.trim().is_empty() {
                            skip = false;
                            continue;
                        }
                        skip = false;
                    }
                    lines.push(line);
                }
                lines.join("\n")
            };

            let new_content = format!(
                "{cleaned}\n\
                 # Added by mvmctl for darwin.linux-builder\n\
                 {builders_line}\n\
                 builders-use-substitutes = true\n"
            );

            let tmp_path = "/tmp/mvm-nix-custom-append.conf";
            if let Ok(mut f) = std::fs::File::create(tmp_path)
                && f.write_all(new_content.as_bytes()).is_ok()
            {
                let status = std::process::Command::new("sudo")
                    .args(["cp", tmp_path, nix_custom.to_str().unwrap_or_default()])
                    .status();
                let _ = std::fs::remove_file(tmp_path);
                if !matches!(status, Ok(s) if s.success()) {
                    return false;
                }

                // Restart nix-daemon so it picks up the new config.
                let restarted = std::process::Command::new("sudo")
                    .args([
                        "launchctl",
                        "kickstart",
                        "-k",
                        "system/systems.determinate.nix-daemon",
                    ])
                    .status()
                    .is_ok_and(|s| s.success());
                if !restarted {
                    let _ = std::process::Command::new("sudo")
                        .args([
                            "launchctl",
                            "kickstart",
                            "-k",
                            "system/org.nixos.nix-daemon",
                        ])
                        .status();
                }
            }
        }

        true
    }
}

/// Ensure the dev image (kernel + rootfs) exists in the cache.
///
/// Returns (kernel_path, rootfs_path). Builds from the dev-image Nix flake
/// if not cached.
fn ensure_dev_image() -> Result<(String, String)> {
    let cache_dir = format!("{}/dev", mvm_core::config::mvm_cache_dir());
    std::fs::create_dir_all(&cache_dir)?;

    let kernel_path = format!("{cache_dir}/vmlinux");
    let rootfs_path = format!("{cache_dir}/rootfs.ext4");

    if std::path::Path::new(&kernel_path).exists() && std::path::Path::new(&rootfs_path).exists() {
        return Ok((kernel_path, rootfs_path));
    }

    // Try Nix build first (works if Linux builder is configured)
    let plat = mvm_core::platform::current();
    if plat.has_host_nix()
        && let Ok(flake_dir) = find_dev_image_flake()
    {
        ui::info("Building dev image via Nix (first time only)...");
        let nix_bin = find_nix_binary();

        // On macOS, ensure the linux-builder SSH config exists so nix-daemon
        // can reach the builder VM on localhost:31022.
        if cfg!(target_os = "macos") && ensure_linux_builder_ssh_config() {
            ui::info("  Linux builder detected and SSH configured.");
        }

        // Stream stderr to the terminal so the user sees build progress,
        // while capturing stdout (which contains the store path).
        let mut child = std::process::Command::new(&nix_bin)
            .args([
                "build",
                &format!(
                    "{flake_dir}#packages.{}.default",
                    mvm_build::dev_build::linux_system()
                ),
                "--no-link",
                "--print-out-paths",
            ])
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::inherit())
            .spawn()
            .context("Failed to run nix build")?;

        let stdout = {
            let mut buf = String::new();
            if let Some(mut out) = child.stdout.take() {
                use std::io::Read;
                let _ = out.read_to_string(&mut buf);
            }
            buf
        };
        let status = child.wait().context("nix build process failed")?;

        if status.success() {
            let store_path = stdout.trim().to_string();
            let ks = format!("{store_path}/vmlinux");
            let rs = format!("{store_path}/rootfs.ext4");
            if std::path::Path::new(&ks).exists() && std::path::Path::new(&rs).exists() {
                std::fs::copy(&ks, &kernel_path)?;
                std::fs::copy(&rs, &rootfs_path)?;
                ui::success("Dev image built and cached.");
                return Ok((kernel_path, rootfs_path));
            }
        }

        // nix build failed. Re-run with captured stderr to detect the error type
        // (the first run streamed stderr to the terminal for user visibility).
        let diag = std::process::Command::new(&nix_bin)
            .args([
                "build",
                &format!(
                    "{flake_dir}#packages.{}.default",
                    mvm_build::dev_build::linux_system()
                ),
                "--no-link",
                "--dry-run",
            ])
            .output()
            .ok();
        let stderr = diag
            .as_ref()
            .map(|o| String::from_utf8_lossy(&o.stderr).into_owned())
            .unwrap_or_default();
        if stderr.contains("required system or feature not available") {
            ui::warn(
                "Nix cannot cross-compile Linux images on this Mac.\n\
                 No Linux builder detected. To fix this, either:\n\n\
                 \x20 1. Run in another terminal (keeps running):\n\
                 \x20    nix run 'nixpkgs#darwin.linux-builder'\n\n\
                 \x20 2. Or add to /etc/nix/nix.conf (permanent):\n\
                 \x20    builders = ssh-ng://builder@linux-builder aarch64-linux /etc/nix/builder_ed25519 4 1 kvm,big-parallel - -\n\
                 \x20    builders-use-substitutes = true\n\n\
                 Falling back to downloading a pre-built dev image...",
            );
        } else {
            ui::warn(&format!("Nix build failed, trying download:\n{stderr}"));
        }
    }

    // Fallback: download pre-built dev image from GitHub release
    download_dev_image(&kernel_path, &rootfs_path)
}

/// Download a pre-built dev image (kernel + rootfs) from GitHub releases.
fn download_dev_image(kernel_path: &str, rootfs_path: &str) -> Result<(String, String)> {
    let version = env!("CARGO_PKG_VERSION");
    let base_url = format!("https://github.com/auser/mvm/releases/download/v{version}");
    // Detect host arch to download the right image.
    // Apple Silicon (aarch64-darwin) needs aarch64-linux image.
    // Intel Mac (x86_64-darwin) needs x86_64-linux image.
    let arch = if cfg!(target_arch = "aarch64") {
        "aarch64"
    } else {
        "x86_64"
    };
    let kernel_url = format!("{base_url}/dev-vmlinux-{arch}");
    let rootfs_url = format!("{base_url}/dev-rootfs-{arch}.ext4");

    ui::info(&format!("Downloading dev image (v{version})..."));

    // Download kernel
    ui::info("  Fetching kernel...");
    download_file(&kernel_url, kernel_path)
        .with_context(|| format!("Failed to download kernel from {kernel_url}"))?;

    // Download rootfs
    ui::info("  Fetching rootfs...");
    download_file(&rootfs_url, rootfs_path)
        .with_context(|| format!("Failed to download rootfs from {rootfs_url}"))?;

    ui::success("Dev image downloaded and cached.");
    Ok((kernel_path.to_string(), rootfs_path.to_string()))
}

/// Download a file from a URL using curl.
fn download_file(url: &str, dest: &str) -> Result<()> {
    let status = std::process::Command::new("curl")
        .args(["-fSL", "--progress-bar", "-o", dest, url])
        .stdin(std::process::Stdio::inherit())
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit())
        .status()
        .context("Failed to run curl")?;

    if !status.success() {
        // Clean up partial download
        let _ = std::fs::remove_file(dest);
        anyhow::bail!(
            "Download failed. The dev image may not be available for v{version}.\n\
             \n\
             To build locally instead, set up a Nix Linux builder:\n\
             \n\
             \x20 Option 1 — Temporary (run in another terminal):\n\
             \x20   nix run 'nixpkgs#darwin.linux-builder'\n\
             \n\
             \x20 Option 2 — Permanent (add to /etc/nix/nix.conf):\n\
             \x20   builders = ssh-ng://builder@linux-builder aarch64-linux /etc/nix/builder_ed25519 4 1 kvm,big-parallel - -\n\
             \x20   builders-use-substitutes = true\n\
             \n\
             Then re-run: mvmctl dev up",
            version = env!("CARGO_PKG_VERSION")
        );
    }
    Ok(())
}

/// Find the `nix` binary, checking PATH and common install locations.
fn find_nix_binary() -> String {
    if which::which("nix").is_ok() {
        return "nix".to_string();
    }
    for path in &[
        "/nix/var/nix/profiles/default/bin/nix",
        "/run/current-system/sw/bin/nix",
    ] {
        if std::path::Path::new(path).exists() {
            return path.to_string();
        }
    }
    "nix".to_string() // fall back to PATH, let the error happen naturally
}

/// Find the dev-image Nix flake directory.
fn find_dev_image_flake() -> Result<String> {
    // Check in the source tree
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let workspace_root = std::path::Path::new(manifest_dir)
        .parent()
        .and_then(|p| p.parent())
        .ok_or_else(|| anyhow::anyhow!("Cannot find workspace root"))?;

    let candidate = workspace_root.join("nix").join("dev-image");
    if candidate.join("flake.nix").exists() {
        return Ok(candidate.to_str().unwrap_or(".").to_string());
    }

    // Fall back to the guest-lib minimal profile
    let guest_lib = workspace_root.join("nix").join("guest-lib");
    if guest_lib.join("flake.nix").exists() {
        return Ok(guest_lib.to_str().unwrap_or(".").to_string());
    }

    anyhow::bail!(
        "Dev image flake not found. Expected at nix/dev-image/flake.nix\n\
         or nix/guest-lib/flake.nix"
    )
}

fn run_setup_steps(force: bool, lima_cpus: u32, lima_mem: u32) -> Result<()> {
    let total = 5;

    // Step 1: Lima VM
    if bootstrap::is_lima_required() {
        let lima_status = lima::get_status()?;
        if !force && matches!(lima_status, lima::LimaStatus::Running) {
            ui::step(1, total, "Lima VM already running — skipping.");
        } else {
            let opts = config::LimaRenderOptions {
                cpus: Some(lima_cpus),
                memory_gib: Some(lima_mem),
                ..Default::default()
            };
            let lima_yaml = config::render_lima_yaml_with(&opts)?;
            ui::info(&format!(
                "Lima VM resources: {} vCPUs, {} GiB memory",
                lima_cpus, lima_mem,
            ));
            ui::step(1, total, "Setting up Lima VM...");
            lima::ensure_running(lima_yaml.path())?;
        }
    } else {
        ui::step(1, total, "Native Linux detected — skipping Lima VM setup.");
    }

    // Step 2: Firecracker (+ jailer from same release tarball)
    if !force && firecracker::is_installed()? {
        ui::step(2, total, "Firecracker already installed — skipping.");
    } else {
        ui::step(2, total, "Installing Firecracker...");
        firecracker::install()?;
    }

    // Step 3: Assets (kernel + squashfs)
    if !force && firecracker::has_base_assets()? {
        ui::step(
            3,
            total,
            "Kernel and rootfs already present \u{2014} skipping.",
        );
    } else {
        ui::step(3, total, "Downloading kernel and rootfs...");
        firecracker::download_assets()?;
    }

    if firecracker::has_squashfs()? && !firecracker::validate_rootfs_squashfs()? {
        ui::warn("Downloaded rootfs is corrupted. Re-downloading...");
        shell::run_in_vm(&format!(
            "rm -f {dir}/ubuntu-*.squashfs.upstream",
            dir = config::MICROVM_DIR,
        ))?;
        firecracker::download_assets()?;
    }

    // Step 4: Rootfs
    ui::step(4, total, "Preparing root filesystem...");
    firecracker::prepare_rootfs()?;

    firecracker::write_state()?;

    // Step 5: Security hardening
    ui::step(5, total, "Setting up security baseline...");
    setup_security_baseline()?;

    Ok(())
}

/// Deploy baseline security artifacts (seccomp profile, audit directory).
///
/// Idempotent — each step checks before acting.
fn setup_security_baseline() -> Result<()> {
    use mvm_runtime::security::{jailer, seccomp};

    // Deploy strict seccomp filter profile
    seccomp::ensure_strict_profile()?;
    ui::info("  Seccomp strict profile deployed.");

    // Create audit log directory structure
    shell::run_in_vm("sudo mkdir -p /var/lib/mvm/tenants")?;
    ui::info("  Audit log directory created.");

    // Report jailer status (installed by firecracker::install() above)
    match jailer::jailer_available() {
        Ok(true) => ui::info("  Jailer binary available."),
        _ => ui::warn("  Jailer binary not found (may not be in this Firecracker release)."),
    }

    Ok(())
}

fn shell_escape(s: &str) -> String {
    if s.contains(' ') || s.contains('\'') || s.contains('"') {
        format!("'{}'", s.replace('\'', "'\\''"))
    } else {
        s.to_string()
    }
}

fn cmd_shell(project: Option<&str>) -> Result<()> {
    lima::require_running()?;

    // Print welcome banner with tool versions
    let fc_ver =
        shell::run_in_vm_stdout("firecracker --version 2>/dev/null | head -1").unwrap_or_default();
    let nix_ver = shell::run_in_vm_stdout("nix --version 2>/dev/null").unwrap_or_default();

    ui::info("mvmctl development shell");
    ui::info(&format!(
        "  Firecracker: {}",
        if fc_ver.trim().is_empty() {
            "not installed"
        } else {
            fc_ver.trim()
        }
    ));
    ui::info(&format!(
        "  Nix:         {}",
        if nix_ver.trim().is_empty() {
            "not installed"
        } else {
            nix_ver.trim()
        }
    ));
    let mvm_in_vm = shell::run_in_vm_stdout("test -f /usr/local/bin/mvmctl && echo yes || echo no")
        .unwrap_or_default();
    if mvm_in_vm.trim() == "yes" {
        let mvm_ver = shell::run_in_vm_stdout("/usr/local/bin/mvmctl --version 2>/dev/null")
            .unwrap_or_default();
        ui::info(&format!(
            "  mvmctl:      {}",
            if mvm_ver.trim().is_empty() {
                "installed"
            } else {
                mvm_ver.trim()
            }
        ));
    } else {
        ui::warn("  mvmctl not installed in VM. Run 'mvmctl sync' to build and install it.");
    }

    ui::info(&format!("  Lima VM:     {}\n", config::VM_NAME));

    // Ensure shell completions and dev aliases are in the VM's ~/.zshrc
    // (the host's ~/.zshrc is separate from the VM's)
    if let Err(e) = shell_init::ensure_shell_init_in_vm() {
        ui::warn(&format!("Shell init in VM failed: {e}"));
    }

    match project {
        Some(path) => {
            let cmd = format!("cd {} && exec bash -l", shell_escape(path));
            shell::replace_process("limactl", &["shell", config::VM_NAME, "bash", "-c", &cmd])
        }
        None => shell::replace_process("limactl", &["shell", config::VM_NAME, "bash", "-l"]),
    }
}

fn cmd_cleanup(keep: Option<usize>, all: bool, verbose: bool) -> Result<()> {
    let keep_count = if all { 0 } else { keep.unwrap_or(5) };

    if !all && keep_count == 0 {
        anyhow::bail!("--keep must be greater than 0 (or use --all)");
    }

    // Show disk usage before cleanup.
    let disk_before = vm_disk_usage_pct();
    if let Some(pct) = disk_before {
        ui::info(&format!("Lima VM disk usage: {}%", pct));
    }

    // Step 1: Clear temp files first — when the disk is 100% full the nix
    // daemon cannot start, so we need to free a little space before GC.
    ui::info("Clearing temporary files...");
    let _ = shell::run_in_vm("sudo rm -rf /tmp/* /var/tmp/* 2>/dev/null");

    // Step 2: Remove old dev-build symlinks and artifacts.
    let env = mvm_runtime::build_env::RuntimeBuildEnv;
    let report = mvm_build::dev_build::cleanup_old_dev_builds(&env, keep_count)?;

    if verbose {
        if report.removed_paths.is_empty() {
            ui::info("No cached build paths removed.");
        } else {
            ui::info("Removed cached build paths:");
            for path in &report.removed_paths {
                println!("  {}", path);
            }
        }
    }

    if all {
        ui::success(&format!(
            "Removed {} cached build(s).",
            report.removed_count
        ));
    } else {
        ui::success(&format!(
            "Removed {} cached build(s), kept newest {}.",
            report.removed_count, keep_count
        ));
    }

    // Step 3: Garbage-collect unreferenced Nix store paths inside the Lima VM.
    ui::info("Running nix-collect-garbage...");
    match shell::run_in_vm_stdout("nix-collect-garbage -d 2>&1 | tail -3") {
        Ok(output) => {
            let trimmed = output.trim();
            if !trimmed.is_empty() {
                println!("{trimmed}");
            }
        }
        Err(e) => {
            // If GC fails (disk too full for daemon), try clearing the Nix
            // user profile links and retrying once.
            ui::warn(&format!("nix-collect-garbage failed: {e}"));
            ui::info("Retrying after clearing Nix profile generations...");
            let _ = shell::run_in_vm("rm -rf ~/.local/state/nix/profiles/* 2>/dev/null");
            match shell::run_in_vm_stdout("nix-collect-garbage -d 2>&1 | tail -3") {
                Ok(output) => {
                    let trimmed = output.trim();
                    if !trimmed.is_empty() {
                        println!("{trimmed}");
                    }
                }
                Err(e2) => ui::warn(&format!("nix-collect-garbage retry failed: {e2}")),
            }
        }
    }

    // Show disk usage after cleanup.
    let disk_after = vm_disk_usage_pct();
    if let Some(pct) = disk_after {
        let freed_msg = match disk_before {
            Some(before) if before > pct => format!(" (freed {}%)", before - pct),
            _ => String::new(),
        };
        ui::success(&format!("Lima VM disk usage: {}%{}", pct, freed_msg));
    }

    Ok(())
}

/// Read the Lima VM root filesystem usage percentage.
fn vm_disk_usage_pct() -> Option<u8> {
    let output = shell::run_in_vm_stdout("df --output=pcent / 2>/dev/null | tail -1").ok()?;
    output.trim().trim_end_matches('%').trim().parse().ok()
}

fn cmd_logs(name: &str, follow: bool, lines: u32, hypervisor: bool) -> Result<()> {
    validate_vm_name(name).with_context(|| format!("Invalid VM name: {:?}", name))?;
    microvm::logs(name, follow, lines, hypervisor)
}

fn cmd_diff(name: &str, json: bool) -> Result<()> {
    validate_vm_name(name).with_context(|| format!("Invalid VM name: {:?}", name))?;

    let instance_dir = microvm::resolve_running_vm_dir(name)?;
    let changes = mvm_guest::vsock::query_fs_diff(&instance_dir)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&changes)?);
    } else if changes.is_empty() {
        ui::info("No filesystem changes detected.");
    } else {
        ui::info(&format!("{} change(s):", changes.len()));
        for change in &changes {
            let prefix = match change.kind {
                mvm_guest::vsock::FsChangeKind::Created => "+",
                mvm_guest::vsock::FsChangeKind::Modified => "~",
                mvm_guest::vsock::FsChangeKind::Deleted => "-",
            };
            if change.size > 0 {
                println!(
                    "  {} {} ({})",
                    prefix,
                    change.path,
                    human_bytes(change.size)
                );
            } else {
                println!("  {} {}", prefix, change.path);
            }
        }
    }

    Ok(())
}

fn human_bytes(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{bytes}B")
    } else if bytes < 1024 * 1024 {
        format!("{:.1}K", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1}M", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1}G", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// Wait for the guest agent to respond to a Ping over vsock.
/// Returns true if the agent is reachable within `timeout_secs`.
fn wait_for_guest_agent(vm_id: &str, timeout_secs: u64) -> bool {
    use std::io::{Read, Write};
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
    let ping = serde_json::to_vec(&mvm_guest::vsock::GuestRequest::Ping).unwrap_or_default();
    let len_bytes = (ping.len() as u32).to_be_bytes();

    while std::time::Instant::now() < deadline {
        if let Ok(mut s) =
            mvm_apple_container::vsock_connect(vm_id, mvm_guest::vsock::GUEST_AGENT_PORT)
            && s.write_all(&len_bytes).is_ok()
            && s.write_all(&ping).is_ok()
            && s.flush().is_ok()
        {
            let mut resp_len = [0u8; 4];
            if s.read_exact(&mut resp_len).is_ok() {
                return true;
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }
    false
}

/// Tell the guest agent to start a vsock→TCP forwarder for the given port.
fn request_port_forward(vm_id: &str, guest_port: u16) -> Result<u32> {
    let mut stream = mvm_apple_container::vsock_connect(vm_id, mvm_guest::vsock::GUEST_AGENT_PORT)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    mvm_guest::vsock::start_port_forward_on(&mut stream, guest_port)
}

/// Forward a port from a running microVM to localhost.
///
/// On macOS this tunnels through Lima's SSH connection; on native Linux
/// it spawns a local socat proxy.
///
/// Each `port_spec` is either `GUEST_PORT` (binds to same local port) or
/// `LOCAL_PORT:GUEST_PORT`.  Multiple ports are forwarded concurrently —
/// background children handle all but the last, and Ctrl-C kills the group.
fn cmd_forward(name: &str, port_specs: &[String]) -> Result<()> {
    validate_vm_name(name).with_context(|| format!("Invalid VM name: {:?}", name))?;
    // Verify the VM is actually running.
    let _abs_dir = resolve_running_vm(name)?;

    // Read the VM's guest IP from run-info.json.
    let info = microvm::read_vm_run_info(name)?;

    // Use CLI port specs if provided, otherwise fall back to persisted ports.
    let parsed: Vec<(u16, u16)> = if port_specs.is_empty() {
        if info.ports.is_empty() {
            anyhow::bail!(
                "VM '{}' has no port mappings configured.\n\
                 Specify ports: mvmctl forward {} <PORT>...\n\
                 Or declare ports in mvm.toml.",
                name,
                name,
            );
        }
        ui::info("Using port mappings from VM config.");
        info.ports.iter().map(|p| (p.host, p.guest)).collect()
    } else {
        port_specs
            .iter()
            .map(|s| parse_port_spec(s))
            .collect::<Result<_>>()?
    };
    let guest_ip = info
        .guest_ip
        .as_deref()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "VM '{}' has no guest_ip in run-info. Was it started with 'mvmctl run'?",
                name,
            )
        })?;

    for &(local_port, guest_port) in &parsed {
        ui::info(&format!(
            "Forwarding localhost:{} -> {}:{} (VM '{}')",
            local_port, guest_ip, guest_port, name,
        ));
    }
    ui::info("Press Ctrl-C to stop forwarding.");

    if bootstrap::is_lima_required() {
        // macOS: SSH port-forward through Lima's SSH connection.
        // SSH -L supports multiple -L flags in a single session.
        lima::require_running()?;
        let home = std::env::var("HOME").unwrap_or_else(|_| "~".to_string());
        let ssh_config = format!("{}/.lima/{}/ssh.config", home, config::VM_NAME);

        let mut cmd = std::process::Command::new("ssh");
        cmd.arg("-F").arg(&ssh_config).arg("-N"); // no remote command
        for &(local_port, guest_port) in &parsed {
            cmd.arg("-L")
                .arg(format!("{}:{}:{}", local_port, guest_ip, guest_port));
        }
        cmd.arg(format!("lima-{}", config::VM_NAME));

        let status = cmd
            .status()
            .context("Failed to start SSH port forward. Is Lima running?")?;

        if !status.success() {
            anyhow::bail!("SSH port forward exited with status {}", status);
        }
    } else {
        // Native Linux: socat proxy (microVM is directly reachable).
        // Spawn a child for each port; wait on all.
        let mut children: Vec<std::process::Child> = Vec::new();
        for &(local_port, guest_port) in &parsed {
            let child = std::process::Command::new("socat")
                .arg(format!("TCP-LISTEN:{},fork,reuseaddr", local_port))
                .arg(format!("TCP:{}:{}", guest_ip, guest_port))
                .spawn()
                .context("Failed to start socat. Install it with: sudo apt install socat")?;
            // Register PID so the signal handler can clean it up.
            if let Ok(mut pids) = CHILD_PIDS.lock() {
                pids.push(child.id());
            }
            children.push(child);
        }
        // Wait for all children to exit (Ctrl-C triggers the signal handler
        // which sends SIGTERM to each tracked child).
        for mut child in children {
            if let Err(e) = child.wait() {
                tracing::warn!("failed to wait on socat child: {e}");
            }
        }
        // Clear tracked PIDs after children exit.
        if let Ok(mut pids) = CHILD_PIDS.lock() {
            pids.clear();
        }
    }

    Ok(())
}

/// Parse a port spec like `3000` or `8080:3000` into `(local, guest)`.
fn parse_port_spec(spec: &str) -> Result<(u16, u16)> {
    if let Some((local, guest)) = spec.split_once(':') {
        let local: u16 = local
            .parse()
            .with_context(|| format!("invalid local port '{}'", local))?;
        let guest: u16 = guest
            .parse()
            .with_context(|| format!("invalid guest port '{}'", guest))?;
        Ok((local, guest))
    } else {
        let port: u16 = spec
            .parse()
            .with_context(|| format!("invalid port '{}'", spec))?;
        Ok((port, port))
    }
}

/// Parse multiple port specs into `PortMapping` values.
fn parse_port_specs(specs: &[String]) -> Result<Vec<mvm_runtime::config::PortMapping>> {
    specs
        .iter()
        .map(|s| {
            let (host, guest) = parse_port_spec(s)?;
            Ok(mvm_runtime::config::PortMapping { host, guest })
        })
        .collect()
}

/// Convert port mappings into a `DriveFile` for the config drive.
/// Writes `export MVM_PORT_MAP="3333:3000,3334:3002"`.
fn ports_to_drive_file(ports: &[mvm_runtime::config::PortMapping]) -> Option<microvm::DriveFile> {
    if ports.is_empty() {
        return None;
    }
    let map_str = ports
        .iter()
        .map(|p| format!("{}:{}", p.host, p.guest))
        .collect::<Vec<_>>()
        .join(",");
    Some(microvm::DriveFile {
        name: "mvm-ports.env".to_string(),
        content: format!("export MVM_PORT_MAP=\"{}\"\n", map_str),
        mode: 0o444,
    })
}

/// Convert env var specs ("KEY=VALUE") into a `DriveFile` for the config drive.
fn env_vars_to_drive_file(env_vars: &[String]) -> Option<microvm::DriveFile> {
    if env_vars.is_empty() {
        return None;
    }
    let content = env_vars
        .iter()
        .map(|kv| format!("export {}", kv))
        .collect::<Vec<_>>()
        .join("\n");
    Some(microvm::DriveFile {
        name: "mvm-env.env".to_string(),
        content: format!("{}\n", content),
        mode: 0o444,
    })
}

fn cmd_ls(_all: bool, json: bool) -> Result<()> {
    use mvm_core::vm_backend::VmInfo;

    let mut all_vms: Vec<VmInfo> = Vec::new();

    // Collect from Apple Container backend
    let ac_backend = AnyBackend::from_hypervisor("apple-container");
    if let Ok(vms) = ac_backend.list() {
        all_vms.extend(vms);
    }

    // Collect from Docker backend
    let docker_backend = AnyBackend::from_hypervisor("docker");
    if let Ok(vms) = docker_backend.list() {
        all_vms.extend(vms);
    }

    // Collect from Firecracker backend (if Lima is running)
    if bootstrap::is_lima_required() {
        if let Ok(lima::LimaStatus::Running) = lima::get_status() {
            let fc_backend = AnyBackend::from_hypervisor("firecracker");
            if let Ok(vms) = fc_backend.list() {
                all_vms.extend(vms);
            }
        }
    } else {
        // Native Linux — Firecracker runs directly
        let fc_backend = AnyBackend::from_hypervisor("firecracker");
        if let Ok(vms) = fc_backend.list() {
            all_vms.extend(vms);
        }
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&all_vms)?);
        return Ok(());
    }

    if all_vms.is_empty() {
        println!("No running VMs.");
        return Ok(());
    }

    // Docker-style table output
    println!(
        "{:<20} {:<18} {:<10} {:<8} {:<10} {:<20} IMAGE",
        "NAME", "BACKEND", "STATUS", "CPUS", "MEMORY", "PORTS"
    );
    for vm in &all_vms {
        let backend_name = if vm.flake_ref.as_deref().is_some() {
            // Determine backend from context
            if mvm_core::platform::current().has_apple_containers() {
                "apple-container"
            } else {
                "firecracker"
            }
        } else {
            "unknown"
        };
        let status = format!("{:?}", vm.status);
        let mem = if vm.memory_mib > 0 {
            format!("{}Mi", vm.memory_mib)
        } else {
            "-".to_string()
        };
        let image = vm
            .flake_ref
            .as_deref()
            .or(vm.profile.as_deref())
            .unwrap_or("-");
        let ports = if vm.ports.is_empty() {
            "-".to_string()
        } else {
            vm.ports
                .iter()
                .map(|p| format!("{}{}", p.host, p.guest))
                .collect::<Vec<_>>()
                .join(", ")
        };
        println!(
            "{:<20} {:<18} {:<10} {:<8} {:<10} {:<20} {}",
            vm.name,
            backend_name,
            status,
            if vm.cpus > 0 {
                vm.cpus.to_string()
            } else {
                "-".to_string()
            },
            mem,
            ports,
            image,
        );
    }

    Ok(())
}

fn cmd_update(check: bool, force: bool, skip_verify: bool) -> Result<()> {
    let result = update::update(check, force, skip_verify);
    if result.is_ok() && !check {
        mvm_core::audit::emit(mvm_core::audit::LocalAuditKind::UpdateInstall, None, None);
    }
    result
}

fn cmd_doctor(json: bool) -> Result<()> {
    crate::doctor::run(json)
}

// ============================================================================
// Error hints
// ============================================================================

/// Wrap a command result with actionable hints for common errors.
fn with_hints(result: Result<()>) -> Result<()> {
    if let Err(ref e) = result {
        let msg = format!("{:#}", e);
        if msg.contains("limactl: command not found") || msg.contains("limactl: not found") {
            ui::warn("Hint: Install Lima with 'brew install lima' or run 'mvmctl bootstrap'.");
        } else if msg.contains("firecracker: command not found")
            || msg.contains("firecracker: not found")
        {
            ui::warn("Hint: Run 'mvmctl setup' to install Firecracker.");
        } else if msg.contains("/dev/kvm") {
            ui::warn(
                "Hint: Enable KVM/virtualization in your BIOS or VM settings.\n      \
                 On macOS, KVM is available inside the Lima VM.",
            );
        } else if msg.contains("Permission denied") && msg.contains(".mvm") {
            ui::warn("Hint: Check directory permissions on ~/.mvm (set MVM_DATA_DIR to override).");
        } else if msg.contains("nix: command not found") || msg.contains("nix: not found") {
            ui::warn("Hint: Nix is installed inside the Lima VM. Run 'mvmctl shell' first.");
        } else if msg.contains("Lima VM is not running") || msg.contains("VM is not started") {
            ui::warn(
                "Hint: Start the dev environment with 'mvmctl dev' or run 'mvmctl setup' \
                 to initialise it first.",
            );
        } else if msg.contains("already exists") && msg.contains("template") {
            ui::warn("Hint: Use '--force' to overwrite the existing template.");
        } else if msg.contains("error: builder for") && msg.contains("failed with exit code") {
            ui::warn(
                "Hint: Nix build failed. Check the log above for the failing derivation.\n      \
                 Common fixes: ensure flake inputs are up to date ('nix flake update'), \
                 or check your flake.nix for syntax errors.",
            );
        } else if msg.contains("does not provide attribute")
            || msg.contains("flake has no")
            || msg.contains("does not provide a package")
        {
            ui::warn(
                "Hint: Flake attribute not found. Your flake.lock may be stale.\n      \
                 Try: nix flake update (inside the Lima VM or flake directory).",
            );
        } else if msg.contains("No space left on device") || msg.contains("ENOSPC") {
            ui::warn(
                "Hint: Disk full. Run 'mvmctl doctor' to check space, \
                 or run 'nix-collect-garbage -d' inside the Lima VM.",
            );
        } else if msg.contains("timed out") || msg.contains("connection refused") {
            ui::warn(
                "Hint: The Lima VM may be unresponsive. Try 'mvmctl status' or \
                 restart with 'mvmctl stop && mvmctl dev'.",
            );
        } else if msg.contains("hash mismatch") && msg.contains("got:") {
            ui::warn(
                "Hint: Fixed-output derivation hash changed. Run \
                 'mvmctl template build <name> --update-hash' to recompute.",
            );
        } else if msg.contains("does it exist?") && msg.contains("template") {
            ui::warn("Hint: List available templates with 'mvmctl template list'.");
        }
    }
    result
}

fn cmd_build(path: &str, output: Option<&str>) -> Result<()> {
    let elf_path = image::build(path, output)?;
    ui::success(&format!("\nImage ready: {}", elf_path));
    ui::info(&format!("Run with: mvmctl start {}", elf_path));
    Ok(())
}

fn cmd_build_flake(flake_ref: &str, profile: Option<&str>, watch: bool, json: bool) -> Result<()> {
    validate_flake_ref(flake_ref)
        .with_context(|| format!("Invalid flake reference: {:?}", flake_ref))?;

    let build_env = mvm_runtime::build_env::default_build_env();
    let env = build_env.as_ref();

    // Skip Lima when Nix is available on the host (macOS with linux-builder).
    let using_host_nix = mvm_core::platform::current().has_host_nix();
    if !using_host_nix && bootstrap::is_lima_required() {
        lima::require_running()?;
    }

    let resolved = resolve_flake_ref(flake_ref)?;
    let watch_enabled = watch && !resolved.contains(':');

    if watch && resolved.contains(':') && !json {
        ui::warn("Watch mode requires a local flake; running a single build instead.");
    }

    loop {
        let profile_display = profile.unwrap_or("default");

        if json {
            PhaseEvent::new("build", "nix-build", "started")
                .with_message(&format!("flake={} profile={}", resolved, profile_display))
                .emit();
        } else {
            ui::step(
                1,
                2,
                &format!("Building flake {} (profile={})", resolved, profile_display),
            );
        }

        let result = match mvm_build::dev_build::dev_build(env, &resolved, profile) {
            Ok(r) => r,
            Err(e) => {
                if json {
                    PhaseEvent::new("build", "nix-build", "failed")
                        .with_error(&format!("{:#}", e))
                        .emit();
                }
                return Err(e);
            }
        };
        if let Err(e) = mvm_build::dev_build::ensure_guest_agent_if_needed(env, &result) {
            ui::warn(&format!(
                "Could not verify guest agent ({}). If built with mkGuest, the agent is already included.",
                e
            ));
        }

        if json {
            #[derive(Serialize)]
            struct BuildResult {
                timestamp: String,
                command: &'static str,
                phase: &'static str,
                status: &'static str,
                revision: String,
                cached: bool,
                kernel: String,
                rootfs: String,
            }
            let event = BuildResult {
                timestamp: chrono::Utc::now().to_rfc3339(),
                command: "build",
                phase: "nix-build",
                status: "completed",
                revision: result.revision_hash.clone(),
                cached: result.cached,
                kernel: result.vmlinux_path.clone(),
                rootfs: result.rootfs_path.clone(),
            };
            if let Ok(j) = serde_json::to_string(&event) {
                println!("{}", j);
            }
        } else {
            ui::step(2, 2, "Build complete");

            if result.cached {
                ui::success(&format!("\nCache hit — revision {}", result.revision_hash));
            } else {
                ui::success(&format!(
                    "\nBuild complete — revision {}",
                    result.revision_hash
                ));
            }

            ui::info(&format!("  Kernel: {}", result.vmlinux_path));
            ui::info(&format!("  Rootfs: {}", result.rootfs_path));
            ui::info(&format!("\nRun with: mvmctl run --flake {}", flake_ref));
        }

        if !watch_enabled {
            return Ok(());
        }

        // Watch mode: wait for filesystem changes using native events
        if !json {
            ui::info("Watching for .nix and .lock changes (Ctrl+C to exit)...");
        }
        match crate::watch::wait_for_changes(&resolved) {
            Ok(trigger) => {
                if !json {
                    let display = crate::watch::display_trigger(&trigger, &resolved);
                    ui::info(&format!("\nChange detected: {display} — rebuilding..."));
                }
            }
            Err(e) => {
                if !json {
                    ui::warn(&format!("Watch error: {e} — falling back to single build"));
                }
                return Ok(());
            }
        }
    }
}

/// Resolve CLI network flags into a `NetworkPolicy`.
/// `--network-preset` and `--network-allow` are mutually exclusive.
fn resolve_network_policy(
    preset: Option<&str>,
    allow: &[String],
) -> Result<mvm_core::network_policy::NetworkPolicy> {
    use mvm_core::network_policy::{HostPort, NetworkPolicy, NetworkPreset};

    match (preset, allow.is_empty()) {
        (Some(_), false) => {
            anyhow::bail!("--network-preset and --network-allow are mutually exclusive")
        }
        (Some(name), true) => {
            let p: NetworkPreset = name.parse()?;
            Ok(NetworkPolicy::preset(p))
        }
        (None, false) => {
            let rules: Vec<HostPort> = allow
                .iter()
                .map(|s| s.parse())
                .collect::<Result<Vec<_>>>()?;
            Ok(NetworkPolicy::allow_list(rules))
        }
        (None, true) => Ok(NetworkPolicy::default()),
    }
}

/// Resolve a flake reference: relative/absolute paths are canonicalized,
/// remote refs (containing `:`) pass through unchanged.
fn resolve_flake_ref(flake_ref: &str) -> Result<String> {
    if flake_ref.contains(':') {
        // Remote ref like "github:user/repo" — pass through
        return Ok(flake_ref.to_string());
    }

    // Local path — canonicalize to absolute
    let path = std::path::Path::new(flake_ref);
    let canonical = path
        .canonicalize()
        .with_context(|| format!("Flake path '{}' does not exist", flake_ref))?;

    Ok(canonical.to_string_lossy().to_string())
}

struct RunParams<'a> {
    flake_ref: Option<&'a str>,
    template_name: Option<&'a str>,
    name: Option<&'a str>,
    profile: Option<&'a str>,
    cpus: Option<u32>,
    memory: Option<u32>,
    config_path: Option<&'a str>,
    volumes: &'a [String],
    hypervisor: &'a str,
    ports: &'a [String],
    env_vars: &'a [String],
    forward: bool,
    metrics_port: u16,
    watch_config: bool,
    watch: bool,
    detach: bool,
    network_policy: mvm_core::network_policy::NetworkPolicy,
    network_name: &'a str,
    seccomp_tier: mvm_security::seccomp::SeccompTier,
    secret_bindings: Vec<mvm_core::secret_binding::SecretBinding>,
}

fn cmd_run(params: RunParams<'_>) -> Result<()> {
    let RunParams {
        flake_ref,
        template_name,
        name,
        profile,
        cpus,
        memory,
        config_path,
        volumes,
        hypervisor,
        ports,
        env_vars,
        forward,
        metrics_port,
        watch_config,
        watch,
        detach,
        network_policy,
        network_name,
        seccomp_tier,
        secret_bindings,
    } = params;
    let _span =
        tracing::info_span!("cmd_run", name = ?name, cpus = ?cpus, memory_mib = ?memory).entered();
    if let Some(n) = name {
        validate_vm_name(n).with_context(|| format!("Invalid VM name: {:?}", n))?;
    }
    if let Some(f) = flake_ref {
        validate_flake_ref(f).with_context(|| format!("Invalid flake reference: {:?}", f))?;
    }
    if let Some(t) = template_name {
        validate_template_name(t).with_context(|| format!("Invalid template name: {:?}", t))?;
    }
    // Auto-select backend when no explicit hypervisor is specified.
    // Priority: KVM (Firecracker direct) → Apple Container → Lima + Firecracker
    let effective_hypervisor = if hypervisor == "firecracker" {
        let plat = mvm_core::platform::current();
        if plat.has_kvm() {
            "firecracker" // native KVM — best option
        } else if plat.has_apple_containers() {
            "apple-container" // macOS 26+ — no Lima
        } else if plat.has_docker() {
            "docker" // universal fallback
        } else {
            "firecracker" // Lima fallback
        }
    } else {
        hypervisor
    };

    // Apple Container doesn't need Lima — skip the upfront check entirely.
    // For Firecracker on macOS, Lima is required for both build and runtime.
    let needs_lima = effective_hypervisor != "apple-container"
        && effective_hypervisor != "docker"
        && bootstrap::is_lima_required();
    if needs_lima {
        lima::require_running()?;
    }
    let _metrics_server = if metrics_port > 0 {
        Some(crate::metrics_server::MetricsServer::start(metrics_port)?)
    } else {
        None
    };

    // Start config watcher so the user is notified if the config file changes
    // while the build or boot is in progress.
    let _config_watcher = if watch_config {
        let config_path = {
            let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
            std::path::PathBuf::from(home)
                .join(".mvm")
                .join("config.toml")
        };
        if config_path.exists() {
            match crate::config_watcher::ConfigWatcher::start(&config_path) {
                Ok(w) => {
                    tracing::info!("Watching ~/.mvm/config.toml for changes");
                    Some(w)
                }
                Err(e) => {
                    tracing::warn!("Could not start config watcher: {e}");
                    None
                }
            }
        } else {
            None
        }
    } else {
        None
    };

    // Generate a VM name if not provided.
    // After codesign re-exec (macOS), the env var preserves the originally
    // generated name so we don't produce a second random name.
    let vm_name = match name {
        Some(n) => n.to_string(),
        None => std::env::var("MVM_REEXEC_NAME").unwrap_or_else(|_| {
            let mut generator = names::Generator::default();
            generator.next().unwrap_or_else(|| "vm-0".to_string())
        }),
    };

    // Register the VM name in the persistent registry (best-effort).
    let registry_path = mvm_runtime::vm::name_registry::registry_path();
    if let Ok(mut registry) = mvm_runtime::vm::name_registry::VmNameRegistry::load(&registry_path) {
        // Deregister stale entry with the same name if it exists
        registry.deregister(&vm_name);
        let _ = registry.register(&vm_name, "", network_name, None, 0);
        let _ = registry.save(&registry_path);
    }

    // Direct boot mode: launchd agent passes kernel/rootfs via env vars.
    // Skip the build/template loading entirely.
    if std::env::var("MVM_DIRECT_BOOT").as_deref() == Ok("1") {
        let kernel = std::env::var("MVM_KERNEL_PATH")
            .map_err(|_| anyhow::anyhow!("MVM_KERNEL_PATH not set"))?;
        let rootfs = std::env::var("MVM_ROOTFS_PATH")
            .map_err(|_| anyhow::anyhow!("MVM_ROOTFS_PATH not set"))?;

        let start_config = mvm_core::vm_backend::VmStartConfig {
            name: vm_name.clone(),
            rootfs_path: rootfs,
            kernel_path: Some(kernel),
            cpus: cpus.unwrap_or(2),
            memory_mib: memory.unwrap_or(512),
            ..Default::default()
        };

        let backend = AnyBackend::from_hypervisor(effective_hypervisor);
        backend.start(&start_config)?;

        // Set up port forwarding from MVM_PORTS env var (via vsock)
        if let Ok(ports_str) = std::env::var("MVM_PORTS")
            && !ports_str.is_empty()
        {
            ui::info("Waiting for guest agent...");
            if wait_for_guest_agent(&vm_name, 30) {
                for spec in ports_str.split(',') {
                    if let Some((host, guest)) = spec.split_once(':')
                        && let (Ok(h), Ok(g)) = (host.parse::<u16>(), guest.parse::<u16>())
                    {
                        let _ = request_port_forward(&vm_name, g);
                        mvm_apple_container::start_port_proxy(&vm_name, h, g);
                        ui::info(&format!("Forwarding localhost:{h} → guest tcp/{g} (vsock)"));
                    }
                }
            } else {
                ui::warn("Guest agent not reachable — port forwarding unavailable.");
            }
        }

        ui::info(&format!("VM '{}' running. Press Ctrl+C to stop.", vm_name));

        // Block until signaled
        let pair = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
        let pair2 = pair.clone();
        let _ = ctrlc::set_handler(move || {
            let (lock, cvar) = &*pair2;
            *lock.lock().unwrap_or_else(|e| e.into_inner()) = true;
            cvar.notify_all();
        });
        let (lock, cvar) = &*pair;
        let mut stopped = lock.lock().unwrap_or_else(|e| e.into_inner());
        while !*stopped {
            stopped = cvar
                .wait_timeout(stopped, std::time::Duration::from_secs(1))
                .unwrap_or_else(|e| e.into_inner())
                .0;
        }
        let _ = backend.stop(&mvm_core::vm_backend::VmId(vm_name));
        return Ok(());
    }

    // Resolve artifact paths from either a pre-built template or a flake build.
    let (
        vmlinux_path,
        initrd_path,
        rootfs_path,
        revision_hash,
        source_flake,
        source_profile,
        tmpl_cpus,
        tmpl_mem,
        snapshot_info,
    ) = if let Some(tmpl) = template_name {
        ui::step(
            1,
            2,
            &format!("Loading template '{}' for VM '{}'", tmpl, vm_name),
        );
        let (spec, vmlinux, initrd, rootfs, rev) =
            mvm_runtime::vm::template::lifecycle::template_artifacts(tmpl)?;
        ui::info(&format!("Using revision {}", rev));

        // Check for pre-built snapshot
        let snap_info = mvm_runtime::vm::template::lifecycle::template_snapshot_info(tmpl)?;
        if snap_info.is_some() {
            ui::info("Snapshot available — will restore instantly");
        }

        (
            vmlinux,
            initrd,
            rootfs,
            rev,
            spec.flake_ref.clone(),
            Some(spec.profile.clone()),
            Some(spec.vcpus as u32),
            Some(spec.mem_mib),
            snap_info,
        )
    } else {
        let flake = flake_ref.expect("--flake or --template required");
        let resolved = resolve_flake_ref(flake)?;
        let profile_display = profile.unwrap_or("default");
        ui::step(
            1,
            2,
            &format!(
                "Building flake {} (profile={}, name={})",
                resolved, profile_display, vm_name
            ),
        );
        let run_build_env = mvm_runtime::build_env::default_build_env();
        let env = run_build_env.as_ref();
        let result = mvm_build::dev_build::dev_build(env, &resolved, profile)?;
        if let Err(e) = mvm_build::dev_build::ensure_guest_agent_if_needed(env, &result) {
            ui::warn(&format!(
                "Could not verify guest agent ({}). If built with mkGuest, the agent is already included.",
                e
            ));
        }
        if result.cached {
            ui::info(&format!("Cache hit — revision {}", result.revision_hash));
        } else {
            ui::info(&format!(
                "Build complete — revision {}",
                result.revision_hash
            ));
        }
        (
            result.vmlinux_path,
            result.initrd_path,
            result.rootfs_path,
            result.revision_hash,
            flake.to_string(),
            profile.map(|s| s.to_string()),
            None,
            None,
            None, // No snapshot for flake builds
        )
    };

    let backend_label = match effective_hypervisor {
        "apple-container" => "Apple Container",
        "qemu" => "QEMU (microvm.nix)",
        _ => "Firecracker VM",
    };
    ui::step(2, 2, &format!("Booting {} '{}'", backend_label, vm_name));

    let rt_config = match config_path {
        Some(p) => image::parse_runtime_config(p)?,
        None => image::RuntimeConfig::default(),
    };

    // Partition --volume specs into dir-inject (config/secrets) and persistent volumes
    let mut volume_cfg: Vec<image::RuntimeVolume> = Vec::new();
    let mut config_files: Vec<microvm::DriveFile> = Vec::new();
    let mut secret_files: Vec<microvm::DriveFile> = Vec::new();

    if !volumes.is_empty() {
        for v in volumes {
            match parse_volume_spec(v)? {
                VolumeSpec::DirInject {
                    host_dir,
                    guest_mount,
                } => match guest_mount.as_str() {
                    "/mnt/config" => {
                        config_files.extend(
                            read_dir_to_drive_files(&host_dir, 0o444)
                                .with_context(|| format!("reading volume '{}'", v))?,
                        );
                    }
                    "/mnt/secrets" => {
                        secret_files.extend(
                            read_dir_to_drive_files(&host_dir, 0o400)
                                .with_context(|| format!("reading volume '{}'", v))?,
                        );
                    }
                    other => anyhow::bail!(
                        "Unsupported guest mount '{}'. Supported: /mnt/config, /mnt/secrets",
                        other
                    ),
                },
                VolumeSpec::Persistent(vol) => volume_cfg.push(vol),
            }
        }
    } else {
        volume_cfg = rt_config.volumes.clone();
    };

    let user_cfg = mvm_core::user_config::load(None);
    let final_cpus = cpus
        .or(rt_config.cpus)
        .or(tmpl_cpus)
        .unwrap_or(user_cfg.default_cpus);
    let final_memory = memory
        .or(rt_config.memory)
        .or(tmpl_mem)
        .unwrap_or(user_cfg.default_memory_mib);

    // Parse port mappings and inject as config drive file
    let port_mappings = parse_port_specs(ports)?;
    if let Some(f) = ports_to_drive_file(&port_mappings) {
        config_files.push(f);
    }

    // Inject env vars as config drive file
    if let Some(f) = env_vars_to_drive_file(env_vars) {
        config_files.push(f);
    }

    // Inject seccomp manifest into config drive if not unrestricted
    if let Some(manifest) = seccomp_tier.to_manifest() {
        let json = serde_json::to_string_pretty(&manifest)
            .context("failed to serialize seccomp manifest")?;
        config_files.push(microvm::DriveFile {
            name: "seccomp.json".to_string(),
            content: json,
            mode: 0o644,
        });
    }

    // Resolve and inject secret bindings
    if !secret_bindings.is_empty() {
        let resolved = mvm_core::secret_binding::ResolvedSecrets::resolve(&secret_bindings)
            .context("failed to resolve secret bindings")?;

        // Write actual secret values to the secrets drive
        for (filename, content) in resolved.to_secret_files() {
            secret_files.push(microvm::DriveFile {
                name: filename,
                content,
                mode: 0o600,
            });
        }

        // Write secret manifest to config drive (no secret values, just metadata)
        config_files.push(microvm::DriveFile {
            name: "secrets-manifest.json".to_string(),
            content: resolved.manifest_json(),
            mode: 0o644,
        });

        // Write placeholder env vars so tools pass existence checks
        let placeholders: Vec<String> = resolved
            .placeholder_env_vars()
            .iter()
            .map(|(k, v)| format!("{}={}", k, v))
            .collect();
        if let Some(f) = env_vars_to_drive_file(&placeholders) {
            config_files.push(microvm::DriveFile {
                name: "secret-env.env".to_string(),
                content: f.content,
                mode: f.mode,
            });
        }

        // Log which secrets are bound (without revealing values)
        for b in &secret_bindings {
            ui::info(&format!(
                "Secret {} bound to {} (header: {})",
                b.env_var, b.target_host, b.header
            ));
        }
    }

    let vm_name_owned = vm_name.clone();
    let has_ports = !port_mappings.is_empty();

    // Stash the generated VM name so that if the Apple Container backend
    // re-execs after codesigning, the new process reuses the same name.
    // SAFETY: called early in single-threaded CLI startup before spawning
    // worker threads; no other threads are reading env vars concurrently.
    unsafe { std::env::set_var("MVM_REEXEC_NAME", &vm_name) };

    // If a template snapshot exists AND the backend supports snapshots,
    // restore from it instead of cold-booting.
    let backend = AnyBackend::from_hypervisor(effective_hypervisor);
    if let Some(ref snap_info) = snapshot_info
        && let Some(tmpl) = template_name
        && backend.capabilities().snapshots
    {
        let slot = microvm::allocate_slot(&vm_name)?;
        let run_config = microvm::FlakeRunConfig {
            name: vm_name,
            slot,
            vmlinux_path,
            initrd_path,
            rootfs_path,
            revision_hash,
            flake_ref: source_flake,
            profile: source_profile,
            cpus: final_cpus,
            memory: final_memory,
            volumes: volume_cfg,
            config_files,
            secret_files,
            ports: port_mappings,
            network_policy: network_policy.clone(),
        };
        let rev = mvm_runtime::vm::template::lifecycle::current_revision_id(tmpl)?;
        let snap_dir = mvm_core::template::template_snapshot_dir(tmpl, &rev);
        ui::step(
            2,
            2,
            &format!("Restoring VM '{}' from snapshot", vm_name_owned),
        );
        microvm::restore_from_template_snapshot(tmpl, &run_config, &snap_dir, snap_info)?;
    } else {
        let start_config = VmStartParams {
            name: vm_name,
            rootfs_path,
            vmlinux_path,
            initrd_path,
            revision_hash,
            flake_ref: source_flake,
            profile: source_profile,
            cpus: final_cpus,
            memory_mib: final_memory,
            volumes: &volume_cfg,
            config_files: &config_files,
            secret_files: &secret_files,
            port_mappings: &port_mappings,
        }
        .into_start_config();

        // Apple Container with -d: install a launchd agent instead of
        // starting the VM in this process. The agent runs as a proper
        // macOS service with its own RunLoop.
        if detach && effective_hypervisor == "apple-container" {
            // Sign the binary before installing the launchd agent so the
            // daemon process launches with the entitlement already in place.
            mvm_apple_container::ensure_signed();

            // Build is already done — install launchd agent with the
            // resolved kernel/rootfs paths (no rebuild in the daemon).
            // Serialize port mappings for the daemon
            let port_specs: Vec<String> = parse_port_specs(ports)
                .unwrap_or_default()
                .iter()
                .map(|p| format!("{}:{}", p.host, p.guest))
                .collect();

            mvm_apple_container::install_launchd_direct(
                &start_config.name,
                start_config.kernel_path.as_deref().unwrap_or(""),
                &start_config.rootfs_path,
                start_config.cpus,
                start_config.memory_mib as u64,
                &port_specs,
            )
            .map_err(|e| anyhow::anyhow!("{e}"))?;
            println!("{vm_name_owned}");
            return Ok(());
        }

        backend.start(&start_config)?;
    }

    mvm_core::audit::emit(
        mvm_core::audit::LocalAuditKind::VmStart,
        Some(&vm_name_owned),
        None,
    );

    // Apple Virtualization VMs live in-process — the process must stay alive.
    if effective_hypervisor == "apple-container" && !detach {
        // Set up port forwarding via vsock (no guest IP needed).
        // 1. Wait for guest agent to be ready on vsock port 52
        // 2. Tell the agent to start vsock→TCP forwarders for each port
        // 3. Start host-side TCP→vsock proxies
        if has_ports {
            let pm_list = parse_port_specs(ports).unwrap_or_default();

            ui::info("Waiting for guest agent...");
            let agent_ready = wait_for_guest_agent(&vm_name_owned, 30);
            if !agent_ready {
                ui::warn("Guest agent not reachable — port forwarding unavailable.");
            } else {
                // Tell guest agent to start vsock forwarders
                for pm in &pm_list {
                    match request_port_forward(&vm_name_owned, pm.guest) {
                        Ok(vsock_port) => {
                            ui::info(&format!(
                                "Guest forwarding vsock:{vsock_port} → tcp/{}",
                                pm.guest
                            ));
                        }
                        Err(e) => {
                            ui::warn(&format!(
                                "Failed to set up guest forwarder for port {}: {e}",
                                pm.guest
                            ));
                        }
                    }
                }

                // Start host-side proxies
                for pm in &pm_list {
                    mvm_apple_container::start_port_proxy(&vm_name_owned, pm.host, pm.guest);
                    ui::info(&format!(
                        "Forwarding localhost:{} → guest tcp/{} (vsock)",
                        pm.host, pm.guest
                    ));
                }

                // Persist port mappings so `ps` can display them
                let ports_str: Vec<String> = pm_list
                    .iter()
                    .map(|p| format!("{}:{}", p.host, p.guest))
                    .collect();
                let ports_file = format!(
                    "{}/.mvm/vms/{}/ports",
                    std::env::var("HOME").unwrap_or_default(),
                    vm_name_owned
                );
                let _ = std::fs::write(&ports_file, ports_str.join(","));
            }
        }

        ui::info(&format!(
            "VM '{}' running. Press Ctrl+C to stop.",
            vm_name_owned
        ));

        // Block until signaled (Ctrl+C or SIGTERM)
        let pair = std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
        let pair2 = pair.clone();
        let _ = ctrlc::set_handler(move || {
            let (lock, cvar) = &*pair2;
            *lock.lock().unwrap_or_else(|e| e.into_inner()) = true;
            cvar.notify_all();
        });

        let (lock, cvar) = &*pair;
        let mut stopped = lock.lock().unwrap_or_else(|e| e.into_inner());
        while !*stopped {
            stopped = cvar
                .wait_timeout(stopped, std::time::Duration::from_secs(1))
                .unwrap_or_else(|e| e.into_inner())
                .0;
        }

        ui::info(&format!("Stopping VM '{}'...", vm_name_owned));
        let _ = backend.stop(&mvm_core::vm_backend::VmId(vm_name_owned.clone()));
        return Ok(());
    }

    if forward {
        if has_ports {
            cmd_forward(&vm_name_owned, &[])?;
        } else {
            ui::warn("--forward was set but no ports were declared. Use -p to specify ports.");
        }
    }

    // Watch mode: on each .nix / flake.lock change, stop the VM, rebuild, reboot.
    if watch {
        let Some(flake) = flake_ref else {
            // Template mode — watch not supported.
            return Ok(());
        };
        if flake.contains(':') {
            ui::warn("--watch requires a local flake; running a single boot instead.");
            return Ok(());
        }
        let flake_dir = resolve_flake_ref(flake)?;
        loop {
            ui::info("Watching for .nix and .lock changes (Ctrl+C to exit)...");
            match crate::watch::wait_for_changes(&flake_dir) {
                Ok(trigger) => {
                    let display = crate::watch::display_trigger(&trigger, &flake_dir);
                    ui::info(&format!("\nChange detected: {display} — rebuilding..."));
                }
                Err(e) => {
                    tracing::warn!("Watch error: {e}");
                    break;
                }
            }

            // Stop the running VM.
            let backend = AnyBackend::default_backend();
            if let Err(e) = backend.stop(&VmId::from(vm_name_owned.as_str())) {
                tracing::warn!("Could not stop '{}': {e}", vm_name_owned);
            }

            // Rebuild the flake.
            let env = mvm_runtime::build_env::RuntimeBuildEnv;
            let result = match mvm_build::dev_build::dev_build(&env, &flake_dir, profile) {
                Ok(r) => r,
                Err(e) => {
                    ui::warn(&format!("Rebuild failed: {e}; waiting for next change..."));
                    continue;
                }
            };
            if let Err(e) = mvm_build::dev_build::ensure_guest_agent_if_needed(&env, &result) {
                tracing::warn!("Guest agent check failed: {e}");
            }
            ui::success(&format!(
                "Build complete — revision {}",
                result.revision_hash
            ));

            // Re-parse volumes, ports and env vars for the fresh boot.
            let rt_cfg_watch = match config_path {
                Some(p) => image::parse_runtime_config(p).unwrap_or_default(),
                None => image::RuntimeConfig::default(),
            };
            let mut w_volume_cfg: Vec<image::RuntimeVolume> = Vec::new();
            let mut w_config_files: Vec<microvm::DriveFile> = Vec::new();
            let mut w_secret_files: Vec<microvm::DriveFile> = Vec::new();
            if !volumes.is_empty() {
                for v in volumes {
                    match parse_volume_spec(v) {
                        Ok(VolumeSpec::DirInject {
                            host_dir,
                            guest_mount,
                        }) => match guest_mount.as_str() {
                            "/mnt/config" => {
                                if let Ok(files) = read_dir_to_drive_files(&host_dir, 0o444) {
                                    w_config_files.extend(files);
                                }
                            }
                            "/mnt/secrets" => {
                                if let Ok(files) = read_dir_to_drive_files(&host_dir, 0o400) {
                                    w_secret_files.extend(files);
                                }
                            }
                            _ => {}
                        },
                        Ok(VolumeSpec::Persistent(vol)) => w_volume_cfg.push(vol),
                        Err(_) => {}
                    }
                }
            } else {
                w_volume_cfg = rt_cfg_watch.volumes.clone();
            }
            let w_port_mappings = parse_port_specs(ports).unwrap_or_default();
            if let Some(f) = ports_to_drive_file(&w_port_mappings) {
                w_config_files.push(f);
            }
            if let Some(f) = env_vars_to_drive_file(env_vars) {
                w_config_files.push(f);
            }
            let w_start_config = VmStartParams {
                name: vm_name_owned.clone(),
                rootfs_path: result.rootfs_path,
                vmlinux_path: result.vmlinux_path,
                initrd_path: result.initrd_path,
                revision_hash: result.revision_hash,
                flake_ref: flake.to_string(),
                profile: profile.map(|s| s.to_string()),
                cpus: final_cpus,
                memory_mib: final_memory,
                volumes: &w_volume_cfg,
                config_files: &w_config_files,
                secret_files: &w_secret_files,
                port_mappings: &w_port_mappings,
            }
            .into_start_config();
            let w_backend = AnyBackend::from_hypervisor(effective_hypervisor);
            if let Err(e) = w_backend.start(&w_start_config) {
                ui::warn(&format!(
                    "Could not start VM: {e}; waiting for next change..."
                ));
            } else {
                mvm_core::audit::emit(
                    mvm_core::audit::LocalAuditKind::VmStart,
                    Some(&vm_name_owned),
                    None,
                );
                ui::success(&format!("VM '{}' rebooted.", vm_name_owned));
            }
        }
    }

    Ok(())
}

/// Read all regular files from a directory into `DriveFile` entries.
fn read_dir_to_drive_files(dir: &str, default_mode: u32) -> Result<Vec<microvm::DriveFile>> {
    let mut files = Vec::new();
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        if entry.file_type()?.is_file() {
            files.push(microvm::DriveFile {
                name: entry.file_name().to_string_lossy().to_string(),
                content: std::fs::read_to_string(entry.path())?,
                mode: default_mode,
            });
        }
    }
    Ok(files)
}

/// Parsed volume specification from the `--volume/-v` CLI flag.
enum VolumeSpec {
    /// Inject host directory contents onto a drive (2-part: `host_dir:/guest/path`).
    DirInject {
        host_dir: String,
        guest_mount: String,
    },
    /// Persistent ext4 volume with explicit size (3-part: `host:/guest/path:size`).
    Persistent(image::RuntimeVolume),
}

fn parse_volume_spec(spec: &str) -> Result<VolumeSpec> {
    let parts: Vec<&str> = spec.splitn(3, ':').collect();
    match parts.len() {
        2 => Ok(VolumeSpec::DirInject {
            host_dir: parts[0].to_string(),
            guest_mount: parts[1].to_string(),
        }),
        3 => Ok(VolumeSpec::Persistent(image::RuntimeVolume {
            host: parts[0].to_string(),
            guest: parts[1].to_string(),
            size: parts[2].to_string(),
        })),
        _ => anyhow::bail!(
            "Invalid volume '{}'. Expected host_dir:/guest/path or host:/guest/path:size",
            spec
        ),
    }
}

/// Load fleet config from an explicit path or auto-discover mvm.toml.
fn load_fleet_config(
    config_path: Option<&str>,
) -> Result<Option<(fleet::FleetConfig, std::path::PathBuf)>> {
    match config_path {
        Some(path) => {
            let content = std::fs::read_to_string(path)
                .with_context(|| format!("Failed to read {}", path))?;
            let config: fleet::FleetConfig =
                toml::from_str(&content).with_context(|| format!("Failed to parse {}", path))?;
            let dir = std::path::Path::new(path)
                .parent()
                .unwrap_or(std::path::Path::new("."))
                .to_path_buf();
            Ok(Some((config, dir)))
        }
        None => fleet::find_fleet_config(),
    }
}

fn cmd_down(name: Option<&str>, config_path: Option<&str>) -> Result<()> {
    // Use Apple Container backend on macOS 26+, otherwise default (Firecracker).
    let backend = if mvm_core::platform::current().has_apple_containers() {
        AnyBackend::from_hypervisor("apple-container")
    } else {
        AnyBackend::default_backend()
    };
    match name {
        Some(n) => {
            let result = backend.stop(&VmId::from(n));
            // Deregister from the name registry (best-effort)
            let registry_path = mvm_runtime::vm::name_registry::registry_path();
            if let Ok(mut registry) =
                mvm_runtime::vm::name_registry::VmNameRegistry::load(&registry_path)
            {
                registry.deregister(n);
                let _ = registry.save(&registry_path);
            }
            result
        }
        None => {
            let found = load_fleet_config(config_path)?;
            if let Some((fleet_config, _base_dir)) = found {
                let mut stopped = 0;
                for vm_name in fleet_config.vms.keys() {
                    if backend.stop(&VmId::from(vm_name.as_str())).is_ok() {
                        stopped += 1;
                    }
                }

                // Clean up bridge if no VMs remain
                let remaining = backend.list().unwrap_or_default();
                if remaining.is_empty() {
                    let _ = mvm_runtime::vm::network::bridge_teardown();
                }

                ui::success(&format!("Stopped {} VMs", stopped));
                Ok(())
            } else {
                backend.stop_all()
            }
        }
    }
}

fn cmd_metrics(json: bool) -> Result<()> {
    let metrics = mvm_core::observability::metrics::global();
    if json {
        let snap = metrics.snapshot();
        println!("{}", serde_json::to_string_pretty(&snap)?);
    } else {
        print!("{}", metrics.prometheus_exposition());
    }
    Ok(())
}

fn cmd_completions(shell: clap_complete::Shell) -> Result<()> {
    let mut cmd = Cli::command();
    clap_complete::generate(shell, &mut cmd, "mvmctl", &mut std::io::stdout());
    Ok(())
}

fn cmd_uninstall(yes: bool, all: bool, dry_run: bool) -> Result<()> {
    // Build the action plan. Dry-run avoids any external process calls so it
    // stays fast even when Lima/limactl is unresponsive.
    let mut actions: Vec<String> = vec![
        "Destroy Lima VM 'mvm' (if present)".to_string(),
        "Remove /var/lib/mvm/ (VM state, volumes, run-info)".to_string(),
    ];
    if all {
        actions.push("Remove ~/.mvm/ (config, signing keys)".to_string());
        actions.push("Remove /usr/local/bin/mvmctl (binary)".to_string());
    }

    if dry_run {
        ui::info("Dry run — the following would be removed:");
        for a in &actions {
            println!("{a}");
        }
        return Ok(());
    }

    // Confirmation prompt — also avoids any external calls.
    if !yes {
        ui::info("The following will be removed:");
        for a in &actions {
            println!("{a}");
        }
        if !ui::confirm("Proceed with uninstall?") {
            ui::info("Cancelled.");
            return Ok(());
        }
    }

    // Now query Lima — only when actually performing the uninstall.
    let lima_status = lima::get_status().unwrap_or(lima::LimaStatus::NotFound);

    // Stop running microVMs first (best-effort).
    if matches!(lima_status, lima::LimaStatus::Running)
        && let Err(e) = microvm::stop()
    {
        tracing::warn!("failed to stop microVMs before uninstall: {e}");
    }

    // Destroy Lima VM.
    if !matches!(lima_status, lima::LimaStatus::NotFound) {
        ui::info("Destroying Lima VM...");
        if let Err(e) = lima::destroy() {
            tracing::warn!("failed to destroy Lima VM: {e}");
        }
    }

    // Remove /var/lib/mvm/.
    let state_dir = std::path::Path::new("/var/lib/mvm");
    if state_dir.exists() {
        ui::info("Removing /var/lib/mvm/...");
        let status = std::process::Command::new("sudo")
            .args(["rm", "-rf", "/var/lib/mvm"])
            .status();
        match status {
            Ok(s) if s.success() => {}
            Ok(s) => tracing::warn!("sudo rm /var/lib/mvm exited with status {s}"),
            Err(e) => tracing::warn!("failed to remove /var/lib/mvm: {e}"),
        }
    }

    if all {
        // Remove ~/.mvm/.
        if let Ok(home) = std::env::var("HOME") {
            let config_dir = std::path::PathBuf::from(home).join(".mvm");
            if config_dir.exists() {
                ui::info("Removing ~/.mvm/...");
                if let Err(e) = std::fs::remove_dir_all(&config_dir) {
                    tracing::warn!("failed to remove ~/.mvm/: {e}");
                }
            }
        }

        // Remove /usr/local/bin/mvmctl.
        let bin = std::path::Path::new("/usr/local/bin/mvmctl");
        if bin.exists() {
            ui::info("Removing /usr/local/bin/mvmctl...");
            let status = std::process::Command::new("sudo")
                .args(["rm", "-f", "/usr/local/bin/mvmctl"])
                .status();
            match status {
                Ok(s) if s.success() => {}
                Ok(s) => tracing::warn!("sudo rm mvmctl exited with status {s}"),
                Err(e) => tracing::warn!("failed to remove /usr/local/bin/mvmctl: {e}"),
            }
        }
    }

    mvm_core::audit::emit(mvm_core::audit::LocalAuditKind::Uninstall, None, None);
    ui::success("Uninstall complete.");
    Ok(())
}

// ============================================================================
// Audit commands
// ============================================================================

fn cmd_audit(action: AuditCmd) -> Result<()> {
    match action {
        AuditCmd::Tail { lines, follow } => cmd_audit_tail(lines, follow),
    }
}

// ============================================================================
// Flake commands
// ============================================================================

fn cmd_flake(action: FlakeCmd) -> Result<()> {
    match action {
        FlakeCmd::Check { flake, json } => cmd_flake_check(&flake, json),
    }
}

fn cmd_flake_check(flake: &str, json: bool) -> Result<()> {
    let resolved = resolve_flake_ref(flake)?;

    if bootstrap::is_lima_required() {
        lima::require_running()?;
    }

    let script = format!("nix flake check {resolved}");

    if json {
        // Capture combined stdout+stderr so we can embed it in JSON.
        let output = shell::run_in_vm_capture(&script);
        match output {
            Ok(out) => {
                let combined = format!(
                    "{}{}",
                    String::from_utf8_lossy(&out.stdout),
                    String::from_utf8_lossy(&out.stderr)
                );
                if out.status.success() {
                    println!("{{\"valid\":true}}");
                } else {
                    let msg = combined.trim().replace('"', "'");
                    println!("{{\"valid\":false,\"error\":\"{msg}\"}}");
                    std::process::exit(1);
                }
                Ok(())
            }
            Err(e) => {
                let msg = e.to_string().replace('"', "'");
                println!("{{\"valid\":false,\"error\":\"{msg}\"}}");
                std::process::exit(1);
            }
        }
    } else {
        // Stream output directly so the user sees nix progress in real time.
        match shell::run_in_vm_visible(&script) {
            Ok(()) => {
                ui::success("Flake is valid.");
                Ok(())
            }
            Err(e) => Err(e.context("Flake check failed")),
        }
    }
}

fn cmd_audit_tail(lines: usize, follow: bool) -> Result<()> {
    let log_path = mvm_core::audit::default_audit_log();
    let path = std::path::Path::new(&log_path);

    if !path.exists() {
        ui::info(&format!(
            "No audit log found. Events are recorded at {log_path}."
        ));
        return Ok(());
    }

    print_last_n_lines(path, lines)?;

    if !follow {
        return Ok(());
    }

    // Tail -f: track file position and poll for new content.
    let mut pos = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);

    loop {
        std::thread::sleep(std::time::Duration::from_millis(500));
        if !path.exists() {
            continue;
        }
        let new_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
        if new_len > pos {
            let mut file = std::fs::File::open(path)?;
            use std::io::{BufRead, Seek, SeekFrom};
            file.seek(SeekFrom::Start(pos))?;
            let reader = std::io::BufReader::new(&file);
            for line in reader.lines() {
                let line = line?;
                print_audit_line(&line);
            }
            pos = new_len;
        }
    }
}

fn print_last_n_lines(path: &std::path::Path, n: usize) -> Result<()> {
    use std::io::BufRead;
    let file =
        std::fs::File::open(path).with_context(|| format!("Failed to open {}", path.display()))?;
    let reader = std::io::BufReader::new(file);
    let lines: Vec<String> = reader.lines().map_while(Result::ok).collect();
    let start = lines.len().saturating_sub(n);
    for line in &lines[start..] {
        print_audit_line(line);
    }
    Ok(())
}

fn print_audit_line(line: &str) {
    match serde_json::from_str::<mvm_core::audit::LocalAuditEvent>(line) {
        Ok(event) => {
            let kind = serde_json::to_string(&event.kind)
                .unwrap_or_default()
                .trim_matches('"')
                .to_string();
            let vm = event
                .vm_name
                .as_deref()
                .map(|n| format!("  [{n}]"))
                .unwrap_or_default();
            let detail = event
                .detail
                .as_deref()
                .map(|d| format!("  {d}"))
                .unwrap_or_default();
            println!("{ts}  {kind}{vm}{detail}", ts = event.timestamp);
        }
        Err(_) => {
            // Non-local-audit line — print as-is (fleet AuditEntry, etc.)
            println!("{line}");
        }
    }
}

// ============================================================================
// Template commands
// ============================================================================

fn cmd_template(action: TemplateCmd) -> Result<()> {
    match action {
        TemplateCmd::Create {
            name,
            flake,
            profile,
            role,
            cpus,
            mem,
            data_disk,
        } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            validate_flake_ref(&flake)
                .with_context(|| format!("Invalid flake reference: {:?}", flake))?;
            let mem_mb = parse_human_size(&mem).context("Invalid memory size")?;
            let data_disk_mb = parse_human_size(&data_disk).context("Invalid data disk size")?;
            template_cmd::create_single(&name, &flake, &profile, &role, cpus, mem_mb, data_disk_mb)
        }
        TemplateCmd::CreateMulti {
            base,
            flake,
            profile,
            roles,
            cpus,
            mem,
            data_disk,
        } => {
            validate_template_name(&base)
                .with_context(|| format!("Invalid template base name: {:?}", base))?;
            validate_flake_ref(&flake)
                .with_context(|| format!("Invalid flake reference: {:?}", flake))?;
            let mem_mb = parse_human_size(&mem).context("Invalid memory size")?;
            let data_disk_mb = parse_human_size(&data_disk).context("Invalid data disk size")?;
            let role_list: Vec<String> = roles.split(',').map(|s| s.trim().to_string()).collect();
            template_cmd::create_multi(
                &base,
                &flake,
                &profile,
                &role_list,
                cpus,
                mem_mb,
                data_disk_mb,
            )
        }
        TemplateCmd::Build {
            name,
            force,
            snapshot,
            config,
            update_hash,
        } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::build(&name, force, snapshot, config.as_deref(), update_hash)
        }
        TemplateCmd::Push { name, revision } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::push(&name, revision.as_deref())
        }
        TemplateCmd::Pull { name, revision } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::pull(&name, revision.as_deref())
        }
        TemplateCmd::Verify { name, revision } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::verify(&name, revision.as_deref())
        }
        TemplateCmd::List { json } => template_cmd::list(json),
        TemplateCmd::Info { name, json } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::info(&name, json)
        }
        TemplateCmd::Edit {
            name,
            flake,
            profile,
            role,
            cpus,
            mem,
            data_disk,
        } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            if let Some(ref f) = flake {
                validate_flake_ref(f)
                    .with_context(|| format!("Invalid flake reference: {:?}", f))?;
            }
            let mem_mb = mem
                .as_ref()
                .map(|s| parse_human_size(s))
                .transpose()
                .context("Invalid memory size")?;
            let data_disk_mb = data_disk
                .as_ref()
                .map(|s| parse_human_size(s))
                .transpose()
                .context("Invalid data disk size")?;
            template_cmd::edit(
                &name,
                flake.as_deref(),
                profile.as_deref(),
                role.as_deref(),
                cpus,
                mem_mb,
                data_disk_mb,
            )
        }
        TemplateCmd::Delete { name, force } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            template_cmd::delete(&name, force)
        }
        TemplateCmd::Init {
            name,
            local,
            vm,
            dir,
            preset,
            prompt,
        } => {
            validate_template_name(&name)
                .with_context(|| format!("Invalid template name: {:?}", name))?;
            let use_local = local && !vm;
            template_cmd::init(&name, use_local, &dir, preset.as_deref(), prompt.as_deref())
        }
    }
}

/// Resolve a VM name to its absolute directory path inside the Lima VM
/// and verify it is running.
fn resolve_running_vm(name: &str) -> Result<String> {
    if bootstrap::is_lima_required() {
        lima::require_running()?;
    }

    let abs_vms = shell::run_in_vm_stdout(&format!("echo {}", config::VMS_DIR))?;
    let abs_dir = format!("{}/{}", abs_vms, name);
    let pid_file = format!("{}/fc.pid", abs_dir);

    if !firecracker::is_vm_running(&pid_file)? {
        anyhow::bail!(
            "VM '{}' is not running. Use 'mvmctl status' to list running VMs.",
            name
        );
    }

    Ok(abs_dir)
}

// ============================================================================
// Config commands
// ============================================================================

fn cmd_config(action: ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Show => cmd_config_show(),
        ConfigAction::Edit => cmd_config_edit(),
        ConfigAction::Set { key, value } => cmd_config_set(&key, &value),
    }
}

fn cmd_config_show() -> Result<()> {
    let cfg = mvm_core::user_config::load(None);
    let text = toml::to_string_pretty(&cfg).context("Failed to serialize config")?;
    print!("{}", text);
    Ok(())
}

fn cmd_config_edit() -> Result<()> {
    // Ensure config file exists (load creates it with defaults if absent).
    let _ = mvm_core::user_config::load(None);
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
    let config_path = std::path::PathBuf::from(home)
        .join(".mvm")
        .join("config.toml");
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "nano".to_string());
    let status = std::process::Command::new(&editor)
        .arg(&config_path)
        .status()
        .with_context(|| format!("Failed to launch editor {:?}", editor))?;
    if !status.success() {
        anyhow::bail!("Editor exited with status {}", status);
    }
    Ok(())
}

fn cmd_config_set(key: &str, value: &str) -> Result<()> {
    let mut cfg = mvm_core::user_config::load(None);
    mvm_core::user_config::set_key(&mut cfg, key, value)?;
    mvm_core::user_config::save(&cfg, None)?;
    println!("Set {} = {}", key, value);
    Ok(())
}

// ============================================================================
// Network management
// ============================================================================

fn cmd_network(action: NetworkCmd) -> Result<()> {
    use mvm_core::dev_network::{DevNetwork, network_path, networks_dir, validate_network_name};

    match action {
        NetworkCmd::Create { name, subnet: _ } => {
            validate_network_name(&name)?;
            let dir = networks_dir();
            std::fs::create_dir_all(&dir)?;

            let path = network_path(&name);
            if std::path::Path::new(&path).exists() {
                anyhow::bail!("Network {:?} already exists", name);
            }

            // Find the next available slot by scanning existing networks
            let mut max_slot: u8 = 0;
            if let Ok(entries) = std::fs::read_dir(&dir) {
                for entry in entries.flatten() {
                    if let Ok(text) = std::fs::read_to_string(entry.path())
                        && let Ok(net) = serde_json::from_str::<DevNetwork>(&text)
                    {
                        let parts: Vec<&str> = net.subnet.split('.').collect();
                        if parts.len() >= 3
                            && let Ok(s) = parts[2].parse::<u8>()
                        {
                            max_slot = max_slot.max(s);
                        }
                    }
                }
            }

            let net = if name == "default" {
                DevNetwork::default_network()
            } else {
                DevNetwork::new(&name, max_slot + 1)?
            };

            let json = serde_json::to_string_pretty(&net)?;
            std::fs::write(&path, json)?;

            mvm_core::audit::emit(
                mvm_core::audit::LocalAuditKind::NetworkCreate,
                None,
                Some(&name),
            );

            ui::success(&format!(
                "Created network {:?} (bridge={}, subnet={})",
                net.name, net.bridge_name, net.subnet
            ));
            Ok(())
        }
        NetworkCmd::List => {
            let dir = networks_dir();
            if !std::path::Path::new(&dir).exists() {
                ui::info("No networks configured.");
                return Ok(());
            }

            let mut networks: Vec<DevNetwork> = Vec::new();
            for entry in std::fs::read_dir(&dir)?.flatten() {
                if entry.path().extension().is_some_and(|e| e == "json")
                    && let Ok(text) = std::fs::read_to_string(entry.path())
                    && let Ok(net) = serde_json::from_str::<DevNetwork>(&text)
                {
                    networks.push(net);
                }
            }

            if networks.is_empty() {
                ui::info("No networks configured.");
            } else {
                println!("{:<15} {:<15} {:<20}", "NAME", "BRIDGE", "SUBNET");
                for net in &networks {
                    println!(
                        "{:<15} {:<15} {:<20}",
                        net.name, net.bridge_name, net.subnet
                    );
                }
            }
            Ok(())
        }
        NetworkCmd::Inspect { name } => {
            let path = network_path(&name);
            if !std::path::Path::new(&path).exists() {
                anyhow::bail!("Network {:?} not found", name);
            }
            let text = std::fs::read_to_string(&path)?;
            let net: DevNetwork = serde_json::from_str(&text)?;
            println!("{}", serde_json::to_string_pretty(&net)?);
            Ok(())
        }
        NetworkCmd::Remove { name } => {
            if name == "default" {
                anyhow::bail!("Cannot remove the default network");
            }
            let path = network_path(&name);
            if !std::path::Path::new(&path).exists() {
                anyhow::bail!("Network {:?} not found", name);
            }
            std::fs::remove_file(&path)?;

            mvm_core::audit::emit(
                mvm_core::audit::LocalAuditKind::NetworkRemove,
                None,
                Some(&name),
            );

            ui::success(&format!("Removed network {:?}", name));
            Ok(())
        }
    }
}

// ============================================================================
// Image catalog
// ============================================================================

fn cmd_image(action: ImageCmd) -> Result<()> {
    let catalog = load_bundled_catalog();

    match action {
        ImageCmd::List => {
            if catalog.entries.is_empty() {
                ui::info("No images in catalog.");
            } else {
                println!(
                    "{:<20} {:<40} {:<6} {:<8}",
                    "NAME", "DESCRIPTION", "CPUS", "MEM"
                );
                for entry in &catalog.entries {
                    println!(
                        "{:<20} {:<40} {:<6} {:<8}",
                        entry.name,
                        entry.description,
                        entry.default_cpus,
                        format!("{}M", entry.default_memory_mib),
                    );
                }
            }
            Ok(())
        }
        ImageCmd::Search { query } => {
            let results = catalog.search(&query);
            if results.is_empty() {
                ui::info(&format!("No images matching {:?}", query));
            } else {
                println!("{:<20} {:<40} {:<30}", "NAME", "DESCRIPTION", "TAGS");
                for entry in results {
                    println!(
                        "{:<20} {:<40} {:<30}",
                        entry.name,
                        entry.description,
                        entry.tags.join(", "),
                    );
                }
            }
            Ok(())
        }
        ImageCmd::Fetch { name } => {
            let entry = catalog
                .find(&name)
                .ok_or_else(|| anyhow::anyhow!("Image {:?} not found in catalog", name))?;

            ui::info(&format!(
                "Fetching image {:?} from {}...",
                entry.name, entry.flake_ref
            ));
            ui::info("This will create a template and build it via Nix.");
            ui::info(&format!(
                "Equivalent to: mvmctl template create {} --flake {} --profile {} && mvmctl template build {}",
                entry.name, entry.flake_ref, entry.profile, entry.name
            ));

            mvm_core::audit::emit(
                mvm_core::audit::LocalAuditKind::ImageFetch,
                None,
                Some(&name),
            );

            // Create a template from the catalog entry, then build it
            template_cmd::create_single(
                &entry.name,
                &entry.flake_ref,
                &entry.profile,
                "worker",
                entry.default_cpus,
                entry.default_memory_mib,
                0, // no data disk
            )?;
            ui::success(&format!("Created template {:?} from catalog.", entry.name));

            ui::info(&format!("Building template {:?}...", entry.name));
            template_cmd::build(&entry.name, false, false, None, false)?;
            ui::success(&format!(
                "Image {:?} is ready. Run with: mvmctl up --template {}",
                entry.name, entry.name
            ));
            Ok(())
        }
        ImageCmd::Info { name } => {
            let entry = catalog
                .find(&name)
                .ok_or_else(|| anyhow::anyhow!("Image {:?} not found in catalog", name))?;
            println!("{}", serde_json::to_string_pretty(entry)?);
            Ok(())
        }
    }
}

/// Load the bundled image catalog with built-in presets.
fn load_bundled_catalog() -> mvm_core::catalog::Catalog {
    mvm_core::catalog::Catalog {
        schema_version: 1,
        entries: vec![
            mvm_core::catalog::CatalogEntry {
                name: "minimal".to_string(),
                description: "Bare-bones microVM with init only".to_string(),
                flake_ref: ".".to_string(),
                profile: "minimal".to_string(),
                default_cpus: 1,
                default_memory_mib: 256,
                tags: vec!["base".to_string(), "minimal".to_string()],
            },
            mvm_core::catalog::CatalogEntry {
                name: "http".to_string(),
                description: "HTTP server (Nginx or custom)".to_string(),
                flake_ref: ".".to_string(),
                profile: "http".to_string(),
                default_cpus: 2,
                default_memory_mib: 512,
                tags: vec!["web".to_string(), "http".to_string(), "nginx".to_string()],
            },
            mvm_core::catalog::CatalogEntry {
                name: "postgres".to_string(),
                description: "PostgreSQL database server".to_string(),
                flake_ref: ".".to_string(),
                profile: "postgres".to_string(),
                default_cpus: 2,
                default_memory_mib: 1024,
                tags: vec![
                    "database".to_string(),
                    "sql".to_string(),
                    "postgres".to_string(),
                ],
            },
            mvm_core::catalog::CatalogEntry {
                name: "worker".to_string(),
                description: "Background job worker".to_string(),
                flake_ref: ".".to_string(),
                profile: "worker".to_string(),
                default_cpus: 2,
                default_memory_mib: 512,
                tags: vec!["worker".to_string(), "background".to_string()],
            },
            mvm_core::catalog::CatalogEntry {
                name: "python".to_string(),
                description: "Python runtime environment".to_string(),
                flake_ref: ".".to_string(),
                profile: "python".to_string(),
                default_cpus: 2,
                default_memory_mib: 512,
                tags: vec!["python".to_string(), "runtime".to_string()],
            },
        ],
    }
}

// ============================================================================
// Cache management
// ============================================================================

fn cmd_cache(action: CacheCmd) -> Result<()> {
    let cache_dir = mvm_core::config::mvm_cache_dir();

    match action {
        CacheCmd::Info => {
            println!("Cache directory: {cache_dir}");
            let path = std::path::Path::new(&cache_dir);
            if path.exists() {
                let size = dir_size(path);
                println!("Disk usage: {}", human_bytes(size));
            } else {
                println!("(not yet created)");
            }
            Ok(())
        }
        CacheCmd::Prune { dry_run } => {
            let path = std::path::Path::new(&cache_dir);
            if !path.exists() {
                ui::info("Cache directory does not exist. Nothing to prune.");
                return Ok(());
            }

            // Prune: remove empty subdirectories and temp files
            let mut removed = 0u64;
            let mut freed = 0u64;
            for entry in walkdir(path)? {
                let entry_path = entry.path();
                // Remove temp files (mvm-lima-*, .tmp)
                if let Some(name) = entry_path.file_name().and_then(|n| n.to_str())
                    && (name.starts_with("mvm-lima-") || name.ends_with(".tmp"))
                {
                    let size = entry_path.metadata().map(|m| m.len()).unwrap_or(0);
                    if dry_run {
                        println!(
                            "Would remove: {} ({})",
                            entry_path.display(),
                            human_bytes(size)
                        );
                    } else if entry_path.is_dir() {
                        let _ = std::fs::remove_dir_all(entry_path);
                    } else {
                        let _ = std::fs::remove_file(entry_path);
                    }
                    removed += 1;
                    freed += size;
                }
            }

            if removed == 0 {
                ui::info("Nothing to prune.");
            } else if dry_run {
                ui::info(&format!(
                    "Would remove {} items, freeing {}",
                    removed,
                    human_bytes(freed)
                ));
            } else {
                ui::success(&format!(
                    "Pruned {} items, freed {}",
                    removed,
                    human_bytes(freed)
                ));
            }
            Ok(())
        }
    }
}

/// Recursively calculate directory size in bytes.
fn dir_size(path: &std::path::Path) -> u64 {
    walkdir(path)
        .unwrap_or_default()
        .iter()
        .filter(|e| e.path().is_file())
        .map(|e| e.path().metadata().map(|m| m.len()).unwrap_or(0))
        .sum()
}

/// Simple recursive directory walker.
fn walkdir(path: &std::path::Path) -> Result<Vec<std::fs::DirEntry>> {
    let mut entries = Vec::new();
    if path.is_dir() {
        for entry in std::fs::read_dir(path)? {
            let entry = entry?;
            let epath = entry.path();
            let is_dir = epath.is_dir();
            entries.push(entry);
            if is_dir && let Ok(sub) = walkdir(&epath) {
                entries.extend(sub);
            }
        }
    }
    Ok(entries)
}

// ============================================================================
// Init wizard
// ============================================================================

fn cmd_init(non_interactive: bool, lima_cpus: u32, lima_mem: u32) -> Result<()> {
    use mvm_core::dev_network::{DevNetwork, network_path, networks_dir};

    ui::info("Welcome to mvmctl! Running first-time setup...\n");

    // Step 1: Platform detection
    let plat = mvm_core::platform::current();
    ui::info(&format!("Platform: {}", platform_label(plat)));

    if plat.has_apple_containers() {
        ui::info("Apple Container support detected (macOS 26+).");
    }

    // Step 2: Check and install dependencies
    ui::info("\nChecking dependencies...");
    match bootstrap::check_package_manager() {
        Ok(()) => {}
        Err(e) => {
            if non_interactive {
                return Err(e);
            }
            ui::warn(&format!("Package manager issue: {e}"));
            ui::info("Please install a package manager and retry.");
            return Err(e);
        }
    }

    if plat.needs_lima() {
        ui::info("Ensuring Lima is installed...");
        bootstrap::ensure_lima()?;
    }

    // Step 3: Run setup steps (create Lima VM, install Firecracker, Nix)
    ui::info("\nSetting up development environment...");
    run_setup_steps(false, lima_cpus, lima_mem)?;

    // Step 4: Create default network if it doesn't exist
    let dir = networks_dir();
    let default_path = network_path("default");
    if !std::path::Path::new(&default_path).exists() {
        ui::info("\nCreating default network...");
        std::fs::create_dir_all(&dir)?;
        let net = DevNetwork::default_network();
        let json = serde_json::to_string_pretty(&net)?;
        std::fs::write(&default_path, json)?;
        ui::success(&format!(
            "Created default network (bridge={}, subnet={})",
            net.bridge_name, net.subnet
        ));
    } else {
        ui::info("\nDefault network already configured.");
    }

    // Step 5: Create XDG directories
    ui::info("\nCreating data directories...");
    let dirs = [
        mvm_core::config::mvm_cache_dir(),
        mvm_core::config::mvm_config_dir(),
        mvm_core::config::mvm_state_dir(),
        mvm_core::config::mvm_share_dir(),
    ];
    for d in &dirs {
        std::fs::create_dir_all(d)?;
    }

    // Step 6: Show available images
    ui::info("\nAvailable images in catalog:");
    let catalog = load_bundled_catalog();
    for entry in &catalog.entries {
        ui::info(&format!("  {}{}", entry.name, entry.description));
    }

    ui::success("\nSetup complete!");
    ui::info("Next steps:");
    ui::info("  mvmctl dev              # Enter development environment");
    ui::info("  mvmctl image list       # Browse available images");
    ui::info("  mvmctl doctor           # Verify everything is working");
    ui::info("  mvmctl up --flake .     # Build and run a VM from a Nix flake");

    Ok(())
}

fn platform_label(plat: mvm_core::platform::Platform) -> &'static str {
    match plat {
        mvm_core::platform::Platform::MacOS => "macOS (Lima + Firecracker)",
        mvm_core::platform::Platform::LinuxNative => "Linux (native KVM)",
        mvm_core::platform::Platform::LinuxNoKvm => "Linux (no KVM — limited)",
        mvm_core::platform::Platform::Wsl2 => "WSL2 (Linux via Windows)",
        mvm_core::platform::Platform::Windows => "Windows (experimental)",
    }
}

// ============================================================================
// Security status
// ============================================================================

fn cmd_security(action: SecurityCmd) -> Result<()> {
    match action {
        SecurityCmd::Status { json } => cmd_security_status(json),
    }
}

fn cmd_security_status(json: bool) -> Result<()> {
    use mvm_core::security::{PostureCheck, SecurityLayer};
    use mvm_security::posture::SecurityPosture;

    let mut checks = Vec::new();

    // Check audit logging
    let audit_path = mvm_core::audit::default_audit_log();
    let audit_exists = std::path::Path::new(&audit_path).exists();
    checks.push(PostureCheck {
        layer: SecurityLayer::AuditLogging,
        name: "Local audit log".to_string(),
        passed: audit_exists,
        detail: if audit_exists {
            format!("Active at {audit_path}")
        } else {
            format!("Not found at {audit_path}")
        },
    });

    // Check XDG directory structure
    let share_dir = mvm_core::config::mvm_share_dir();
    let xdg_exists = std::path::Path::new(&share_dir).exists();
    checks.push(PostureCheck {
        layer: SecurityLayer::ConfigImmutability,
        name: "XDG data directory".to_string(),
        passed: xdg_exists,
        detail: if xdg_exists {
            format!("Present at {share_dir}")
        } else {
            "Not yet created — run `mvmctl init`".to_string()
        },
    });

    // Check default network
    let net_path = mvm_core::dev_network::network_path("default");
    let net_exists = std::path::Path::new(&net_path).exists();
    checks.push(PostureCheck {
        layer: SecurityLayer::NetworkIsolation,
        name: "Default dev network".to_string(),
        passed: net_exists,
        detail: if net_exists {
            "Configured".to_string()
        } else {
            "Not configured — run `mvmctl init` or `mvmctl network create default`".to_string()
        },
    });

    // Check seccomp availability
    checks.push(PostureCheck {
        layer: SecurityLayer::SeccompFilter,
        name: "Seccomp profiles".to_string(),
        passed: true,
        detail: "5-tier profiles available (essential → unrestricted)".to_string(),
    });

    // Check vsock auth
    checks.push(PostureCheck {
        layer: SecurityLayer::VsockAuth,
        name: "Vsock authentication".to_string(),
        passed: true,
        detail: "Ed25519 signing with replay protection".to_string(),
    });

    // Check guest hardening (no SSH)
    checks.push(PostureCheck {
        layer: SecurityLayer::GuestHardening,
        name: "No SSH policy".to_string(),
        passed: true,
        detail: "Vsock-only guest communication (no sshd)".to_string(),
    });

    // Check supply chain
    checks.push(PostureCheck {
        layer: SecurityLayer::SupplyChainIntegrity,
        name: "Nix-based builds".to_string(),
        passed: true,
        detail: "All images built from Nix flakes (content-addressed)".to_string(),
    });

    let timestamp = mvm_core::time::utc_now();
    let report = SecurityPosture::evaluate(checks, &timestamp);

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print!("{}", SecurityPosture::summary(&report));

        let uncovered = SecurityPosture::uncovered_layers(&report.checks);
        if !uncovered.is_empty() {
            println!("\nUncovered layers (no checks):");
            for layer in uncovered {
                println!("  - {:?}", layer);
            }
        }
    }

    Ok(())
}

// ============================================================================
// Console (PTY-over-vsock)
// ============================================================================

fn cmd_console(name: &str, command: Option<&str>) -> Result<()> {
    validate_vm_name(name).with_context(|| format!("Invalid VM name: {:?}", name))?;

    if let Some(cmd) = command {
        // One-shot command execution — detect backend for both Firecracker and Apple Container
        let resp = if let Ok(mut stream) =
            mvm_apple_container::vsock_connect(name, mvm_guest::vsock::GUEST_AGENT_PORT)
        {
            mvm_guest::vsock::send_request(
                &mut stream,
                &mvm_guest::vsock::GuestRequest::Exec {
                    command: cmd.to_string(),
                    stdin: None,
                    timeout_secs: Some(30),
                },
            )?
        } else {
            let instance_dir = microvm::resolve_running_vm_dir(name)?;
            mvm_guest::vsock::exec_at(
                &mvm_guest::vsock::vsock_uds_path(&instance_dir),
                cmd,
                None,
                30,
            )?
        };
        match resp {
            mvm_guest::vsock::GuestResponse::ExecResult {
                exit_code,
                stdout,
                stderr,
            } => {
                if !stdout.is_empty() {
                    print!("{stdout}");
                }
                if !stderr.is_empty() {
                    eprint!("{stderr}");
                }
                if exit_code != 0 {
                    std::process::exit(exit_code);
                }
                Ok(())
            }
            mvm_guest::vsock::GuestResponse::Error { message } => {
                anyhow::bail!("Console exec error: {message}")
            }
            other => anyhow::bail!("Unexpected response: {other:?}"),
        }
    } else {
        // Interactive PTY session
        console_interactive(name)
    }
}

/// Open an interactive PTY console to a running VM.
///
/// Backend type for console connections.
enum ConsoleBackend {
    AppleContainer(String),
    /// Connect via the daemon's vsock proxy Unix socket.
    VsockProxy(String),
    Firecracker(String),
}

/// Connect to a vsock port via the daemon's Unix socket proxy.
fn vsock_proxy_connect(proxy_path: &str, port: u32) -> Result<std::os::unix::net::UnixStream> {
    use std::io::Write;
    let mut stream = std::os::unix::net::UnixStream::connect(proxy_path)
        .with_context(|| format!("Failed to connect to vsock proxy at {proxy_path}"))?;
    stream.write_all(&port.to_le_bytes())?;
    Ok(stream)
}

/// Open an interactive PTY console to a running VM.
///
/// Supports Firecracker (via UDS vsock), Apple Container (via direct vsock),
/// and vsock proxy (via daemon Unix socket for cross-process access).
fn console_interactive(name: &str) -> Result<()> {
    // Get terminal size
    let (cols, rows) = get_terminal_size();

    // Send ConsoleOpen request via the control channel
    ui::info(&format!(
        "Opening console to VM {:?} ({}x{})...",
        name, cols, rows
    ));

    // Determine backend: try in-process Apple Container, then vsock proxy, then Firecracker UDS
    let backend =
        if mvm_apple_container::vsock_connect(name, mvm_guest::vsock::GUEST_AGENT_PORT).is_ok() {
            ConsoleBackend::AppleContainer(name.to_string())
        } else if std::path::Path::new(&dev_vsock_proxy_path()).exists() {
            ConsoleBackend::VsockProxy(dev_vsock_proxy_path())
        } else {
            let instance_dir = microvm::resolve_running_vm_dir(name)?;
            ConsoleBackend::Firecracker(instance_dir)
        };

    // Send ConsoleOpen on the control channel
    let (resp, connect_data) = match &backend {
        ConsoleBackend::AppleContainer(vm_id) => {
            let mut stream =
                mvm_apple_container::vsock_connect(vm_id, mvm_guest::vsock::GUEST_AGENT_PORT)
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
            let resp = mvm_guest::vsock::send_request(
                &mut stream,
                &mvm_guest::vsock::GuestRequest::ConsoleOpen { cols, rows },
            )?;
            (resp, backend)
        }
        ConsoleBackend::VsockProxy(proxy_path) => {
            let mut stream = vsock_proxy_connect(proxy_path, mvm_guest::vsock::GUEST_AGENT_PORT)?;
            let resp = mvm_guest::vsock::send_request(
                &mut stream,
                &mvm_guest::vsock::GuestRequest::ConsoleOpen { cols, rows },
            )?;
            (resp, backend)
        }
        ConsoleBackend::Firecracker(instance_dir) => {
            let uds = mvm_guest::vsock::vsock_uds_path(instance_dir);
            let mut stream = mvm_guest::vsock::connect_to(&uds, 10)?;
            let resp = mvm_guest::vsock::send_request(
                &mut stream,
                &mvm_guest::vsock::GuestRequest::ConsoleOpen { cols, rows },
            )?;
            (resp, backend)
        }
    };

    let (session_id, data_port) = match resp {
        mvm_guest::vsock::GuestResponse::ConsoleOpened {
            session_id,
            data_port,
        } => (session_id, data_port),
        mvm_guest::vsock::GuestResponse::Error { message } => {
            anyhow::bail!("Console open failed: {message}");
        }
        other => {
            anyhow::bail!("Unexpected response: {other:?}");
        }
    };

    ui::info(&format!(
        "Console session {} opened, connecting to data port {}...",
        session_id, data_port
    ));

    // Small delay to let the guest agent bind the data port
    std::thread::sleep(std::time::Duration::from_millis(200));

    // Connect to the data port for raw I/O
    let data_stream = match &connect_data {
        ConsoleBackend::AppleContainer(vm_id) => {
            mvm_apple_container::vsock_connect(vm_id, data_port)
                .map_err(|e| anyhow::anyhow!("Failed to connect to console data port: {e}"))?
        }
        ConsoleBackend::VsockProxy(proxy_path) => vsock_proxy_connect(proxy_path, data_port)?,
        ConsoleBackend::Firecracker(instance_dir) => {
            // Firecracker vsock multiplexes all ports on the same UDS
            let uds = mvm_guest::vsock::vsock_uds_path(instance_dir);
            mvm_guest::vsock::connect_to(&uds, 10)
                .context("Failed to connect to console data port")?
        }
    };

    mvm_core::audit::emit(
        mvm_core::audit::LocalAuditKind::ConsoleSessionStart,
        Some(name),
        Some(&format!("session_id={session_id}")),
    );

    // Set up SIGWINCH handler to forward terminal resizes
    let resize_sender = setup_sigwinch_handler(&connect_data, session_id);

    // Enter raw terminal mode and suppress the Ctrl-C handler so that
    // Ctrl+C is forwarded as a raw byte (\x03) to the guest shell
    // instead of killing mvmctl.
    IN_CONSOLE_MODE.store(true, std::sync::atomic::Ordering::SeqCst);
    let orig_termios = enter_raw_mode()?;
    let result = run_console_relay(data_stream);

    // Restore terminal and clean up
    restore_terminal(&orig_termios);
    IN_CONSOLE_MODE.store(false, std::sync::atomic::Ordering::SeqCst);
    drop(resize_sender);

    mvm_core::audit::emit(
        mvm_core::audit::LocalAuditKind::ConsoleSessionEnd,
        Some(name),
        Some(&format!("session_id={session_id}")),
    );

    println!("\nConsole session ended.");
    result.map(|_| ())
}

/// Flag set by the SIGWINCH signal handler.
static SIGWINCH_RECEIVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

extern "C" fn sigwinch_handler(_sig: libc::c_int) {
    SIGWINCH_RECEIVED.store(true, std::sync::atomic::Ordering::SeqCst);
}

/// Set up a SIGWINCH signal handler that forwards terminal resizes to the guest.
///
/// Returns a sender that keeps the background thread alive. Drop it to stop.
fn setup_sigwinch_handler(
    backend: &ConsoleBackend,
    session_id: u32,
) -> Option<std::sync::mpsc::Sender<()>> {
    use std::sync::atomic::Ordering;

    // Clone backend info for the resize thread
    let backend_info = match backend {
        ConsoleBackend::AppleContainer(vm_id) => ConsoleBackend::AppleContainer(vm_id.clone()),
        ConsoleBackend::VsockProxy(path) => ConsoleBackend::VsockProxy(path.clone()),
        ConsoleBackend::Firecracker(dir) => ConsoleBackend::Firecracker(dir.clone()),
    };

    let (tx, rx) = std::sync::mpsc::channel::<()>();

    // Install SIGWINCH handler
    unsafe {
        libc::signal(
            libc::SIGWINCH,
            sigwinch_handler as *const () as libc::sighandler_t,
        );
    }

    // Background thread polls for resize signals
    std::thread::spawn(move || {
        loop {
            std::thread::sleep(std::time::Duration::from_millis(250));

            // Stop if session ended (sender dropped)
            if let Err(std::sync::mpsc::TryRecvError::Disconnected) = rx.try_recv() {
                break;
            }

            if !SIGWINCH_RECEIVED.swap(false, Ordering::SeqCst) {
                continue;
            }

            let (cols, rows) = get_terminal_size();

            // Send ConsoleResize via the control channel (best-effort)
            let _ = match &backend_info {
                ConsoleBackend::AppleContainer(vm_id) => {
                    mvm_apple_container::vsock_connect(vm_id, mvm_guest::vsock::GUEST_AGENT_PORT)
                        .ok()
                        .and_then(|mut stream| {
                            mvm_guest::vsock::send_request(
                                &mut stream,
                                &mvm_guest::vsock::GuestRequest::ConsoleResize {
                                    session_id,
                                    cols,
                                    rows,
                                },
                            )
                            .ok()
                        })
                }
                ConsoleBackend::VsockProxy(proxy_path) => {
                    vsock_proxy_connect(proxy_path, mvm_guest::vsock::GUEST_AGENT_PORT)
                        .ok()
                        .and_then(|mut stream| {
                            mvm_guest::vsock::send_request(
                                &mut stream,
                                &mvm_guest::vsock::GuestRequest::ConsoleResize {
                                    session_id,
                                    cols,
                                    rows,
                                },
                            )
                            .ok()
                        })
                }
                ConsoleBackend::Firecracker(instance_dir) => {
                    let uds = mvm_guest::vsock::vsock_uds_path(instance_dir);
                    mvm_guest::vsock::connect_to(&uds, 5)
                        .ok()
                        .and_then(|mut stream| {
                            mvm_guest::vsock::send_request(
                                &mut stream,
                                &mvm_guest::vsock::GuestRequest::ConsoleResize {
                                    session_id,
                                    cols,
                                    rows,
                                },
                            )
                            .ok()
                        })
                }
            };
        }
    });

    Some(tx)
}

/// Get the current terminal size.
fn get_terminal_size() -> (u16, u16) {
    // SAFETY: ioctl with valid fd (stdout)
    unsafe {
        let mut ws: libc::winsize = std::mem::zeroed();
        if libc::ioctl(1, libc::TIOCGWINSZ, &mut ws) == 0 && ws.ws_col > 0 && ws.ws_row > 0 {
            (ws.ws_col, ws.ws_row)
        } else {
            (80, 24)
        }
    }
}

/// Put the terminal in raw mode and return the original termios for restoration.
fn enter_raw_mode() -> Result<libc::termios> {
    unsafe {
        let mut orig: libc::termios = std::mem::zeroed();
        if libc::tcgetattr(0, &mut orig) != 0 {
            anyhow::bail!("Failed to get terminal attributes");
        }

        let mut raw = orig;
        libc::cfmakeraw(&mut raw);
        if libc::tcsetattr(0, libc::TCSANOW, &raw) != 0 {
            anyhow::bail!("Failed to set raw terminal mode");
        }

        Ok(orig)
    }
}

/// Restore the terminal to its original mode.
fn restore_terminal(orig: &libc::termios) {
    unsafe {
        libc::tcsetattr(0, libc::TCSANOW, orig);
    }
}

/// Relay raw bytes between stdin/stdout and a vsock data stream.
///
/// Exits when the guest closes the connection (e.g. `exit` or Ctrl+D
/// in the shell) or when the user types the `~.` escape sequence
/// (Enter, then `~.`, same as SSH).
///
fn run_console_relay(data_stream: std::os::unix::net::UnixStream) -> Result<()> {
    use std::io::{Read, Write};
    use std::os::unix::io::AsRawFd;

    let read_stream = data_stream
        .try_clone()
        .context("Failed to clone data stream")?;
    let write_stream = data_stream;
    let stdin_fd = std::io::stdin().as_raw_fd();
    let vsock_fd = read_stream.as_raw_fd();

    // Save original flags so we can restore stdin after the relay exits.
    let orig_stdin_flags = unsafe { libc::fcntl(stdin_fd, libc::F_GETFL) };
    unsafe {
        libc::fcntl(stdin_fd, libc::F_SETFL, orig_stdin_flags | libc::O_NONBLOCK);
        libc::fcntl(vsock_fd, libc::F_SETFL, libc::O_NONBLOCK);
    }

    let mut stdout = std::io::stdout();
    let mut writer = write_stream;
    let mut buf = [0u8; 4096];

    loop {
        let mut fds = [
            libc::pollfd {
                fd: stdin_fd,
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: vsock_fd,
                events: libc::POLLIN,
                revents: 0,
            },
        ];
        let ret = unsafe { libc::poll(fds.as_mut_ptr(), 2, 500) };
        if ret < 0 {
            if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            break;
        }

        // vsock → stdout (guest output)
        if fds[1].revents & libc::POLLIN != 0 {
            match (&read_stream).read(&mut buf) {
                Ok(0) => break,
                Ok(n) => {
                    let _ = stdout.write_all(&buf[..n]);
                    let _ = stdout.flush();
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(_) => break,
            }
        }
        if fds[1].revents & (libc::POLLHUP | libc::POLLERR) != 0
            && fds[1].revents & libc::POLLIN == 0
        {
            break;
        }

        // stdin → vsock (host input)
        if fds[0].revents & (libc::POLLIN | libc::POLLHUP) != 0 {
            let mut inbuf = [0u8; 1024];
            match std::io::stdin().read(&mut inbuf) {
                Ok(0) => break,
                Ok(n) => {
                    if writer.write_all(&inbuf[..n]).is_err() {
                        break;
                    }
                    let _ = writer.flush();
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(_) => break,
            }
        }
    }

    // Restore stdin to its original blocking mode
    unsafe {
        libc::fcntl(stdin_fd, libc::F_SETFL, orig_stdin_flags);
    }

    Ok(())
}

// ============================================================================
// Utilities
// ============================================================================

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

    #[test]
    fn test_cleanup_defaults() {
        let cli = Cli::try_parse_from(["mvmctl", "cleanup"]).unwrap();
        match cli.command {
            Commands::Cleanup { keep, all, verbose } => {
                assert_eq!(keep, None);
                assert!(!all);
                assert!(!verbose);
            }
            _ => panic!("Expected Cleanup command"),
        }
    }

    #[test]
    fn test_cleanup_keep_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "cleanup", "--keep", "9"]).unwrap();
        match cli.command {
            Commands::Cleanup { keep, all, verbose } => {
                assert_eq!(keep, Some(9));
                assert!(!all);
                assert!(!verbose);
            }
            _ => panic!("Expected Cleanup command"),
        }
    }

    #[test]
    fn test_cleanup_all_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "cleanup", "--all"]).unwrap();
        match cli.command {
            Commands::Cleanup { keep, all, verbose } => {
                assert_eq!(keep, None);
                assert!(all);
                assert!(!verbose);
            }
            _ => panic!("Expected Cleanup command"),
        }
    }

    #[test]
    fn test_cleanup_verbose_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "cleanup", "--verbose"]).unwrap();
        match cli.command {
            Commands::Cleanup { keep, all, verbose } => {
                assert_eq!(keep, None);
                assert!(!all);
                assert!(verbose);
            }
            _ => panic!("Expected Cleanup command"),
        }
    }

    // ---- Build --flake tests ----

    #[test]
    fn test_build_flake_with_profile() {
        let cli = Cli::try_parse_from(["mvmctl", "build", "--flake", ".", "--profile", "gateway"])
            .unwrap();
        match cli.command {
            Commands::Build { flake, profile, .. } => {
                assert_eq!(flake.as_deref(), Some("."));
                assert_eq!(profile.as_deref(), Some("gateway"));
            }
            _ => panic!("Expected Build command"),
        }
    }

    #[test]
    fn test_build_flake_defaults_to_no_profile() {
        let cli = Cli::try_parse_from(["mvmctl", "build", "--flake", "."]).unwrap();
        match cli.command {
            Commands::Build { flake, profile, .. } => {
                assert_eq!(flake.as_deref(), Some("."));
                assert!(profile.is_none(), "profile should be None when omitted");
            }
            _ => panic!("Expected Build command"),
        }
    }

    #[test]
    fn test_build_mvmfile_mode_still_works() {
        let cli = Cli::try_parse_from(["mvmctl", "build", "myimage"]).unwrap();
        match cli.command {
            Commands::Build { path, flake, .. } => {
                assert_eq!(path, "myimage");
                assert!(flake.is_none(), "Mvmfile mode should have no --flake");
            }
            _ => panic!("Expected Build command"),
        }
    }

    #[test]
    fn test_resolve_flake_ref_remote_passthrough() {
        let resolved = resolve_flake_ref("github:user/repo").unwrap();
        assert_eq!(resolved, "github:user/repo");
    }

    #[test]
    fn test_resolve_flake_ref_remote_with_path() {
        let resolved = resolve_flake_ref("github:user/repo#attr").unwrap();
        assert_eq!(resolved, "github:user/repo#attr");
    }

    #[test]
    fn test_resolve_flake_ref_absolute_path() {
        let resolved = resolve_flake_ref("/tmp").unwrap();
        // /tmp may be a symlink on macOS to /private/tmp
        assert!(
            resolved == "/tmp" || resolved == "/private/tmp",
            "unexpected resolved path: {}",
            resolved
        );
    }

    #[test]
    fn test_resolve_flake_ref_nonexistent_fails() {
        let result = resolve_flake_ref("/nonexistent/path/that/does/not/exist");
        assert!(result.is_err());
    }

    // ---- Run command tests ----

    #[test]
    fn test_run_parses_all_flags() {
        let cli = Cli::try_parse_from([
            "mvmctl",
            "run",
            "--flake",
            ".",
            "--profile",
            "full",
            "--cpus",
            "4",
            "--memory",
            "2048",
        ])
        .unwrap();
        match cli.command {
            Commands::Up {
                flake,
                profile,
                cpus,
                memory,
                ..
            } => {
                assert_eq!(flake, Some(".".to_string()));
                assert_eq!(profile.as_deref(), Some("full"));
                assert_eq!(cpus, Some(4));
                assert_eq!(memory, Some("2048".to_string()));
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_defaults() {
        let cli = Cli::try_parse_from(["mvmctl", "run", "--flake", "."]).unwrap();
        match cli.command {
            Commands::Up {
                flake,
                template,
                name,
                profile,
                cpus,
                memory,
                volume,
                hypervisor,
                ..
            } => {
                assert_eq!(flake, Some(".".to_string()));
                assert!(template.is_none(), "template should be None when omitted");
                assert!(name.is_none(), "name should be None when omitted");
                assert!(profile.is_none(), "profile should be None when omitted");
                assert!(cpus.is_none(), "cpus should be None when omitted");
                assert!(memory.is_none(), "memory should be None when omitted");
                assert_eq!(volume.len(), 0);
                assert_eq!(hypervisor, "firecracker");
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_requires_source() {
        let result = Cli::try_parse_from(["mvmctl", "run"]);
        assert!(result.is_err(), "run should require --flake or --template");
    }

    #[test]
    fn test_run_template_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "run", "--template", "openclaw"]).unwrap();
        match cli.command {
            Commands::Up {
                flake, template, ..
            } => {
                assert!(flake.is_none());
                assert_eq!(template, Some("openclaw".to_string()));
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_flake_and_template_conflict() {
        let result =
            Cli::try_parse_from(["mvmctl", "run", "--flake", ".", "--template", "openclaw"]);
        assert!(
            result.is_err(),
            "--flake and --template should be mutually exclusive"
        );
    }

    #[test]
    fn test_run_volume_dir_inject() {
        let cli = Cli::try_parse_from([
            "mvmctl",
            "run",
            "--flake",
            ".",
            "-v",
            "/tmp/config:/mnt/config",
            "-v",
            "/tmp/secrets:/mnt/secrets",
        ])
        .unwrap();
        match cli.command {
            Commands::Up { volume, .. } => {
                assert_eq!(volume.len(), 2);
                assert_eq!(volume[0], "/tmp/config:/mnt/config");
                assert_eq!(volume[1], "/tmp/secrets:/mnt/secrets");
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_volume_persistent() {
        let cli =
            Cli::try_parse_from(["mvmctl", "run", "--flake", ".", "-v", "/data:/mnt/data:4G"])
                .unwrap();
        match cli.command {
            Commands::Up { volume, .. } => {
                assert_eq!(volume.len(), 1);
                assert_eq!(volume[0], "/data:/mnt/data:4G");
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_parse_volume_spec_dir_inject() {
        let spec = parse_volume_spec("/tmp/config:/mnt/config").unwrap();
        match spec {
            VolumeSpec::DirInject {
                host_dir,
                guest_mount,
            } => {
                assert_eq!(host_dir, "/tmp/config");
                assert_eq!(guest_mount, "/mnt/config");
            }
            _ => panic!("Expected DirInject"),
        }
    }

    #[test]
    fn test_parse_volume_spec_persistent() {
        let spec = parse_volume_spec("/data:/mnt/data:4G").unwrap();
        match spec {
            VolumeSpec::Persistent(vol) => {
                assert_eq!(vol.host, "/data");
                assert_eq!(vol.guest, "/mnt/data");
                assert_eq!(vol.size, "4G");
            }
            _ => panic!("Expected Persistent"),
        }
    }

    #[test]
    fn test_parse_volume_spec_invalid() {
        let result = parse_volume_spec("just-a-path");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_volume_spec_unsupported_mount() {
        let spec = parse_volume_spec("/tmp/foo:/mnt/custom").unwrap();
        // The spec itself parses fine — the error happens at routing time in cmd_run
        match spec {
            VolumeSpec::DirInject { guest_mount, .. } => {
                assert_eq!(guest_mount, "/mnt/custom");
            }
            _ => panic!("Expected DirInject"),
        }
    }

    #[test]
    fn test_run_port_and_env_flags() {
        let cli = Cli::try_parse_from([
            "mvmctl",
            "run",
            "--flake",
            ".",
            "-p",
            "3333:3000",
            "-p",
            "3334:3002",
            "-e",
            "NODE_ENV=production",
            "-e",
            "DEBUG=true",
        ])
        .unwrap();
        match cli.command {
            Commands::Up { port, env, .. } => {
                assert_eq!(port, vec!["3333:3000", "3334:3002"]);
                assert_eq!(env, vec!["NODE_ENV=production", "DEBUG=true"]);
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_port_and_env_default_empty() {
        let cli = Cli::try_parse_from(["mvmctl", "run", "--flake", "."]).unwrap();
        match cli.command {
            Commands::Up { port, env, .. } => {
                assert!(port.is_empty());
                assert!(env.is_empty());
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_forward_flag() {
        let cli = Cli::try_parse_from([
            "mvmctl",
            "run",
            "--flake",
            ".",
            "-p",
            "3333:3000",
            "--forward",
        ])
        .unwrap();
        match cli.command {
            Commands::Up { forward, port, .. } => {
                assert!(forward);
                assert_eq!(port, vec!["3333:3000"]);
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_run_forward_default_false() {
        let cli = Cli::try_parse_from(["mvmctl", "run", "--flake", "."]).unwrap();
        match cli.command {
            Commands::Up { forward, .. } => {
                assert!(!forward);
            }
            _ => panic!("Expected Run command"),
        }
    }

    #[test]
    fn test_parse_port_specs_multiple() {
        let specs = vec!["3333:3000".to_string(), "8080".to_string()];
        let result = parse_port_specs(&specs).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].host, 3333);
        assert_eq!(result[0].guest, 3000);
        assert_eq!(result[1].host, 8080);
        assert_eq!(result[1].guest, 8080);
    }

    #[test]
    fn test_parse_port_specs_empty() {
        let specs: Vec<String> = vec![];
        let result = parse_port_specs(&specs).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_ports_to_drive_file() {
        use mvm_runtime::config::PortMapping;
        let ports = vec![
            PortMapping {
                host: 3333,
                guest: 3000,
            },
            PortMapping {
                host: 3334,
                guest: 3002,
            },
        ];
        let f = ports_to_drive_file(&ports).unwrap();
        assert_eq!(f.name, "mvm-ports.env");
        assert!(f.content.contains("MVM_PORT_MAP=\"3333:3000,3334:3002\""));
        assert_eq!(f.mode, 0o444);
    }

    #[test]
    fn test_ports_to_drive_file_empty() {
        assert!(ports_to_drive_file(&[]).is_none());
    }

    #[test]
    fn test_env_vars_to_drive_file() {
        let vars = vec!["NODE_ENV=production".to_string(), "DEBUG=true".to_string()];
        let f = env_vars_to_drive_file(&vars).unwrap();
        assert_eq!(f.name, "mvm-env.env");
        assert!(f.content.contains("export NODE_ENV=production"));
        assert!(f.content.contains("export DEBUG=true"));
        assert_eq!(f.mode, 0o444);
    }

    #[test]
    fn test_env_vars_to_drive_file_empty() {
        let vars: Vec<String> = vec![];
        assert!(env_vars_to_drive_file(&vars).is_none());
    }

    // ---- VM subcommand tests ----

    // ---- Up/Down command tests ----

    #[test]
    fn test_down_parses_no_args() {
        let cli = Cli::try_parse_from(["mvmctl", "down"]).unwrap();
        match cli.command {
            Commands::Down { name, config } => {
                assert!(name.is_none());
                assert!(config.is_none());
            }
            _ => panic!("Expected Down command"),
        }
    }

    #[test]
    fn test_down_parses_with_name() {
        let cli = Cli::try_parse_from(["mvmctl", "down", "gw"]).unwrap();
        match cli.command {
            Commands::Down { name, config } => {
                assert_eq!(name.as_deref(), Some("gw"));
                assert!(config.is_none());
            }
            _ => panic!("Expected Down command"),
        }
    }

    #[test]
    fn test_down_parses_with_config() {
        let cli = Cli::try_parse_from(["mvmctl", "down", "-f", "my-fleet.toml"]).unwrap();
        match cli.command {
            Commands::Down { name, config } => {
                assert!(name.is_none());
                assert_eq!(config.as_deref(), Some("my-fleet.toml"));
            }
            _ => panic!("Expected Down command"),
        }
    }

    // ---- read_dir_to_drive_files tests ----

    #[test]
    fn test_read_dir_to_drive_files_reads_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.txt"), "hello").unwrap();
        std::fs::write(dir.path().join("b.env"), "KEY=val").unwrap();

        let files = read_dir_to_drive_files(dir.path().to_str().unwrap(), 0o444).unwrap();
        assert_eq!(files.len(), 2);

        let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
        assert!(names.contains(&"a.txt"));
        assert!(names.contains(&"b.env"));

        for f in &files {
            assert_eq!(f.mode, 0o444);
        }
    }

    #[test]
    fn test_read_dir_to_drive_files_skips_directories() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("file.txt"), "content").unwrap();
        std::fs::create_dir(dir.path().join("subdir")).unwrap();

        let files = read_dir_to_drive_files(dir.path().to_str().unwrap(), 0o400).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].name, "file.txt");
        assert_eq!(files[0].mode, 0o400);
    }

    #[test]
    fn test_read_dir_to_drive_files_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let files = read_dir_to_drive_files(dir.path().to_str().unwrap(), 0o444).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn test_read_dir_to_drive_files_nonexistent_dir() {
        let result = read_dir_to_drive_files("/nonexistent/path/abc123", 0o444);
        assert!(result.is_err());
    }

    // ---- Forward command tests ----

    #[test]
    fn test_forward_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "forward", "swift", "3000"]).unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                // Positional ports land in `ports`, flag ports in `port`.
                assert!(port.is_empty());
                assert_eq!(ports, vec!["3000"]);
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_forward_with_port_mapping() {
        let cli = Cli::try_parse_from(["mvmctl", "forward", "swift", "8080:3000"]).unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                assert!(port.is_empty());
                assert_eq!(ports, vec!["8080:3000"]);
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_forward_with_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "forward", "swift", "-p", "3000"]).unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                assert_eq!(port, vec!["3000"]);
                assert!(ports.is_empty());
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_forward_multiple_ports() {
        let cli =
            Cli::try_parse_from(["mvmctl", "forward", "swift", "-p", "3000", "-p", "8080:443"])
                .unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                assert_eq!(port, vec!["3000", "8080:443"]);
                assert!(ports.is_empty());
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_forward_multiple_positional() {
        let cli = Cli::try_parse_from(["mvmctl", "forward", "swift", "3000", "8080:443"]).unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                assert!(port.is_empty());
                assert_eq!(ports, vec!["3000", "8080:443"]);
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_forward_no_ports_parses() {
        // forward with no ports should parse successfully — cmd_forward
        // falls back to persisted ports from run-info.json
        let cli = Cli::try_parse_from(["mvmctl", "forward", "swift"]).unwrap();
        match cli.command {
            Commands::Forward { name, port, ports } => {
                assert_eq!(name, "swift");
                assert!(port.is_empty());
                assert!(ports.is_empty());
            }
            _ => panic!("Expected Forward command"),
        }
    }

    #[test]
    fn test_parse_port_spec_single() {
        let (local, guest) = parse_port_spec("3000").unwrap();
        assert_eq!(local, 3000);
        assert_eq!(guest, 3000);
    }

    #[test]
    fn test_parse_port_spec_mapping() {
        let (local, guest) = parse_port_spec("8080:3000").unwrap();
        assert_eq!(local, 8080);
        assert_eq!(guest, 3000);
    }

    #[test]
    fn test_parse_port_spec_invalid() {
        assert!(parse_port_spec("abc").is_err());
        assert!(parse_port_spec("abc:3000").is_err());
        assert!(parse_port_spec("3000:abc").is_err());
        assert!(parse_port_spec("99999").is_err());
    }

    // -------------------------------------------------------------------------
    // Alias tests (Phase 4)
    // -------------------------------------------------------------------------

    #[test]
    fn test_ls_alias_for_ps() {
        let cli = Cli::try_parse_from(["mvmctl", "ls"]).unwrap();
        assert!(matches!(cli.command, Commands::Ps { .. }));
    }

    #[test]
    fn test_ps_command() {
        let cli = Cli::try_parse_from(["mvmctl", "ps"]).unwrap();
        assert!(matches!(cli.command, Commands::Ps { .. }));
    }

    #[test]
    fn test_start_alias_for_run() {
        // 'start' is already an alias on Run — verify it still works
        assert!(Cli::try_parse_from(["mvmctl", "start", "--flake", "."]).is_ok());
    }

    // -------------------------------------------------------------------------
    // Metrics tests (Phase 1)
    // -------------------------------------------------------------------------

    #[test]
    fn test_metrics_command_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "metrics"]).unwrap();
        assert!(matches!(cli.command, Commands::Metrics { json: false }));
    }

    #[test]
    fn test_metrics_json_flag_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "metrics", "--json"]).unwrap();
        assert!(matches!(cli.command, Commands::Metrics { json: true }));
    }

    #[test]
    fn test_metrics_snapshot_serializes_to_json() {
        let snap = mvm_core::observability::metrics::global().snapshot();
        let json = serde_json::to_string(&snap).expect("snapshot must serialize");
        assert!(json.contains("requests_total"));
        assert!(json.contains("instances_created"));
    }

    #[test]
    fn test_prometheus_exposition_has_expected_metrics() {
        let prom = mvm_core::observability::metrics::global().prometheus_exposition();
        assert!(prom.contains("mvm_requests_total"));
        assert!(prom.contains("mvm_instances_created_total"));
        assert!(prom.contains("# HELP"));
        assert!(prom.contains("# TYPE"));
    }

    // ---- Config command tests ----

    #[test]
    fn test_config_show_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "config", "show"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Config {
                action: ConfigAction::Show
            }
        ));
    }

    #[test]
    fn test_config_set_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "config", "set", "lima_cpus", "4"]).unwrap();
        match cli.command {
            Commands::Config {
                action: ConfigAction::Set { key, value },
            } => {
                assert_eq!(key, "lima_cpus");
                assert_eq!(value, "4");
            }
            _ => panic!("Expected Config Set command"),
        }
    }

    #[test]
    fn test_config_show_output_contains_lima_cpus() {
        let tmp = tempfile::tempdir().unwrap();
        let cfg = mvm_core::user_config::MvmConfig::default();
        mvm_core::user_config::save(&cfg, Some(tmp.path())).unwrap();
        let loaded = mvm_core::user_config::load(Some(tmp.path()));
        let text = toml::to_string_pretty(&loaded).unwrap();
        assert!(text.contains("lima_cpus"));
    }

    #[test]
    fn test_config_set_persists() {
        let tmp = tempfile::tempdir().unwrap();
        let mut cfg = mvm_core::user_config::load(Some(tmp.path()));
        mvm_core::user_config::set_key(&mut cfg, "lima_cpus", "4").unwrap();
        mvm_core::user_config::save(&cfg, Some(tmp.path())).unwrap();
        let reloaded = mvm_core::user_config::load(Some(tmp.path()));
        assert_eq!(reloaded.lima_cpus, 4);
    }

    #[test]
    fn test_config_set_unknown_key_fails() {
        let mut cfg = mvm_core::user_config::MvmConfig::default();
        let err = mvm_core::user_config::set_key(&mut cfg, "nonexistent_key", "5").unwrap_err();
        assert!(err.to_string().contains("Unknown config key"));
    }

    // ---- Uninstall command tests ----

    #[test]
    fn test_uninstall_parses_defaults() {
        let cli = Cli::try_parse_from(["mvmctl", "uninstall", "--yes"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Uninstall {
                yes: true,
                all: false,
                dry_run: false,
            }
        ));
    }

    #[test]
    fn test_uninstall_dry_run_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "uninstall", "--dry-run", "--yes"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Uninstall {
                yes: true,
                all: false,
                dry_run: true,
            }
        ));
    }

    #[test]
    fn test_uninstall_all_flag_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "uninstall", "--all", "--yes"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Uninstall {
                yes: true,
                all: true,
                dry_run: false,
            }
        ));
    }

    // ---- Audit command tests ----

    #[test]
    fn test_audit_tail_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "audit", "tail"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Audit {
                action: AuditCmd::Tail {
                    lines: 20,
                    follow: false,
                }
            }
        ));
    }

    #[test]
    fn test_audit_tail_follow_parses() {
        let cli =
            Cli::try_parse_from(["mvmctl", "audit", "tail", "--follow", "--lines", "50"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Audit {
                action: AuditCmd::Tail {
                    lines: 50,
                    follow: true,
                }
            }
        ));
    }

    #[test]
    fn test_audit_tail_no_log_prints_message() {
        // When no audit log exists, cmd_audit_tail should succeed with a
        // helpful message rather than an error.
        let tmp = tempfile::tempdir().unwrap();
        let nonexistent = tmp.path().join("audit.jsonl");
        // Path doesn't exist — simulate the early-return path.
        assert!(!nonexistent.exists());
    }

    // ---- Clap value parser tests ----

    #[test]
    fn test_clap_port_spec_valid() {
        assert!(clap_port_spec("8080").is_ok());
        assert!(clap_port_spec("8080:80").is_ok());
        assert!(clap_port_spec("443:443").is_ok());
        assert!(clap_port_spec("0:0").is_ok());
    }

    #[test]
    fn test_clap_port_spec_invalid() {
        assert!(clap_port_spec("").is_err());
        assert!(clap_port_spec("abc").is_err());
        assert!(clap_port_spec("8080:abc").is_err());
        assert!(clap_port_spec("abc:80").is_err());
        assert!(clap_port_spec("99999").is_err()); // out of u16 range
    }

    #[test]
    fn test_clap_volume_spec_valid() {
        assert!(clap_volume_spec("/host:/guest").is_ok());
        assert!(clap_volume_spec("/host/path:/guest/mount").is_ok());
        assert!(clap_volume_spec("/host:/guest:1G").is_ok());
        assert!(clap_volume_spec("./local:/app").is_ok());
    }

    #[test]
    fn test_clap_volume_spec_invalid() {
        assert!(clap_volume_spec("").is_err());
        assert!(clap_volume_spec("nocolon").is_err());
        assert!(clap_volume_spec(":/guest").is_err()); // empty host
    }

    #[test]
    fn test_clap_vm_name_valid() {
        assert!(clap_vm_name("my-vm").is_ok());
        assert!(clap_vm_name("vm1").is_ok());
        assert!(clap_vm_name("a").is_ok());
    }

    #[test]
    fn test_clap_vm_name_invalid() {
        assert!(clap_vm_name("").is_err());
        assert!(clap_vm_name("UPPER").is_err());
        assert!(clap_vm_name("has space").is_err());
        assert!(clap_vm_name("-leading").is_err());
    }

    #[test]
    fn test_clap_flake_ref_valid() {
        assert!(clap_flake_ref(".").is_ok());
        assert!(clap_flake_ref("github:org/repo").is_ok());
        assert!(clap_flake_ref("/absolute/path").is_ok());
    }

    #[test]
    fn test_clap_flake_ref_invalid() {
        assert!(clap_flake_ref("").is_err());
        assert!(clap_flake_ref(". ; rm -rf /").is_err());
        assert!(clap_flake_ref("$(evil)").is_err());
    }

    #[test]
    fn test_run_rejects_invalid_vm_name_at_parse_time() {
        // Clap should reject bad --name values before any command runs.
        let result = Cli::try_parse_from(["mvmctl", "run", "--flake", ".", "--name", "INVALID"]);
        assert!(
            result.is_err(),
            "uppercase VM name should fail at parse time"
        );
    }

    #[test]
    fn test_run_rejects_invalid_flake_at_parse_time() {
        let result =
            Cli::try_parse_from(["mvmctl", "run", "--flake", ". ; rm -rf /", "--name", "vm1"]);
        assert!(
            result.is_err(),
            "shell-injection flake ref should fail at parse time"
        );
    }

    #[test]
    fn test_run_rejects_invalid_port_at_parse_time() {
        let result = Cli::try_parse_from(["mvmctl", "run", "--flake", ".", "--port", "notaport"]);
        assert!(result.is_err(), "invalid port should fail at parse time");
    }

    // ---- Config defaults wired into cmd_run ----

    #[test]
    fn test_run_uses_config_default_cpus() {
        // When --cpus is omitted, the config default should be applied.
        let cfg = mvm_core::user_config::MvmConfig {
            default_cpus: 4,
            ..mvm_core::user_config::MvmConfig::default()
        };

        // Simulate the resolution logic from the Commands::Up dispatch.
        let cli_cpus: Option<u32> = None;
        let effective = cli_cpus.or(Some(cfg.default_cpus));
        assert_eq!(effective, Some(4));
    }

    #[test]
    fn test_run_cli_flag_overrides_config_cpus() {
        // When --cpus is provided, it takes precedence over config.
        let cfg = mvm_core::user_config::MvmConfig {
            default_cpus: 4,
            ..mvm_core::user_config::MvmConfig::default()
        };

        let cli_cpus: Option<u32> = Some(8);
        let effective = cli_cpus.or(Some(cfg.default_cpus));
        assert_eq!(effective, Some(8));
    }

    #[test]
    fn test_run_uses_config_default_memory() {
        let cfg = mvm_core::user_config::MvmConfig {
            default_memory_mib: 2048,
            ..mvm_core::user_config::MvmConfig::default()
        };

        let cli_memory: Option<u32> = None;
        let effective = cli_memory.or(Some(cfg.default_memory_mib));
        assert_eq!(effective, Some(2048));
    }

    #[test]
    fn test_run_cli_flag_overrides_config_memory() {
        let cfg = mvm_core::user_config::MvmConfig {
            default_memory_mib: 2048,
            ..mvm_core::user_config::MvmConfig::default()
        };

        let cli_memory: Option<u32> = Some(512);
        let effective = cli_memory.or(Some(cfg.default_memory_mib));
        assert_eq!(effective, Some(512));
    }

    #[test]
    fn test_resolve_network_policy_default() {
        let policy = resolve_network_policy(None, &[]).unwrap();
        assert!(policy.is_unrestricted());
    }

    #[test]
    fn test_resolve_network_policy_preset() {
        let policy = resolve_network_policy(Some("dev"), &[]).unwrap();
        assert!(!policy.is_unrestricted());
        let rules = policy.resolve_rules().unwrap();
        assert!(rules.iter().any(|r| r.host == "github.com"));
    }

    #[test]
    fn test_resolve_network_policy_allow_list() {
        let allow = vec![
            "github.com:443".to_string(),
            "api.openai.com:443".to_string(),
        ];
        let policy = resolve_network_policy(None, &allow).unwrap();
        let rules = policy.resolve_rules().unwrap();
        assert_eq!(rules.len(), 2);
    }

    #[test]
    fn test_resolve_network_policy_mutual_exclusion() {
        let allow = vec!["github.com:443".to_string()];
        let result = resolve_network_policy(Some("dev"), &allow);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_network_policy_invalid_preset() {
        let result = resolve_network_policy(Some("bogus"), &[]);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_network_policy_invalid_allow_entry() {
        let allow = vec!["not-a-host-port".to_string()];
        let result = resolve_network_policy(None, &allow);
        assert!(result.is_err());
    }

    // --- Network CLI tests ---

    #[test]
    fn test_network_list_help() {
        let cli = Cli::try_parse_from(["mvmctl", "network", "list"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_network_create_help() {
        let cli = Cli::try_parse_from(["mvmctl", "network", "create", "mynet"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_network_inspect_help() {
        let cli = Cli::try_parse_from(["mvmctl", "network", "inspect", "mynet"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_network_remove_help() {
        let cli = Cli::try_parse_from(["mvmctl", "network", "rm", "mynet"]);
        assert!(cli.is_ok());
    }

    // --- Image CLI tests ---

    #[test]
    fn test_image_list_help() {
        let cli = Cli::try_parse_from(["mvmctl", "image", "list"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_image_search_help() {
        let cli = Cli::try_parse_from(["mvmctl", "image", "search", "http"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_image_fetch_help() {
        let cli = Cli::try_parse_from(["mvmctl", "image", "fetch", "minimal"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_image_info_help() {
        let cli = Cli::try_parse_from(["mvmctl", "image", "info", "postgres"]);
        assert!(cli.is_ok());
    }

    // --- Console CLI tests ---

    #[test]
    fn test_console_help() {
        let cli = Cli::try_parse_from(["mvmctl", "console", "myvm"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_console_with_command() {
        let cli = Cli::try_parse_from(["mvmctl", "console", "myvm", "--command", "ls"]);
        assert!(cli.is_ok());
        match cli.unwrap().command {
            Commands::Console { name, command } => {
                assert_eq!(name, "myvm");
                assert_eq!(command.as_deref(), Some("ls"));
            }
            _ => panic!("Expected Console command"),
        }
    }

    // --- Init CLI tests ---

    #[test]
    fn test_init_defaults() {
        let cli = Cli::try_parse_from(["mvmctl", "init"]).unwrap();
        match cli.command {
            Commands::Init {
                non_interactive,
                lima_cpus,
                lima_mem,
            } => {
                assert!(!non_interactive);
                assert_eq!(lima_cpus, 8);
                assert_eq!(lima_mem, 16);
            }
            _ => panic!("Expected Init command"),
        }
    }

    #[test]
    fn test_init_non_interactive() {
        let cli = Cli::try_parse_from(["mvmctl", "init", "--non-interactive", "--lima-cpus", "4"])
            .unwrap();
        match cli.command {
            Commands::Init {
                non_interactive,
                lima_cpus,
                ..
            } => {
                assert!(non_interactive);
                assert_eq!(lima_cpus, 4);
            }
            _ => panic!("Expected Init command"),
        }
    }

    // --- Security CLI tests ---

    #[test]
    fn test_security_status_help() {
        let cli = Cli::try_parse_from(["mvmctl", "security", "status"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_security_status_json() {
        let cli = Cli::try_parse_from(["mvmctl", "security", "status", "--json"]).unwrap();
        match cli.command {
            Commands::Security {
                action: SecurityCmd::Status { json },
            } => {
                assert!(json);
            }
            _ => panic!("Expected Security Status command"),
        }
    }

    // --- Cache CLI tests ---

    #[test]
    fn test_cache_info() {
        let cli = Cli::try_parse_from(["mvmctl", "cache", "info"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cache_prune() {
        let cli = Cli::try_parse_from(["mvmctl", "cache", "prune"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cache_prune_dry_run() {
        let cli = Cli::try_parse_from(["mvmctl", "cache", "prune", "--dry-run"]).unwrap();
        match cli.command {
            Commands::Cache {
                action: CacheCmd::Prune { dry_run },
            } => {
                assert!(dry_run);
            }
            _ => panic!("Expected Cache Prune command"),
        }
    }

    // --- Up --network flag tests ---

    #[test]
    fn test_up_network_default() {
        let cli = Cli::try_parse_from(["mvmctl", "up", "--flake", "."]).unwrap();
        match cli.command {
            Commands::Up { network, .. } => {
                assert_eq!(network, "default");
            }
            _ => panic!("Expected Up command"),
        }
    }

    #[test]
    fn test_up_network_custom() {
        let cli =
            Cli::try_parse_from(["mvmctl", "up", "--flake", ".", "--network", "isolated"]).unwrap();
        match cli.command {
            Commands::Up { network, .. } => {
                assert_eq!(network, "isolated");
            }
            _ => panic!("Expected Up command"),
        }
    }

    #[test]
    fn test_template_init_defaults_to_no_preset_or_prompt() {
        let cli = Cli::try_parse_from(["mvmctl", "template", "init", "demo", "--local"]).unwrap();
        match cli.command {
            Commands::Template {
                action: TemplateCmd::Init { preset, prompt, .. },
            } => {
                assert!(preset.is_none(), "preset should be None when omitted");
                assert!(prompt.is_none(), "prompt should be None when omitted");
            }
            _ => panic!("Expected Template Init command"),
        }
    }

    #[test]
    fn test_template_init_parses_prompt_flag() {
        let cli = Cli::try_parse_from([
            "mvmctl",
            "template",
            "init",
            "demo",
            "--local",
            "--prompt",
            "python worker that polls an API",
        ])
        .unwrap();
        match cli.command {
            Commands::Template {
                action: TemplateCmd::Init { prompt, preset, .. },
            } => {
                assert_eq!(prompt.as_deref(), Some("python worker that polls an API"));
                assert!(preset.is_none(), "preset should remain None when omitted");
            }
            _ => panic!("Expected Template Init command"),
        }
    }

    // --- Apple Container dev tests ---

    #[test]
    fn test_dev_up_with_lima_flag() {
        let cli = Cli::try_parse_from(["mvmctl", "dev", "up", "--lima"]).unwrap();
        match cli.command {
            Commands::Dev {
                action: Some(DevCmd::Up { lima, .. }),
            } => {
                assert!(lima);
            }
            _ => panic!("Expected Dev Up command"),
        }
    }

    #[test]
    fn test_dev_down_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "dev", "down"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_dev_shell_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "dev", "shell"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_dev_status_parses() {
        let cli = Cli::try_parse_from(["mvmctl", "dev", "status"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_is_apple_container_dev_running_returns_bool() {
        // Just verify it doesn't panic — actual result depends on platform
        let _ = is_apple_container_dev_running();
    }
}