smix-cli 2.1.0

smix — AI-native iOS Simulator automation CLI.
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
//! smix — AI-native iOS Simulator automation CLI (binary entry).
//!
//! `smix sim` is the sole device-control surface — raw `simctl` is not
//! expected in workflows. Every device argument accepts an explicit
//! UDID or an alias recorded in `.smix/sims.json` (resolved
//! deterministically by `smix_simctl::registry`; never against the live
//! simulator set). Unwrapped long-tail subcommands go through
//! `smix sim exec`, which keeps simctl's original argument shape and
//! injects the resolved UDID.

mod act;
mod authoring;
mod bench;
mod capsule;
mod down;
/// Distributed `smix run --nodes`: roster parsing, cross-node flow
/// sharding, readiness gate, ssh fan-out and merged reporting.
mod federation;
#[cfg(test)]
mod guide_gate;
mod init;
mod parallel;
mod readiness;

#[cfg(test)]
mod release_record;
mod runner_android;
mod script;

use clap::{Parser, Subcommand};
use smix_simctl::registry::{self, RegistryError, SimRegistry};
use smix_simctl::{Appearance, DeviceControlError, LaunchResult, SimctlClient};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

#[derive(Parser, Debug)]
#[command(
    name = "smix",
    about = "AI-native iOS Simulator + Android emulator automation",
    version,
    long_about = "\
smix — AI-native automation for iOS Simulator + Android emulator.

What smix is:
  · A single tool that owns the full sim/emulator lifecycle (boot →
    capsule → flow → teardown).
  · A pinned-device model: every command takes an explicit DEVICE
    (registry alias from `.smix/sims.json` or raw UDID). There is no
    `--device booted` fallback; ambiguity is a bug, not a feature.
  · A three-layer architecture: sense (tree / find / OCR / popups) and
    act (tap / fill / swipe / press-key) are core flat capabilities;
    decide lives in driver impls.
  · Two yaml dialects:
      - smix flows (read maestro-format yaml, plus smix-native extensions:
        ocrText / anchorRelative / fallback / cross-platform `app:`).
        Run via `smix run flow.yaml`.
      - smix-native run-script (shell-friendly sequential subcommand
        driver). Run via `smix run-script script.yaml`.
  · AI-readable failures: every error carries visibleElements +
    suggestions + code, not just a stack trace.

What smix is NOT:
  · Not a build tool. smix does not build the app under test; you build,
    smix installs + drives.
  · Not a maestro wrapper. We read maestro's yaml format because flow
    files are portable, not because we are bound to its product surface.

Quick start:
  smix sim boot <DEVICE>                # boot a registered sim/emulator
  smix capsule up <DEVICE>               # start runner (XCUITest on iOS,
                                         # Kotlin instrumentation on Android)
  smix run flow.yaml --device <DEVICE>   # execute a flow
  smix find --selector-id <a11y-id>      # ad-hoc probe (one-shot)
  smix tree --json                       # inspect current a11y tree
  smix capsule down <DEVICE>             # teardown

Subcommand categories:
  Environment:
    doctor, sim, runner, capsule, down

  Flow execution:
    run             (maestro-format yaml flow)
    run-script      (smix-native sequential subcommand script)

  Live probes (require a running runner):
    tap, find, wait-for, fill, press-key, scroll, hide-keyboard,
    tree, describe, system-popups

Documentation:
  - Master AI guide:    docs/AI_GUIDE.md
  - Quickstart:         docs/ai-guide/01-quickstart.md
  - CLI reference:      docs/ai-guide/05-cli.md
  - Cookbook:           docs/ai-guide/08-cookbook.md
  - Errors + remedies:  docs/ai-guide/07-errors.md

Sim safety hook:
  Bare `xcrun simctl <verb>` is BLOCKED for mutating verbs (read-only
  `simctl list` is allowed). Use typed `smix sim ...` subcommands or
  `smix sim exec <DEVICE> ...` for passthrough. The hook requires an
  explicit device id — there is no 'booted' / blanket selector.
"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

// A clap top-level command enum: parsed once, held as a single value, never
// stored in bulk. `Run` legitimately carries ~20 flag fields while `Doctor` is
// a unit — the variant-size spread is by design, not the memory bloat this lint
// guards against. Boxing `Run`'s fields into a separate Args struct buys lint
// compliance at the cost of clap-derive machinery for no runtime gain; the
// inline allow is the sanctioned exception (same idiom as `RunError` in
// smix-adapter-maestro, per the workspace lints policy).
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, Debug)]
enum Cmd {
    /// Register a simulator under an alias, creating the `.smix` registry.
    /// This is the bootstrap: alias-form device refs have nothing to
    /// resolve against until one exists.
    Init {
        /// Alias to register under.
        #[arg(long, default_value = "dev")]
        alias: String,
        /// UDID to register. Required when more than one simulator is
        /// available — init does not choose between devices.
        #[arg(long)]
        device: Option<String>,
        /// Path to the `.app` bundle to install on it. The device is
        /// booted first: `simctl install` refuses a shut-down device, and
        /// a freshly registered one is shut down.
        #[arg(long)]
        app: Option<PathBuf>,
    },
    /// Say whether this machine can drive anything yet, and if not, what
    /// to run next. `--json` for the same verdict in machine form.
    Doctor {
        /// Emit the verdict as JSON instead of prose.
        #[arg(long)]
        json: bool,
    },
    /// Perf regression gate: measure the in-process corpus, compare
    /// against the committed baseline, and fail on a >5% slowdown or a
    /// metric that stopped being measured. The absolute `perf_gate`
    /// ceilings catch a spike; this catches slow drift under them.
    Bench {
        /// Overwrite the committed baseline with this run's measurement
        /// instead of comparing against it.
        #[arg(long = "update-baseline", default_value_t = false)]
        update_baseline: bool,
        /// Read the "current" measurement from a JSON file instead of
        /// measuring. For tests and CI reproduction; skips the
        /// machine-sensitive measurement.
        #[arg(long = "current-file")]
        current_file: Option<std::path::PathBuf>,
        /// Baseline JSON to compare against. Defaults to the committed
        /// `crates/smix-cli/bench/baseline.json`.
        #[arg(long = "baseline-file")]
        baseline_file: Option<std::path::PathBuf>,
    },
    /// Runtime observability commands. `dump` pretty-prints the
    /// runner's recent subprocess ring buffer + open sessions + sim
    /// health so a failed flow can be diagnosed without a new smix
    /// patch.
    Diagnostic {
        #[command(subcommand)]
        action: DiagnosticAction,
    },
    /// Manage simulators. `<DEVICE>` = explicit UDID, or an alias /
    /// deviceName in the workspace's `.smix` registry (env SMIX_SIMS_JSON
    /// overrides discovery).
    Sim {
        #[command(subcommand)]
        action: SimAction,
    },
    /// Manage the XCUITest runner session (host-side xcodebuild handle).
    Runner {
        #[command(subcommand)]
        action: RunnerAction,
    },
    /// Tear down every smix-owned residual process and recycle registered
    /// sims (per-UDID; never touches sims outside .smix/sims.json).
    Down,
    /// End-to-end capsule bring-up / tear-down: headless boot, capture,
    /// and runner start with `--record`. The guard rejects a windowed
    /// session by default; pass `--soft` to accept the soft-capsule
    /// fallback.
    Capsule {
        #[command(subcommand)]
        action: CapsuleAction,
    },
    /// Host-resolve and dispatch a tap on the running runner. Reads
    /// `SMIX_RUNNER_PORT` env (default 22087). Selector shorthand:
    /// `id:<a11y-id>` / `text:<plain>` / `label:<acc-label>` / `role:<role>`.
    Tap {
        /// Selector in `<kind>:<value>` shorthand.
        selector: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Boolean existence probe (POST /find). Prints `exists=<bool>`.
    /// Same selector shorthand as `smix tap`.
    Find {
        selector: String,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Poll `/find` every 250ms until the selector resolves or
    /// `--timeout` expires. Mirrors SDK `App::wait_for` semantics; useful in
    /// shell loops driving the runner from outside Rust.
    WaitFor {
        selector: String,
        /// Timeout in seconds (default 5).
        #[arg(long, default_value_t = 5)]
        timeout: u64,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Type text into the matched field. Equivalent to the flow yaml
    /// `inputText:` verb. Selector shorthand same as `smix tap`.
    Fill {
        selector: String,
        #[arg(long)]
        text: String,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Issue a hardware / IME key press. Key shorthand: `return`
    /// (alias `enter`), `delete` (alias `backspace`), `tab`, `space`,
    /// `escape` / `esc`, `arrowUp` / `up`, `arrowDown` / `down`,
    /// `arrowLeft` / `left`, `arrowRight` / `right`, `home`, `lock`,
    /// `volumeUp` / `volume-up`, `volumeDown` / `volume-down`.
    PressKey {
        /// KeyName shorthand (see help text).
        key: String,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Scroll until the selector becomes visible. Direction:
    /// `up` / `down` / `left` / `right`.
    Scroll {
        selector: String,
        #[arg(long)]
        direction: String,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Dismiss the soft keyboard if visible.
    HideKeyboard {
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Print the runner's current a11y tree. `--json` emits
    /// wire JSON; default emits an indented text outline.
    Tree {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Print the runner's high-level ScreenDescription: the visible
    /// interactive elements aggregated from the current a11y tree.
    Describe {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Print the runner's current SpringBoard system-popup list.
    SystemPopups {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Press a button on a SpringBoard system popup. Both ids come from
    /// `smix system-popups` output (popup `id` + one of its buttons'
    /// `id`). Errors when the popup or button no longer exists.
    SystemPopupAction {
        popup_id: String,
        button_id: String,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Sequential script driver. Reads a yaml file describing ordered
    /// smix subcommand invocations (see `crates/smix-cli/src/script.rs`
    /// for the schema). Lightweight shell-friendly alternative to
    /// chaining `smix tap … && smix fill …`. smix-native dialect — NOT
    /// the maestro yaml flow format (for that, use `smix run`).
    RunScript {
        /// Path to the script yaml file.
        path: PathBuf,
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Run a flow file end-to-end. smix flows are written in a yaml
    /// dialect we share with maestro (so existing flows are reusable),
    /// extended with smix-native selectors (ocr / anchor-relative /
    /// fallback) and cross-platform `app:` resolver.
    ///
    /// The runner (`smix capsule up`) must be up first.
    #[command(long_about = "\
Run a flow file end-to-end on the connected sim/emulator.

A smix flow is a yaml document with two parts: a header (app id / logical \
key) and an ordered list of steps. smix accepts the maestro yaml format \
(40 verbs: assertVisible, tapOn, inputText, scroll, runFlow, ...) plus \
smix-native extensions (ocrText / anchorRelative / fallback selectors, \
cross-platform `app:` resolver via smix-apps.yaml).

Prerequisites:
  1. Sim / emulator booted with a known device id (registry alias or UDID)
  2. Runner up (`smix capsule up <DEVICE>`)
  3. App installed + (optionally) launched

Common invocations:
  # iOS (capsule default port 22087)
  smix run --device ios-17 flow.yaml

  # Android (Kotlin runner on adb-forwarded :28080)
  smix run --device emulator-5554 --platform android \\
      --apps-config smix-apps.yaml --runner-port 28080 flow.yaml

  # Skip auto-foreground (app already on screen)
  smix run --device <DEVICE> --no-launch flow.yaml

Exit codes:
  0  success
  2  yaml parse error
  3  runtime SDK failure (sim / app problem mid-flow)
  4  unknown verb / direction
  5  runFlow cycle / file IO
  6  runner unreachable (capsule not up / wrong port)

Documentation: docs/AI_GUIDE.md
")]
    Run {
        /// Path(s) to flow yaml file(s). One or more files can be
        /// listed; the runner is up'd once and reused across all
        /// flows. Per-flow debug-output subdirectory when
        /// `--debug-output` is set (`<dir>/<flow-basename>/step-*.json`).
        /// Exit code = max(per-flow codes). `--fail-fast` aborts the
        /// batch on the first failure.
        #[arg(required = true, num_args = 1..)]
        flows: Vec<PathBuf>,
        /// Device id — registry alias (preferred) or raw UDID. smix is
        /// strict about explicit device id: there is no `--device booted`
        /// fallback. Same `<DEVICE>` form used by `smix sim ...` /
        /// `smix capsule ...`.
        #[arg(long, env = "SMIX_UDID")]
        device: Option<String>,
        /// Additional sims for `--parallel`. Repeatable. The flows are
        /// sharded round-robin across `--device` plus every
        /// `--also-device`; each shard runs as its own single-sim
        /// `smix run`, so a shard is the ordinary sequential path pinned
        /// to one sim. Ignored when `--parallel` is 1.
        #[arg(long = "also-device")]
        also_device: Vec<String>,
        /// Run up to N sims concurrently, sharding the listed flows
        /// across `--device` + `--also-device`. Default 1 = the
        /// single-sim path, byte-identical. Capped at the number of sims
        /// given.
        #[arg(long, default_value_t = 1)]
        parallel: usize,
        /// Distributed run: shard the flows across the nodes in a roster
        /// yaml (each node runs its own simulators; results merge into one
        /// JSON report on stdout, exit = worst of nodes).
        #[arg(long, conflicts_with_all = ["device", "also_device", "parallel"])]
        nodes: Option<PathBuf>,
        /// Bundle id / Android package for `App::foreground` (skipped
        /// with --no-launch). Overridden by `appId:` / `app:` in the
        /// yaml header.
        #[arg(long)]
        bundle_id: Option<String>,
        /// Runner port. iOS default 22087, Android 28080 by convention.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
        /// Skip the initial foreground call. Use when the app is
        /// already on screen (e.g. launched via `smix sim launch` or
        /// `adb shell am start`). Saves 3-5s cold-start latency.
        #[arg(long, default_value_t = false)]
        no_launch: bool,
        /// Run with the device's own animation settings instead of
        /// quietening them.
        ///
        /// By default a run asks the device to stop animating first:
        /// Android's three animation scales go to zero, iOS gets Reduce
        /// Motion (XCUITest cannot reach the app's own animation flag,
        /// so that is as far as it goes). Both are read back and the
        /// run refuses if they did not take. Pass this when motion is
        /// the subject — recording a demo, or an `assertScreenshot`
        /// baseline whose frames include a transition.
        #[arg(long, default_value_t = false)]
        animations: bool,
        /// Target platform.
        #[arg(long, value_enum, env = "SMIX_PLATFORM", default_value_t = RunPlatform::Ios)]
        platform: RunPlatform,
        /// Path to `smix-apps.yaml` cross-platform app resolver config.
        /// When the yaml header uses `app: <logicalKey>`, this resolver
        /// maps to platform-specific bundle id / Android package.
        #[arg(long, env = "SMIX_APPS_CONFIG")]
        apps_config: Option<PathBuf>,
        /// Env var for yaml `${NAME}` interpolation. Repeatable:
        /// `--env A=1 --env B=2`. Wins over inherited process env
        /// (which is the fallback). Matches maestro `test -e KEY=VAL`
        /// semantics. VALUE may contain `=`.
        #[arg(long = "env", value_parser = parse_kv_pair, action = clap::ArgAction::Append)]
        env: Vec<(String, String)>,
        /// Directory for debug artifacts. Currently writes
        /// `<dir>/run-summary.json` at exit. Per-step files + on-fail
        /// screenshots ship in a follow-up.
        #[arg(long = "debug-output")]
        debug_output: Option<PathBuf>,
        /// Verbose logging (debug-level tracing on adapter/sdk/driver
        /// crates).
        #[arg(long, default_value_t = false)]
        verbose: bool,
        /// Output format. `human` (default): unchanged. `json`: emits a
        /// single top-level JSON object on stdout at exit summarizing
        /// the run + any terminal ExpectationFailure.
        #[arg(long, value_enum, default_value_t = RunOutputFormat::Human)]
        format: RunOutputFormat,
        /// Send `App-Activate: true` header on every runner request so
        /// the iOS runner calls `.activate()` on the resolved target
        /// before each operation. Auto-recovers from cases where a
        /// briefly-foregrounded other app (Preferences / an OS preview)
        /// latched XCUITest's implicit app-under-test to the wrong
        /// bundle. Costs ~50-100ms per request; opt-in.
        #[arg(long, default_value_t = false)]
        activate: bool,
        /// Batch semantics. Default: run all listed flows sequentially,
        /// exit code = max(per-flow codes). `--fail-fast`: abort the
        /// batch after the first flow that exits non-zero.
        #[arg(long, default_value_t = false)]
        fail_fast: bool,
        /// Per-flow retry count. Default 1 = one attempt only.
        /// `--retry 2` = up to 2 attempts per flow; if the first fails
        /// and the second succeeds, the flow's exit code is that of the
        /// second.
        /// Each attempt is recorded in `~/.local/share/smix/flow-attempts.json`
        /// with status + errorClass + wallMs + any `.ips` that
        /// appeared during the attempt (attribution vs whole-batch).
        /// `smix diagnostic dump` reads that file and surfaces the
        /// attribution table under a `recent flows` section.
        #[arg(long = "retry", default_value_t = 1)]
        retry: u32,
        /// Append an implicit `expect.signal { regex }` step to the end
        /// of each flow. The `--timeout` value is used as the timeout
        /// (default 8000ms).
        #[arg(long = "await-signal")]
        await_signal: Option<String>,
        /// Prepend an implicit `expect.signal { regex, timeoutMs }`
        /// step at the START of the flow, blocking until the regex is
        /// observed in the metro log tail. Symmetric to
        /// `--await-signal`. Requires `--metro-log-url` also set.
        /// Useful when a visual/perf gate prelaunches the app and must
        /// wait for a bootstrap-ready signal before the flow starts.
        #[arg(long = "gate-signal")]
        gate_signal: Option<String>,
        /// Timeout in ms for `--gate-signal`. Default 60000. Zero
        /// disables the timeout (waits forever).
        #[arg(long = "gate-signal-timeout", default_value_t = 60_000)]
        gate_signal_timeout_ms: u64,
        /// Append an implicit `expectLogClean` step to the end of each
        /// flow. Emits an ExpectationFailure if any non-allowlisted log
        /// entry has been observed during the run (allowlist from
        /// `.smix/config.yaml` `metroLog.allowlist`).
        #[arg(long = "expect-log-clean", default_value_t = false)]
        expect_log_clean: bool,
        /// Metro log source URL, overrides `.smix/config.yaml`
        /// `metroLog.url`. Format: `ws://127.0.0.1:8081/logs` for
        /// expo/metro WebSocket, or `file:///path/to/log` for on-disk
        /// tail fallback.
        #[arg(long = "metro-log-url")]
        metro_log_url: Option<String>,
        /// Path to a fixture registry JSON file. Enables the
        /// `- fixture: <id>` yaml verb.
        #[arg(long = "fixture-registry")]
        fixture_registry: Option<PathBuf>,
        /// Type into whatever holds focus, skipping a11y-focus
        /// resolution, for `inputText` / `fill`. For RN apps whose
        /// hidden `<TextInput>` the a11y tree cannot address — the
        /// case where the default path finds nothing to tap.
        #[arg(long = "force-key-events", default_value_t = false)]
        force_key_events: bool,
        /// Disable auto-annotate on `--debug-output` fail-PNG (default:
        /// annotate with a red circle + step summary text label at the
        /// top of the screenshot). Use when downstream tooling expects
        /// raw screenshot pixels.
        #[arg(long = "no-fail-annotate", default_value_t = false)]
        no_fail_annotate: bool,
        /// Parse-only gate. Reads every listed flow yaml, resolves any
        /// `runFlow:` includes, and reports parse / include errors.
        /// Does not connect to a runner, does not need a simulator, and
        /// does not execute any step. Exit 0 on clean parse across
        /// every flow; non-zero on the first error, listing all
        /// remaining flows unparsed. Suitable for CI pre-flight.
        ///
        /// Accepts `--dry-run` as an equivalent alias (idiomatic in
        /// most CLI tools).
        #[arg(long = "check", alias = "dry-run", default_value_t = false)]
        check: bool,
    },
    /// Static maestro → smix yaml codemod. Renames verbs to smix
    /// canonical form (tapOn → tap, extendedWaitUntil → expect +
    /// timeoutMs, retry.max → retry.maxRetries, etc.) and strips
    /// deprecated arg forms. Unknown verbs are preserved verbatim with
    /// a WARN line to stderr.
    ///
    /// Modes:
    ///   smix migrate                        — read stdin, write stdout
    ///   smix migrate flow.yaml              — read file, write stdout
    ///   smix migrate --in-place a.yaml ...  — rewrite files in place
    ///
    /// Comments, copyright headers, and blank lines survive the
    /// rewrite byte-identical (the codemod is line-based; only the
    /// verb and argument-key portions of step lines are modified).
    Migrate {
        /// One or more input yaml paths. When empty, reads from stdin.
        #[arg(num_args = 0..)]
        paths: Vec<PathBuf>,
        /// Rewrite each input file in place. A parse failure on any
        /// one file leaves that file untouched; other files still get
        /// rewritten. Overall exit != 0 if any file failed. Not
        /// allowed when reading from stdin.
        #[arg(long, default_value_t = false)]
        in_place: bool,
    },
    /// Annotate a PNG with circle / arrow / text / box / line
    /// primitives. Mini-DSL per annotation:
    ///
    ///   kind ',' key:value (',' key:value)*
    ///
    /// Examples:
    ///   smix annotate in.png out.png \\
    ///     --annotate "circle,at:100_100,color:red,radius:40" \\
    ///     --annotate "arrow,from:10_10,to:200_200,color:blue" \\
    ///     --annotate "text,at:50_50,content:hello,color:green,size:24"
    ///     --font /path/to/font.ttf
    Annotate {
        /// Input PNG path.
        input: PathBuf,
        /// Output PNG path.
        output: PathBuf,
        /// One or more annotation specs (see mini-DSL above).
        #[arg(long = "annotate", num_args = 1..)]
        annotations: Vec<String>,
        /// PNG compression preset: `fast`, `balanced` (default),
        /// `aggressive`.
        #[arg(long, default_value = "balanced")]
        compression: String,
        /// TTF font path (required for text annotations).
        #[arg(long)]
        font: Option<PathBuf>,
    },
    /// Authoring subcommands. Compose yaml against a live sim:
    /// suggest selectors matching a partial spec, capture or diff
    /// a11y tree baselines for visual gates.
    Authoring {
        #[command(subcommand)]
        action: AuthoringAction,
    },
}

#[derive(Subcommand, Debug)]
enum AuthoringAction {
    /// Generate a flow (maestro yaml or rust test) from recorded IRAction
    /// JSON — the record -> generate glue. The input is the JSON any capture
    /// leg produces (iOS / Android / web), so a recording from any platform
    /// becomes a flow through the one platform-neutral generator.
    Generate {
        /// Recorded IRAction JSON file (a `Vec<IRAction>`).
        input: PathBuf,
        /// Output format.
        #[arg(long, value_enum, default_value_t = authoring::GenFormat::Maestro)]
        format: authoring::GenFormat,
        /// Output flow file.
        #[arg(long, short)]
        output: PathBuf,
        /// App / bundle id embedded in the generated flow.
        #[arg(long, default_value = "com.example")]
        app_id: String,
        /// Test fn name (rust format only).
        #[arg(long, default_value = "recorded")]
        test_fn_name: String,
    },
    /// Record a live session on a runner and generate a flow. Records for
    /// `--duration` seconds while you drive the app, then generates from the
    /// captured IRAction. Android today (its runner emits IRAction directly).
    TapRecord {
        /// Output flow file.
        #[arg(long, short)]
        output: PathBuf,
        /// Seconds to record while you interact.
        #[arg(long, default_value_t = 10)]
        duration: u64,
        /// Output format.
        #[arg(long, value_enum, default_value_t = authoring::GenFormat::Maestro)]
        format: authoring::GenFormat,
        /// Runner HTTP port (default: the device's registered port, else
        /// 28080 — the Android runner's default).
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port that
        /// device is registered on.
        #[arg(long)]
        device: Option<String>,
        /// App / bundle id embedded in the generated flow.
        #[arg(long, default_value = "com.example")]
        app_id: String,
        /// Test fn name (rust format only).
        #[arg(long, default_value = "recorded")]
        test_fn_name: String,
    },
    /// Suggest selectors matching a partial spec against the current
    /// sim state. Runs against a live runner on `--port`. Examples:
    ///   smix authoring suggest 'id: qa-*'
    ///   smix authoring suggest 'Sign In'
    Suggest {
        /// Partial selector spec.
        partial: String,
        /// Runner HTTP port. Defaults to SMIX_RUNNER_PORT env or 22087.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Capture the current a11y tree JSON to a file for baseline use.
    CaptureTree {
        /// Output path for the JSON baseline.
        output: PathBuf,
        /// Runner HTTP port.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Diff the current sim a11y tree against a baseline JSON file
    /// and report structural differences. Exit code 0 = clean,
    /// exit code 2 = diff found.
    DiffTree {
        /// Baseline a11y tree JSON path.
        baseline: PathBuf,
        /// Runner HTTP port.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
    },
    /// Read a failed flow's on-disk bundle, ask a local `claude` to
    /// propose edits, and write the amended flow. Device-free: consumes
    /// a bundle already on disk (produce it with `smix run
    /// --debug-output <dir> --format json > <dir>/failure.json`); this
    /// subcommand does not run the flow itself.
    Propose {
        /// The failed flow yaml.
        flow: PathBuf,
        /// The on-disk bundle dir (run-summary.json + failure.json + …).
        #[arg(long)]
        bundle: PathBuf,
        /// Output path for the amended flow yaml.
        #[arg(long, short)]
        output: PathBuf,
    },
    /// Session recording. Sample the a11y tree at `--interval-ms`
    /// for `--duration-secs`; write a yaml scaffold with assertVisible
    /// steps for stable-visible IDs.
    Record {
        /// Output yaml scaffold path.
        output: PathBuf,
        /// Total recording duration in seconds. Default 10.
        #[arg(long, default_value_t = 10)]
        duration_secs: u64,
        /// Sampling interval in milliseconds. Default 500.
        #[arg(long, default_value_t = 500)]
        interval_ms: u64,
        /// Runner HTTP port.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. Used here only to find the runner port
        /// that device is registered on — it does not change which
        /// simulator or app the call is dispatched to, because the
        /// port already names the runner.
        #[arg(long)]
        device: Option<String>,
        /// Bundle id to write into the recorded flow. Without it the
        /// scaffold names a placeholder, and a flow naming an app that
        /// does not exist fails at its first step — so a recording could
        /// not be run back without an edit.
        #[arg(long)]
        app_id: Option<String>,
    },
}

/// Output-format enum mirroring [`smix_adapter_maestro::OutputFormat`].
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum RunOutputFormat {
    Human,
    Json,
    /// JUnit XML output for CI test-report pipelines.
    Junit,
}

impl RunOutputFormat {
    fn to_adapter(self) -> smix_adapter_maestro::OutputFormat {
        match self {
            Self::Human => smix_adapter_maestro::OutputFormat::Human,
            Self::Json => smix_adapter_maestro::OutputFormat::Json,
            Self::Junit => smix_adapter_maestro::OutputFormat::Junit,
        }
    }
}

#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum RunPlatform {
    Ios,
    Android,
}

impl RunPlatform {
    fn to_flow(self) -> smix_adapter_maestro::FlowPlatform {
        match self {
            Self::Ios => smix_adapter_maestro::FlowPlatform::Ios,
            Self::Android => smix_adapter_maestro::FlowPlatform::Android,
        }
    }
}

#[derive(Subcommand, Debug)]
enum CapsuleAction {
    /// Bring up sim + start capture + start runner in record mode.
    Up {
        device: String,
        /// Bundle id the runner binds to. Required — `capsule up` runs
        /// `runner up`, which refuses to start without a target bundle,
        /// so a capsule without this flag could never complete.
        #[arg(long)]
        bundle: String,
        /// Foreground the app instead of relaunching it.
        ///
        /// Bringing the capsule up restarts the target app, dropping
        /// whatever screen had been navigated to — and the next flow
        /// then fails with `ELEMENT_NOT_FOUND` against a splash
        /// screen. Same meaning as `smix run --no-launch`, which has
        /// had it for longer.
        #[arg(long = "no-launch", default_value_t = false)]
        no_launch: bool,
        /// Fail instead of degrading when Simulator.app is on screen.
        ///
        /// For CI, where a window means something is wrong. On a dev
        /// machine `expo run:ios` opens Simulator.app by design, so a
        /// capsule there degrades to soft with a warning rather than
        /// refusing — a condition that is normal for a whole class of
        /// users reads as an error only once before it reads as noise.
        #[arg(long, default_value_t = false)]
        require_hard: bool,
        /// Allow the "soft capsule" fallback when the Simulator UI is
        /// open (otherwise the guard rejects the boot to avoid
        /// contention with a user-visible Simulator session).
        #[arg(long)]
        soft: bool,
        /// Skip the `/api/capture/start` request that starts the HLS
        /// capture pipeline. Set this when the flow itself invokes
        /// `simctl io recordVideo` so the two do not contend for the
        /// "Host recording is already in progress" mutex.
        #[arg(long)]
        no_capture: bool,
    },
    /// Reverse teardown: runner down + capture stop + sim shutdown.
    Down { device: String },
}

#[derive(Subcommand, Debug)]
enum RunnerAction {
    /// Start the runner on a device; blocks until /health answers.
    Up {
        device: String,
        /// Which runner to bring up. `ios` drives xcodebuild + the
        /// XCUITest runner; `android` installs the instrumentation APK,
        /// forwards the port, and `am instrument`s the Kotlin runner.
        #[arg(long, value_enum, default_value_t = RunPlatform::Ios)]
        platform: RunPlatform,
        /// Bundle id the runner binds its XCUIApplication to. iOS only,
        /// and required there: `runner up` refuses to start without one
        /// (the help used to claim a com.apple.Preferences default that
        /// the implementation rejects). On Android it is refused rather
        /// than ignored — that runner takes its target from the
        /// App-Bundle-Id header per request, not at startup.
        #[arg(long)]
        bundle: Option<String>,
        /// Explicit path to `SmixRunner.xcodeproj`. Wins over
        /// `$SMIX_RUNNER_PROJECT` env and the install-shipped default
        /// at `~/.local/share/smix/runner/`. See resolve_runner_project
        /// cascade in runner.rs.
        #[arg(long = "runner-project", env = "SMIX_RUNNER_PROJECT")]
        runner_project: Option<PathBuf>,
        /// Bind the runner to an explicit port. Priority (high → low):
        /// this flag → `.smix/sims.json` `runnerPort` field →
        /// `SMIX_RUNNER_PORT` env → 22087 default. Two sims with
        /// distinct `runnerPort` in sims.json can run their own runner
        /// concurrently without collision.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
        /// After `/health` returns 200, spawn a detached
        /// `smix runner supervise` sidecar and record its pid in
        /// `.smix/runner/state.json`. `smix runner down` cascades a
        /// SIGTERM to the sidecar before tearing down xcodebuild.
        /// Sidecar log at `.smix/runner/supervise-<UDID>.log`.
        #[arg(long = "supervise", default_value_t = false)]
        supervise: bool,
        /// Foreground the app instead of relaunching it.
        ///
        /// Bringing the runner up restarts the target app, which drops
        /// whatever screen was on it — and the next flow then fails
        /// with `ELEMENT_NOT_FOUND` against a splash screen. Same
        /// meaning as `smix run --no-launch`, which has had it for
        /// longer.
        #[arg(long = "no-launch", default_value_t = false)]
        no_launch: bool,
    },
    /// Stop the runner (SIGINT-first to avoid the crash-report dialog).
    Down {
        /// Which runner to stop. `android` needs `--device` too: adb
        /// commands must name their device, or they act on whichever
        /// one happens to be attached.
        #[arg(long, value_enum, default_value_t = RunPlatform::Ios)]
        platform: RunPlatform,
        /// Android only: the adb serial (e.g. `emulator-5554`).
        #[arg(long)]
        device: Option<String>,
    },
    /// Cycle the runner: down + up on the same device/port/bundle.
    /// Preserves the per-udid derived-data directory so the warm re-up
    /// finishes in ~3 s. Errors if no runner state.json exists — use
    /// `runner up` for a cold start.
    Cycle {
        /// Explicit path to `SmixRunner.xcodeproj`. Same cascade as
        /// `runner up` — see `resolve_runner_project`.
        #[arg(long = "runner-project", env = "SMIX_RUNNER_PROJECT")]
        runner_project: Option<PathBuf>,
    },
    /// Attach a supervisor to a running runner: tail its log and
    /// auto-`cycle` on interrupt patterns (`** TEST INTERRUPTED **` /
    /// `SchemeActionResultOperation started unexpectedly`). Foreground
    /// process; SIGINT or SIGTERM cleanly exits. Session persistence
    /// preserves client session ids across each cycle.
    Supervise {
        /// Explicit path to `SmixRunner.xcodeproj` for the cycle
        /// operation. Same cascade as `runner up`.
        #[arg(long = "runner-project", env = "SMIX_RUNNER_PROJECT")]
        runner_project: Option<PathBuf>,
    },
    /// List every session the runner currently tracks.
    /// Reads `POST /session/list`. Useful for post-cycle diagnostics.
    ListSessions,
    /// Extract the CLI's embedded Swift runner sources
    /// into `~/.local/share/smix/runner/`. Normally auto-invoked by
    /// `smix runner up` when the on-disk `.smix-runner-version` file
    /// is missing or does not match the CLI version; this verb makes
    /// the operation explicit for troubleshooting or first-time setup
    /// on an air-gapped machine. Backs up any pre-existing runner tree
    /// to `~/.local/share/smix/runner.bak-<ts>/` before writing.
    Install {
        /// Destination directory. Defaults to
        /// `$XDG_DATA_HOME/smix/runner/` (falling back to
        /// `~/.local/share/smix/runner/`).
        #[arg(long)]
        path: Option<PathBuf>,
        /// Extract even when the version file already matches the CLI
        /// version. Useful when the on-disk tree has been manually
        /// edited and you want a clean baseline.
        #[arg(long, default_value_t = false)]
        force: bool,
    },
}

#[derive(Subcommand, Debug)]
enum SimAction {
    /// List available simulators (Rust port: `xcrun simctl list devices -j`).
    List {
        /// Output as JSON instead of human-readable table.
        #[arg(long)]
        json: bool,
    },
    /// Print the UDID a device ref resolves to.
    Resolve { device: String },
    /// Record a simulator in `.smix/sims.json` under an alias, creating
    /// the registry when absent. This is the bootstrap: alias-form
    /// device refs fail on a fresh checkout until a registry exists.
    /// Device name / runtime / device type are read from `simctl list`,
    /// so only the UDID and alias are needed.
    Register {
        alias: String,
        #[arg(long)]
        udid: String,
        /// BCP 47 locale to enforce at boot (e.g. `ja-JP`). Optional.
        #[arg(long)]
        locale: Option<String>,
        /// Dedicated runner port for this sim. Optional.
        #[arg(long = "runner-port")]
        runner_port: Option<u16>,
    },
    /// Boot a simulator.
    Boot { device: String },
    /// Shutdown a simulator.
    Shutdown { device: String },
    /// Erase a simulator's data.
    Erase { device: String },
    /// Take a screenshot (PNG). Pass `-` to write raw PNG to stdout.
    Screenshot { device: String, out: PathBuf },
    /// Launch an app by bundle id; prints the pid. Accepts repeatable
    /// `--child-env KEY=VAL` flags to inject `SIMCTL_CHILD_KEY=VAL` envp
    /// onto the simctl process — the launched app reads it back via
    /// `ProcessInfo().environment["KEY"]`. Used to prelaunch an app
    /// before any `openLink` so iOS treats the URL as in-app routing
    /// (sidesteps the SpringBoard "Open in '`<App>`'?" dialog).
    Launch {
        device: String,
        bundle_id: String,
        /// `--child-env KEY=VAL` (repeatable). KEY is the bare name the
        /// app reads; the `SIMCTL_CHILD_` prefix is added automatically.
        /// Already-prefixed keys pass through unchanged.
        #[arg(long = "child-env", value_parser = parse_kv_pair, action = clap::ArgAction::Append)]
        child_env: Vec<(String, String)>,
        /// Process-level launch arguments forwarded after a `--`
        /// separator to `xcrun simctl launch ... -- <args>`. Mirrors
        /// maestro yaml `launchApp.arguments`. Conventionally an
        /// alternating `-key value` shape, but treated as opaque argv.
        #[arg(last = true)]
        launch_args: Vec<String>,
    },
    /// Terminate an app by bundle id.
    Terminate { device: String, bundle_id: String },
    /// Install an .app bundle.
    Install { device: String, app_path: PathBuf },
    /// Uninstall an app by bundle id.
    Uninstall { device: String, bundle_id: String },
    /// Open a URL on the simulator.
    Openurl { device: String, url: String },
    /// Set simulator UI appearance (light / dark).
    Appearance {
        device: String,
        #[arg(value_parser = parse_appearance)]
        mode: Appearance,
    },
    /// Reset keychain on a simulator.
    KeychainReset { device: String },
    /// Set the sim's locale (`AppleLanguages` + `AppleLocale`
    /// NSGlobalDomain). By default writes the values but
    /// does NOT reboot; running apps cache locale at process-start so
    /// they'll continue in the old locale until relaunched. Pass
    /// `--reboot` to have smix shut the sim down and boot it back up
    /// so the next app launch picks up the new locale cleanly.
    ///
    /// Note: `.smix/sims.json` `locale:` field is applied at *next
    /// sim boot* (by `smix runner up` / `smix sim boot`); this command
    /// covers the "sim is already booted, want to change locale now"
    /// gap.
    Locale {
        device: String,
        /// BCP-47 tag (e.g. `en`, `en-US`, `ja`, `zh-Hans`).
        lang: String,
        /// Shut the sim down and boot it back up after writing the
        /// locale, so the change is visible to apps launched next.
        #[arg(long)]
        reboot: bool,
    },
    /// Passthrough for simctl subcommands smix has not wrapped yet:
    /// `smix sim exec <DEVICE> <VERB> [ARGS...]` runs
    /// `xcrun simctl <VERB> <UDID> [ARGS...]` with simctl's original
    /// argument shape. If any arg is the literal `{udid}`, the resolved
    /// UDID substitutes there instead of being injected after the verb.
    Exec {
        device: String,
        verb: String,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

/// Parse `KEY=VAL` clap value. Empty KEY or missing `=` is rejected.
/// KEY is taken verbatim (caller / [`smix_simctl::compose_child_env`]
/// adds `SIMCTL_CHILD_` prefix); VAL may contain `=` characters (only
/// the first `=` splits).
fn parse_kv_pair(s: &str) -> Result<(String, String), String> {
    let (k, v) = s
        .split_once('=')
        .ok_or_else(|| format!("expected `KEY=VALUE`, got `{s}`"))?;
    if k.is_empty() {
        return Err(format!("empty KEY in `{s}`"));
    }
    Ok((k.to_string(), v.to_string()))
}

fn parse_appearance(s: &str) -> Result<Appearance, String> {
    match s.to_ascii_lowercase().as_str() {
        "light" => Ok(Appearance::Light),
        "dark" => Ok(Appearance::Dark),
        other => Err(format!("expected 'light' or 'dark', got {:?}", other)),
    }
}

/// Resolve a device ref to a UDID. Explicit UDID short-circuits without
/// touching the registry; aliases need a readable .smix/sims.json (env
/// SMIX_SIMS_JSON overrides upward discovery from cwd).
fn resolve_device(device_ref: &str) -> Result<String, CliError> {
    if registry::is_udid(device_ref) {
        return Ok(device_ref.to_ascii_uppercase());
    }
    let path = registry_path()?;
    Ok(SimRegistry::load(&path)?.resolve(device_ref)?)
}

/// Resolve the path to `.smix/sims.json` (env override or upward
/// discovery from cwd). Extracted from [`resolve_device`] so the caller
/// can also load a [`SimRegistry`] to read sim spec fields like `locale`.
/// Returns `Ok(None)` only when an explicit UDID was given upstream and
/// the registry is genuinely absent — the caller passes the UDID through
/// without spec lookup.
fn registry_path() -> Result<PathBuf, CliError> {
    if let Some(p) = std::env::var_os("SMIX_SIMS_JSON") {
        return Ok(PathBuf::from(p));
    }
    let cwd = std::env::current_dir()
        .map_err(|e| CliError::Other(format!("cannot determine cwd: {e}")))?;
    SimRegistry::discover(&cwd).ok_or_else(|| {
        CliError::Other(format!(
            "no .smix registry was found upward from {} — pass an explicit \
             UDID or set SMIX_SIMS_JSON",
            cwd.display()
        ))
    })
}

/// Best-effort `RegisteredSim` lookup. Returns `None` (not an error)
/// when the device was given as a raw UDID with no registry entry for
/// it — `smix sim boot <unregistered-udid>` is legitimate.
fn lookup_registered(device_ref: &str) -> Option<smix_simctl::registry::RegisteredSim> {
    let path = registry_path().ok()?;
    let reg = SimRegistry::load(&path).ok()?;
    reg.lookup(device_ref).cloned()
}

#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    match run(cli).await {
        Ok(code) => code,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(1)
        }
    }
}

async fn run(cli: Cli) -> Result<ExitCode, CliError> {
    // Enable subprocess-ring persistence so
    // `/diagnostic/dump` payloads survive supervisor cycles that used
    // to wipe the in-memory ring. Path is $XDG_DATA_HOME/smix or
    // ~/.local/share/smix; best-effort — a missing $HOME is a no-op.
    if let Some(dir) = std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
    {
        // One store directory for all three. They used to be three JSON
        // files here; passing the old filenames still worked (the store
        // resolves a `.json` path to its parent) but it read as though
        // smix still wrote them.
        let diag_root = dir.join("smix");
        smix_simctl::set_subprocess_ring_persist_path(diag_root.clone());
        // resetAppData counter persistence so
        // `smix diagnostic dump` (later, separate process) sees the
        // count from any prior `smix run` invocations.
        smix_simctl::set_reset_app_data_counters_persist_path(diag_root.clone());
        // Flow-attempts persistence for retry
        // attribution. `smix run` records per-flow attempts here,
        // `smix diagnostic dump` reads back for the `recent flows`
        // section.
        smix_simctl::set_flow_attempts_persist_path(diag_root);
    }

    let simctl = SimctlClient::new();
    match cli.cmd {
        Cmd::Init { alias, device, app } => {
            cmd_init(&simctl, &alias, device.as_deref(), app.as_deref()).await?
        }
        Cmd::Doctor { json } => cmd_doctor(&simctl, json).await?,
        Cmd::Bench {
            update_baseline,
            current_file,
            baseline_file,
        } => {
            let default_baseline = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("bench")
                .join("baseline.json");
            let baseline_path = baseline_file.unwrap_or(default_baseline);
            bench::run(update_baseline, current_file.as_deref(), &baseline_path)
                .map_err(CliError::Other)?;
        }
        Cmd::Diagnostic { action } => cmd_diagnostic(action).await?,
        Cmd::Sim { action } => match action {
            SimAction::List { json } => cmd_sim_list(&simctl, json).await?,
            SimAction::Resolve { device } => {
                println!("{}", resolve_device(&device)?);
            }
            SimAction::Register {
                alias,
                udid,
                locale,
                runner_port,
            } => {
                let udid = udid.to_ascii_uppercase();
                if !registry::is_udid(&udid) {
                    return Err(CliError::Other(format!(
                        "--udid {udid:?} is not UDID-form (8-4-4-4-12 hex); \
                         find it via `smix sim list`"
                    )));
                }
                let devices = simctl.list_devices().await?;
                let device = devices
                    .iter()
                    .find(|d| d.udid.eq_ignore_ascii_case(&udid))
                    .ok_or_else(|| {
                        CliError::Other(format!(
                            "simctl knows no device {udid} — check `smix sim list`"
                        ))
                    })?;
                // Env override, discovered registry, else a fresh
                // `.smix/sims.json` in cwd — register is the one verb
                // that must work before the file exists.
                let path = registry_path().unwrap_or_else(|_| PathBuf::from(".smix/sims.json"));
                let outcome = SimRegistry::register(
                    &path,
                    &alias,
                    smix_simctl::registry::RegisteredSim {
                        device_name: device.name.clone(),
                        udid: device.udid.to_ascii_uppercase(),
                        runtime: device.runtime_identifier.clone(),
                        device_type: device.device_type_identifier.clone(),
                        locale,
                        runner_port,
                    },
                )?;
                let verb = match outcome {
                    smix_simctl::registry::RegisterOutcome::Added => "registered",
                    smix_simctl::registry::RegisterOutcome::Updated => "updated",
                };
                // The store, not `sims.json` — the file this used to
                // name is no longer written, and pointing a user at it
                // sends them to look at stale bytes or nothing at all.
                println!(
                    "{verb}: {alias}{} ({}) in {}",
                    device.udid,
                    device.name,
                    smix_simctl::registry::store_dir(&path).display()
                );
            }
            SimAction::Boot { device } => {
                let udid = resolve_device(&device)?;
                simctl.boot(&udid).await?;
                println!("booted: {udid}");
                // Registry-driven locale enforcement. When the SimEntry
                // has a `locale` field, ensure the sim's
                // NSGlobalDomain AppleLanguages first entry matches; if
                // it doesn't, write the prefs + shutdown+boot once. This
                // covers the "sim defaulted to the wrong language" case
                // where an app was built for a locale different from the
                // sim's persisted default.
                if let Some(spec) = lookup_registered(&device)
                    && let Some(desired) = spec.locale.as_ref()
                {
                    let current = simctl.current_locale(&udid).await.ok().flatten();
                    if current.as_deref() == Some(desired.as_str()) {
                        println!("locale: {desired} ok");
                    } else {
                        eprintln!(
                            "locale: enforcing {desired} (current {})",
                            current.as_deref().unwrap_or("<unset>")
                        );
                        simctl.set_locale(&udid, desired).await?;
                        // Defaults apply at process start — must reboot.
                        simctl.shutdown(&udid).await?;
                        simctl
                            .boot_and_wait(&udid, std::time::Duration::from_secs(60))
                            .await?;
                        println!("locale: {desired} enforced + sim re-booted");
                    }
                }
            }
            SimAction::Shutdown { device } => {
                let udid = resolve_device(&device)?;
                simctl.shutdown(&udid).await?;
                println!("shutdown: {udid}");
            }
            SimAction::Erase { device } => {
                let udid = resolve_device(&device)?;
                simctl.erase(&udid).await?;
                println!("erased: {udid}");
            }
            SimAction::Screenshot { device, out } => {
                let udid = resolve_device(&device)?;
                let png = simctl.screenshot(&udid).await?;
                if out.as_os_str() == "-" {
                    use std::io::Write;
                    std::io::stdout()
                        .write_all(&png)
                        .map_err(|e| CliError::Other(format!("write stdout: {e}")))?;
                } else {
                    std::fs::write(&out, &png)
                        .map_err(|e| CliError::Other(format!("write {}: {e}", out.display())))?;
                    println!(
                        "screenshot: {udid}{} ({} bytes)",
                        out.display(),
                        png.len()
                    );
                }
            }
            SimAction::Launch {
                device,
                bundle_id,
                child_env,
                launch_args,
            } => {
                let udid = resolve_device(&device)?;
                let pairs: Vec<(&str, &str)> = child_env
                    .iter()
                    .map(|(k, v)| (k.as_str(), v.as_str()))
                    .collect();
                let LaunchResult { pid } = simctl
                    .launch_with_args_and_env(&udid, &bundle_id, &launch_args, &pairs)
                    .await?;
                println!("launched: {bundle_id} on {udid} (pid {pid})");
            }
            SimAction::Terminate { device, bundle_id } => {
                let udid = resolve_device(&device)?;
                simctl.terminate(&udid, &bundle_id).await?;
                println!("terminated: {bundle_id} on {udid}");
            }
            SimAction::Install { device, app_path } => {
                let udid = resolve_device(&device)?;
                simctl
                    .install(&udid, &app_path.display().to_string())
                    .await?;
                println!("installed: {} on {udid}", app_path.display());
            }
            SimAction::Uninstall { device, bundle_id } => {
                let udid = resolve_device(&device)?;
                simctl.uninstall(&udid, &bundle_id).await?;
                println!("uninstalled: {bundle_id} on {udid}");
            }
            SimAction::Openurl { device, url } => {
                let udid = resolve_device(&device)?;
                simctl.open_url(&udid, &url).await?;
                println!("opened: {url} on {udid}");
            }
            SimAction::Appearance { device, mode } => {
                let udid = resolve_device(&device)?;
                simctl.set_appearance(&udid, mode).await?;
                println!("appearance: {udid}{}", mode.as_str());
            }
            SimAction::KeychainReset { device } => {
                let udid = resolve_device(&device)?;
                simctl.keychain_reset(&udid).await?;
                println!("keychain reset: {udid}");
            }
            SimAction::Locale {
                device,
                lang,
                reboot,
            } => {
                let udid = resolve_device(&device)?;
                // Read current locale first — no-op if already desired.
                let current = simctl.current_locale(&udid).await.ok().flatten();
                if current.as_deref() == Some(lang.as_str()) {
                    println!("locale already: {lang}");
                    return Ok(ExitCode::SUCCESS);
                }
                simctl.set_locale(&udid, &lang).await?;
                if reboot {
                    println!("locale: written {lang} — rebooting sim to apply");
                    simctl.shutdown(&udid).await?;
                    simctl.boot(&udid).await?;
                    println!("locale: {lang} enforced (sim rebooted)");
                } else {
                    println!(
                        "locale: written {lang}\n\
                         note: running apps cache locale at process-start — \
                         restart the target app, or re-run with `--reboot` to \
                         cycle the sim so subsequent launches see the new locale."
                    );
                }
            }
            SimAction::Exec { device, verb, args } => {
                return cmd_sim_exec(&device, &verb, &args).await;
            }
        },
        Cmd::Runner { action } => {
            let root = smix_workspace_root()?;
            match action {
                RunnerAction::Up {
                    device,
                    platform,
                    bundle,
                    runner_project,
                    runner_port: port_flag,
                    supervise,
                    no_launch,
                } => {
                    if platform == RunPlatform::Android {
                        reject_ios_only_up_flags(
                            bundle.is_some(),
                            runner_project.is_some(),
                            supervise,
                        )
                        .map_err(CliError::Other)?;
                        let port = port_flag.unwrap_or(runner_android::DEFAULT_ANDROID_PORT);
                        // The adb serial IS the device id — there is no
                        // registry indirection on this path.
                        runner_android::up(&root, &device, port, 180).map_err(CliError::Other)?;
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    // Port priority chain:
                    //   1. `--runner-port` flag / SMIX_RUNNER_PORT env
                    //   2. `.smix/sims.json` `runnerPort` field for this alias
                    //   3. 22087 default (CLI convention)
                    let sims_port = lookup_registered(&device).and_then(|s| s.runner_port);
                    let port = port_flag.or(sims_port).unwrap_or(22087);
                    let udid = resolve_device(&device)?;
                    // Bare `smix runner up` defaults to record_enabled=false;
                    // the capsule path (`capsule::up`) overrides to true
                    // via TEST_RUNNER_SMIX_RECORD_ENABLED=1.
                    smix_capsule::runner::up(
                        &root,
                        &udid,
                        port,
                        bundle.as_deref(),
                        runner_project.as_deref(),
                        smix_capsule::runner::UpOptions {
                            supervise,
                            attach_without_relaunch: no_launch,
                            ..Default::default()
                        },
                    )
                    .map_err(CliError::Other)?;
                }
                RunnerAction::Down { platform, device } => {
                    if platform == RunPlatform::Android {
                        let serial = device.ok_or_else(|| {
                            CliError::Other(
                                "runner down --platform android needs --device \
                                 <adb-serial>: an adb command without one acts on \
                                 whichever device is attached"
                                    .to_string(),
                            )
                        })?;
                        let port = std::env::var("SMIX_RUNNER_PORT")
                            .ok()
                            .and_then(|p| p.parse().ok())
                            .unwrap_or(runner_android::DEFAULT_ANDROID_PORT);
                        runner_android::down(&root, &serial, port).map_err(CliError::Other)?;
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    let port = runner_port();
                    smix_capsule::runner::down(&root, port).map_err(CliError::Other)?;
                }
                RunnerAction::Cycle { runner_project } => {
                    let port = runner_port();
                    smix_capsule::runner::cycle(&root, port, runner_project.as_deref())
                        .map_err(CliError::Other)?;
                }
                RunnerAction::Supervise { runner_project } => {
                    smix_capsule::runner::supervise(&root, runner_project.as_deref())
                        .map_err(CliError::Other)?;
                }
                RunnerAction::ListSessions => {
                    let port = runner_port();
                    let client = smix_runner_client::HttpRunnerClient::new(port);
                    // `run` is already inside `#[tokio::main]`; a second
                    // runtime here panics with "Cannot start a runtime
                    // from within a runtime" on every call.
                    let resp = client
                        .list_sessions()
                        .await
                        .map_err(|e| CliError::Other(format!("/session/list: {e}")))?;
                    if resp.sessions.is_empty() {
                        println!("(no open sessions)");
                    } else {
                        println!(
                            "{:<38} {:<40} openedAtMs        lastActivatedAtMs",
                            "sessionId", "bundleId"
                        );
                        for s in &resp.sessions {
                            println!(
                                "{:<38} {:<40} {:<17} {}",
                                s.session_id, s.bundle_id, s.opened_at_ms, s.last_activated_at_ms,
                            );
                        }
                    }
                }
                RunnerAction::Install { path, force } => {
                    let target = path.unwrap_or_else(|| {
                        smix_capsule::runner::installed_runner_dir()
                            .unwrap_or_else(|| PathBuf::from("~/.local/share/smix/runner"))
                    });
                    if !force {
                        // Delegate to the same auto-sync used inside
                        // `runner up`. Idempotent when already current.
                        match smix_capsule::runner::ensure_installed_runner_synced(&target) {
                            Ok(smix_capsule::runner::SyncOutcome::AlreadyCurrent) => {
                                println!(
                                    "runner install: already at v{} — nothing to do (pass --force to re-extract).",
                                    smix_runner_sources::SOURCES_VERSION
                                );
                            }
                            Ok(smix_capsule::runner::SyncOutcome::Extracted {
                                previous_version,
                                ..
                            }) => {
                                let from = previous_version.as_deref().unwrap_or("<none>");
                                println!(
                                    "runner install: extracted v{} into {} (was {}).",
                                    smix_runner_sources::SOURCES_VERSION,
                                    target.display(),
                                    from
                                );
                            }
                            Err(e) => {
                                return Err(CliError::Other(format!(
                                    "runner install: sync failed at {}: {e}",
                                    target.display()
                                )));
                            }
                        }
                    } else {
                        // Force path: unconditional extract with backup.
                        match smix_runner_sources::extract_to(&target, true) {
                            Ok(report) => {
                                let backup_note = report
                                    .backup
                                    .as_ref()
                                    .map(|b| {
                                        format!(" (previous tree backed up to {})", b.display())
                                    })
                                    .unwrap_or_default();
                                // Said out loud rather than done quietly:
                                // deleting a directory the user never
                                // asked about should not be something
                                // they discover from `du`.
                                let pruned_note = if report.pruned_backups.is_empty() {
                                    String::new()
                                } else {
                                    format!(
                                        " Removed {} older backup tree(s), keeping the newest {}.",
                                        report.pruned_backups.len(),
                                        smix_runner_sources::BACKUPS_KEPT
                                    )
                                };
                                println!(
                                    "runner install: extracted {} files at v{} into {}{}.{}",
                                    report.file_count,
                                    report.version_written,
                                    target.display(),
                                    backup_note,
                                    pruned_note
                                );
                            }
                            Err(e) => {
                                return Err(CliError::Other(format!(
                                    "runner install --force: {e}"
                                )));
                            }
                        }
                    }
                }
            }
        }
        Cmd::Down => {
            let root = smix_workspace_root()?;
            down::run(&root, runner_port())
                .await
                .map_err(CliError::Other)?;
        }
        Cmd::Capsule { action } => {
            let root = smix_workspace_root()?;
            let port = runner_port();
            let capture_endpoint = std::env::var("SMIX_CAPTURE_ENDPOINT")
                .unwrap_or_else(|_| "http://127.0.0.1:8787".to_string());
            match action {
                CapsuleAction::Up {
                    device,
                    bundle,
                    soft,
                    require_hard,
                    no_capture,
                    no_launch,
                } => {
                    let udid = resolve_device(&device)?;
                    capsule::up(capsule::UpOptions {
                        root: &root,
                        udid: &udid,
                        runner_port: port,
                        capture_endpoint: &capture_endpoint,
                        bundle: Some(&bundle),
                        soft,
                        require_hard,
                        no_capture,
                        no_launch,
                    })
                    .await
                    .map_err(CliError::Other)?;
                }
                CapsuleAction::Down { device } => {
                    let udid = resolve_device(&device)?;
                    capsule::down(&root, &udid).await.map_err(CliError::Other)?;
                }
            }
        }
        Cmd::Tap {
            selector,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_tap(selector, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Find {
            selector,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_find(selector, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::WaitFor {
            selector,
            timeout,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_wait_for(selector, timeout, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Fill {
            selector,
            text,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_fill(selector, text, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::PressKey { key, port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_press_key(key, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Scroll {
            selector,
            direction,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_scroll(selector, direction, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::HideKeyboard { port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_hide_keyboard(p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Tree { json, port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_tree(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Describe { json, port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_describe(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::SystemPopups { json, port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_system_popups(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::SystemPopupAction {
            popup_id,
            button_id,
            port,
            device,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            act::cmd_system_popup_action(&popup_id, &button_id, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::RunScript { path, port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            script::cmd_run_script(&path, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Run {
            flows,
            device,
            also_device,
            parallel,
            nodes,
            bundle_id,
            animations,
            runner_port,
            no_launch,
            platform,
            apps_config,
            env,
            debug_output,
            verbose,
            format,
            activate,
            fail_fast,
            retry,
            await_signal,
            gate_signal,
            gate_signal_timeout_ms,
            expect_log_clean,
            metro_log_url,
            fixture_registry,
            force_key_events,
            no_fail_annotate,
            check,
        } => {
            // v2 break #3: resolve the four behavior switches once, here
            // at the CLI edge. Priority: `.smix/config.yaml switches.*` >
            // `SMIX_*` env > default(false). This resolver is the ONLY
            // place these four env names carry weight on the `smix run` /
            // `--check` path; reading one (env source) earns a named
            // deprecation warn. The resolved values are injected into the
            // parser (via FlowArgs → thread-local override) and the sdk
            // (via FlowArgs → App builder) — parser/sdk keep their own env
            // reads solely as the non-CLI fallback.
            let switches = smix_capsule::runner::load_switches();
            let sw_auto_ocr = smix_capsule::runner::resolve_switch(
                switches.auto_ocr_fallback,
                "SMIX_AUTO_OCR_FALLBACK",
            );
            let sw_ai_assertions = smix_capsule::runner::resolve_switch(
                switches.enable_ai_assertions,
                "SMIX_ENABLE_AI_ASSERTIONS",
            );
            let sw_assert_no_autorecord = smix_capsule::runner::resolve_switch(
                switches.assert_screenshot_no_autorecord,
                "SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD",
            );
            let sw_launch_reinstall = smix_capsule::runner::resolve_switch(
                switches.launch_fresh_force_reinstall,
                "SMIX_LAUNCH_FRESH_FORCE_REINSTALL",
            );
            let warn_if_env = |r: &smix_capsule::runner::ResolvedSwitch,
                               env_name: &str,
                               key: &str| {
                if r.source == smix_capsule::runner::SwitchSource::Env {
                    eprintln!(
                        "warning: {env_name} is deprecated; use .smix/config.yaml switches.{key}"
                    );
                }
            };
            if check {
                // `--check` only parses, so only the two parse-time
                // switches matter here. Warn for those, then pin them on
                // the parser override seam right before parse_flow_yaml —
                // synchronous, no tokio, so no thread-migration concern.
                warn_if_env(&sw_auto_ocr, "SMIX_AUTO_OCR_FALLBACK", "autoOcrFallback");
                warn_if_env(
                    &sw_ai_assertions,
                    "SMIX_ENABLE_AI_ASSERTIONS",
                    "enableAiAssertions",
                );
                smix_adapter_maestro::set_auto_ocr_fallback_override(Some(sw_auto_ocr.value));
                smix_adapter_maestro::set_ai_assertions_override(Some(sw_ai_assertions.value));
                // Invoked via either `--check` or its `--dry-run`
                // alias; render prefix neutrally so the output reads
                // correctly for both.
                let mut fail = 0u8;
                let mut step_total: usize = 0;
                for flow_path in &flows {
                    match std::fs::read_to_string(flow_path) {
                        Ok(yaml) => match smix_adapter_maestro::parse_flow_yaml(&yaml) {
                            Ok(flow) => {
                                let n = flow.steps.len();
                                step_total += n;
                                eprintln!(
                                    "smix run: parse OK  {} ({n} step{})",
                                    flow_path.display(),
                                    if n == 1 { "" } else { "s" },
                                );
                            }
                            Err(e) => {
                                eprintln!("smix run: parse FAIL {}: {e}", flow_path.display());
                                fail = 2;
                            }
                        },
                        Err(e) => {
                            eprintln!("smix run: parse FAIL {}: read: {e}", flow_path.display());
                            fail = 2;
                        }
                    }
                }
                if fail == 0 {
                    eprintln!(
                        "smix run: parse OK — {} flow{}, {step_total} total step{}",
                        flows.len(),
                        if flows.len() == 1 { "" } else { "s" },
                        if step_total == 1 { "" } else { "s" },
                    );
                }
                return Ok(std::process::ExitCode::from(fail));
            }

            // Federation lane: shard the flows across the nodes in a
            // roster yaml. Devices come from the roster (`--nodes`
            // conflicts with `--device`/`--also-device`/`--parallel`),
            // the leaves run remotely under `--format json`, and the
            // merged report is one JSON document on stdout — exit is
            // the worst of nodes. Sync/rebuild never happen here: the
            // readiness gate only judges (repair is the sync script's
            // job), and a red gate fast-fails before anything fans out.
            if let Some(nodes_path) = &nodes {
                let yaml = std::fs::read_to_string(nodes_path)
                    .map_err(|e| CliError::Other(format!("read {}: {e}", nodes_path.display())))?;
                let node_specs =
                    federation::parse_nodes(&yaml).map_err(|e| CliError::Other(e.to_string()))?;
                // Flow paths are repo-relative and must exist on every
                // node at the same path; the scheduler repo is the
                // authority, so a flow missing here fails fast before
                // any ssh is dialed.
                for flow in &flows {
                    if !flow.is_file() {
                        return Err(CliError::Other(format!(
                            "flow not found locally: {} — flow paths are repo-relative \
                             and must exist on every node (scheduler repo is the authority)",
                            flow.display()
                        )));
                    }
                }
                // Same CLI-sourced passthrough set as the parallel lane,
                // except `--debug-output`: the remote leaves stage their
                // artifacts under the fixed per-repo dir and the user's
                // directory is the local rsync-pull target instead.
                // Every token is shell-quoted — passthrough rides the
                // remote command string verbatim.
                let mut passthrough: Vec<String> = Vec::new();
                if let Some(b) = &bundle_id {
                    passthrough.push("--bundle-id".into());
                    passthrough.push(b.clone());
                }
                if no_launch {
                    passthrough.push("--no-launch".into());
                }
                if animations {
                    passthrough.push("--animations".into());
                }
                if activate {
                    passthrough.push("--activate".into());
                }
                if verbose {
                    passthrough.push("--verbose".into());
                }
                if fail_fast {
                    passthrough.push("--fail-fast".into());
                }
                if retry != 1 {
                    passthrough.push("--retry".into());
                    passthrough.push(retry.to_string());
                }
                passthrough.push("--platform".into());
                passthrough.push(
                    match platform {
                        RunPlatform::Ios => "ios",
                        RunPlatform::Android => "android",
                    }
                    .into(),
                );
                if let Some(a) = &apps_config {
                    passthrough.push("--apps-config".into());
                    passthrough.push(a.display().to_string());
                }
                if debug_output.is_some() {
                    passthrough.push("--debug-output".into());
                    passthrough.push(federation::FED_ARTIFACT_DIR.into());
                }
                for (k, v) in &env {
                    passthrough.push("--env".into());
                    passthrough.push(format!("{k}={v}"));
                }
                let passthrough: Vec<String> = passthrough
                    .iter()
                    .map(|t| federation::shell_quote(t))
                    .collect();
                let flow_strs: Vec<String> =
                    flows.iter().map(|p| p.display().to_string()).collect();
                let slots = federation::expand_slots(&node_specs);
                let assignments = federation::assign_flows(flow_strs.len(), &slots);
                let merged = federation::run_federation(
                    &node_specs,
                    &assignments,
                    &flow_strs,
                    &passthrough,
                    debug_output.as_deref(),
                )
                .map_err(|e| CliError::Other(e.to_string()))?;
                let doc = serde_json::to_string(&merged)
                    .map_err(|e| CliError::Other(format!("serialize merged report: {e}")))?;
                println!("{doc}");
                return Ok(std::process::ExitCode::from(merged.aggregate_exit));
            }

            // Parallel multi-sim. Shard the flows across `--device` +
            // `--also-device`, each shard a child `smix run` pinned to
            // one sim — so a shard reuses the sequential single-sim path
            // verbatim rather than re-implementing it concurrently. Only
            // when >1 sim is actually in play; `--parallel 1` (default)
            // or a single device falls through to the path below,
            // byte-identical.
            let all_devices: Vec<String> = device
                .iter()
                .cloned()
                .chain(also_device.iter().cloned())
                .collect();
            let sim_count = parallel::effective_sim_count(parallel, all_devices.len());
            if sim_count > 1 {
                let devices = &all_devices[..sim_count];
                let flow_strs: Vec<String> =
                    flows.iter().map(|p| p.display().to_string()).collect();
                let buckets = parallel::shard_flows(flow_strs.len(), sim_count);
                let shards: Vec<(String, Vec<String>)> = buckets
                    .iter()
                    .enumerate()
                    .map(|(i, idxs)| {
                        (
                            devices[i].clone(),
                            idxs.iter().map(|&j| flow_strs[j].clone()).collect(),
                        )
                    })
                    .collect();
                // CLI-sourced flags a child needs; behaviour switches and
                // the flow's own appId are inherited via config/env and
                // yaml. runner_port is per-sim (skipped → each child
                // resolves its own); await/gate signals are batch
                // coordination, not per-shard; --parallel/--also-device
                // never recurse.
                let mut passthrough: Vec<String> = Vec::new();
                if let Some(b) = &bundle_id {
                    passthrough.push("--bundle-id".into());
                    passthrough.push(b.clone());
                }
                if no_launch {
                    passthrough.push("--no-launch".into());
                }
                if animations {
                    passthrough.push("--animations".into());
                }
                if activate {
                    passthrough.push("--activate".into());
                }
                if verbose {
                    passthrough.push("--verbose".into());
                }
                if fail_fast {
                    passthrough.push("--fail-fast".into());
                }
                if retry != 1 {
                    passthrough.push("--retry".into());
                    passthrough.push(retry.to_string());
                }
                passthrough.push("--platform".into());
                passthrough.push(
                    match platform {
                        RunPlatform::Ios => "ios",
                        RunPlatform::Android => "android",
                    }
                    .into(),
                );
                if let Some(a) = &apps_config {
                    passthrough.push("--apps-config".into());
                    passthrough.push(a.display().to_string());
                }
                if let Some(d) = &debug_output {
                    passthrough.push("--debug-output".into());
                    passthrough.push(d.display().to_string());
                }
                for (k, v) in &env {
                    passthrough.push("--env".into());
                    passthrough.push(format!("{k}={v}"));
                }
                let exe = std::env::current_exe()
                    .map_err(|e| CliError::Other(format!("cannot find smix binary: {e}")))?;
                let code = parallel::run_parallel(&exe, &shards, &passthrough);
                return Ok(std::process::ExitCode::from(code));
            }

            // The verbose flag sets SMIX_LOG=debug for this process
            // only. tracing_subscriber (initialized in whichever binary
            // set it up) will pick it up.
            if verbose && std::env::var_os("SMIX_LOG").is_none() {
                // SAFETY: process is single-threaded here (before any
                // adapter/sdk async setup). setting env is safe.
                unsafe { std::env::set_var("SMIX_LOG", "debug") };
            }
            // Resolve device alias if registry has it; else pass raw.
            let udid = device
                .as_deref()
                .map(|d| resolve_device(d).unwrap_or_else(|_| d.to_string()));
            // No placeholder default: run_flow resolves the app from the
            // flow's own appId when the flag is absent. The literal
            // com.example.app default here once made the quickstart form
            // undriveable. `attribution_bundle` below is best-effort for
            // .ips crash attribution only.
            let bundle = bundle_id.clone();
            // Same priority chain as `runner up`: flag/env → the
            // registry's per-sim runnerPort → 22087. `smix run` used to
            // skip the registry, so a sim registered on a dedicated port
            // got its runner bound there and then dialed on 22087.
            let port = run_port(runner_port, || {
                device
                    .as_deref()
                    .and_then(lookup_registered)
                    .and_then(|sim| sim.runner_port)
            });
            let plat = platform.to_flow();
            let out_fmt = format.to_adapter();
            // The run path consumes all four switches. Warn once for any
            // sourced from a deprecated env var, then inject Some(value)
            // into every flow's FlowArgs below.
            warn_if_env(&sw_auto_ocr, "SMIX_AUTO_OCR_FALLBACK", "autoOcrFallback");
            warn_if_env(
                &sw_ai_assertions,
                "SMIX_ENABLE_AI_ASSERTIONS",
                "enableAiAssertions",
            );
            warn_if_env(
                &sw_assert_no_autorecord,
                "SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD",
                "assertScreenshotNoAutorecord",
            );
            warn_if_env(
                &sw_launch_reinstall,
                "SMIX_LAUNCH_FRESH_FORCE_REINSTALL",
                "launchFreshForceReinstall",
            );

            // Batch invocation. When N flows are listed, iterate;
            // exit = max(per-flow codes). Per-flow debug-output subdir
            // keyed by flow basename.
            let multi_flow = flows.len() > 1;
            let mut worst_exit: u8 = 0;
            for (idx, flow_path) in flows.iter().enumerate() {
                // Per-flow debug-output subdir when running multiple
                // flows. Single-flow batches keep the raw dir for
                // backwards byte-compat.
                let per_flow_debug = debug_output.as_ref().map(|d| {
                    if multi_flow {
                        let stem = flow_path
                            .file_stem()
                            .and_then(|s| s.to_str())
                            .unwrap_or("flow")
                            .to_string();
                        d.join(stem)
                    } else {
                        d.clone()
                    }
                });
                if multi_flow {
                    eprintln!(
                        "smix run: [{}/{}] {}",
                        idx + 1,
                        flows.len(),
                        flow_path.display()
                    );
                }
                // Per-flow retry loop + attempt attribution.
                // Retry only fires on non-zero exit. Each attempt records
                // status + errorClass (best-effort from exit code) + wallMs
                // + any new `.ips` for the target bundle appearing between
                // attempt start and end. `flow-attempts.json` persistence
                // + `smix diagnostic dump` overlay surface the attribution
                // table.
                let attribution_bundle: Option<String> = bundle.clone().or_else(|| {
                    smix_adapter_maestro::parse_flow_file(flow_path)
                        .ok()
                        .map(|f| f.app_id)
                        .filter(|a| !a.is_empty())
                });
                let max_attempts = retry.max(1);
                let mut attempts: Vec<smix_runner_wire::FlowAttempt> = Vec::new();
                let flow_name = flow_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| flow_path.display().to_string());
                let mut final_code: u8 = 1;
                for attempt_index in 0..max_attempts {
                    if attempt_index > 0 {
                        eprintln!("smix run: retry #{attempt_index} for flow {flow_name}");
                    }
                    let ips_before = ips_snapshot(attribution_bundle.as_deref());
                    let started = std::time::Instant::now();
                    let code =
                        smix_adapter_maestro::run_flow_code(smix_adapter_maestro::FlowArgs {
                            flow: flow_path.clone(),
                            udid: udid.clone(),
                            bundle_id: bundle.clone(),
                            runner_port: port,
                            animations,
                            no_launch,
                            platform: plat,
                            apps_config: apps_config.clone(),
                            env_vars: env.clone(),
                            debug_output: per_flow_debug.clone(),
                            verbose,
                            format: out_fmt,
                            auto_activate: activate,
                            metro_log_url: metro_log_url.clone(),
                            await_signal: await_signal.clone(),
                            gate_signal: gate_signal.clone(),
                            gate_signal_timeout_ms,
                            expect_log_clean,
                            fixture_registry: fixture_registry.clone(),
                            force_key_events,
                            no_fail_annotate,
                            auto_ocr_fallback: Some(sw_auto_ocr.value),
                            ai_assertions: Some(sw_ai_assertions.value),
                            assert_screenshot_no_autorecord: Some(sw_assert_no_autorecord.value),
                            launch_fresh_force_reinstall: Some(sw_launch_reinstall.value),
                        })
                        .await;
                    let wall_ms = started.elapsed().as_millis() as u64;
                    let ips_after = ips_snapshot(attribution_bundle.as_deref());
                    let new_ips: Option<String> =
                        ips_after.iter().find(|p| !ips_before.contains(*p)).cloned();
                    // The adapter's real exit-code table (entry.rs
                    // run_error_to_exit): 2 parse, 3 expectation/SDK,
                    // 4 unknown verb, 5 cycle/IO, 6 unreachable. The old
                    // mapping here invented 1=expectation and 2=timeout,
                    // so parse errors were attributed as timeouts and
                    // real expectation failures as bare EXIT_3.
                    let (status, error_class) = match code {
                        0 => ("ok".to_string(), None),
                        2 => ("error".to_string(), Some("PARSE_ERROR".to_string())),
                        3 => ("error".to_string(), Some("EXPECTATION_FAILURE".to_string())),
                        4 => ("error".to_string(), Some("UNKNOWN_VERB".to_string())),
                        5 => ("error".to_string(), Some("FLOW_IO_ERROR".to_string())),
                        6 => ("error".to_string(), Some("RUNNER_UNREACHABLE".to_string())),
                        130 | 143 => ("interrupted".to_string(), Some("SIGNAL".to_string())),
                        n => ("error".to_string(), Some(format!("EXIT_{n}"))),
                    };
                    let mut a = smix_runner_wire::FlowAttempt::default();
                    a.attempt_index = attempt_index;
                    a.status = status;
                    a.error_class = error_class;
                    a.ips_generated = new_ips;
                    a.wall_ms = wall_ms;
                    attempts.push(a);
                    final_code = code;
                    if code == 0 {
                        break;
                    }
                }
                // Persist per-flow attempts so `smix diagnostic dump`
                // (later, separate process) can render the attribution.
                // Wire type doesn't implement the trait; convert to local
                // shape here (thin adapter).
                struct AttemptView<'a>(&'a smix_runner_wire::FlowAttempt);
                impl<'a> smix_simctl::FlowAttemptShape for AttemptView<'a> {
                    fn attempt_index(&self) -> u32 {
                        self.0.attempt_index
                    }
                    fn status(&self) -> &str {
                        &self.0.status
                    }
                    fn error_class(&self) -> Option<&str> {
                        self.0.error_class.as_deref()
                    }
                    fn ips_generated(&self) -> Option<&str> {
                        self.0.ips_generated.as_deref()
                    }
                    fn wall_ms(&self) -> u64 {
                        self.0.wall_ms
                    }
                }
                let views: Vec<AttemptView> = attempts.iter().map(AttemptView).collect();
                smix_simctl::record_flow_attempts(&flow_name, &views);
                worst_exit = worst_exit.max(final_code);
                if fail_fast && final_code != 0 {
                    eprintln!(
                        "smix run: --fail-fast — aborting batch on first failure (exit={final_code})"
                    );
                    break;
                }
            }
            return Ok(ExitCode::from(worst_exit));
        }
        Cmd::Migrate { paths, in_place } => {
            return cmd_migrate(paths, in_place).await;
        }
        Cmd::Annotate {
            input,
            output,
            annotations,
            compression,
            font,
        } => {
            return cmd_annotate(input, output, annotations, compression, font).await;
        }
        Cmd::Authoring { action } => match action {
            AuthoringAction::Suggest {
                partial,
                port,
                device,
            } => {
                return authoring::cmd_suggest(runner_dial_port(port, device.as_deref()), partial)
                    .await;
            }
            AuthoringAction::Generate {
                input,
                format,
                output,
                app_id,
                test_fn_name,
            } => {
                return authoring::cmd_generate(input, format, output, app_id, test_fn_name).await;
            }
            AuthoringAction::TapRecord {
                output,
                duration,
                format,
                port,
                device,
                app_id,
                test_fn_name,
            } => {
                // The run_port ladder, with the Android runner's 28080 as
                // the final rung: tap-record is Android-only today.
                let port = port
                    .or_else(|| {
                        device
                            .as_deref()
                            .and_then(lookup_registered)
                            .and_then(|sim| sim.runner_port)
                    })
                    .unwrap_or(28080);
                return authoring::cmd_tap_record(
                    port,
                    duration,
                    format,
                    output,
                    app_id,
                    test_fn_name,
                )
                .await;
            }
            AuthoringAction::CaptureTree {
                output,
                port,
                device,
            } => {
                return authoring::cmd_capture_tree(
                    runner_dial_port(port, device.as_deref()),
                    output,
                )
                .await;
            }
            AuthoringAction::DiffTree {
                baseline,
                port,
                device,
            } => {
                return authoring::cmd_diff_tree(
                    runner_dial_port(port, device.as_deref()),
                    baseline,
                )
                .await;
            }
            AuthoringAction::Propose {
                flow,
                bundle,
                output,
            } => {
                return authoring::cmd_propose(flow, bundle, output).await;
            }
            AuthoringAction::Record {
                output,
                duration_secs,
                interval_ms,
                port,
                device,
                app_id,
            } => {
                return authoring::cmd_record_session(
                    runner_dial_port(port, device.as_deref()),
                    duration_secs,
                    interval_ms,
                    output,
                    app_id,
                )
                .await;
            }
        },
    }
    Ok(ExitCode::SUCCESS)
}

/// CLI wrapper around `smix_annotate::Annotator`.
async fn cmd_annotate(
    input: PathBuf,
    output: PathBuf,
    annotations: Vec<String>,
    compression: String,
    font: Option<PathBuf>,
) -> Result<ExitCode, CliError> {
    use smix_annotate::{Annotator, Compression};
    let png = std::fs::read(&input)
        .map_err(|e| CliError::Other(format!("read {}: {e}", input.display())))?;
    let mut ann = Annotator::new(&png)
        .map_err(|e| CliError::Other(format!("decode {}: {e}", input.display())))?;
    if let Some(fp) = &font {
        let font_bytes = std::fs::read(fp)
            .map_err(|e| CliError::Other(format!("read font {}: {e}", fp.display())))?;
        ann = ann.font(font_bytes);
    }
    for spec in &annotations {
        let a = parse_annotation_spec(spec)
            .map_err(|e| CliError::Other(format!("annotation `{spec}`: {e}")))?;
        ann = ann.add(a);
    }
    let comp = match compression.to_lowercase().as_str() {
        "fast" => Compression::Fast,
        "balanced" => Compression::Balanced,
        "aggressive" => Compression::Aggressive,
        other => {
            return Err(CliError::Other(format!(
                "unknown compression preset `{other}`"
            )));
        }
    };
    ann = ann.compression(comp);
    let bytes = ann
        .render()
        .map_err(|e| CliError::Other(format!("render: {e}")))?;
    std::fs::write(&output, bytes)
        .map_err(|e| CliError::Other(format!("write {}: {e}", output.display())))?;
    eprintln!("smix annotate: wrote {}", output.display());
    Ok(ExitCode::SUCCESS)
}

/// Parse one annotation spec from the mini-DSL:
///   kind ',' key:value (',' key:value)*
fn parse_annotation_spec(spec: &str) -> Result<smix_annotate::Annotation, String> {
    use smix_annotate::{Annotation, Color, Position};
    let parts: Vec<&str> = spec.split(',').collect();
    let kind = parts
        .first()
        .ok_or_else(|| "empty spec".to_string())?
        .trim();
    let mut kv = std::collections::BTreeMap::new();
    for part in &parts[1..] {
        let (k, v) = part
            .split_once(':')
            .ok_or_else(|| format!("expected key:value, got `{part}`"))?;
        kv.insert(k.trim(), v.trim());
    }
    let get_color = |default: Color| -> Result<Color, String> {
        Ok(match kv.get("color") {
            Some(s) => Color::parse(s).map_err(|e| e.to_string())?,
            None => default,
        })
    };
    let get_pos = |key_prefix: &str, default_key: &str| -> Result<Position, String> {
        let key = if kv.contains_key(key_prefix) {
            key_prefix
        } else {
            default_key
        };
        let v = kv.get(key).ok_or_else(|| format!("missing `{key}`"))?;
        // v is either "X,Y" absolute — but comma already split. Use
        // `at:X_Y` (underscore or pipe separator) instead of `x=X;y=Y`.
        let parts: Vec<&str> = v.split(['_', '|']).collect();
        if parts.len() != 2 {
            return Err(format!(
                "position `{v}` — expected `X_Y` (underscore or pipe separator)"
            ));
        }
        let x: i32 = parts[0]
            .parse()
            .map_err(|_| format!("bad x `{}`", parts[0]))?;
        let y: i32 = parts[1]
            .parse()
            .map_err(|_| format!("bad y `{}`", parts[1]))?;
        Ok(Position::pixel(x, y))
    };
    match kind {
        "circle" => {
            let at = get_pos("at", "at")?;
            let color = get_color(Color::RED)?;
            let radius: i32 = kv
                .get("radius")
                .map(|s| s.parse().unwrap_or(30))
                .unwrap_or(30);
            let stroke: i32 = kv
                .get("stroke")
                .map(|s| s.parse().unwrap_or(3))
                .unwrap_or(3);
            Ok(Annotation::circle(at)
                .color(color)
                .radius(radius)
                .stroke(stroke)
                .build())
        }
        "arrow" => {
            let from = get_pos("from", "from")?;
            let to = get_pos("to", "to")?;
            let color = get_color(Color::BLUE)?;
            let stroke: i32 = kv
                .get("stroke")
                .map(|s| s.parse().unwrap_or(4))
                .unwrap_or(4);
            Ok(Annotation::arrow(from, to)
                .color(color)
                .stroke(stroke)
                .build())
        }
        "text" => {
            let at = get_pos("at", "at")?;
            let content = kv
                .get("content")
                .ok_or_else(|| "missing `content`".to_string())?
                .to_string();
            let color = get_color(Color::WHITE)?;
            let size: f32 = kv
                .get("size")
                .map(|s| s.parse().unwrap_or(24.0))
                .unwrap_or(24.0);
            Ok(Annotation::text(at, content)
                .color(color)
                .size(size)
                .build())
        }
        "box" => {
            let at = get_pos("at", "at")?;
            let width: i32 = kv
                .get("width")
                .and_then(|s| s.parse().ok())
                .ok_or_else(|| "missing `width`".to_string())?;
            let height: i32 = kv
                .get("height")
                .and_then(|s| s.parse().ok())
                .ok_or_else(|| "missing `height`".to_string())?;
            let color = get_color(Color::YELLOW)?;
            let stroke: i32 = kv
                .get("stroke")
                .map(|s| s.parse().unwrap_or(2))
                .unwrap_or(2);
            Ok(Annotation::box_(at, width, height)
                .color(color)
                .stroke(stroke)
                .build())
        }
        "line" => {
            let from = get_pos("from", "from")?;
            let to = get_pos("to", "to")?;
            let color = get_color(Color::CYAN)?;
            let stroke: i32 = kv
                .get("stroke")
                .map(|s| s.parse().unwrap_or(2))
                .unwrap_or(2);
            Ok(Annotation::line(from, to)
                .color(color)
                .stroke(stroke)
                .build())
        }
        other => Err(format!(
            "unknown annotation kind `{other}` (expected circle/arrow/text/box/line)"
        )),
    }
}

/// Thin wrapper around `smix_migrate::Migrator`. Three input modes
/// (stdin / file→stdout / in-place batch); unified stderr WARN for
/// unknown verbs; per-file exit-code aggregation.
async fn cmd_migrate(paths: Vec<PathBuf>, in_place: bool) -> Result<ExitCode, CliError> {
    use std::io::{Read, Write};
    let migrator = smix_migrate::Migrator::default();

    // stdin mode
    if paths.is_empty() {
        if in_place {
            eprintln!("smix migrate: --in-place requires at least one path");
            return Ok(ExitCode::from(2));
        }
        let mut buf = String::new();
        if let Err(e) = std::io::stdin().read_to_string(&mut buf) {
            eprintln!("smix migrate: failed to read stdin: {e}");
            return Ok(ExitCode::from(2));
        }
        match migrator.migrate(&buf) {
            Ok((out, report)) => {
                warn_unknown(&report.unknown_verbs, "<stdin>");
                warn_unknown_selector_keys(&report.unknown_selector_keys, "<stdin>");
                print!("{out}");
                std::io::stdout().flush().ok();
                Ok(ExitCode::SUCCESS)
            }
            Err(e) => {
                eprintln!("smix migrate: <stdin>: {e}");
                Ok(ExitCode::from(2))
            }
        }
    } else {
        let mut worst: u8 = 0;
        let mut totals = Totals::default();
        for path in &paths {
            let input = match std::fs::read_to_string(path) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("smix migrate: read {}: {e}", path.display());
                    worst = worst.max(2);
                    continue;
                }
            };
            match migrator.migrate(&input) {
                Ok((out, report)) => {
                    warn_unknown(&report.unknown_verbs, &path.display().to_string());
                    warn_unknown_selector_keys(
                        &report.unknown_selector_keys,
                        &path.display().to_string(),
                    );
                    if in_place {
                        // Atomic-ish rewrite. Write to sibling
                        // `.smix-migrate.tmp` then rename, so a process
                        // kill mid-write doesn't corrupt the original
                        // file.
                        let tmp = path.with_extension("smix-migrate.tmp");
                        if let Err(e) = std::fs::write(&tmp, &out) {
                            eprintln!("smix migrate: write tmp {}: {e}", tmp.display());
                            worst = worst.max(3);
                            continue;
                        }
                        if let Err(e) = std::fs::rename(&tmp, path) {
                            eprintln!("smix migrate: rename {}: {e}", tmp.display());
                            worst = worst.max(3);
                            continue;
                        }
                        eprintln!(
                            "smix migrate: rewrote {}{}",
                            path.display(),
                            describe_changes(&report)
                        );
                        totals.files += 1;
                        totals.renames += report.renamed.len();
                        totals.unknown += report.unknown_verbs.len();
                        totals.subflows += report.subflow_refs;
                    } else {
                        print!("{out}");
                        std::io::stdout().flush().ok();
                    }
                }
                Err(e) => {
                    eprintln!("smix migrate: {}: {e}", path.display());
                    worst = worst.max(2);
                }
            }
        }
        if in_place {
            totals.report(paths.len());
        }
        Ok(ExitCode::from(worst))
    }
}

/// What a migrate run did, across every file it touched.
#[derive(Default)]
struct Totals {
    files: usize,
    renames: usize,
    unknown: usize,
    subflows: usize,
}

impl Totals {
    fn report(&self, asked_for: usize) {
        if asked_for > 1 {
            eprintln!(
                "smix migrate: {} of {} file(s) rewritten, {} rename(s)",
                self.files, asked_for, self.renames
            );
        }
        // The two things a caller has to act on. Neither is a failure, and
        // both are invisible once the command exits, so they are said out
        // loud rather than left in the diff.
        if self.unknown > 0 {
            eprintln!(
                "smix migrate: {} verb(s) had no smix equivalent and were left as they were \
                 — the flow will not parse until you replace them",
                self.unknown
            );
        }
        if self.subflows > 0 {
            eprintln!(
                "smix migrate: {} runFlow reference(s) point at files this run did not open \
                 — migrate those too",
                self.subflows
            );
        }
    }
}

/// One file's changes, for the line printed as it is rewritten.
fn describe_changes(report: &smix_migrate::MigrateReport) -> String {
    if report.renamed.is_empty() {
        return format!("no changes, {} step(s)", report.step_count);
    }
    let mut counts: Vec<(&str, &str, usize)> = Vec::new();
    for rename in &report.renamed {
        match counts.iter_mut().find(|c| c.0 == rename.from) {
            Some(c) => c.2 += 1,
            None => counts.push((rename.from, rename.to, 1)),
        }
    }
    let detail: Vec<String> = counts
        .iter()
        .map(|(from, to, n)| {
            if *n == 1 {
                format!("{from}{to}")
            } else {
                format!("{from}{to} ×{n}")
            }
        })
        .collect();
    format!(
        "{} rename(s) in {} step(s): {}",
        report.renamed.len(),
        report.step_count,
        detail.join(", ")
    )
}

fn warn_unknown(unknown: &[String], src: &str) {
    if !unknown.is_empty() {
        eprintln!(
            "smix migrate: WARN {}: unknown verb(s) preserved verbatim: {}",
            src,
            unknown.join(", ")
        );
    }
}

/// Selector keys v2 refuses. Distinct from unknown verbs: those are
/// preserved and may still be smix-native, while these WILL fail to
/// parse — so the wording says so rather than "preserved verbatim".
fn warn_unknown_selector_keys(keys: &[String], src: &str) {
    if !keys.is_empty() {
        eprintln!(
            "smix migrate: WARN {}: selector key(s) v2 does not accept: {} \
             — flows using them fail to parse; remove them or use a \
             supported selector",
            src,
            keys.join(", ")
        );
    }
}

fn runner_port() -> u16 {
    std::env::var("SMIX_RUNNER_PORT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(22087)
}

/// Extract the numeric exit code from a `std::process::ExitCode`.
///
/// `ExitCode` has no public conversion back to `u8` (Rust chose "opaque so
/// platforms can widen later" for the stability guarantee), but the internal
/// `impl Debug` prints `ExitCode(unix_exit_status(N))` on Unix. Parse it back.
/// For the batch-invocation path we only need to compare codes; the parsed u8
/// is fed straight into `ExitCode::from(u8)` for the process exit. Success
/// (Debug "ExitCode(unix_exit_status(0))") maps to 0.
/// smix workspace root = nearest ancestor with a `.smix/` dir (env
/// SMIX_WORKSPACE overrides discovery).
fn smix_workspace_root() -> Result<PathBuf, CliError> {
    if let Some(p) = std::env::var_os("SMIX_WORKSPACE") {
        return Ok(PathBuf::from(p));
    }
    let cwd = std::env::current_dir()
        .map_err(|e| CliError::Other(format!("cannot determine cwd: {e}")))?;
    smix_capsule::runner::workspace_root(&cwd).ok_or_else(|| {
        CliError::Other(format!(
            "no .smix/ workspace found upward from {} — cd into the smix \
             workspace or set SMIX_WORKSPACE",
            cwd.display()
        ))
    })
}

// ---- subcommand impls --------------------------------------------------

/// Build the simctl argv for an exec passthrough: `{udid}` placeholder
/// substitution when present, otherwise UDID injected right after the verb
/// (simctl's device position for every device-taking subcommand).
/// Catch a udid passed where the alias already implied one.
///
/// `smix sim exec insight openurl <UDID> "insight://…"` shifts the URL
/// into simctl's device slot, and simctl answers
/// `Simulator device failed to open <UDID>. (OSStatus error -50)` —
/// which names neither the mistake nor the fix. The device is part of
/// `sim exec`'s own shape, so a second one is always a mistake.
///
/// Only for verbs whose arity is known. A passthrough that guessed at
/// every verb would refuse the ones it had not heard of, and the point
/// of a passthrough is the verbs nobody thought about.
fn exec_arity_complaint(verb: &str, args: &[String]) -> Option<String> {
    const DEVICE_IMPLIED: &[&str] = &["openurl", "launch", "terminate", "install", "uninstall"];
    if !DEVICE_IMPLIED.contains(&verb) {
        return None;
    }
    let looks_like_udid =
        |a: &String| a.len() == 36 && a.split('-').map(str::len).eq([8, 4, 4, 4, 12]);
    let stray = args.iter().position(looks_like_udid)?;
    Some(format!(
        "`{verb}` takes no device argument — `sim exec <ALIAS|UDID>` already named one, \
         and simctl would read `{}` as the device and everything after it shifted by one. \
         Drop it: `smix sim exec <ALIAS> {verb} {}`",
        args[stray],
        args.iter()
            .enumerate()
            .filter(|(i, _)| *i != stray)
            .map(|(_, a)| a.as_str())
            .collect::<Vec<_>>()
            .join(" ")
    ))
}

fn exec_argv(verb: &str, udid: &str, args: &[String]) -> Vec<String> {
    let mut argv = vec![verb.to_string()];
    if args.iter().any(|a| a == "{udid}") {
        argv.extend(args.iter().map(|a| {
            if a == "{udid}" {
                udid.to_string()
            } else {
                a.clone()
            }
        }));
    } else {
        argv.push(udid.to_string());
        argv.extend(args.iter().cloned());
    }
    argv
}

async fn cmd_sim_exec(device: &str, verb: &str, args: &[String]) -> Result<ExitCode, CliError> {
    let udid = resolve_device(device)?;
    if let Some(complaint) = exec_arity_complaint(verb, args) {
        return Err(CliError::Other(complaint));
    }
    let argv = exec_argv(verb, &udid, args);
    // exec(2), not spawn: the caller's pid becomes simctl itself, so shell
    // job control (`& ... kill -INT $!`) reaches simctl directly — required
    // for recordVideo, whose output is only finalized on a clean SIGINT.
    use std::os::unix::process::CommandExt;
    let err = std::process::Command::new("xcrun")
        .arg("simctl")
        .args(&argv)
        .exec();
    Err(CliError::Other(format!("exec xcrun simctl: {err}")))
}

#[derive(Subcommand, Debug)]
enum DiagnosticAction {
    /// Print everything smix has persisted, as JSON.
    ///
    /// The state used to be JSON files you could `cat`; it is an
    /// embedded store now, and this is what keeps it as readable as it
    /// was. A value that is not valid JSON is shown as hex rather than
    /// stopping the dump — this is what you run when something is
    /// already wrong.
    Store {
        /// Which store: the workspace's `.smix`, or another path.
        #[arg(long, default_value = ".smix")]
        root: PathBuf,
    },
    /// Pretty-print the runner's runtime observability snapshot:
    /// recent subprocess argvs + exit codes + timings, open sessions,
    /// sim-health state, supervisor pid, uptime. Calls
    /// `POST /diagnostic/dump` on the runner. When the runner is too
    /// old to serve that route, falls back to the client-side ring
    /// buffer only.
    Dump {
        /// JSON output instead of the human table.
        #[arg(long, default_value_t = false)]
        json: bool,
        /// Path to an external metro log file. If set, the dump tails
        /// the last N lines of this file (see `--metro-log-tail-lines`)
        /// into a `metro log tail` section (and into
        /// `runner.metroLogTail` on the JSON payload). Covers the case
        /// where metro was started externally (e.g. redirected to a log
        /// file), which smix's own log-gate would otherwise skip.
        #[arg(long = "metro-log")]
        metro_log: Option<PathBuf>,
        /// Number of trailing lines to read from `--metro-log`.
        /// Ignored when `--metro-log` is unset.
        #[arg(long = "metro-log-tail-lines", default_value_t = 200)]
        metro_log_tail_lines: usize,
    },
}

/// Snapshot the current set of `.ips` filenames under
/// `~/Library/Logs/DiagnosticReports/` matching the target bundle id
/// (or every `.ips` entry when `bundle_id` is None).
/// Used before / after each flow attempt so retry attribution can
/// diff the sets and attribute any new `.ips` to the attempt that
/// generated it.
///
/// Best-effort: returns empty on unreadable directory. Cost per call:
/// a single readdir + up to ~30 filename comparisons on a typical
/// developer machine.
fn ips_snapshot(bundle_id: Option<&str>) -> std::collections::HashSet<String> {
    let mut set: std::collections::HashSet<String> = Default::default();
    let Some(home) = std::env::var_os("HOME") else {
        return set;
    };
    let dir = std::path::PathBuf::from(home).join("Library/Logs/DiagnosticReports");
    let Ok(read_dir) = std::fs::read_dir(&dir) else {
        return set;
    };
    // Match logic: when `bundle_id` is set, look for the last
    // component after the final `.` — bundle-id-shaped names
    // (com.foo.bar) match against the .ips filename prefix in
    // heuristic-match mode. When None, include EVERY `.ips` file:
    // callers use this snapshot as a before/after diff around a flow
    // run, so time-bounding does the relevance filtering — any crash
    // report that appears during the flow window is a candidate
    // regardless of process name.
    let bundle_leaf = bundle_id
        .and_then(|b| b.rsplit('.').next())
        .map(|s| s.to_lowercase());
    for entry in read_dir.flatten() {
        let name = entry.file_name().to_string_lossy().to_lowercase();
        if !name.ends_with(".ips") {
            continue;
        }
        let interesting = match &bundle_leaf {
            Some(leaf) => name.contains(leaf),
            None => true,
        };
        if interesting {
            set.insert(entry.file_name().to_string_lossy().into_owned());
        }
    }
    set
}

/// Read the last `n` lines from `path`. Seeks
/// from EOF backward in 8 KB chunks, splitting on `\n`, until it has
/// gathered `n` lines or reached BOF. Handles the "file smaller than
/// one chunk" and "file has no trailing newline" cases. Returns
/// oldest → newest ordered lines with newlines stripped.
///
/// Not tokio — this is called from a sync context (dump command is
/// sync-shaped inside an async fn) and the operation is one-shot at
/// dump time. For streaming tail during a run, use
/// `smix_metro_log::subscriber::FileTailSubscriber` which handles the
/// growing-file case.
fn tail_lines(path: &Path, n: usize) -> std::io::Result<Vec<String>> {
    use std::io::{Read, Seek, SeekFrom};
    let mut f = std::fs::File::open(path)?;
    let end = f.seek(SeekFrom::End(0))?;
    if end == 0 || n == 0 {
        return Ok(Vec::new());
    }
    let chunk_size: u64 = 8192;
    let mut pos = end;
    let mut buf: Vec<u8> = Vec::new();
    let mut line_count = 0usize;
    // Read backward until we have n+1 newlines (so we can drop the
    // partial line at the start) or we hit BOF.
    while pos > 0 && line_count <= n {
        let read_from = pos.saturating_sub(chunk_size);
        let read_len = (pos - read_from) as usize;
        pos = read_from;
        f.seek(SeekFrom::Start(read_from))?;
        let mut chunk = vec![0u8; read_len];
        f.read_exact(&mut chunk)?;
        chunk.append(&mut buf);
        buf = chunk;
        line_count = buf.iter().filter(|&&b| b == b'\n').count();
    }
    let text = String::from_utf8_lossy(&buf).into_owned();
    let mut lines: Vec<String> = text.lines().map(|s| s.to_string()).collect();
    if lines.len() > n {
        lines = lines.split_off(lines.len() - n);
    }
    Ok(lines)
}

async fn cmd_diagnostic(action: DiagnosticAction) -> Result<(), CliError> {
    match action {
        DiagnosticAction::Store { root } => {
            let store = smix_store::Store::open(&root)
                .map_err(|e| CliError::Other(format!("open store at {}: {e}", root.display())))?;
            let dumped = store
                .dump_json()
                .map_err(|e| CliError::Other(format!("dump store: {e}")))?;
            println!("{dumped}");
        }
        DiagnosticAction::Dump {
            json,
            metro_log,
            metro_log_tail_lines,
        } => {
            let port = runner_port();
            let client = smix_runner_client::HttpRunnerClient::new(port);
            let mut resp = match client.diagnostic_dump().await {
                Ok(r) => r,
                Err(e) => {
                    eprintln!(
                        "warning: /diagnostic/dump unreachable ({e}); \
                         showing client-side ring buffer only"
                    );
                    smix_runner_wire::DiagnosticDumpResponse::default()
                }
            };
            // CLI-side metro log tail. Read at
            // dump time from the file path (not from the runner) so
            // it works even when the runner never saw the log tail
            // and doesn't require the runner to have been booted
            // with a subscriber. See smix-metro-log FileTailSubscriber
            // for the runtime path used by `smix run`'s
            // `expect.signal` / `expect.signals` verbs.
            if let Some(ref path) = metro_log {
                match tail_lines(path, metro_log_tail_lines) {
                    Ok(lines) => resp.metro_log_tail = lines,
                    Err(e) => {
                        eprintln!(
                            "warning: --metro-log {} unreadable ({e}); \
                             metro log tail will be empty in dump",
                            path.display()
                        );
                    }
                }
            }
            // Overlay CLI-side resetAppData
            // counters onto the wire response before display. The
            // runner never sees resetAppData dispatches (they're
            // host-side simctl-openurl calls), so the wire counters
            // for these fields arrive as 0; we merge from the
            // CLI-persisted store.
            let reset_counters = smix_simctl::reset_app_data_counters_snapshot();
            resp.session_counters.reset_app_data_total = reset_counters.reset_app_data_total;
            resp.session_counters.reset_app_data_timed_out =
                reset_counters.reset_app_data_timed_out;
            // Overlay per-flow retry attribution from the
            // CLI-persisted store. Runner side never sees flow-level
            // retry (it's CLI-orchestrated), so wire arrives empty and
            // we merge from disk here.
            let recent_flows = smix_simctl::recent_flow_attempts();
            resp.recent_flows = recent_flows
                .into_iter()
                .map(|f| {
                    let mut rec = smix_runner_wire::FlowAttemptRecord::default();
                    rec.flow_name = f.flow_name;
                    rec.attempts = f
                        .attempts
                        .into_iter()
                        .map(|a| {
                            let mut w = smix_runner_wire::FlowAttempt::default();
                            w.attempt_index = a.attempt_index;
                            w.status = a.status;
                            w.error_class = a.error_class;
                            w.ips_generated = a.ips_generated;
                            w.wall_ms = a.wall_ms;
                            w
                        })
                        .collect();
                    rec
                })
                .collect();
            let client_side = smix_simctl::recent_subprocesses();

            if json {
                let payload = serde_json::json!({
                    "runner": resp,
                    "clientSubprocesses": client_side.iter().map(|r| serde_json::json!({
                        "argv": r.argv,
                        "exitCode": r.exit_code,
                        "wallMs": r.wall_ms,
                        "stderrHead": r.stderr_head,
                        "timestampMs": r.timestamp.duration_since(std::time::UNIX_EPOCH)
                            .map(|d| d.as_millis() as u64).unwrap_or(0),
                    })).collect::<Vec<_>>(),
                });
                println!(
                    "{}",
                    serde_json::to_string_pretty(&payload).unwrap_or_default()
                );
                return Ok(());
            }

            println!("=== runner runtime snapshot ===");
            println!("uptime:         {}ms", resp.uptime_ms);
            println!("sim health:     {}", resp.sim_health);
            if let Some(pid) = resp.supervisor_pid {
                println!("supervisor pid: {pid}");
            } else {
                println!("supervisor pid: (none)");
            }
            println!();
            println!("=== open sessions ({}) ===", resp.sessions.len());
            for s in &resp.sessions {
                println!(
                    "  {:<38} {:<40} openedAtMs={} lastActivatedAtMs={}",
                    s.session_id, s.bundle_id, s.opened_at_ms, s.last_activated_at_ms
                );
            }
            println!();
            // Surface the always-emitted counter fields so callers
            // can numerically check "did the observability actually
            // reach this workload" without dropping into `--json`.
            let ac = &resp.alive_cache;
            println!("=== app-alive cache counters ===");
            println!(
                "  wired={} markDead={} markAlive={} suppressHit={} suppressMiss={}",
                ac.wired,
                ac.mark_dead_total,
                ac.mark_alive_total,
                ac.suppress_hit_total,
                ac.suppress_miss_total,
            );
            println!(
                "  reprobeAttempted={} reprobeSucceeded={} reprobeInvalidatedEarly={} reprobeExhaustedWindow={}",
                ac.reprobe_attempted_total,
                ac.reprobe_succeeded_total,
                ac.reprobe_invalidated_early,
                ac.reprobe_exhausted_window,
            );
            let sc = &resp.session_counters;
            println!();
            println!("=== session lifecycle counters (cumulative, survive close) ===");
            println!(
                "  opened={} closed={} relaunch={} terminate={} launch={}",
                sc.opened_total,
                sc.closed_total,
                sc.relaunch_app_total,
                sc.terminate_app_total,
                sc.launch_app_total,
            );
            println!(
                "  terminate: viaXCUIApplication={} viaFallback={}  # fallback>0 = cooperative terminate failed → potential .ips writes",
                sc.terminate_app_via_xcuiapplication, sc.terminate_app_via_fallback,
            );
            println!(
                "  launch:    reachedForeground={} timedOutBeforeForeground={}  # timedOut>0 → next call may fire during launch → bug_type 309",
                sc.launch_app_reached_foreground, sc.launch_app_timed_out_before_foreground,
            );
            // resetAppData + interactive fingerprint.
            println!(
                "  resetAppData: total={} timedOut={}  # timedOut>0 → URL scheme fired but reset-complete log-line never arrived",
                sc.reset_app_data_total, sc.reset_app_data_timed_out,
            );
            println!(
                "  interactive: reachedInteractive={} timedOutBeforeInteractive={}  # timedOut>0 → process foreground but a11y tree unusable (splash / dev-launcher / sparse annotation)",
                sc.launch_app_reached_interactive, sc.launch_app_timed_out_before_interactive,
            );
            // Top-level lastInteractiveNamedIds sample.
            if !resp.last_interactive_named_ids.is_empty() {
                println!(
                    "  lastInteractiveNamedIds ({}): {}",
                    resp.last_interactive_named_ids.len(),
                    resp.last_interactive_named_ids.join(", "),
                );
            } else {
                println!(
                    "  lastInteractiveNamedIds: []  # no launch has completed with a non-empty sample yet",
                );
            }
            println!();
            // External metro log tail. Only printed
            // when the user passed `--metro-log <path>` to this dump
            // command; the runner doesn't buffer for us.
            if !resp.metro_log_tail.is_empty() {
                println!(
                    "=== metro log tail (last {} of file) ===",
                    resp.metro_log_tail.len()
                );
                for line in &resp.metro_log_tail {
                    println!("  {}", line);
                }
                println!();
            }
            // Retry-attribution roll-up.
            if !resp.recent_flows.is_empty() {
                println!("=== recent flows (retry attribution) ===");
                for flow in &resp.recent_flows {
                    println!("  flow: {}", flow.flow_name);
                    for attempt in &flow.attempts {
                        let err = attempt
                            .error_class
                            .as_deref()
                            .map(|c| format!(" errorClass={c}"))
                            .unwrap_or_default();
                        let ips = attempt
                            .ips_generated
                            .as_deref()
                            .map(|p| format!(" ipsGenerated={p}"))
                            .unwrap_or_default();
                        println!(
                            "    attempt #{} status={} wallMs={}{}{}",
                            attempt.attempt_index, attempt.status, attempt.wall_ms, err, ips,
                        );
                    }
                }
                println!();
            }
            println!(
                "=== runner-side subprocesses (last {} of {}) ===",
                resp.recent_subprocesses.len().min(20),
                resp.recent_subprocesses.len(),
            );
            for r in resp.recent_subprocesses.iter().rev().take(20) {
                let code = r
                    .exit_code
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "-".into());
                let head = if r.stderr_head.is_empty() {
                    String::new()
                } else {
                    format!(" err={:?}", r.stderr_head)
                };
                println!(
                    "  {:>13}ms  code={:>3}  {}{}",
                    r.wall_ms,
                    code,
                    r.argv.join(" "),
                    head
                );
            }
            println!();
            println!(
                "=== client-side subprocesses (last {} of {}) ===",
                client_side.len().min(20),
                client_side.len(),
            );
            for r in client_side.iter().rev().take(20) {
                let code = r
                    .exit_code
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "-".into());
                let head = if r.stderr_head.is_empty() {
                    String::new()
                } else {
                    format!(" err={:?}", r.stderr_head)
                };
                println!(
                    "  {:>13}ms  code={:>3}  simctl {}{}",
                    r.wall_ms,
                    code,
                    r.argv.join(" "),
                    head
                );
            }
        }
    }
    Ok(())
}

async fn cmd_init(
    simctl: &SimctlClient,
    alias: &str,
    device: Option<&str>,
    app: Option<&Path>,
) -> Result<(), CliError> {
    let devices = simctl.list_devices().await?;
    let candidates: Vec<init::Candidate> = devices
        .iter()
        .filter(|d| d.is_available)
        .map(|d| init::Candidate {
            udid: d.udid.clone(),
            name: d.name.clone(),
        })
        .collect();

    // The same resolution `smix sim register` uses — env override,
    // discovered registry, else a fresh `.smix/sims.json` in cwd. Init
    // writing anywhere else would produce a registry the rest of smix
    // does not read, which is worse than not writing one.
    let path = registry_path().unwrap_or_else(|_| PathBuf::from(".smix/sims.json"));
    let existing: Vec<String> = SimRegistry::load(&path)
        .map(|reg| reg.sims().keys().cloned().collect())
        .unwrap_or_default();

    let plan = match init::plan_init(&candidates, alias, device, &existing) {
        Ok(plan) => plan,
        Err(refusal) => {
            return Err(CliError::Other(format!(
                "{}\n{}",
                refusal.reason, refusal.remedy
            )));
        }
    };

    let sim = devices
        .iter()
        .find(|d| d.udid == plan.udid)
        .map(|d| registry::RegisteredSim {
            udid: d.udid.to_ascii_uppercase(),
            device_name: d.name.clone(),
            runtime: d.runtime_identifier.clone(),
            device_type: d.device_type_identifier.clone(),
            runner_port: None,
            locale: None,
        })
        .ok_or_else(|| CliError::Other(format!("device {} vanished mid-init", plan.udid)))?;
    SimRegistry::register(&path, &plan.alias, sim)
        .map_err(|e| CliError::Other(format!("register: {e}")))?;

    println!(
        "registered `{}` -> {} in {}",
        plan.alias,
        plan.udid,
        path.display()
    );

    // Registering a device is half of what someone arrives with; the other
    // half is an app. Installing it here is what lets the next command
    // carry a real bundle id instead of a placeholder to fill in.
    let bundle = match app {
        Some(app_path) => {
            // simctl refuses to install on a shut-down device, and a device
            // that was just registered is shut down. Booting is part of
            // installing here, not a step to leave someone to discover from
            // a raw CoreSimulator error code.
            if let Err(e) = simctl.boot(&plan.udid).await
                && !e.to_string().contains("current state: Booted")
            {
                return Err(CliError::Other(format!("boot {}: {e}", plan.udid)));
            }
            let id = bundle_id_of(app_path)?;
            simctl
                .install(&plan.udid, &app_path.display().to_string())
                .await
                .map_err(|e| CliError::Other(format!("install {}: {e}", app_path.display())))?;
            println!("installed {} ({id})", app_path.display());
            Some(id)
        }
        None => None,
    };

    println!();
    match bundle {
        Some(id) => println!("next: smix capsule up {} --bundle {id}", plan.alias),
        None => println!(
            "next: smix capsule up {} --bundle <your.bundle.id>",
            plan.alias
        ),
    }
    println!("      boots the device and starts the runner that carries every tap and query");
    Ok(())
}

/// The bundle id declared by an `.app`.
///
/// Read rather than asked for: it is already inside the bundle, and making
/// someone supply it is asking them to retype something they have no
/// reason to know by heart.
fn bundle_id_of(app: &Path) -> Result<String, CliError> {
    let plist = app.join("Info.plist");
    if !plist.exists() {
        return Err(CliError::Other(format!(
            "{} has no Info.plist — is it an .app bundle?",
            app.display()
        )));
    }
    let out = std::process::Command::new("plutil")
        .args(["-extract", "CFBundleIdentifier", "raw", "-o", "-"])
        .arg(&plist)
        .output()
        .map_err(|e| CliError::Other(format!("plutil: {e}")))?;
    if !out.status.success() {
        return Err(CliError::Other(format!(
            "{} declares no CFBundleIdentifier",
            plist.display()
        )));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Whether the capture server is answering on its default endpoint.
///
/// A plain TCP connect: `capsule up` only needs the process to be there,
/// and asking for a health route would couple doctor to a surface that is
/// not this module's business.
fn capture_server_reachable() -> bool {
    use std::net::{SocketAddr, TcpStream};
    use std::time::Duration;
    let addr: SocketAddr = ([127, 0, 0, 1], 8787).into();
    TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok()
}

async fn cmd_doctor(simctl: &SimctlClient, json: bool) -> Result<(), CliError> {
    // Gather, then judge. The judging is `readiness::assess`, a pure
    // function with its ordering under test — which is the only way the
    // "what do I run next" answer stays correct as checks are added.
    let simctl_facts = match simctl.list_runtimes().await {
        Ok(runtimes) => {
            let devices = simctl.list_devices().await.unwrap_or_default();
            Some(readiness::SimctlFacts {
                available_runtimes: runtimes.iter().filter(|r| r.is_available).count(),
                available_devices: devices.iter().filter(|d| d.is_available).count(),
            })
        }
        // Not an error to report and abort on: "simctl does not run" is
        // the most useful thing doctor can say, and it can only say it by
        // continuing.
        Err(_) => None,
    };

    let registry = std::env::current_dir()
        .ok()
        .and_then(|cwd| SimRegistry::discover(&cwd))
        .and_then(|path| SimRegistry::load(&path).ok())
        .map(|reg| readiness::RegistryFacts {
            aliases: reg.sims().len(),
            first_alias: reg.sims().keys().next().cloned(),
        });

    let port: u16 = std::env::var("SMIX_RUNNER_PORT")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(22087);

    let verdict = readiness::assess(&readiness::Facts {
        simctl: simctl_facts,
        registry,
        runner_up: smix_capsule::runner::health_ok(port),
        capture_server_up: capture_server_reachable(),
    });

    if json {
        let out = serde_json::to_string_pretty(&verdict)
            .map_err(|e| CliError::Other(format!("serialize: {e}")))?;
        println!("{out}");
        return Ok(());
    }

    println!("smix doctor");
    println!("============");
    for check in &verdict.checks {
        let mark = match check.status {
            readiness::Status::Ok => "\u{2713}",
            readiness::Status::Blocked => "\u{2717}",
            readiness::Status::Skipped => "\u{2022}",
        };
        println!("{mark} {}", check.detail);
    }
    println!("{}", readiness::PLATFORM_NOTE);
    match &verdict.next {
        Some(next) => {
            println!();
            println!("next: {}", next.command);
            println!("      {}", next.reason);
        }
        None => println!("\nready — nothing left to set up"),
    }
    Ok(())
}

async fn cmd_sim_list(simctl: &SimctlClient, json: bool) -> Result<(), CliError> {
    let devices = simctl.list_devices().await?;
    if json {
        let out = serde_json::to_string_pretty(&devices)
            .map_err(|e| CliError::Other(format!("serialize: {e}")))?;
        println!("{}", out);
        return Ok(());
    }
    // Compact human-readable table.
    println!("{:<40} {:<28} {:<10} RUNTIME", "UDID", "NAME", "STATE");
    for d in &devices {
        let runtime_short = d
            .runtime_identifier
            .rsplit('.')
            .next()
            .unwrap_or(d.runtime_identifier.as_str());
        println!(
            "{:<40} {:<28} {:<10} {runtime_short}",
            d.udid, d.name, d.state
        );
    }
    Ok(())
}

// ---- errors -----------------------------------------------------------

#[derive(Debug)]
enum CliError {
    Simctl(DeviceControlError),
    Registry(RegistryError),
    Other(String),
}

impl From<DeviceControlError> for CliError {
    fn from(e: DeviceControlError) -> Self {
        CliError::Simctl(e)
    }
}

impl From<RegistryError> for CliError {
    fn from(e: RegistryError) -> Self {
        CliError::Registry(e)
    }
}

impl std::fmt::Display for CliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CliError::Simctl(e) => write!(f, "{e}"),
            CliError::Registry(e) => write!(f, "{e}"),
            CliError::Other(s) => write!(f, "{s}"),
        }
    }
}

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

/// The port `smix run` dials: explicit flag (or SMIX_RUNNER_PORT via
/// clap's env binding), else the registry's per-sim `runnerPort`, else
/// the convention.
///
/// A function rather than an inline chain so the priority can be
/// asserted. `smix run` used to skip the registry entirely, so a sim
/// registered on a dedicated port had its runner bound there and then
/// dialled on 22087; the chain has been right since that was fixed and
/// unwatched ever since.
///
/// The registry lookup is a closure because reading it is a disk touch
/// worth skipping when the caller already said which port to use.
fn run_port(flag: Option<u16>, registered: impl FnOnce() -> Option<u16>) -> u16 {
    flag.or_else(registered).unwrap_or(act::DEFAULT_RUNNER_PORT)
}

/// The port a single-shot verb dials.
///
/// The same ladder [`run_port`] walks, with the env rung read here
/// rather than bound by clap: these verbs spell the flag `--port`, and
/// giving that one an `env =` would silently widen what
/// `SMIX_RUNNER_PORT` means for anyone passing `--port` explicitly
/// alongside it.
///
/// They had no `--device` at all until the guide gate asked, so the
/// registry rung was unreachable from them: in a workspace with a sim
/// registered on 22088, `smix run` dialled 22088 and `smix tap`
/// dialled 22087, and nothing said so.
fn runner_dial_port(flag: Option<u16>, device: Option<&str>) -> u16 {
    run_port(flag.or_else(act::runner_port_from_env_opt), || {
        device
            .and_then(lookup_registered)
            .and_then(|sim| sim.runner_port)
    })
}

/// Refuse `runner up` flags that only the iOS path implements.
///
/// The Android branch reads `--runner-port` and nothing else. It used to
/// accept the other three silently: `--bundle` went nowhere (the Android
/// runner is `am instrument`-hosted and learns its target from the
/// `App-Bundle-Id` header on each request, not at startup), so its help
/// text — "Required: `runner up` refuses to start without one" — was
/// false on this platform; `--runner-project` points at an .xcodeproj;
/// and `--supervise` promises a sidecar that `runner supervise` has no
/// Android path for at all, which is the worst of the three, because a
/// user who asked for supervision and got none is told nothing.
///
/// Same species as the four defects fixed the same week — a parameter
/// accepted and dropped — but one branch deep, where a scan for "clap
/// fields nobody reads" cannot see it: every one of these IS read, on
/// the other platform.
fn reject_ios_only_up_flags(
    bundle: bool,
    runner_project: bool,
    supervise: bool,
) -> Result<(), String> {
    let offenders: Vec<&str> = [
        (bundle, "--bundle"),
        (runner_project, "--runner-project"),
        (supervise, "--supervise"),
    ]
    .into_iter()
    .filter_map(|(given, name)| given.then_some(name))
    .collect();

    if offenders.is_empty() {
        return Ok(());
    }

    Err(format!(
        "runner up --platform android does not implement {}: {} iOS-only. \
         Drop the flag — the Android runner takes its target app from the \
         App-Bundle-Id header per request, builds no Xcode project, and has \
         no supervise sidecar. Only --runner-port applies on this platform.",
        offenders.join(" / "),
        if offenders.len() == 1 {
            "it is"
        } else {
            "they are"
        },
    ))
}

// ---- tests --------------------------------------------------------------

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

    const UDID: &str = "5D087114-ECB3-443C-8DDB-40EEF9CFB90C";

    // tail_lines behavior lock-ins. Small chunk
    // reads deliberately (not just 1 huge chunk) so the "read
    // backward in 8 KB chunks" logic is exercised for files smaller,
    // equal, and larger than one chunk.

    #[test]
    fn tail_lines_returns_last_n_when_file_larger_than_chunk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("big.log");
        let content = (0..5000)
            .map(|i| format!("line-{i}"))
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(&path, format!("{content}\n")).unwrap();
        let tail = tail_lines(&path, 3).unwrap();
        assert_eq!(tail, vec!["line-4997", "line-4998", "line-4999"]);
    }

    #[test]
    fn tail_lines_returns_all_when_file_smaller_than_n() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("small.log");
        std::fs::write(&path, "one\ntwo\nthree\n").unwrap();
        let tail = tail_lines(&path, 10).unwrap();
        assert_eq!(tail, vec!["one", "two", "three"]);
    }

    #[test]
    fn tail_lines_handles_no_trailing_newline() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("noeol.log");
        std::fs::write(&path, "alpha\nbeta").unwrap();
        let tail = tail_lines(&path, 5).unwrap();
        assert_eq!(tail, vec!["alpha", "beta"]);
    }

    #[test]
    fn tail_lines_returns_empty_for_zero_n() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("any.log");
        std::fs::write(&path, "content\n").unwrap();
        assert!(tail_lines(&path, 0).unwrap().is_empty());
    }

    #[test]
    fn tail_lines_returns_empty_for_empty_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("empty.log");
        std::fs::write(&path, b"").unwrap();
        assert!(tail_lines(&path, 100).unwrap().is_empty());
    }

    #[test]
    fn tail_lines_survives_utf8_split_across_chunk_boundary() {
        // Craft a file where a multibyte utf-8 sequence straddles our
        // 8192-byte chunk boundary. Uses "😀" (4 bytes) placed at
        // offsets that land on the boundary. String::from_utf8_lossy
        // must produce a valid string even if one chunk has partial
        // bytes.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("utf8.log");
        // 8189 bytes of ASCII + one 😀 (4 bytes) so the 😀 starts at
        // offset 8189 = the first chunk read covers bytes 0..8192,
        // which cuts the emoji in half.
        let prefix = "a".repeat(8189);
        let content = format!("{prefix}😀\ntail-line\n");
        std::fs::write(&path, content).unwrap();
        let tail = tail_lines(&path, 1).unwrap();
        assert_eq!(tail, vec!["tail-line"]);
    }

    #[test]
    fn authoring_propose_parses_flow_bundle_out() {
        let cli = Cli::try_parse_from([
            "smix",
            "authoring",
            "propose",
            "corrupt.yaml",
            "--bundle",
            "bundle-dir",
            "-o",
            "amended.yaml",
        ])
        .unwrap();
        let Cmd::Authoring {
            action:
                AuthoringAction::Propose {
                    flow,
                    bundle,
                    output,
                },
        } = cli.cmd
        else {
            panic!("expected authoring propose")
        };
        assert_eq!(flow, std::path::PathBuf::from("corrupt.yaml"));
        assert_eq!(bundle, std::path::PathBuf::from("bundle-dir"));
        assert_eq!(output, std::path::PathBuf::from("amended.yaml"));
    }

    #[test]
    fn exec_parses_hyphen_args_verbatim() {
        let cli = Cli::try_parse_from([
            "smix",
            "sim",
            "exec",
            "02",
            "status_bar",
            "override",
            "--time",
            "9:41",
        ])
        .unwrap();
        let Cmd::Sim {
            action: SimAction::Exec { device, verb, args },
        } = cli.cmd
        else {
            panic!("expected sim exec");
        };
        assert_eq!(device, "02");
        assert_eq!(verb, "status_bar");
        assert_eq!(args, ["override", "--time", "9:41"]);
    }

    /// The mistake that produced an opaque OSStatus -50.
    #[test]
    fn a_second_device_argument_is_named_as_the_mistake() {
        let complaint = exec_arity_complaint(
            "openurl",
            &[
                "74CAF762-06F0-4687-9D29-E737A435AEAF".to_string(),
                "insight://x".to_string(),
            ],
        )
        .expect("a udid passed to openurl is always a mistake");
        assert!(
            complaint.contains("takes no device argument"),
            "{complaint}"
        );
        assert!(
            complaint.contains("smix sim exec <ALIAS> openurl insight://x"),
            "it has to show the corrected command: {complaint}"
        );
    }

    /// A verb this does not know about is passed straight through.
    ///
    /// Guessing at arity for every verb would refuse the ones nobody
    /// thought about, and those are what a passthrough is for.
    #[test]
    fn an_unknown_verb_is_not_second_guessed() {
        assert!(
            exec_arity_complaint(
                "spawn",
                &["74CAF762-06F0-4687-9D29-E737A435AEAF".to_string()]
            )
            .is_none()
        );
    }

    #[test]
    fn an_ordinary_call_is_not_complained_about() {
        assert!(exec_arity_complaint("openurl", &["insight://x".to_string()]).is_none());
    }

    #[test]
    fn exec_argv_injects_udid_after_verb() {
        let argv = exec_argv(
            "push",
            UDID,
            &["com.example.app".into(), "payload.json".into()],
        );
        assert_eq!(argv, ["push", UDID, "com.example.app", "payload.json"]);
    }

    #[test]
    fn exec_argv_substitutes_placeholder_instead_of_injecting() {
        let argv = exec_argv(
            "spawn",
            UDID,
            &[
                "-s".into(),
                "{udid}".into(),
                "launchctl".into(),
                "list".into(),
            ],
        );
        assert_eq!(argv, ["spawn", "-s", UDID, "launchctl", "list"]);
    }

    // `--child-env KEY=VAL` repeatable flag on `sim launch` composes
    // `SIMCTL_CHILD_*` envp at dispatch time.
    #[test]
    fn sim_launch_parses_repeated_child_env_flags() {
        let cli = Cli::try_parse_from([
            "smix",
            "sim",
            "launch",
            "02",
            "com.example.app",
            "--child-env",
            "SMIX_PERF_RECEIVER_URL=http://127.0.0.1:9999",
            "--child-env",
            "LAUNCH_FORCE_PUSH=true",
        ])
        .expect("parse sim launch with --child-env x2");
        let Cmd::Sim {
            action:
                SimAction::Launch {
                    device,
                    bundle_id,
                    child_env,
                    launch_args,
                },
        } = cli.cmd
        else {
            panic!("expected sim launch");
        };
        assert_eq!(device, "02");
        assert_eq!(bundle_id, "com.example.app");
        assert_eq!(
            child_env,
            vec![
                (
                    "SMIX_PERF_RECEIVER_URL".to_string(),
                    "http://127.0.0.1:9999".to_string(),
                ),
                ("LAUNCH_FORCE_PUSH".to_string(), "true".to_string()),
            ]
        );
        assert!(launch_args.is_empty());
    }

    // Trailing launch arguments after `--` go to simctl as
    // `xcrun simctl launch ... -- <args>`; ProcessInfo.arguments reads
    // them. Mirrors maestro yaml launchApp.arguments.
    #[test]
    fn sim_launch_parses_trailing_launch_args_after_double_dash() {
        let cli = Cli::try_parse_from([
            "smix",
            "sim",
            "launch",
            "02",
            "com.example.app",
            "--child-env",
            "K=V",
            "--",
            "-uitestV2Root",
            "YES",
        ])
        .expect("parse trailing args");
        let Cmd::Sim {
            action:
                SimAction::Launch {
                    launch_args,
                    child_env,
                    ..
                },
        } = cli.cmd
        else {
            panic!("expected sim launch");
        };
        assert_eq!(launch_args, vec!["-uitestV2Root", "YES"]);
        assert_eq!(child_env.len(), 1);
    }

    #[test]
    fn sim_launch_without_child_env_yields_empty_vec() {
        let cli = Cli::try_parse_from(["smix", "sim", "launch", "02", "com.example.app"])
            .expect("parse bare launch");
        let Cmd::Sim {
            action: SimAction::Launch { child_env, .. },
        } = cli.cmd
        else {
            panic!("expected sim launch");
        };
        assert!(child_env.is_empty());
    }

    #[test]
    fn sim_launch_rejects_child_env_without_equals() {
        let err = Cli::try_parse_from([
            "smix",
            "sim",
            "launch",
            "02",
            "com.example.app",
            "--child-env",
            "NOEQUALS",
        ])
        .expect_err("must reject KEY without =");
        let msg = format!("{err}");
        assert!(
            msg.contains("KEY=VALUE") || msg.contains("="),
            "expected error to hint KEY=VALUE shape; got: {msg}"
        );
    }

    #[test]
    fn sim_launch_rejects_child_env_with_empty_key() {
        let err = Cli::try_parse_from([
            "smix",
            "sim",
            "launch",
            "02",
            "com.example.app",
            "--child-env",
            "=just_value",
        ])
        .expect_err("must reject empty KEY");
        let msg = format!("{err}");
        assert!(msg.contains("empty KEY"), "msg: {msg}");
    }

    #[test]
    fn parse_kv_pair_allows_equals_in_value() {
        let (k, v) = super::parse_kv_pair("URL=http://h:9999/p=q&r=s").expect("parse");
        assert_eq!(k, "URL");
        assert_eq!(v, "http://h:9999/p=q&r=s");
    }

    #[test]
    fn every_device_subcommand_accepts_alias_ref() {
        // Parse-level guarantee that the surface is alias-first: no
        // subcommand should reject a non-UDID device string at parse time.
        for argv in [
            vec!["smix", "sim", "boot", "02"],
            vec!["smix", "sim", "shutdown", "ios-17"],
            vec!["smix", "sim", "erase", "02"],
            vec!["smix", "sim", "screenshot", "02", "/tmp/x.png"],
            vec!["smix", "sim", "launch", "02", "com.example.app"],
            vec!["smix", "sim", "terminate", "02", "com.example.app"],
            vec!["smix", "sim", "install", "02", "/tmp/App.app"],
            vec!["smix", "sim", "uninstall", "02", "com.example.app"],
            vec!["smix", "sim", "openurl", "02", "https://example.com"],
            vec!["smix", "sim", "appearance", "02", "dark"],
            vec!["smix", "sim", "keychain-reset", "02"],
            vec!["smix", "sim", "resolve", "02"],
        ] {
            Cli::try_parse_from(&argv).unwrap_or_else(|e| panic!("{argv:?} failed to parse: {e}"));
        }
    }

    #[test]
    fn android_runner_up_takes_only_the_port_flag() {
        assert!(reject_ios_only_up_flags(false, false, false).is_ok());

        for (bundle, project, supervise, expected) in [
            (true, false, false, "--bundle"),
            (false, true, false, "--runner-project"),
            (false, false, true, "--supervise"),
        ] {
            let err = reject_ios_only_up_flags(bundle, project, supervise)
                .expect_err("an iOS-only flag must be refused, not dropped");
            assert!(err.contains(expected), "{expected} unnamed in: {err}");
            assert!(
                err.contains("--runner-port"),
                "the refusal must say what DOES work: {err}"
            );
        }
    }

    #[test]
    fn every_dropped_flag_is_named_at_once() {
        // One flag per run would make a user re-run three times to
        // discover three problems.
        let err = reject_ios_only_up_flags(true, true, true).expect_err("all three are iOS-only");
        for flag in ["--bundle", "--runner-project", "--supervise"] {
            assert!(err.contains(flag), "{flag} unnamed in: {err}");
        }
        assert!(err.contains("they are"), "plural form expected in: {err}");
    }
    /// `--animations` exists on `smix run` and is off by default.
    ///
    /// The default is the whole change: a run quietens the device
    /// unless this is passed. Read off the clap tree rather than the
    /// help text, because the text is generated from the tree and
    /// checking it would be checking the rendering.
    #[test]
    fn the_animations_flag_is_off_by_default() {
        use clap::CommandFactory;
        let cli = Cli::command();
        let run = cli
            .get_subcommands()
            .find(|c| c.get_name() == "run")
            .expect("`smix run` still exists");
        let arg = run
            .get_arguments()
            .find(|a| a.get_id() == "animations")
            .expect("`smix run --animations` exists");
        assert_eq!(
            arg.get_default_values(),
            ["false"],
            "the flag stopped defaulting to false, so a run no longer \
             quietens the device unless asked"
        );
    }

    /// The port `smix run` dials, in priority order.
    ///
    /// Extracted so the chain can be asserted rather than only read.
    /// It was already correct — and recorded as broken for three days,
    /// because nothing anywhere would have gone red either way.
    #[test]
    fn run_port_flag_wins() {
        assert_eq!(run_port(Some(22099), || Some(23000)), 22099);
    }

    #[test]
    fn run_port_falls_back_to_registry() {
        assert_eq!(run_port(None, || Some(22099)), 22099);
    }

    #[test]
    fn run_port_defaults_to_22087() {
        assert_eq!(run_port(None, || None), 22087);
    }

    /// Laziness is behaviour, not an implementation detail: with an
    /// explicit port there is no reason to read the registry off disk.
    /// A refactor to something eager would be invisible without this.
    #[test]
    fn run_port_skips_registry_lookup_when_flag_present() {
        let consulted = std::cell::Cell::new(false);
        let port = run_port(Some(22099), || {
            consulted.set(true);
            Some(23000)
        });
        assert_eq!(port, 22099);
        assert!(
            !consulted.get(),
            "registry was read despite an explicit port"
        );
    }
}