smix-cli 14.0.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
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
//! 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 this machine's registry (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.

// Every `print!` / `println!` in this crate is these, not std's: they are
// defined before the modules below so textual scoping hands them to all of
// them. std's versions panic when the reader has gone (SP1) — see
// `write_stdout`.
macro_rules! print {
    ($($arg:tt)*) => { $crate::write_stdout(format_args!($($arg)*)) };
}
macro_rules! println {
    () => { $crate::write_stdout(format_args!("\n")) };
    ($($arg:tt)*) => { $crate::write_stdout(format_args!("{}\n", format_args!($($arg)*))) };
}

mod act;
mod authoring;
mod bench;
mod boot_avd;
mod boot_cold;
mod boot_record;
mod capsule;
mod platform;
mod tree_cmd;
use platform::{DeviceDial, RunPlatform, dial_platform, resolve_run_platform};
mod departures;
mod device_hub;
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 lease_cmd;
mod parallel;
mod readiness;
mod record_cmd;
mod runner_list;

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
    (an alias from this machine's registry — `smix sim list` — or a 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. Omitted, it is derived from the
        /// project directory's name, so two projects do not both silently
        /// register as "dev".
        #[arg(long)]
        alias: Option<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,
        /// The runner to ask, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// 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,
    },
    /// Report which runner this session would dial and what it has open.
    ///
    /// Read-only. The CLI counterpart of the `smix_session_state` MCP
    /// tool — the one query answerable before anything is bound.
    Session {
        #[command(subcommand)]
        action: SessionAction,
    },
    /// 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 a sim the registry does not hold).
    Down {
        /// The runner this sweep stops first, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// Inspect and settle the device resource ledger: who holds a device,
    /// what they left open, and closing it gracefully when they are gone.
    Lease {
        #[command(subcommand)]
        action: LeaseAction,
    },
    /// Record the device screen. The recording is written into the device
    /// ledger, so it survives the process that started it and can be
    /// closed gracefully if that process dies.
    Record {
        #[command(subcommand)]
        action: RecordAction,
    },
    /// 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,
        /// Which language to read an `ocrText:` selector in — `zh-Hans`,
        /// `ja`, `en`. Repeatable, best first. Left out, the recogniser
        /// works out the language itself; naming the wrong one does not
        /// fail, it misreads.
        #[arg(long = "ocr-locale")]
        ocr_locale: Vec<String>,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
        /// Write a frame to this path the moment the tap returns.
        ///
        /// For UI that does not wait: a control bar that hides itself
        /// after a few seconds outlives neither a second command nor the
        /// turn between two tool calls. One call takes the picture from
        /// the same process that tapped — measured at about 88 ms after
        /// the tap returns, against roughly 325 ms going out to device
        /// tooling.
        ///
        /// A tap that fails writes nothing: a frame taken after a tap
        /// that did not land looks like evidence and is a picture of the
        /// screen nothing happened on.
        #[arg(long = "then-screenshot", value_name = "OUT")]
        then_screenshot: Option<PathBuf>,
    },
    /// Boolean existence probe (POST /find). Prints `exists=<bool>`.
    /// Same selector shorthand as `smix tap`.
    Find {
        /// Which element to look for, in `<kind>:<value>` shorthand.
        selector: String,
        /// Which language to read an `ocrText:` selector in — `zh-Hans`,
        /// `ja`, `en`. Repeatable, best first. Left out, the recogniser
        /// works out the language itself; naming the wrong one does not
        /// fail, it misreads.
        #[arg(long = "ocr-locale")]
        ocr_locale: Vec<String>,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// 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 {
        /// Which element to wait for, in `<kind>:<value>` shorthand.
        selector: String,
        /// Timeout in seconds (default 5).
        #[arg(long, default_value_t = 5)]
        timeout: u64,
        /// Which language to read an `ocrText:` selector in — `zh-Hans`,
        /// `ja`, `en`. Repeatable, best first. Left out, the recogniser
        /// works out the language itself; naming the wrong one does not
        /// fail, it misreads.
        #[arg(long = "ocr-locale")]
        ocr_locale: Vec<String>,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
        /// Wait until the element is gone, instead of until it appears.
        ///
        /// Mirrors `smix_assert_not_visible`, which the MCP server has
        /// and the CLI did not — so a flow could wait for a spinner to
        /// show and not for it to disappear.
        #[arg(long)]
        absent: bool,
    },
    /// Type text into the matched field. Equivalent to the flow yaml
    /// `inputText:` verb. Selector shorthand same as `smix tap`.
    Fill {
        /// Which field to type into, in `<kind>:<value>` shorthand.
        selector: String,
        /// The text to type.
        #[arg(long)]
        text: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// Press a key by name: `return`, `delete`, `back`, `home`,
    /// `volume up`, maestro's `Enter` / `Backspace`, the arrows and the
    /// rest. Case, spaces, `_` and `-` do not matter; an unknown name is
    /// refused with the whole list. `back` is the flow's `back`: system
    /// back on Android, the navigation bar's back on iOS, and it fails
    /// when nothing went back.
    PressKey {
        /// The key's name, read as a flow's `pressKey` reads it.
        key: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// Swipe once through the content. `direction` names what you
    /// want to see — `down` reveals what is below — not which way the
    /// finger moves. Direction: `up` / `down` / `left` / `right`.
    ///
    /// Mirrors `smix_swipe`, which the MCP server has had since it
    /// existed while the CLI had nothing. Use `scroll` when you want to
    /// stop at an element; this is the one-gesture form.
    Swipe {
        /// `up` / `down` / `left` / `right`. Leave it out when giving
        /// `--from` and `--to`.
        direction: Option<String>,
        /// Where the finger starts, as `X%,Y%` or `X,Y` in 0..1 —
        /// the authorised coordinate escape hatch (§9 #3), for screens
        /// with nothing nameable to swipe between. Requires `--to`.
        #[arg(long = "from")]
        from_point: Option<String>,
        /// Where the finger ends, same form as `--from`.
        #[arg(long = "to")]
        to_point: Option<String>,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// Swipe until the selector's target is wholly in view — the same
    /// loop `scrollUntilVisible` runs, with its defaults (100% visible,
    /// 20 s). Direction: `up` / `down` / `left` / `right`.
    Scroll {
        /// Which element to bring into view, in `<kind>:<value>` shorthand.
        /// `ocrText:` works too: after each swipe the tree is read first,
        /// then OCR.
        selector: String,
        /// Which way to travel through the content — names what you want to
        /// SEE, not the finger's path. `up` / `down` / `left` / `right`.
        #[arg(long)]
        direction: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// Dismiss the soft keyboard if visible.
    HideKeyboard {
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// Print the runner's current a11y tree. `--json` emits
    /// wire JSON; default emits an indented text outline.
    Tree {
        /// Emit machine-readable JSON instead of the human outline.
        #[arg(long)]
        json: bool,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
        /// Print the software keyboard's keys.
        ///
        /// They are collapsed by default: a key per letter plus
        /// `Next keyboard`, `Dictate`, shift and delete is around sixty
        /// nodes that are the same sixty on every screen of every app,
        /// and this output is read by an AI paying for each one. The
        /// keyboard node itself always prints, with the number of keys
        /// it holds — so nothing disappears without saying so.
        #[arg(long)]
        keyboard: bool,
        /// Which reader to ask: `auto` (default), `probe`, or `a11y`.
        ///
        /// `auto` is what a flow does — the app's own semantics tree
        /// when it carries the probe, the accessibility projection
        /// otherwise — and it is what you want unless you are comparing
        /// the two. Naming one asks that one and fails if it cannot
        /// answer, rather than quietly handing back the other: a tool
        /// comparing two readers that is silently given the same tree
        /// twice reports perfect agreement.
        #[arg(long, default_value = "auto")]
        reader: TreeReader,
    },
    /// Print the runner's high-level ScreenDescription: the visible
    /// interactive elements aggregated from the current a11y tree.
    Describe {
        /// Emit machine-readable JSON instead of the human outline.
        #[arg(long)]
        json: bool,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
    },
    /// Print the runner's current SpringBoard system-popup list.
    SystemPopups {
        /// Emit machine-readable JSON instead of the human outline.
        #[arg(long)]
        json: bool,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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 {
        /// Which popup, as `smix system-popups` reports it.
        popup_id: String,
        /// Which button on it, as that same listing reports it.
        button_id: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        /// `--runner-port` is accepted too — `smix run` spells it that way.
        #[arg(long, alias = "runner-port")]
        port: Option<u16>,
        /// Device UDID, or an alias / deviceName in the workspace's
        /// `.smix` registry. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[arg(long)]
        device: Option<String>,
        /// Which platform the device is, for a device this machine has not
        /// registered. A registered device's own kind is read otherwise.
        #[arg(long, value_enum)]
        platform: Option<RunPlatform>,
    },
    /// 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.
        ///
        /// `--port` is accepted too: the act verbs (`tap`, `find`, `fill`)
        /// spell the same thing that way, and a caller moving between
        /// them met `error: unexpected argument '--port'` with a
        /// suggestion of `--format`. One concept, two spellings, and
        /// nothing said which belonged where.
        #[arg(long, alias = "port", 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. When the run ends the
        /// scales are put back to what they were, including after an
        /// interrupted run, by the next run on that device; a physical
        /// Android device is left as it is. 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. Left out, it is read from `--device`: an
        /// emulator is Android, a simulator is iOS. Pass it only for a
        /// device the registry cannot classify, or a run with no
        /// `--device` at all.
        #[arg(long, value_enum, env = "SMIX_PLATFORM")]
        platform: Option<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. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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. It finds the runner port that device is
        /// registered on, and — where a verb behaves differently by
        /// platform (fill, find, tap and the rest of the act surface) —
        /// reads the driver from the device's registered kind, so an
        /// Android device is driven through its own runner, not simctl.
        #[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,
        }
    }
}

/// Which of the two readers `smix tree` should ask.
///
/// smix has one perception primitive and two things that satisfy it. A
/// flow takes whichever is available, best first, and says which
/// answered. A reader comparing the two needs to ask each by name —
/// and to be told "that one cannot answer here" rather than handed the
/// other, because a comparison silently given the same tree twice
/// reports that the two agree perfectly.
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum TreeReader {
    /// The app's own semantics tree when it carries the probe, the
    /// accessibility projection otherwise. What a flow does.
    Auto,
    /// The app's semantics tree, through the smix probe.
    Probe,
    /// The accessibility projection, which every app has.
    A11y,
}

impl TreeReader {
    fn to_act(self) -> act::TreeReader {
        match self {
            Self::Auto => act::TreeReader::Auto,
            Self::Probe => act::TreeReader::Probe,
            Self::A11y => act::TreeReader::A11y,
        }
    }
}

#[derive(Subcommand, Debug)]
enum CapsuleAction {
    /// Bring up sim + start capture + start runner in record mode.
    Up {
        /// Which device to bring the capsule up on, by UDID or registry alias.
        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 a simulator window is on
        /// screen (Simulator.app on Xcode <= 26; Device Hub on Xcode 27
        /// does not react to a boot, so it never trips this).
        ///
        /// For CI, where a window means something is wrong. On a dev
        /// machine `expo run:ios` opens the simulator UI 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 a Simulator.app (Xcode <= 26)
        /// window 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,
        /// The runner to start, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// Reverse teardown: runner down + capture stop + sim shutdown.
    Down {
        /// Which device to tear the capsule down on, by UDID or registry alias.
        device: String,
        /// The runner to stop, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
}

#[derive(Subcommand, Debug)]
enum RecordAction {
    /// Start recording to a file.
    Start {
        /// Which device to record, by UDID or registry alias.
        device: String,
        /// Where to write the mp4.
        #[arg(long)]
        output: PathBuf,
    },
    /// Stop the recording, letting it write its trailer.
    Stop { device: String },
    /// Whether this device is recording, and where it is writing.
    Status { device: String },
}

#[derive(Subcommand, Debug)]
enum LeaseAction {
    /// Every device with a ledger, and whether its holder is still there.
    List,
    /// One device: the holder, what is open, and the verdict.
    Status {
        /// The device: an alias, a UDID or a serial.
        device: String,
        /// Print the device's ledger as JSON — `{"device", "path", "lease",
        /// "heldBy"}`: the file it lives in, the lease as it is stored (null
        /// when there is none), and who holds the device now — `{"pid",
        /// "cmd", "alive"}`, or null when a new claim would be granted —
        /// for a script to read instead of building the ledger's path or
        /// judging the holder itself.
        #[arg(long)]
        json: bool,
    },
    /// Close what a dead holder left open, by the graceful path it never
    /// got to take. A live holder is reported, never preempted.
    Reconcile { device: String },
    /// Answer for a device this machine did not boot.
    ///
    /// The decision every release was already making and leaving
    /// nowhere. A dedicated emulator started by hand has no ledger, so
    /// nothing here may drive it — and the only way through was an
    /// environment variable that says "it is mine" to one command and is
    /// forgotten the moment it exits. The next run makes the same
    /// decision again, and no one can read who made it last time.
    ///
    /// A claim grants exactly one of the two things a boot row grants:
    /// this device is yours to drive, and is not yours to switch off.
    /// `lease owner` reports it as a claim rather than a boot, so the
    /// difference is never invisible, and the ledger ends it when the
    /// device goes off.
    ///
    /// Refused while somebody else's live session holds the device —
    /// claiming is a statement about an unheld device, not a way past
    /// a held one.
    Claim { device: String },
    /// Give up a claim made by `lease claim`.
    ///
    /// Removes only the claim. A device this machine really did boot
    /// keeps saying so, because that row answers a different question.
    Release { device: String },
    /// Who answers for this device, in one line and an exit code.
    ///
    /// `0` means a ledger says smix booted it, and names the session;
    /// `3` means no ledger says that — somebody else turned it on, or
    /// nobody wrote it down; `1` means the question could not be asked.
    /// Three codes rather than two: a check that answers "safe" when it
    /// means "I do not know" is the shape this cycle keeps finding.
    ///
    /// A claim answers `0` as well, and says so in words: it is the same
    /// entitlement to drive and deliberately not the same entitlement to
    /// shut down. Callers that act on the exit code inherit claims
    /// without being changed; a caller that cares which it is has the
    /// sentence.
    ///
    /// Not a teardown permission. It answers "did smix boot this",
    /// which is not "did *you* boot this" — a shell script's `smix sim
    /// boot` exits immediately, so the session that booted the device
    /// is never the one asking. A script that shut down whatever this
    /// reported as smix's would take away a device another run is
    /// using. What it is for is the question that could not be answered
    /// on 2026-08-11: a runner was found holding port 22087, the rule
    /// said find its owner before touching it, and the owner was
    /// recorded in a tree nobody was standing in.
    Owner { device: String },
    /// Fold per-checkout ledgers into this machine's.
    ///
    /// Ledgers used to live in whichever `.smix/` was above the working
    /// directory. Adds and never removes; running it twice does nothing
    /// the second time.
    Migrate {
        /// A checkout (or its `.smix/leases`) to read. Repeatable.
        /// Defaults to the one above the working directory.
        #[arg(long = "from", value_name = "DIR")]
        from: Vec<PathBuf>,
        /// Say what would move and move nothing.
        ///
        /// The same decision path as the real thing, split only at the
        /// write — a rehearsal that works the answer out for itself is
        /// answering about itself.
        #[arg(long)]
        dry_run: bool,
    },
    /// Delete ledgers that no longer describe anything.
    ///
    /// A ledger that can only be added to stops describing the machine:
    /// a holder that died without releasing, or a boot row for a device
    /// that is off, sits there for ever and every later command has to
    /// reason around it. Says what it deleted and why; keeps everything
    /// else and says why too.
    Prune {
        /// Report what would go, and delete nothing.
        #[arg(long)]
        dry_run: bool,
        /// Look at this one device's ledger and no other.
        ///
        /// Prune reads every ledger on the machine, and a machine is
        /// shared: without this, cleaning up after your own device meant
        /// running a judgement over somebody else's rows too.
        #[arg(long, value_name = "DEVICE")]
        device: Option<String>,
    },
    /// Devices that left while a ledger still said they were here.
    ///
    /// Noticed by the next `run`, `runner`, `sim` or `lease` command after
    /// the device went: an emulator that exited, a simulator shut down
    /// from outside, a phone unplugged. Each entry says which device (and
    /// its AVD), when it was noticed, when its ledger last heard from it,
    /// who held it, whether smix booted it, what answers on its port now,
    /// and — for an emulator smix started — the last lines it printed on
    /// its console. An emulator smix did not start has no console here to
    /// read, and its exit status is nobody's to collect.
    History {
        /// Print the history as JSON.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand, Debug)]
enum RunnerAction {
    /// Start the runner on a device; blocks until /health answers.
    Up {
        /// The device to bring the runner up on.
        ///
        /// `--device` names the same thing and is accepted, because
        /// `runner down` takes it that way. One pair of commands with
        /// two shapes for the same argument is a trip somebody takes
        /// every time — and the guards and guides that suggested the
        /// flag form were, until now, suggesting something this command
        /// answered with "a similar argument exists: '--supervise'".
        #[arg(value_name = "DEVICE", required_unless_present = "device_flag")]
        device: Option<String>,
        /// The device, named rather than positional. See `device`.
        #[arg(long = "device", conflicts_with = "device")]
        device_flag: Option<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,
        /// The app under test: `runner up` finishes with it in front. On
        /// a fresh bring-up it is relaunched, or only brought forward with
        /// `--no-launch` — the same on both platforms. On Android it is
        /// also brought forward when the runner was already up and the
        /// app was not in front.
        ///
        /// Required on iOS, where the runner binds its XCUIApplication to
        /// it. Optional on Android, whose runner takes its target from the
        /// App-Bundle-Id header per request — without it, `runner up`
        /// leaves whatever is in front where it is, and never brings an
        /// app nobody named forward. With it, an app killed by `adb
        /// install` is brought back rather than leaving the first step of
        /// the next flow to find the launcher.
        #[arg(long)]
        bundle: Option<String>,
        /// Explicit path to `SmixRunner.xcodeproj`. Wins over
        /// `$SMIX_RUNNER_PROJECT` env and the install-shipped default
        /// under `~/.local/share/smix/runner-sources/ios/`. 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 → the device's registered `runnerPort`
        /// (`smix sim register --runner-port`) → `SMIX_RUNNER_PORT` env →
        /// 22087 default. Two sims registered with distinct ports 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 the
        /// device's ledger, beside the runner. `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,
        /// Apple developer team id, for a physical device.
        ///
        /// Discovered from this machine's signing identities when
        /// omitted. Needed only when several teams could sign, which is
        /// a question smix refuses to answer for you.
        #[arg(long)]
        team: Option<String>,
        /// Keep the app where it is: foreground it instead of
        /// relaunching it.
        ///
        /// **Reach for this when the runner died mid-session and you
        /// are several screens deep.** Bringing the runner back up
        /// restarts the target app by default, so the navigation is
        /// gone and the next step fails against a splash screen —
        /// somebody re-walked three or four screens a dozen times in an
        /// afternoon before finding this flag, because the text here
        /// described the problem without saying it was also the answer.
        ///
        /// Same meaning as `smix run --no-launch`, which has had it for
        /// longer.
        #[arg(long = "no-launch", default_value_t = false)]
        no_launch: bool,
        /// Cycle a runner of ours whose session has stopped working,
        /// instead of reporting it as already up.
        ///
        /// `/health` says the runner's HTTP server is answering; it
        /// cannot see the app binding, so reinstalling the app leaves a
        /// runner that answers 200 and drives nothing — and this command,
        /// reading only that, used to say "already up" and return
        /// success. Without this flag it now says no and names the fix;
        /// with it, it runs the fix: the same in-place cycle as
        /// `smix runner cycle`, seconds, no xcodebuild restart.
        ///
        /// It does not reach across to a runner recorded for another
        /// device, or to one the device ledger has no record of. Those are
        /// refused with or without it — `runner down --include-unrecorded`
        /// is the sanctioned way through, and it is a separate decision
        /// on purpose.
        #[arg(long = "force", default_value_t = false)]
        force: bool,
        /// Android: also replace a runner a live process other than this
        /// one is holding.
        ///
        /// `--force` is not this. It means "cycle a runner of ours whose
        /// session has stopped working", and the case here is a runner
        /// that is working fine and belongs to somebody else. An Android
        /// device has one runner, so bringing ours up ends theirs;
        /// without this flag that is refused and their command line is
        /// printed instead.
        #[arg(long = "take-over", default_value_t = false)]
        take_over: 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>,
        /// Also stop a runner on this port that this workspace has no
        /// record of.
        ///
        /// Off by default: an unrecorded runner may belong to another
        /// session, and ending one by accident is how a sweep once took
        /// out somebody else's work. `runner up` refuses such a port for
        /// the same reason — this flag is the sanctioned way through,
        /// and it is a sentence somebody says rather than something that
        /// happens.
        #[arg(long = "include-unrecorded", default_value_t = false)]
        include_unrecorded: bool,
        /// Android: also end a runner a live process other than this one
        /// is holding.
        ///
        /// An Android device has one runner -- one instrumentation
        /// package, one device-side port -- so there is no version of
        /// this that ends only ours. Without the flag, a device somebody
        /// else is driving is refused and their command line is printed.
        /// This is not `--include-unrecorded`, which means "one the
        /// ledger does not know about"; the case here is one the ledger
        /// knows perfectly well and says is not yours.
        #[arg(long = "take-over", default_value_t = false)]
        take_over: bool,
        /// Which runner's port, when it is not the default.
        ///
        /// `runner up` has taken this flag all along and `down` did
        /// not, reading `SMIX_RUNNER_PORT` instead. So the obvious
        /// pairing — up with `--runner-port N`, down with the same —
        /// failed the argument parse, and a teardown written that way
        /// left the runner running. Ours did, in the e2e written to
        /// prove this very release: the check passed, the process
        /// outlived it, and `|| true` on the cleanup line meant nothing
        /// said so.
        #[arg(long)]
        runner_port: Option<u16>,
    },
    /// Hold a port forward open to a physical device. Runs in the
    /// foreground until killed.
    ///
    /// `runner up` spawns this for a physical device; it is documented
    /// because a process that appears in `ps` and in the device ledger
    /// should be findable, not a mystery.
    Forward {
        /// Device UDID.
        device: String,
        /// Port, the same on both sides.
        #[arg(long, default_value_t = 22087)]
        port: u16,
    },
    /// Remove the Android instrumentation package `runner up` installed.
    ///
    /// Android only: the iOS runner is not installed as a standalone
    /// package, it is launched by xcodebuild and leaves nothing behind.
    Uninstall {
        /// Which platform. Only `android` is meaningful here.
        #[arg(long, value_enum, default_value_t = RunPlatform::Android)]
        platform: RunPlatform,
        /// Device serial. Required — an unpinned uninstall would reach
        /// whatever is attached.
        #[arg(long)]
        device: 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 the device ledger records no runner on
    /// the port — use `runner up` for a cold start.
    ///
    /// iOS only, and it says so when handed anything else. It took no
    /// device at all until 6.6, which is how it came to read one
    /// platform's records about the other's runner.
    Cycle {
        /// Which platform. iOS only — Android is refused by name
        /// rather than by reading the wrong platform's records.
        #[arg(long, value_enum, default_value_t = RunPlatform::Ios)]
        platform: RunPlatform,
        /// 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>,
        /// The runner to cycle, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// 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>,
        /// The port of the runner to watch. It is how the supervisor
        /// finds its runner in the device ledger: a checkout can drive
        /// several simulators at once, each on its own port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// List every session the runner currently tracks.
    /// Reads `POST /session/list`. Useful for post-cycle diagnostics.
    ListSessions {
        /// The runner to ask, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// Every smix runner on this machine: its port, its device, and
    /// whether the ledgers know about it.
    ///
    /// Not `list-sessions`, which asks one runner what app sessions it
    /// has open. This asks the machine what runners it has at all —
    /// reading the ledgers and the listening sockets and putting them
    /// side by side, because a runner nobody wrote down is exactly the
    /// one you cannot decide about.
    ///
    /// Reads only by default. It never signals a process, and without
    /// `--prune` it never writes a ledger, and always exits 0: a command
    /// meant to be run before touching anything has to be safe to run.
    List {
        /// Delete the rows whose recorded process is gone.
        ///
        /// A read-mostly command gets one explicit write rather than a
        /// tidy-up nobody asked for — the same shape as
        /// `--include-unrecorded`: clearing up is a thing somebody says
        /// out loud.
        ///
        /// Only `process-gone` rows, which are the ones this command can
        /// prove ended: the recorded pid, and the start time that tells
        /// a recycled number from the real process. A row that is merely
        /// not listening is left alone — that is `lease reconcile`'s
        /// question, and it has closes to perform that this does not.
        ///
        /// Reported by a consumer: four rows, four dead pids, and
        /// nothing that cleared them. `down` refuses a runner this
        /// workspace never recorded, so the ledger is what decides
        /// whether a device can be shut down — and a ledger filling with
        /// dead rows makes that decision rest on a list nobody maintains.
        #[arg(long, default_value_t = false)]
        prune: bool,
    },
    /// Extract the CLI's embedded Swift runner sources into the tree for
    /// them, `~/.local/share/smix/runner-sources/ios/<version>-<digest>/`
    /// — one per set of sources, so another smix on this machine keeps
    /// its own. Normally done by `smix runner up`; this verb makes it
    /// explicit for troubleshooting or first-time setup on an air-gapped
    /// machine. With `--path`, extracts into that directory instead,
    /// backing any tree already there up beside it.
    Install {
        /// Destination directory. Defaults to this binary's tree under
        /// `$XDG_DATA_HOME/smix/runner-sources/ios/` (falling back to
        /// `~/.local/share/smix/runner-sources/ios/`).
        #[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,
        /// List the devices smix has recorded, with their aliases,
        /// instead of the ones the platform reports.
        ///
        /// These are two different questions and nothing answered the
        /// second one. `smix sim list` asks simctl and adb, so it
        /// returns the same thing from every checkout whether or not
        /// device records are shared — which made it useless as
        /// evidence that they are.
        #[arg(long)]
        registered: bool,
    },
    /// Print the identifier a device ref resolves to, and which book said so.
    ///
    /// The identifier goes to stdout, alone, so `$(smix sim resolve x)`
    /// keeps working. Which registry answered goes to stderr: this
    /// machine's, a checkout's legacy `.smix/sims.json`, or the one
    /// `SMIX_SIMS_JSON` names. When this machine's registry and a
    /// checkout's book give the alias to two different devices, nothing
    /// is printed to stdout and the command fails naming both.
    ///
    /// A harness driving smix from outside should read this — with
    /// `--json` — rather than any registry file: `.smix/sims.json` is a
    /// legacy book smix reads and never writes.
    Resolve {
        /// The alias to look up.
        device: String,
        /// One JSON object: `ref`, `id`, `alias`, `source` (`kind` and
        /// `path`), `deviceKind`, and for an emulator its `avd`.
        #[arg(long)]
        json: bool,
    },
    /// Record a device 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, and a physical device
    /// cannot be addressed at all until it is registered.
    ///
    /// A virtual device is checked against the catalogue its own
    /// platform keeps — `--kind simulator` (the default) against
    /// `simctl`, `--kind emulator` against `adb` — and its name and
    /// runtime are read from there, so only the UDID and alias are
    /// needed. A physical device is taken as given: nothing here can
    /// enumerate the world's phones, which is why registering one is a
    /// deliberate act rather than a lookup.
    Register {
        /// The short name this device answers to from now on.
        alias: String,
        /// The device's own identifier: a CoreSimulator UDID, an
        /// `emulator-<port>` serial, or a phone's UDID.
        #[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>,
        /// What kind of device this is.
        ///
        /// Defaults to a simulator, which is the case that must keep
        /// working without anyone learning a new flag. A physical value
        /// changes two things: the identifier is taken as given rather
        /// than looked up in simctl (which lists no phones), and
        /// destructive actions are refused on it until
        /// `smix sim allow-destructive` is run once.
        #[arg(long, value_enum, default_value_t = DeviceKindArg::Simulator)]
        kind: DeviceKindArg,
        /// Human-readable name for a physical device. Ignored for
        /// simulators, whose name comes from simctl.
        #[arg(long)]
        name: Option<String>,
    },
    /// Boot a simulator.
    Boot {
        /// Which device to boot, by UDID or registry alias.
        device: String,
        /// Boot an Android emulator from scratch instead of its Quick Boot
        /// snapshot, which keeps whatever state the device stopped in.
        #[arg(long)]
        cold: bool,
    },
    /// Shutdown a simulator.
    Shutdown {
        /// Which device to shut down, by UDID or registry alias.
        device: String,
    },
    /// Erase a simulator's data.
    Erase {
        /// Which device to wipe, by UDID or registry alias.
        device: String,
    },
    /// Take a screenshot (PNG). Pass `-` to write raw PNG to stdout.
    Screenshot {
        /// Which device to photograph, by UDID or registry alias.
        device: String,
        /// Where to write the PNG.
        out: PathBuf,
        /// The runner that photographs a phone `devicectl` cannot, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// 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 {
        /// Which device, by UDID or registry alias.
        device: String,
        /// The app to launch.
        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 {
        /// Which device, by UDID or registry alias.
        device: String,
        /// The app to stop.
        bundle_id: String,
    },
    /// Put an app on a device: an `.app` on a simulator, an `.apk` on an
    /// Android emulator or phone.
    ///
    /// A simulator goes through `simctl`, an emulator or an Android
    /// phone through `adb`. A physical iPhone has no path here and is
    /// refused rather than attempted — installing on one needs
    /// `devicectl` and a provisioning profile, which nothing in smix
    /// wires up.
    ///
    /// adb's own failures are passed through as it reports them: an
    /// `.apk` signed by a different key does not replace the installed
    /// one, and you get adb's words for why rather than smix's guess.
    Install {
        /// Which device, by UDID or registry alias.
        device: String,
        /// Path to the `.app` bundle or `.apk` to install.
        app_path: PathBuf,
    },
    /// Take an app off a device, by bundle id on Apple platforms and by
    /// package name on Android.
    ///
    /// Reaches every kind of device smix can address. On a physical one
    /// it is refused until that device has been opted in with `smix sim
    /// allow-destructive <device>` — taking an app off somebody's phone
    /// removes its data with it.
    Uninstall {
        /// Which device, by UDID or registry alias.
        device: String,
        /// The app to remove.
        bundle_id: String,
    },
    /// Let an Android device reach a service running on this machine.
    ///
    /// The app under test dials `127.0.0.1:<port>` on the device and
    /// lands on `127.0.0.1:<port>` here — `--to` sends it to a
    /// different port on this side. A consumer's suite starts its API
    /// stub on the host; without this, a phone on the cable has no way
    /// to reach it at all, and an emulator has only a special address
    /// to remember.
    ///
    /// What is opened stays open: it survives this command, the runner,
    /// and the flow. It goes when `--remove` names it, when the device
    /// goes away, or when a teardown closes the ledger row this writes.
    ///
    /// Android only. A simulator already shares this machine's loopback
    /// and needs nothing; a physical iPhone has no such channel, and
    /// both say so rather than doing nothing quietly.
    Reverse {
        /// Which device, by serial or registry alias.
        device: String,
        /// The port the app dials on the device. It also names the
        /// route later, for `--remove`.
        port: u16,
        /// The port on this machine to land on. Defaults to the same
        /// number the device dials.
        #[arg(long, conflicts_with = "remove")]
        to: Option<u16>,
        /// Close the route this port names instead of opening one.
        #[arg(long)]
        remove: bool,
    },
    /// Turn the device's screen on.
    ///
    /// Lights the screen and waits until the power manager agrees it is
    /// on. It does **not** unlock: a device with a passcode keeps its
    /// keyguard, and the name says only what it does.
    ///
    /// Android only — a simulator's screen never sleeps, and devicectl
    /// can read a phone's lock state but not change it.
    Wake {
        /// Which device, by serial or registry alias.
        device: String,
    },
    /// Keep the screen on while the device is charging, or stop.
    ///
    /// A device setting, so it outlives the run that set it. Reading it
    /// back is part of the command: `svc power stayon` reports nothing
    /// about whether the setting took.
    ///
    /// Android only, for the same reasons as `wake`.
    StayAwake {
        /// Which device, by serial or registry alias.
        device: String,
        /// `on` to hold the screen awake on a charger, `off` to stop.
        ///
        /// `action = Set` because clap gives a `bool` field the flag
        /// treatment by default, and a positional that takes no value
        /// is a command that cannot be built at all.
        #[arg(value_parser = parse_on_off, action = clap::ArgAction::Set)]
        state: bool,
    },
    /// Grant, revoke or reset one runtime permission for an app.
    ///
    /// `simctl privacy` on a simulator and `pm grant` / `pm revoke` on
    /// Android. A physical iPhone refuses: those grants are the owner's,
    /// and devicectl has no equivalent.
    Permission {
        /// Which device, by UDID, serial or registry alias.
        device: String,
        /// The app the permission belongs to.
        bundle_id: String,
        /// Which permission, e.g. `camera`, `location`, `post-notifications`.
        permission: String,
        /// What to do with it.
        #[arg(value_parser = parse_permission_action)]
        action: String,
    },
    /// Print which app is in front.
    ///
    /// A read, not a command: it reports the app the device has resumed
    /// and changes nothing. Nothing resumed — a lock screen, a device
    /// still booting — prints that and exits 0.
    ///
    /// Android only: neither simctl nor devicectl reports this, and the
    /// runner answers it for an Apple device (`smix tree` names the app
    /// it read).
    Frontmost {
        /// Which device, by serial or registry alias.
        device: String,
        /// Print JSON instead of a line of prose.
        #[arg(long)]
        json: bool,
    },
    /// Print the crashes the device has recorded.
    ///
    /// Exits 0 whether or not it finds any: a read that found nothing
    /// is not a failure, and exiting non-zero would kill a healthy run
    /// under `set -e`.
    ///
    /// Android only — a simulator's reports land in this machine's own
    /// folder, which is not divided by device, and a phone's stay on the
    /// phone.
    Crashes {
        /// Which device, by serial or registry alias.
        device: String,
        /// Only reports naming this process.
        #[arg(long)]
        app: Option<String>,
        /// Print JSON instead of prose.
        #[arg(long)]
        json: bool,
    },
    /// Open a URL on the simulator.
    Openurl {
        /// Which device, by UDID or registry alias.
        device: String,
        /// The URL to open — a deeplink the app registered, or any scheme the OS handles.
        url: String,
    },
    /// Set simulator UI appearance (light / dark).
    Appearance {
        /// Which device, by UDID or registry alias.
        device: String,
        /// `light` or `dark`.
        #[arg(value_parser = parse_appearance)]
        mode: Appearance,
    },
    /// Allow destructive actions on a physical device, once.
    ///
    /// Simulators are never gated — they can be erased and rebuilt in a
    /// minute. A phone cannot, so wiping app data, resetting a keychain
    /// or uninstalling on one is refused until this is run. Recorded in
    /// the registry rather than confirmed per command: a confirmation
    /// that has to be typed every time ends up pasted into a script.
    AllowDestructive {
        /// Which device this consent is recorded for, by UDID or registry alias.
        device: String,
    },
    /// Forget one alias.
    ///
    /// Removes the name, not the device — another alias for the same
    /// device keeps working. The other half of `register`, which
    /// without it could only ever add.
    Unregister {
        /// The alias to forget.
        alias: String,
    },
    /// Fold per-checkout device registries into this machine's.
    ///
    /// Device records used to live in whichever `.smix/` was above the
    /// working directory, so a machine with four checkouts had four
    /// answers about the same simulators. This copies them into one
    /// place. It adds and never removes: the source registries are left
    /// exactly where they are, and running it twice does nothing the
    /// second time.
    Migrate {
        /// A checkout (or its `.smix`) to read. Repeatable. Defaults to
        /// the one above the working directory.
        ///
        /// There is no index of checkouts on a machine, so the ones
        /// that are not underfoot have to be named. Better than guessing
        /// at a list and quietly missing the tree somebody actually
        /// cares about.
        #[arg(long = "from", value_name = "DIR")]
        from: Vec<PathBuf>,
        /// Say what would move and move nothing.
        #[arg(long)]
        dry_run: bool,
    },
    KeychainReset {
        /// Which device, by UDID or registry alias.
        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: a locale registered with the device (`smix sim register
    /// --locale`) 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 {
        /// Which device, by UDID or registry alias.
        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 {
        /// Which device, by UDID or registry alias.
        device: String,
        /// The simctl verb to run.
        verb: String,
        /// Everything after the verb, passed through untouched.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

/// `on` / `off` as a bool. Anything else is rejected at parse time,
/// naming both spellings — a value nobody recognises must not become a
/// default, which is how `stay-awake maybe` would quietly turn it off.
fn parse_on_off(s: &str) -> Result<bool, String> {
    match s.trim().to_ascii_lowercase().as_str() {
        "on" => Ok(true),
        "off" => Ok(false),
        other => Err(format!("expected `on` or `off`, got `{other}`")),
    }
}

/// One of `grant` / `revoke` / `reset`, kept as the string the action
/// enum parses downstream.
fn parse_permission_action(s: &str) -> Result<String, String> {
    match s.trim().to_ascii_lowercase().as_str() {
        a @ ("grant" | "revoke" | "reset") => Ok(a.to_string()),
        other => Err(format!(
            "expected `grant`, `revoke` or `reset`, got `{other}`"
        )),
    }
}

/// 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)),
    }
}

/// Whether a device reference is asking "where is my device" rather
/// than naming a slot outright.
///
/// A caller who types `emulator-5556` has named the slot; answering
/// their literal with a refusal because some row in some checkout also
/// mentions that port would make `--device emulator-5556` unusable. The
/// identity question belongs to the alias path, which is where P1 lives.
fn alias_needs_identity_check(device_ref: &str) -> bool {
    !registry::is_emulator_serial(device_ref) && !registry::is_udid(device_ref)
}

/// Where an emulator smix starts writes its console: one file per start,
/// in this machine's directory.
///
/// Per start and not per AVD, because the file that matters is the one
/// from the run that died, and a restart would overwrite it.
fn emulator_console_path(avd: &str) -> Result<std::path::PathBuf, CliError> {
    let root = smix_lease::store::machine_root().ok_or_else(|| {
        CliError::Other(
            "no machine-level directory to keep the emulator's console in — neither \
             HOME nor XDG_DATA_HOME is set"
                .to_string(),
        )
    })?;
    let stamp = smix_lease::store::now_rfc3339().replace(':', "-");
    Ok(root
        .join("emulator-console")
        .join(format!("{avd}-{stamp}.log")))
}

/// A serial nothing answers on, for an AVD whose registered port is taken.
///
/// The candidates come from the ports adb already lists; each is then
/// asked of the OS, because a port can be held by something adb does not
/// list — an emulator still starting, or one wedged on its way out.
fn free_console_serial() -> Result<String, CliError> {
    let taken: Vec<u16> = smix_adb::AdbClient::new()
        .live_devices()
        .unwrap_or_default()
        .iter()
        .filter_map(|(serial, _)| serial.strip_prefix("emulator-")?.parse().ok())
        .flat_map(|p: u16| [p, p + 1])
        .collect();
    smix_adb::AdbClient::console_port_candidates(&taken)
        .into_iter()
        .find(|p| {
            std::net::TcpListener::bind(("127.0.0.1", *p)).is_ok()
                && std::net::TcpListener::bind(("127.0.0.1", p + 1)).is_ok()
        })
        .map(|p| format!("emulator-{p}"))
        .ok_or_else(|| {
            CliError::Other(
                "every emulator console port adb scans (5554–5682) is in use".to_string(),
            )
        })
}

/// Turn an emulator alias into the serial that emulator answers on today.
///
/// `emulator-<port>` is a slot. The row records one, and on 2026-09-23
/// the row for `sim-smix-android-01` recorded `emulator-5554` while that
/// port was answering for a consumer's `qip-consumer-36` — so every
/// alias-driven install, flow and `runner up` would have gone to their
/// device. Registration has written the AVD name down since emulators
/// became registrable, and `smix sim boot` starts the device by it;
/// this is the other half, which was missing: reading it back.
fn emulator_alias_address(
    sim: &smix_simctl::registry::RegisteredSim,
) -> smix_simctl::registry::EmulatorAddress {
    let live = smix_adb::AdbClient::new().live_emulators();
    registry::emulator_address(sim.avd_name(), &sim.udid, &live)
}

/// The same answer, as the thing a caller who wants to *drive* it needs.
///
/// `sim boot` reads the answer itself: "not running" is a refusal here
/// and the whole job there, and folding the two together would have
/// made the refusal recommend a command this very check refuses.
fn address_emulator_alias(
    device_ref: &str,
    sim: &smix_simctl::registry::RegisteredSim,
) -> Result<String, CliError> {
    use smix_simctl::registry::EmulatorAddress;
    match emulator_alias_address(sim) {
        EmulatorAddress::At { serial } => Ok(serial),
        EmulatorAddress::MovedTo { serial, recorded } => {
            eprintln!(
                "note: {device_ref} is running as {serial}, not the {recorded} it was \
                 registered on — an emulator serial is a port, and this one took a \
                 different one this time"
            );
            Ok(serial)
        }
        addr => Err(emulator_address_refusal(device_ref, sim, addr)),
    }
}

/// What to say when an emulator alias cannot be turned into a device.
///
/// One wording, read by both the driving path and `sim boot`: they refuse
/// for the same two reasons, and two copies of a sentence drift.
fn emulator_address_refusal(
    device_ref: &str,
    sim: &smix_simctl::registry::RegisteredSim,
    addr: smix_simctl::registry::EmulatorAddress,
) -> CliError {
    use smix_simctl::registry::EmulatorAddress;
    CliError::Other(match addr {
        EmulatorAddress::NotRunning {
            avd,
            slot_now: Some(other),
        } => format!(
            "{device_ref} names the AVD `{avd}`, which is not running. {} is running \
             `{other}` — a different device that happens to hold the port this alias \
             was registered on. Start yours with `smix sim boot {device_ref}`.",
            sim.udid
        ),
        EmulatorAddress::NotRunning {
            avd,
            slot_now: None,
        } => format!(
            "{device_ref} names the AVD `{avd}`, which is not running. \
             Start it with `smix sim boot {device_ref}`."
        ),
        EmulatorAddress::NoIdentityRecorded { serial } => format!(
            "{device_ref} records the port {serial} and nothing else, and a port is \
             whichever emulator booted into it first — it may be somebody else's \
             today. Register it once while yours is running and the AVD name is \
             kept: `smix sim register {device_ref} --udid {serial} --kind emulator`."
        ),
        // Both of these are answers, not refusals; the callers take them
        // before ever asking for a sentence.
        EmulatorAddress::At { serial } | EmulatorAddress::MovedTo { serial, .. } => format!(
            "{device_ref} resolves to {serial}; this is not a refusal and nothing \
             should have asked for one"
        ),
    })
}

/// Resolve a device ref to the identifier its platform addresses it by.
///
/// An alias is answered by this machine's registry, or by a checkout's
/// legacy book when only that holds it; when the two give the alias to
/// different devices it is refused, naming both (§9 #9). A raw UDID used
/// to short-circuit straight through, and that was the hole: an
/// identifier nobody registered went past every gate and reached an
/// executor, where it was stopped only if that executor happened not to
/// recognise it. `simctl` does not recognise a phone, so for a while
/// nothing bad came of it — but `devicectl` does, and it can uninstall.
/// So a raw UDID now has to be one of ours: either registered, or a
/// simulator the platform itself lists.
fn resolve_device(device_ref: &str) -> Result<String, CliError> {
    if registry::is_udid(device_ref) {
        let udid = device_ref.to_ascii_uppercase();
        let known = if lookup_registered(&udid).is_some() {
            // The class does not matter here — what may be *done* to a
            // registered device is `guard_destructive`'s question.
            smix_lease::Known::Registered(smix_lease::DeviceClass {
                physical: false,
                destructive_opt_in: false,
            })
        } else if simctl_knows(&udid) {
            smix_lease::Known::UnregisteredVirtual
        } else {
            smix_lease::Known::Unknown
        };
        smix_lease::may_address(&udid, known).map_err(|e| CliError::Other(e.to_string()))?;
        return Ok(udid);
    }
    // An adb serial is an identifier too. Without this, `emulator-5554`
    // fell through to the alias lookup and came back "unknown device
    // ref" — from a tool that had just listed it, screenshotted it, and
    // accepted it at `sim register`. Resolving is only about what this
    // reference means and whether it may be addressed; whether a
    // particular verb can act on that kind of device is
    // `guard_sim_verb`'s question, asked separately.
    if registry::is_emulator_serial(device_ref) {
        smix_lease::may_address(device_ref, smix_lease::Known::UnregisteredVirtual)
            .map_err(|e| CliError::Other(e.to_string()))?;
        return Ok(device_ref.to_string());
    }
    let view = load_registry();
    let resolved = view.resolve_ref(device_ref)?.id;
    note_if_unmigrated(&view, device_ref);
    if alias_needs_identity_check(device_ref)
        && let Some(sim) = view.registry.lookup(device_ref)
        && sim.kind == smix_simctl::registry::DeviceKind::Emulator
    {
        return address_emulator_alias(device_ref, sim);
    }
    Ok(resolved)
}

/// Resolve an Android device ref to the serial `adb` will be given.
///
/// The iOS side gets its addressability check inside [`resolve_device`],
/// because every iOS command goes through it. Android had no such place:
/// the serial went straight to `adb`, so "whichever phone happens to be
/// plugged in" was addressable by anyone who typed its serial — the exact
/// shape that put smix's runner on somebody's personal handset on
/// 2026-07-17.
///
/// Case is preserved rather than upper-cased the way UDIDs are: `adb`
/// serials are matched verbatim, and `EMULATOR-5554` is not a device.
fn resolve_android_serial(device_ref: &str) -> Result<String, CliError> {
    // The same stop `resolve_device` makes: a checkout's book that gives
    // this alias to another device halts the decision, it does not make it.
    if alias_needs_identity_check(device_ref)
        && let Err(e @ smix_simctl::registry::RegistryError::Diverged { .. }) =
            load_registry().resolve_ref(device_ref)
    {
        return Err(e.into());
    }
    let registered = lookup_registered(device_ref);
    let known = match &registered {
        Some(s) => smix_lease::Known::Registered(smix_lease::DeviceClass {
            physical: s.kind.is_physical(),
            destructive_opt_in: s.destructive_opt_in,
        }),
        // Not a heuristic: `adb` is the one naming these. An emulator is
        // `emulator-<port>`; a physical device answers with its hardware
        // serial, which never takes that form. An emulator is virtual,
        // so it needs no registration — the same standing a simulator
        // has, decided by the same function rather than by an early
        // return that skipped past it.
        None if device_ref.starts_with("emulator-") => smix_lease::Known::UnregisteredVirtual,
        None => smix_lease::Known::Unknown,
    };
    smix_lease::may_address(device_ref, known).map_err(|e| CliError::Other(e.to_string()))?;
    // An alias resolves to the device it names — which is not the same
    // as the serial it was registered with, because that serial is a
    // port. A serial given directly is already the answer.
    match &registered {
        Some(sim)
            if sim.kind == smix_simctl::registry::DeviceKind::Emulator
                && alias_needs_identity_check(device_ref) =>
        {
            address_emulator_alias(device_ref, sim)
        }
        _ => Ok(registered.map_or_else(|| device_ref.to_string(), |s| s.udid)),
    }
}

/// Which platform's tooling addresses this device.
///
/// Read from the registry when it is there, and inferred only where the
/// inference is a consequence of an invariant rather than a guess:
/// `resolve_device` has, since C15, let a raw identifier through only
/// when the platform itself claims it — a simulator `simctl` lists or an
/// `emulator-<port>` serial. So an unregistered reference that reached
/// this point is one of those two, and nothing else.
fn device_kind_of(device_ref: &str) -> smix_simctl::registry::DeviceKind {
    classify_device(&load_registry().registry, device_ref)
}

/// What kind of device a ref names, given a registry to ask.
///
/// Split from [`device_kind_of`] so it can be checked against a
/// registry somebody wrote down. As one function it read whatever this
/// machine happened to have registered, and its test passed or failed
/// on that — which it did, the day the device records moved and a
/// registered `emulator-5554` started making the uppercase spelling
/// resolve to it.
fn classify_device(reg: &SimRegistry, device_ref: &str) -> smix_simctl::registry::DeviceKind {
    use smix_simctl::registry::DeviceKind;
    if let Some(sim) = reg.lookup(device_ref) {
        return sim.kind;
    }
    if registry::is_emulator_serial(device_ref) {
        return DeviceKind::Emulator;
    }
    DeviceKind::Simulator
}

/// Does `simctl` list a simulator with this UDID?
///
/// Only ever asked when the registry missed, so the common case pays
/// nothing for it. A substring match over the JSON is enough and cannot
/// collide: a UDID is 36 characters of a shape nothing else in that
/// document has.
///
/// A machine with no `xcrun` answers no, which is the truthful answer —
/// there are no simulators there for the UDID to be one of.
fn simctl_knows(udid: &str) -> bool {
    std::process::Command::new("xcrun")
        .args(["simctl", "list", "devices", "-j"])
        .output()
        .is_ok_and(|out| {
            out.status.success()
                && String::from_utf8_lossy(&out.stdout)
                    .to_ascii_uppercase()
                    .contains(udid)
        })
}

/// Does `adb` list a device with this serial?
///
/// [`simctl_knows`]'s twin, and deliberately the same shape: each virtual
/// device is checked against the catalogue its own platform keeps. Case
/// is preserved — `adb` matches serials verbatim.
fn adb_knows(serial: &str) -> bool {
    // An adb that cannot start has said why, once, on stderr.
    let Ok(mut adb) = smix_adb::std_command() else {
        return false;
    };
    adb.arg("devices").output().is_ok_and(|out| {
        out.status.success()
            && String::from_utf8_lossy(&out.stdout)
                .lines()
                // `adb devices` prints "<serial>\t<state>"; a device
                // that is listed as `offline` or `unauthorized` is
                // known but cannot be driven, and registering an
                // alias for one would hand out a name that fails
                // later somewhere else.
                .any(|l| {
                    l.split('\t').next().is_some_and(|s| s == serial)
                        && l.split('\t').nth(1).is_some_and(|s| s.trim() == "device")
                })
    })
}

/// The device a `sim` verb was pointed at, if it names one.
///
/// Exhaustive for the same reason as [`sim_verb_supports`]: a new verb
/// has to say whether it takes a device before this compiles.
fn sim_action_device(action: &SimAction) -> Option<&str> {
    match action {
        SimAction::List { .. } | SimAction::Migrate { .. } => None,
        SimAction::Unregister { .. } => None,
        SimAction::Register { udid, .. } => Some(udid),
        SimAction::Resolve { device, .. }
        | SimAction::Boot { device, .. }
        | SimAction::Shutdown { device }
        | SimAction::Erase { device }
        | SimAction::Screenshot { device, .. }
        | SimAction::Launch { device, .. }
        | SimAction::Terminate { device, .. }
        | SimAction::Install { device, .. }
        | SimAction::Uninstall { device, .. }
        | SimAction::Reverse { device, .. }
        | SimAction::Wake { device }
        | SimAction::StayAwake { device, .. }
        | SimAction::Permission { device, .. }
        | SimAction::Frontmost { device, .. }
        | SimAction::Crashes { device, .. }
        | SimAction::Openurl { device, .. }
        | SimAction::Appearance { device, .. }
        | SimAction::AllowDestructive { device }
        | SimAction::KeychainReset { device }
        | SimAction::Locale { device, .. }
        | SimAction::Exec { device, .. } => Some(device),
    }
}

/// Which device kinds each `smix sim` verb can actually act on.
///
/// An exhaustive match, deliberately: adding a verb will not compile
/// until somebody says which devices it works on. The alternative is a
/// hand-kept list of "the verbs I remembered to check", which is how
/// `capsule up` came to run `simctl boot` against an emulator and sit
/// there until it timed out 120 seconds later, reporting the timeout
/// rather than the mistake.
///
/// `None` means the verb takes no device, or acts on the registry
/// rather than the device.
fn sim_verb_supports(action: &SimAction) -> Option<Vec<smix_simctl::registry::DeviceKind>> {
    use DeviceKind::{Emulator, Simulator};
    use smix_simctl::registry::DeviceKind;

    // Derived, not written down again. Every verb that is a
    // `DeviceControl` method takes its answer from the platform table,
    // which is reconciled against the implementations themselves.
    //
    // The two lists used to be kept apart, and by 10.2 they disagreed in
    // five places -- every one of them the CLI refusing something the
    // backend carries out. `launch`, `terminate` and `openurl` were
    // simulator-only while `AndroidDeviceControl` ran all three through
    // `am`; `install` excluded a registered iPhone after
    // `DevicectlClient::install` was wired; `keychain-reset` claimed one
    // the table refuses. A consumer met the first of those on a handset,
    // and read "this command runs through simctl" as a report that the
    // install they had just run had broken something.
    if let Some(table_action) = table_action_of(action) {
        return Some(
            DeviceKind::ALL
                .iter()
                .copied()
                .filter(|kind| {
                    smix_sdk::device_control::availability(table_action, *kind)
                        == Some(smix_sdk::device_control::Availability::Works)
                })
                .collect(),
        );
    }

    // What is left is the verbs that are not device-control methods, so
    // the table has no row to derive from. Exhaustive, deliberately:
    // adding a verb will not compile until somebody says which devices
    // it works on. The alternative is a hand-kept list of "the verbs I
    // remembered to check", which is how `capsule up` came to run
    // `simctl boot` against an emulator and sit there until it timed out
    // 120 seconds later, reporting the timeout rather than the mistake.
    //
    // `None` means the verb takes no device, or acts on the registry
    // rather than the device.
    //
    // Powering a device on and off is not an Apple-only idea, so both
    // virtual kinds have it. Physical devices are absent on purpose:
    // section 9 #1 gates them behind registration and a per-device
    // opt-in, and nothing here should decide a phone's power state.
    const POWERABLE: &[DeviceKind] = &[Simulator, Emulator];
    // simctl and nothing else. An emulator's counterparts exist
    // (`emulator -avd`, `adb shell am start`, `adb shell settings`) but
    // none of them is wired here, and pretending otherwise is how a
    // caller ends up waiting out a 120-second timeout.
    const SIMCTL: &[DeviceKind] = &[Simulator];
    Some(
        match action {
            // No device, or the registry rather than the device.
            SimAction::List { .. }
            | SimAction::Register { .. }
            | SimAction::AllowDestructive { .. }
            | SimAction::Migrate { .. }
            | SimAction::Unregister { .. }
            | SimAction::Resolve { .. } => return None,

            SimAction::Boot { .. } | SimAction::Shutdown { .. } => POWERABLE,

            SimAction::Erase { .. }
            | SimAction::Appearance { .. }
            | SimAction::Locale { .. }
            | SimAction::Exec { .. } => SIMCTL,

            // Answered above, from the table.
            SimAction::Screenshot { .. }
            | SimAction::KeychainReset { .. }
            | SimAction::Uninstall { .. }
            | SimAction::Install { .. }
            | SimAction::Reverse { .. }
            | SimAction::Wake { .. }
            | SimAction::StayAwake { .. }
            | SimAction::Frontmost { .. }
            | SimAction::Crashes { .. }
            | SimAction::Permission { .. }
            | SimAction::Launch { .. }
            | SimAction::Terminate { .. }
            | SimAction::Openurl { .. } => unreachable!("answered by the platform table"),
        }
        .to_vec(),
    )
}

/// Which entry of the platform table answers for this verb, if any.
///
/// Exhaustive on purpose, like its two neighbours: a new verb has to
/// say whether the table already holds a sentence for it.
///
/// Only `reverse` maps today, and the rest are `None` deliberately —
/// not because nothing else could. The generic sentence below says
/// "this command runs through simctl", which is true of the verbs that
/// do and false of any verb that does not; `reverse` is the first of
/// the second kind, and pointing it at the table is what keeps the
/// refusal honest. Mapping the others is a change to what every one of
/// them says, and belongs with somebody reading each in turn.
fn table_action_of(action: &SimAction) -> Option<&'static str> {
    match action {
        SimAction::Reverse { .. } => Some("reverse_port"),
        SimAction::Wake { .. } => Some("wake"),
        SimAction::StayAwake { .. } => Some("set_stay_awake"),
        SimAction::Permission { .. } => Some("set_permission"),
        SimAction::Frontmost { .. } => Some("frontmost_app"),
        SimAction::Crashes { .. } => Some("crash_reports"),
        // The lifecycle verbs. Each has a row because each is a
        // `DeviceControl` method with real implementations behind it,
        // and pointing at the row is what stopped the CLI keeping a
        // second opinion about where they work.
        SimAction::Launch { .. } => Some("launch"),
        SimAction::Terminate { .. } => Some("terminate"),
        SimAction::Install { .. } => Some("install"),
        SimAction::Uninstall { .. } => Some("uninstall"),
        SimAction::Openurl { .. } => Some("open_url"),
        SimAction::Screenshot { .. } => Some("screenshot"),
        SimAction::KeychainReset { .. } => Some("keychain_reset"),
        // No row, because none of these is a `DeviceControl` method:
        // powering a device, erasing it, and the three simulator-only
        // settings. Their refusals are built from their own support
        // list instead, by `refusal_for`.
        SimAction::List { .. }
        | SimAction::Register { .. }
        | SimAction::Resolve { .. }
        | SimAction::Migrate { .. }
        | SimAction::Unregister { .. }
        | SimAction::AllowDestructive { .. }
        | SimAction::Boot { .. }
        | SimAction::Shutdown { .. }
        | SimAction::Erase { .. }
        | SimAction::Appearance { .. }
        | SimAction::Locale { .. }
        | SimAction::Exec { .. } => None,
    }
}

/// Refuse a verb this device kind has no path for, naming what does.
fn guard_sim_verb(action: &SimAction, device: &str) -> Result<(), CliError> {
    let Some(kinds) = sim_verb_supports(action) else {
        return Ok(());
    };
    let kind = device_kind_of(device);
    if kinds.contains(&kind) {
        return Ok(());
    }
    Err(CliError::Other(refusal_for(action, device, kind)))
}

/// Whatever drives this kind of device.
///
/// One place decides which tool addresses which kind. It was three
/// hand-written `match device_kind_of(...)` arms before this, on their
/// way to six, and one of them was already wrong: `uninstall` sent a
/// registered iPhone to `simctl`, which lists no phones. A verb that
/// reaches a new kind of device should not also have to know how.
fn device_control_for(
    kind: smix_simctl::registry::DeviceKind,
    udid: &str,
) -> Box<dyn smix_sdk::device_control::DeviceControl> {
    use smix_simctl::registry::DeviceKind;
    match kind {
        DeviceKind::Simulator => Box::new(smix_sdk::ios_device::IosDeviceControl::new()),
        DeviceKind::Emulator | DeviceKind::PhysicalAndroid => {
            Box::new(smix_sdk::android_device::AndroidDeviceControl::new())
        }
        DeviceKind::PhysicalIos => Box::new(smix_sdk::devicectl_device::DevicectlClient::new(udid)),
    }
}

/// What to say when a verb has no path on this kind of device.
///
/// Split from [`guard_sim_verb`] so the sentence can be read without a
/// registry: the guard resolves the kind from whatever this machine has
/// recorded, and a test of the wording that went through it would pass
/// or fail on that.
fn refusal_for(
    action: &SimAction,
    device: &str,
    kind: smix_simctl::registry::DeviceKind,
) -> String {
    use smix_simctl::registry::DeviceKind;
    // The table's own words when it has them: it is where every other
    // refusal's wording lives, and it says why *this* device cannot and
    // where the caller should go instead.
    if let Some(table_action) = table_action_of(action)
        && let Some(smix_sdk::device_control::Availability::RefusedByName { why, instead }) =
            smix_sdk::device_control::availability(table_action, kind)
    {
        return format!("{device} cannot do this: {why}\nInstead: {instead}");
    }
    // What is left has no row, so the sentence is built from the verb's
    // own support list rather than asserting a tool.
    //
    // It used to say "this command runs through simctl", which is true
    // of the six verbs that do and false of every verb that does not,
    // and it carried a line about `runner up` on any Android device --
    // advice about a different verb entirely. A consumer ran
    // `smix sim launch` after installing an app, met that paragraph, and
    // read it as a report that the install had taken their runner down.
    let name_of = |kind| match kind {
        DeviceKind::Simulator => "an iOS Simulator",
        DeviceKind::Emulator => "an Android emulator",
        DeviceKind::PhysicalIos => "a physical iPhone or iPad",
        DeviceKind::PhysicalAndroid => "a physical Android device",
    };
    let works_on = sim_verb_supports(action)
        .unwrap_or_default()
        .into_iter()
        .map(name_of)
        .collect::<Vec<_>>()
        .join(", ");
    format!(
        "{device} is {}, and this command has no path to it.\nIt works on: {works_on}.",
        name_of(kind)
    )
}

/// Where a device fact is written: this machine.
///
/// A simulator's UDID, its runtime version and whether destruction has
/// been allowed on it are facts about the machine, not about the tree
/// you happen to be standing in. This used to walk up from the working
/// directory, which is why four checkouts here each held their own
/// answer — and why on 2026-08-11 a runner on port 22087 was on the
/// books and invisible at the same time: the books were another
/// workspace's.
///
/// `SMIX_SIMS_JSON` still wins, and still means exactly one registry —
/// tests and gates use it to work against a registry of their own, and
/// a machine-level fallback under it would let the real one leak in.
fn registry_path() -> Result<PathBuf, CliError> {
    if let Some(p) = std::env::var_os("SMIX_SIMS_JSON") {
        return Ok(PathBuf::from(p));
    }
    SimRegistry::machine_dir().ok_or_else(|| {
        CliError::Other(
            "no machine-level place to keep device records — neither HOME nor \
             XDG_DATA_HOME is set. Set SMIX_MACHINE_DIR, or point \
             SMIX_SIMS_JSON at a registry."
                .into(),
        )
    })
}

/// The merged registry, from wherever this machine keeps device facts.
///
/// Delegates to the core resolution rather than repeating it: `smix
/// down` and `smix doctor` read the same records, and three callers
/// each deciding where the registry lives is how four checkouts came to
/// hold four answers in the first place.
fn load_registry() -> smix_simctl::registry::MergedRegistry {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    SimRegistry::open_all(&cwd)
}

/// Say so when a device is recorded in a checkout and not on this machine.
///
/// A record only one tree holds is a record the next tree cannot act on.
fn note_if_unmigrated(view: &smix_simctl::registry::MergedRegistry, device_ref: &str) {
    let Some(sim) = view.registry.lookup(device_ref) else {
        return;
    };
    let Some((alias, from)) = view.unmigrated.iter().find(|(alias, _)| {
        view.registry
            .lookup(alias)
            .is_some_and(|s| s.udid.eq_ignore_ascii_case(&sim.udid))
    }) else {
        return;
    };
    eprintln!(
        "note: `{alias}` is recorded in {} and not on this machine — another \
         checkout cannot see it. `smix sim migrate` moves it.",
        from.display()
    );
}

/// The one line `smix sim resolve` writes to stderr: which book answered.
fn resolution_line(
    device_ref: &str,
    sim: Option<&smix_simctl::registry::RegisteredSim>,
    source: &smix_simctl::registry::Source,
) -> String {
    use smix_simctl::registry::Source;
    let book = match source {
        Source::Machine(p) => format!("this machine's registry ({})", p.display()),
        Source::Checkout(p) => format!(
            "{} — a checkout's legacy book, read and never written; `smix sim migrate` \
             records it on this machine",
            p.display()
        ),
        Source::Named(p) => format!("the registry SMIX_SIMS_JSON names ({})", p.display()),
        Source::Literal => {
            return format!("{device_ref} is an identifier itself; no registry was consulted");
        }
    };
    match sim.and_then(|s| s.avd_name()) {
        Some(avd) => format!("resolved `{device_ref}` (AVD `{avd}`) from {book}"),
        None => format!("resolved `{device_ref}` from {book}"),
    }
}

/// `smix sim resolve --json`: the shape a harness reads instead of a file.
fn resolution_json(
    device_ref: &str,
    id: &str,
    resolved: Option<&smix_simctl::registry::Resolved>,
    sim: Option<&smix_simctl::registry::RegisteredSim>,
    source: &smix_simctl::registry::Source,
) -> serde_json::Value {
    use smix_simctl::registry::Source;
    let (kind, path) = match source {
        Source::Machine(p) => ("machine", Some(p)),
        Source::Checkout(p) => ("checkout", Some(p)),
        Source::Named(p) => ("named", Some(p)),
        Source::Literal => ("literal", None),
    };
    let mut v = serde_json::json!({
        "ref": device_ref,
        "id": id,
        "alias": resolved.map_or(device_ref, |r| r.alias.as_str()),
        "source": { "kind": kind, "path": path.map(|p| p.display().to_string()) },
        "deviceKind": sim.map(|s| {
            serde_json::to_value(s.kind).expect("a unit enum with derived Serialize always serialises")
        }),
    });
    if let Some(avd) = sim.and_then(|s| s.avd_name()) {
        v["avd"] = serde_json::Value::String(avd.to_string());
    }
    v
}

/// 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> {
    load_registry().registry.lookup(device_ref).cloned()
}

/// Set once stdout's reader has gone; every later write is dropped.
static STDOUT_READER_LEFT: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// What `print!` and `println!` do in this crate.
///
/// A reader that stops reading (`smix sim list | head -1`) is not a
/// failure of the work: smix stops writing to stdout and finishes what it
/// was doing, and the exit code reports that work. The two usual answers
/// are both wrong here. Restoring SIGPIPE's default kills smix silently
/// the same way when a child it feeds on stdin exits early (simctl,
/// codesign, devicectl all take stdin). Exiting at once — with 0 or 141 —
/// would leave a `smix run … | head` device halfway through a flow, and 0
/// would call that a pass. No smix command streams forever and relies on
/// SIGPIPE to stop (`runner forward` prints once, then holds), so carrying
/// on cannot hang anyone.
///
/// Any other write error is std's panic, unchanged.
fn write_stdout(args: std::fmt::Arguments<'_>) {
    use std::io::Write;
    use std::sync::atomic::Ordering;
    if STDOUT_READER_LEFT.load(Ordering::Relaxed) {
        return;
    }
    if let Err(e) = std::io::stdout().lock().write_fmt(args) {
        if e.kind() == std::io::ErrorKind::BrokenPipe {
            STDOUT_READER_LEFT.store(true, Ordering::Relaxed);
            return;
        }
        panic!("failed printing to stdout: {e}");
    }
}

#[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)
        }
    }
}

/// Record that smix booted (or found running) this emulator, with which
/// AVD it is when that is known. A write that fails is said, not fatal:
/// the device is up either way.
fn record_emulator_boot(udid: &str, claim: BootClaim, identity: Option<smix_lease::Resource>) {
    let Ok(leases) = smix_capsule::runner::machine_leases() else {
        return;
    };
    if let Err(e) = smix_lease::store::record_boot(&leases, udid, claim == BootClaim::ClaimAsOurs) {
        eprintln!("warning: boot not recorded in the device ledger: {e}");
    }
    if let Some(row) = identity
        && let Err(e) = smix_lease::store::add_resource(&leases, udid, row)
    {
        eprintln!("warning: which AVD {udid} is was not recorded in the device ledger: {e}");
    }
}

/// Take back a boot record written before a start that never came up.
fn withdraw_emulator_boot(udid: &str) {
    let Ok(leases) = smix_capsule::runner::machine_leases() else {
        return;
    };
    if let Err(e) = smix_lease::store::drop_resource_kind(
        &leases,
        udid,
        &smix_lease::Resource::Booted { by_us: true },
    ) {
        eprintln!("warning: the boot record for {udid} was not withdrawn: {e}");
    }
}

/// The command as typed, verb and first argument: `smix sim boot`,
/// `smix run flows/login.yaml`. Enough to say who noticed something.
fn invoked_as() -> String {
    let args: Vec<String> = std::env::args().skip(1).take(2).collect();
    format!("smix {}", args.join(" "))
}

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. Best-effort — a machine with no home
    // for smix's data is a no-op.
    if let Some(diag_root) = smix_lease::store::machine_root() {
        // 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.
        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);
    }

    // Before the verbs that touch devices, compare the ledgers with what
    // is here. A device that left while a ledger still described it is
    // kept as a fact by whichever of these runs next — the only moment
    // anything will ever notice.
    if matches!(
        cli.cmd,
        Cmd::Run { .. } | Cmd::Runner { .. } | Cmd::Sim { .. } | Cmd::Lease { .. }
    ) {
        departures::notice(&invoked_as()).await;
    }

    let simctl = SimctlClient::new();
    match cli.cmd {
        Cmd::Init { alias, device, app } => {
            cmd_init(&simctl, alias.as_deref(), device.as_deref(), app.as_deref()).await?
        }
        Cmd::Doctor {
            json,
            runner_port: port,
        } => cmd_doctor(&simctl, json, port.unwrap_or_else(runner_port)).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::Session { action } => cmd_session(action).await?,
        Cmd::Sim { action } => {
            // One gate for every `sim` verb, before any of them runs.
            // Putting it inside the arms would mean remembering it in
            // each — and the arms that most needed it are exactly the
            // ones nobody remembered.
            // Governance before transport. Both can refuse the same
            // verb on the same device; the difference is what the
            // person is told, and only one of the two is the rule.
            guard_destructive_action(&action)?;
            if let Some(device) = sim_action_device(&action) {
                guard_sim_verb(&action, device)?;
            }
            match action {
                SimAction::List { json, registered } => {
                    if registered {
                        cmd_sim_list_registered(json)?;
                    } else {
                        cmd_sim_list(&simctl, json).await?;
                    }
                }
                SimAction::Migrate { from, dry_run } => cmd_sim_migrate(from, dry_run)?,
                SimAction::Unregister { alias } => {
                    let path = registry_path()?;
                    let sim = SimRegistry::unregister(&path, &alias)
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    println!("forgot `{alias}` -> {} in {}", sim.udid, path.display());
                }
                SimAction::Resolve { device, json } => {
                    let id = resolve_device(&device)?;
                    let view = load_registry();
                    let resolved = view.resolve_ref(&device).ok();
                    let sim = view.registry.lookup(&device);
                    let source = resolved
                        .as_ref()
                        .map_or(smix_simctl::registry::Source::Literal, |r| r.source.clone());
                    if json {
                        println!(
                            "{}",
                            resolution_json(&device, &id, resolved.as_ref(), sim, &source)
                        );
                    } else {
                        eprintln!("{}", resolution_line(&device, sim, &source));
                        println!("{id}");
                    }
                }
                SimAction::Register {
                    alias,
                    udid,
                    locale,
                    runner_port,
                    kind,
                    name,
                } => {
                    let kind = kind.to_registry();
                    let udid = registry::canonical_identifier(kind, &udid);
                    registry::identifier_fits(kind, &udid)
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    if kind == smix_simctl::registry::DeviceKind::Emulator {
                        if !adb_knows(&udid) {
                            return Err(CliError::Other(format!(
                                "adb lists no running device {udid} — check `adb devices`.\n\
                             An emulator is checked against adb the way a simulator is \
                             checked against simctl; only a physical device is taken as \
                             given, because nothing here can enumerate the world's phones."
                            )));
                        }
                        // Which AVD this serial is running, taken now,
                        // while the emulator is up — the check above just
                        // proved it is. A serial identifies the emulator
                        // answering today; the AVD name is what starts one
                        // tomorrow, and nothing later in the day can recover
                        // it from a device that has since stopped.
                        let avd = smix_adb::AdbClient::new()
                            .avd_name(&udid)
                            .await
                            .ok()
                            .filter(|a| !a.is_empty());
                        let path = registry_path()?;
                        let outcome = SimRegistry::register(
                            &path,
                            &alias,
                            smix_simctl::registry::RegisteredSim {
                                device_name: name.unwrap_or_else(|| alias.clone()),
                                udid: udid.clone(),
                                runtime: String::new(),
                                device_type: String::new(),
                                avd_name: avd,
                                locale,
                                runner_port,
                                kind,
                                destructive_opt_in: false,
                            },
                        )?;
                        let verb = match outcome {
                            smix_simctl::registry::RegisterOutcome::Added => "registered",
                            smix_simctl::registry::RegisterOutcome::Updated => "updated",
                        };
                        println!(
                            "{verb}: {alias} → {udid} (Android emulator) in {}",
                            smix_simctl::registry::store_dir(&path).display()
                        );
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    // A physical device is taken as given.
                    //
                    // simctl lists simulators and nothing else, so the
                    // lookup below would refuse every phone that exists. The
                    // identifier is whatever addresses it — a UDID for iOS,
                    // an adb serial for Android — and neither is checked
                    // against a catalogue, because there is no catalogue to
                    // check against. Registration is the deliberate act;
                    // that is the whole point of requiring it.
                    if kind.is_physical() {
                        let path = registry_path()?;
                        let outcome = SimRegistry::register(
                            &path,
                            &alias,
                            smix_simctl::registry::RegisteredSim {
                                device_name: name.unwrap_or_else(|| alias.clone()),
                                udid: udid.clone(),
                                runtime: String::new(),
                                device_type: String::new(),
                                avd_name: None,
                                locale,
                                runner_port,
                                kind,
                                // Never on by registration. Allowing
                                // destruction has to be its own decision, or
                                // it is not a decision.
                                destructive_opt_in: false,
                            },
                        )?;
                        let verb = match outcome {
                            smix_simctl::registry::RegisterOutcome::Added => "registered",
                            smix_simctl::registry::RegisterOutcome::Updated => "updated",
                        };
                        println!(
                            "{verb}: {alias} → {udid} (physical device) in {}",
                            smix_simctl::registry::store_dir(&path).display()
                        );
                        println!(
                            "destructive actions are refused on it until \
                         `smix sim allow-destructive {alias}`"
                        );
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    // The shape check that used to live here now runs above
                    // for every kind, and names the right world when it
                    // refuses — telling an Android user their serial "is not
                    // UDID-form" described the shape of a thing they were not
                    // registering.
                    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`"
                            ))
                        })?;
                    // The machine registry, which `open_store` creates on
                    // first write — register is the one verb that has to
                    // work before any registry exists. It used to fall
                    // back to `.smix/sims.json` in the working directory
                    // when that resolution failed, which meant a device
                    // record landing somewhere no other tree would ever
                    // read. There is no good place to put it silently.
                    let path = registry_path()?;
                    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(),
                            avd_name: None,
                            locale,
                            runner_port,
                            // Not a guess: this record is built from what
                            // `simctl list devices` returned, and simctl only
                            // ever lists simulators. A physical device is
                            // registered by a different path.
                            kind: smix_simctl::registry::DeviceKind::Simulator,
                            destructive_opt_in: false,
                        },
                    )?;
                    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, cold } => {
                    // Booting asks a different question than driving does:
                    // "where should this start" rather than "where is it".
                    // `resolve_device` refuses an emulator alias whose AVD
                    // is not running, which is precisely the state this
                    // command exists to leave — so the port to start on
                    // comes from the row, and the identity check below
                    // decides whether starting is the right move at all.
                    let registered = lookup_registered(&device);
                    let booting_emulator = registered
                        .as_ref()
                        .is_some_and(|s| s.kind == smix_simctl::registry::DeviceKind::Emulator)
                        && alias_needs_identity_check(&device);
                    let udid = if booting_emulator {
                        let sim = registered.as_ref().expect("checked above");
                        match emulator_alias_address(sim) {
                            smix_simctl::registry::EmulatorAddress::At { serial }
                            | smix_simctl::registry::EmulatorAddress::MovedTo { serial, .. } => {
                                serial
                            }
                            smix_simctl::registry::EmulatorAddress::NotRunning {
                                avd,
                                slot_now: Some(other),
                            } => {
                                // The identity is the AVD name; the port is only
                                // where it answers today. The registered one is
                                // somebody else's now, so start ours on a free one.
                                let serial = free_console_serial()?;
                                eprintln!(
                                    "note: {device} was registered on {}, which is \
                                     running `{other}` today; starting `{avd}` on \
                                     {serial} instead",
                                    sim.udid
                                );
                                serial
                            }
                            smix_simctl::registry::EmulatorAddress::NotRunning { .. } => {
                                sim.udid.clone()
                            }
                            addr @ smix_simctl::registry::EmulatorAddress::NoIdentityRecorded {
                                ..
                            } => return Err(emulator_address_refusal(&device, sim, addr)),
                        }
                    } else {
                        resolve_device(&device)?
                    };
                    // An emulator is started by name, not by serial: the
                    // serial is what answers once it is up. The AVD name was
                    // written down at registration, when the device was
                    // provably running and could be asked.
                    let kind = device_kind_of(&device);
                    let running =
                        kind == smix_simctl::registry::DeviceKind::Emulator && adb_knows(&udid);
                    if let Some(why) = cold
                        .then(|| boot_cold::cold_boot_refusal(&device, kind, running))
                        .flatten()
                    {
                        return Err(CliError::Other(why));
                    }
                    if kind == smix_simctl::registry::DeviceKind::Emulator {
                        let already = running;
                        let claim = boot_claim(if already {
                            EmulatorState::AlreadyRunning
                        } else {
                            EmulatorState::WasOff
                        });
                        if !already {
                            let book = load_registry().registry;
                            let at_port: Vec<(&str, &str)> = book
                                .all()
                                .filter(|(_, s)| s.udid.eq_ignore_ascii_case(&udid))
                                .filter_map(|(alias, s)| s.avd_name().map(|avd| (alias, avd)))
                                .collect();
                            let named = booting_emulator
                                .then(|| registered.as_ref().map(|s| s.avd_name()))
                                .flatten();
                            let avd = boot_avd::avd_to_start(&device, &udid, named, &at_port)
                                .map_err(CliError::Other)?;
                            let adb = smix_adb::AdbClient::new();
                            let console = emulator_console_path(&avd)?;
                            let from = if cold {
                                smix_adb::BootFrom::Cold
                            } else {
                                smix_adb::BootFrom::Snapshot
                            };
                            adb.start_emulator_on_with(&avd, &udid, &console, from)
                                .map_err(|e| CliError::Other(format!("{e}")))?;
                            // Recorded as soon as the process is started,
                            // before the wait. The emulator has a process
                            // group of its own and outlives this command, so
                            // a Ctrl-C during the wait left it running with
                            // no record that smix started it — and smix then
                            // refused to stop it (2026-09-25). The record is
                            // withdrawn below, after stopping the emulator,
                            // when it never comes up: the ledger still never
                            // claims a device that is not there once this
                            // command has answered.
                            record_emulator_boot(
                                &udid,
                                claim,
                                Some(smix_lease::Resource::Emulator {
                                    avd: avd.clone(),
                                    console_log: Some(console.display().to_string()),
                                }),
                            );
                            let ready = adb
                                .wait_for_boot(&udid, std::time::Duration::from_secs(180))
                                .await;
                            if let Err(e) = ready {
                                let stopped = match adb.stop_emulator(&udid).await {
                                    Ok(()) => {
                                        withdraw_emulator_boot(&udid);
                                        "it has been stopped and the ledger no longer says \
                                         smix booted it"
                                            .to_string()
                                    }
                                    Err(stop) => format!(
                                        "stopping it failed ({stop}), so the ledger still \
                                         says smix booted it — `smix sim shutdown {udid}` \
                                         once it answers"
                                    ),
                                };
                                return Err(CliError::Other(format!(
                                    "{avd} was started and {udid} did not come up \
                                     within 180s: {e}\n\
                                     {stopped}. What the emulator printed is in {}",
                                    console.display()
                                )));
                            }
                        } else {
                            // Found running: its console is not ours to keep,
                            // but its name is what tells this ledger apart
                            // from the next AVD to take the same port.
                            let identity = match smix_adb::AdbClient::new().avd_name(&udid).await {
                                Ok(avd) if !avd.is_empty() => {
                                    Some(smix_lease::Resource::Emulator {
                                        avd,
                                        console_log: None,
                                    })
                                }
                                _ => None,
                            };
                            record_emulator_boot(&udid, claim, identity);
                        }
                        println!("booted: {udid}");
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    // Whether this command is the one that brought the device
                    // up decides, later, whether smix may shut it down. A
                    // device someone else booted is not ours to turn off as
                    // the price of cleaning up after ourselves.
                    let claim = boot_record::claim_before_boot(&simctl, &udid).await;
                    // Wait for the device to finish booting, not just to accept
                    // the boot. `simctl boot` returns while CoreSimulator is
                    // still bringing the render surfaces up, and a device in
                    // that state answers "Booted" to a listing while
                    // `simctl io … screenshot` fails with "Timeout waiting for
                    // screen surfaces" and `recordVideo` produces a zero-byte
                    // file it reports as written. Printing "booted" then is a
                    // statement that is not yet true, and everything the next
                    // command does with the device fails in ways that do not
                    // name this as the cause.
                    simctl
                        .boot_and_wait(&udid, std::time::Duration::from_secs(120))
                        .await?;
                    println!("booted: {udid}");
                    // Not gated on standing in a workspace. It was, and
                    // "no `.smix` above the working directory" meant no
                    // record of who booted this device — a fact about the
                    // machine, withheld because of where somebody's shell
                    // happened to be.
                    boot_record::record_simulator_boot(&udid, claim);
                    // 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)?;
                    // The comment below this block has said for a while that
                    // the boot row records who may shut a device down. It
                    // was never read: the shutdown went ahead and then
                    // cleared the row. So the rule existed in prose and not
                    // in behaviour, and a device somebody else booted was
                    // stopped by whoever tidied up next.
                    match shutdown_verdict(ownership_of(&udid), &udid) {
                        ShutdownVerdict::Proceed => {}
                        ShutdownVerdict::Refuse { message } => {
                            return Err(CliError::Other(message));
                        }
                    }
                    // Already off is the state that was asked for. Failing
                    // here would also mean never clearing the boot row below,
                    // so a device shut down twice would keep a record saying
                    // smix still owes it a shutdown — forever.
                    //
                    // The mechanism differs by platform and the rule above
                    // does not: `emu kill` and `simctl shutdown` stop a
                    // device in different ways, and both are only reached
                    // once the ledger has said this process may.
                    if device_kind_of(&device) == smix_simctl::registry::DeviceKind::Emulator {
                        let adb = smix_adb::AdbClient::new();
                        if let Err(e) = adb.stop_emulator(&udid).await {
                            // An emulator that is already gone is the state
                            // asked for, same as the simctl arm below.
                            if !format!("{e}").contains("device") {
                                return Err(CliError::Other(format!("could not stop {udid}: {e}")));
                            }
                        }
                    } else {
                        match simctl.shutdown(&udid).await {
                            Ok(()) => {}
                            Err(smix_simctl::DeviceControlError::NonZeroExit {
                                ref stderr,
                                ..
                            }) if stderr.contains("current state: Shutdown") => {}
                            Err(e) => return Err(e.into()),
                        }
                    }
                    // The boot row records who may shut this device down.
                    // Once it is off, the answer is nobody — leaving the row
                    // behind would have a later teardown shut down a device
                    // this process never turned on.
                    if let Ok(leases) = smix_capsule::runner::machine_leases()
                        && let Err(e) = smix_lease::store::drop_resource_kind(
                            &leases,
                            &udid,
                            &smix_lease::Resource::Booted { by_us: true },
                        )
                    {
                        eprintln!("warning: boot row not cleared from the device ledger: {e}");
                    }
                    println!("shutdown: {udid}");
                }
                SimAction::Erase { device } => {
                    let udid = resolve_device(&device)?;
                    simctl.erase(&udid).await?;
                    println!("erased: {udid}");
                }
                SimAction::Screenshot {
                    device,
                    out,
                    runner_port: port_flag,
                } => {
                    use smix_simctl::registry::DeviceKind;
                    let udid = resolve_device(&device)?;
                    // Sense is a flat capability: which tool takes the
                    // picture is smix's problem, not the caller's. What is
                    // not flat is a phone — its screen comes from the
                    // runner's XCUIScreen, and there is no device-tooling
                    // path to it at all. §9#1's third constraint says that
                    // has to be said out loud rather than degraded into an
                    // empty file that every later assertion measures.
                    let png = match device_kind_of(&device) {
                        DeviceKind::Simulator => simctl.screenshot(&udid).await?,
                        DeviceKind::Emulator | DeviceKind::PhysicalAndroid => {
                            use smix_sdk::device_control::DeviceControl;
                            smix_sdk::android_device::AndroidDeviceControl::new()
                                .screenshot(&udid)
                                .await
                                .map_err(|e| CliError::Other(e.to_string()))?
                        }
                        DeviceKind::PhysicalIos => {
                            // Two routes, and the phone says which. Until
                            // Xcode 27 Apple exposed no screen capture for
                            // a phone through devicectl, and the runner's
                            // `XCUIScreen` was the only one — which needs
                            // the runner up. Xcode 27's devicectl has
                            // `capture screenshot`, and a phone that lists
                            // the capability is asked directly.
                            use smix_sdk::device_control::DeviceControl;
                            let phone = smix_sdk::devicectl_device::DevicectlClient::new(&udid);
                            let offers = phone
                                .offers(smix_sdk::devicectl_device::CAPABILITY_SCREENSHOT)
                                .await
                                .ok();
                            match phone_screenshot_route(offers) {
                                PhoneScreenshotRoute::Devicectl => phone
                                    .screenshot(&udid)
                                    .await
                                    .map_err(|e| CliError::Other(e.to_string()))?,
                                PhoneScreenshotRoute::Runner => smix_capsule::runner::screenshot(
                                    port_flag.unwrap_or_else(runner_port),
                                )
                                .map_err(|e| CliError::Other(e.to_string()))?,
                            }
                        }
                    };
                    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 kind = device_kind_of(&device);
                    let pairs: Vec<(&str, &str)> = child_env
                        .iter()
                        .map(|(k, v)| (k.as_str(), v.as_str()))
                        .collect();
                    // `SIMCTL_CHILD_*` is a CoreSimulator facility: the
                    // simulator's launchd hands the variables to the
                    // child. `am start` has no equivalent -- an activity
                    // inherits the system's environment and nothing
                    // else -- so passing them would be dropping them
                    // silently, which §9 #1 ③ is about.
                    if !pairs.is_empty() && kind != smix_simctl::registry::DeviceKind::Simulator {
                        return Err(CliError::Other(format!(
                            "--child-env sets the launched process's environment, and only \
                             a simulator's launchd can do that; {udid} is driven by \
                             {}.\nInstead: pass the values as launch arguments, which \
                             every backend carries.",
                            if kind == smix_simctl::registry::DeviceKind::PhysicalIos {
                                "devicectl"
                            } else {
                                "adb"
                            }
                        )));
                    }
                    let pid = if kind == smix_simctl::registry::DeviceKind::Simulator {
                        let LaunchResult { pid } = simctl
                            .launch_with_args_and_env(&udid, &bundle_id, &launch_args, &pairs)
                            .await?;
                        pid
                    } else {
                        device_control_for(kind, &udid)
                            .launch_with_args(&udid, &bundle_id, &launch_args, None)
                            .await
                            .map_err(|e| CliError::Other(e.to_string()))?
                    };
                    // `am start` reports no pid and the Android backend
                    // returns 0 for it. Printing "(pid 0)" reads as a
                    // process number rather than as its absence.
                    if pid == 0 {
                        println!("launched: {bundle_id} on {udid}");
                    } else {
                        println!("launched: {bundle_id} on {udid} (pid {pid})");
                    }
                }
                SimAction::Terminate { device, bundle_id } => {
                    let udid = resolve_device(&device)?;
                    device_control_for(device_kind_of(&device), &udid)
                        .terminate(&udid, &bundle_id)
                        .await
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    println!("terminated: {bundle_id} on {udid}");
                }
                SimAction::Install { device, app_path } => {
                    let udid = resolve_device(&device)?;
                    let kind = device_kind_of(&device);
                    let control = device_control_for(kind, &udid);
                    // Who was in front before the payload lands.
                    //
                    // A reinstall ends the running copy of the app it
                    // replaces -- `adb install -r` always has -- and
                    // nothing said so. A consumer installed over the app
                    // they were driving, found the next step reading the
                    // launcher, and concluded the install had taken the
                    // runner down. The runner was fine; their app was
                    // gone. Read rather than assumed, and printed only
                    // when it really happened: a line every install
                    // carries is a line readers learn to skip.
                    let before = control.frontmost_app(&udid).await.ok().flatten();
                    control
                        .install(&udid, &app_path.display().to_string())
                        .await
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    println!("installed: {} on {udid}", app_path.display());
                    if let Some(was) = before {
                        let after = control.frontmost_app(&udid).await.ok().flatten();
                        if after.as_ref().map(|f| &f.package) != Some(&was.package) {
                            println!(
                                "  {} was running and this reinstall stopped it — \
                                 bring it back with `smix sim launch {device} {}`",
                                was.package, was.package
                            );
                        }
                    }
                }
                SimAction::Uninstall { device, bundle_id } => {
                    let udid = resolve_device(&device)?;
                    let bundle = bundle_id.clone();
                    // The `_ =>` arm this replaces sent a registered
                    // iPhone to `simctl`, which lists no phones.
                    let control = device_control_for(device_kind_of(&device), &udid);
                    with_device_lease(control.as_ref(), &udid, |leased| async move {
                        leased.uninstall(&bundle).await?;
                        Ok(((), leased))
                    })
                    .await?;
                    println!("uninstalled: {bundle_id} on {udid}");
                }
                SimAction::Reverse {
                    device,
                    port,
                    to,
                    remove,
                } => {
                    use smix_sdk::device_control::DeviceControl;
                    let serial = resolve_android_serial(&device)?;
                    let control = smix_sdk::android_device::AndroidDeviceControl::new();
                    let leases = smix_capsule::runner::machine_leases().map_err(CliError::Other)?;
                    if remove {
                        control
                            .reverse_port_remove(&serial, port)
                            .await
                            .map_err(|e| CliError::Other(e.to_string()))?;
                        smix_lease::store::drop_reverse(&leases, &serial, port)
                            .map_err(|e| CliError::Other(e.to_string()))?;
                        println!("reverse: {serial} tcp:{port} closed");
                    } else {
                        // The device's own port is the default: a caller
                        // who wants them to differ says so.
                        let host_port = to.unwrap_or(port);
                        control
                            .reverse_port(&serial, port, host_port)
                            .await
                            .map_err(|e| CliError::Other(e.to_string()))?;
                        // Written after adb took it, never before. A row
                        // for a route that was never opened would have
                        // the next teardown close something that is not
                        // there, and report a clean device either way.
                        smix_lease::store::record_reverse(
                            &leases, &serial, &serial, port, host_port,
                        )
                        .map_err(|e| CliError::Other(e.to_string()))?;
                        println!(
                            "reverse: {serial} tcp:{port} -> 127.0.0.1:{host_port} \
                             (stays open until `smix sim reverse {device} {port} --remove`, \
                             or until the device goes away)"
                        );
                    }
                }
                SimAction::Wake { device } => {
                    let serial = resolve_android_serial(&device)?;
                    let control = smix_sdk::android_device::AndroidDeviceControl::new();
                    with_device_lease(&control, &serial, |leased| async move {
                        leased.wake().await?;
                        Ok(((), leased))
                    })
                    .await?;
                    println!(
                        "wake: {serial} screen is on \
                         (a passcode lock is untouched — this lights the screen, it does not unlock)"
                    );
                }
                SimAction::StayAwake { device, state } => {
                    let serial = resolve_android_serial(&device)?;
                    let control = smix_sdk::android_device::AndroidDeviceControl::new();
                    with_device_lease(&control, &serial, |leased| async move {
                        leased.set_stay_awake(state).await?;
                        Ok(((), leased))
                    })
                    .await?;
                    let worded = if state { "on" } else { "off" };
                    println!(
                        "stay-awake: {serial} {worded} \
                         (a device setting — it outlives this run until set back)"
                    );
                }
                SimAction::Permission {
                    device,
                    bundle_id,
                    permission,
                    action,
                } => {
                    use smix_sdk::device_control::{DeviceControl, Permission};
                    let parsed = Permission::from_name(&permission).map_err(CliError::Other)?;
                    let what = match action.as_str() {
                        "grant" => smix_sdk::PermissionAction::Grant,
                        "revoke" => smix_sdk::PermissionAction::Revoke,
                        // The value parser admits only these three.
                        _ => smix_sdk::PermissionAction::Reset,
                    };
                    let kind = device_kind_of(&device);
                    if kind == smix_simctl::registry::DeviceKind::Simulator {
                        let udid = resolve_device(&device)?;
                        let control = smix_sdk::ios_device::IosDeviceControl::new();
                        control
                            .set_permission(&udid, &bundle_id, parsed, what)
                            .await
                            .map_err(|e| CliError::Other(e.to_string()))?;
                        println!("permission: {udid} {bundle_id} {} {action}", parsed.name());
                    } else {
                        let serial = resolve_android_serial(&device)?;
                        let control = smix_sdk::android_device::AndroidDeviceControl::new();
                        control
                            .set_permission(&serial, &bundle_id, parsed, what)
                            .await
                            .map_err(|e| CliError::Other(e.to_string()))?;
                        println!(
                            "permission: {serial} {bundle_id} {} {action}",
                            parsed.name()
                        );
                    }
                }
                SimAction::Frontmost { device, json } => {
                    use smix_sdk::device_control::DeviceControl;
                    let serial = resolve_android_serial(&device)?;
                    let control = smix_sdk::android_device::AndroidDeviceControl::new();
                    let front = control
                        .frontmost_app(&serial)
                        .await
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    match (front, json) {
                        (Some(f), true) => println!(
                            "{}",
                            serde_json::json!({ "package": f.package, "activity": f.activity })
                        ),
                        (Some(f), false) => println!("frontmost: {} {}", f.package, f.activity),
                        // Nothing resumed is an answer — a lock screen,
                        // or a device still coming up — so it is said
                        // plainly rather than left to an empty line.
                        (None, true) => println!("null"),
                        (None, false) => {
                            println!("frontmost: nothing is resumed on {serial}");
                        }
                    }
                }
                SimAction::Crashes { device, app, json } => {
                    use smix_sdk::device_control::DeviceControl;
                    let serial = resolve_android_serial(&device)?;
                    let control = smix_sdk::android_device::AndroidDeviceControl::new();
                    let all = control
                        .crash_reports(&serial)
                        .await
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    let shown: Vec<_> = match &app {
                        Some(pkg) => all.iter().filter(|r| r.process.contains(pkg)).collect(),
                        None => all.iter().collect(),
                    };
                    if json {
                        let rows: Vec<_> = shown
                            .iter()
                            .map(|r| {
                                serde_json::json!({
                                    "when": r.when,
                                    "process": r.process,
                                    "summary": r.summary,
                                    "lines": r.lines,
                                })
                            })
                            .collect();
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&rows)
                                .map_err(|e| CliError::Other(e.to_string()))?
                        );
                    } else {
                        for report in &shown {
                            println!("{} {} — {}", report.when, report.process, report.summary);
                            for line in &report.lines {
                                println!("  {line}");
                            }
                        }
                        // How many were filtered out is the evidence
                        // that reads apart from an empty buffer: "none
                        // of them was yours" and "the device recorded
                        // none" are different answers.
                        match &app {
                            Some(pkg) => println!(
                                "crashes: {} of {} report(s) on {serial} name {pkg}",
                                shown.len(),
                                all.len()
                            ),
                            None => {
                                println!("crashes: {} report(s) on {serial}", all.len());
                            }
                        }
                    }
                }
                SimAction::Openurl { device, url } => {
                    let udid = resolve_device(&device)?;
                    device_control_for(device_kind_of(&device), &udid)
                        .open_url(&udid, &url)
                        .await
                        .map_err(|e| CliError::Other(e.to_string()))?;
                    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::AllowDestructive { device } => {
                    let path = registry_path()?;
                    match smix_simctl::registry::SimRegistry::allow_destructive(&path, &device) {
                        Ok((alias, already)) => {
                            if already {
                                println!("{alias}: destructive actions were already allowed");
                            } else {
                                println!(
                                    "{alias}: destructive actions allowed — \
                                 erase / uninstall / keychain-reset will now run on it"
                                );
                            }
                        }
                        Err(e) => return Err(CliError::Other(e.to_string())),
                    }
                }
                SimAction::KeychainReset { device } => {
                    let udid = resolve_device(&device)?;
                    let control = smix_sdk::ios_device::IosDeviceControl::new();
                    with_device_lease(&control, &udid, |leased| async move {
                        leased.keychain_reset().await?;
                        Ok(((), leased))
                    })
                    .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,
                    device_flag,
                    platform,
                    bundle,
                    runner_project,
                    runner_port: port_flag,
                    supervise,
                    team,
                    no_launch,
                    force,
                    take_over,
                } => {
                    // clap has already refused the case where neither
                    // is given, and the case where both are.
                    let device = device
                        .or(device_flag)
                        .expect("clap requires one of the two forms");
                    if platform == RunPlatform::Android {
                        reject_ios_only_up_flags(runner_project.is_some(), supervise)
                            .map_err(CliError::Other)?;
                        let port =
                            port_flag.unwrap_or(smix_capsule::runner_android::DEFAULT_ANDROID_PORT);
                        // The adb serial is the device id, but it still
                        // has to be a device smix was invited to touch:
                        // this installs an APK.
                        let serial = resolve_android_serial(&device)?;
                        let opts = smix_capsule::runner_android::UpOptions {
                            timeout_secs: smix_capsule::runner::up_timeout_secs(
                                smix_capsule::runner::ANDROID_UP_TIMEOUT_SECS,
                            )
                            .map_err(CliError::Other)?,
                            force,
                            take_over,
                            app: bundle,
                            relaunch: !no_launch,
                        };
                        smix_capsule::runner_android::up_with_options(&root, &serial, port, &opts)
                            .map_err(CliError::Other)?;
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    // Port priority chain:
                    //   1. `--runner-port` flag / SMIX_RUNNER_PORT env
                    //   2. the registered `runnerPort` 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)?;
                    // A physical device needs a signing team and a
                    // different destination. Which it is comes from the
                    // registry, not from a guess about the identifier —
                    // §9#1 requires registration precisely so this
                    // question has a recorded answer.
                    let physical_team = match lookup_registered(&device) {
                        Some(sim) if sim.kind.is_physical() => {
                            let facts = smix_capsule::signing::collect_facts(&udid);
                            Some(
                                smix_capsule::signing::resolve_team(team.as_deref(), &facts)
                                    .map_err(|e| CliError::Other(e.to_string()))?,
                            )
                        }
                        _ => None,
                    };
                    // Bare `smix runner up` defaults to record_enabled=false;
                    // the capsule path (`capsule::up`) overrides to true
                    // via TEST_RUNNER_SMIX_RECORD_ENABLED=1.
                    let target = match physical_team.as_deref() {
                        Some(team) => smix_capsule::runner::RunnerTarget::Physical { team },
                        None => smix_capsule::runner::RunnerTarget::Simulator,
                    };
                    // Turn the simulator on here, and write down that we
                    // did. It came up either way — `xcodebuild test
                    // -destination platform=iOS Simulator,id=…` boots it
                    // as a side effect — but then nothing on the machine
                    // could say who turned it on, and `lease owner` exits
                    // 3 for a device that is very much running. That code
                    // is what `pick-dev-sim` reads, so a good simulator
                    // looked busy and the 4.1.0 ship failed on it.
                    //
                    // §9 #9: who booted a device is a fact about the
                    // machine. Letting a subprocess create that fact
                    // without recording it is the same as not having it.
                    if physical_team.is_none() {
                        let simctl = SimctlClient::new();
                        let claim = boot_record::claim_before_boot(&simctl, &udid).await;
                        simctl
                            .boot_and_wait(&udid, std::time::Duration::from_secs(120))
                            .await?;
                        boot_record::record_simulator_boot(&udid, claim);
                    }
                    smix_capsule::runner::up_on(
                        &root,
                        &udid,
                        port,
                        bundle.as_deref(),
                        runner_project.as_deref(),
                        smix_capsule::runner::UpOptions {
                            supervise,
                            attach_without_relaunch: no_launch,
                            force_recover: force,
                            ..Default::default()
                        },
                        target,
                    )
                    .map_err(CliError::Other)?;
                }
                RunnerAction::Forward { device, port } => {
                    let udid = resolve_device(&device)?;
                    let Some(found) = smix_usbmux::find_by_serial(&udid)
                        .map_err(|e| CliError::Other(e.to_string()))?
                    else {
                        return Err(CliError::Other(format!(
                            "usbmux does not see device {udid}. It is the transport smix \
                             drives through, so its view is the one that counts — a device \
                             `devicectl` calls available can still be off the USB bus.\n\
                             Check the cable, then `smix sim list`."
                        )));
                    };
                    let forward = smix_usbmux::forward(found.device_id, port, port)
                        .map_err(|e| CliError::Other(format!("bind 127.0.0.1:{port}: {e}")))?;
                    println!(
                        "forwarding 127.0.0.1:{} -> {udid}:{port}",
                        forward.local_port()
                    );
                    // Hold it open. The forwarder lives for as long as
                    // this process does, which is the whole reason this
                    // subcommand exists — a listener in the `runner up`
                    // process would die with it.
                    loop {
                        std::thread::sleep(std::time::Duration::from_secs(3600));
                    }
                }
                RunnerAction::Uninstall { platform, device } => {
                    if platform != RunPlatform::Android {
                        return Err(CliError::Other(
                            "runner uninstall is Android-only: the iOS runner is launched by \
                             xcodebuild and installs no standalone package"
                                .to_string(),
                        ));
                    }
                    let port = smix_capsule::runner_android::DEFAULT_ANDROID_PORT;
                    let serial = resolve_android_serial(&device)?;
                    smix_capsule::runner_android::uninstall(&serial, port)
                        .map_err(CliError::Other)?;
                }
                RunnerAction::Down {
                    platform,
                    device,
                    include_unrecorded,
                    take_over,
                    runner_port: port_flag,
                } => {
                    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 = port_flag.unwrap_or_else(|| {
                            std::env::var("SMIX_RUNNER_PORT")
                                .ok()
                                .and_then(|p| p.parse().ok())
                                .unwrap_or(smix_capsule::runner_android::DEFAULT_ANDROID_PORT)
                        });
                        let serial = resolve_android_serial(&serial)?;
                        smix_capsule::runner_android::down_with(&serial, port, take_over)
                            .map_err(CliError::Other)?;
                        return Ok(std::process::ExitCode::SUCCESS);
                    }
                    let port = port_flag.unwrap_or_else(runner_port);
                    if include_unrecorded {
                        smix_capsule::runner::down_including_unrecorded(port)
                    } else {
                        smix_capsule::runner::down(port)
                    }
                    .map_err(CliError::Other)?;
                }
                RunnerAction::Cycle {
                    platform,
                    runner_project,
                    runner_port: port_flag,
                } => {
                    // The platform is a flag here, the same shape as
                    // `down` and `up`, rather than a second notation
                    // invented for this verb.
                    //
                    // It used to take neither platform nor device,
                    // dispatch straight into the iOS path, and read
                    // iOS's state.json — so typed against an Android
                    // runner it went looking in another platform's
                    // records, found nothing, and answered "no runner
                    // recorded". A consumer reported that sentence as a
                    // state problem, because that is what it reads as.
                    // The verb had never worked there: `fn cycle` does
                    // not exist in the Android runner at all.
                    //
                    // §9 #1 (iii): a capability that is not available is
                    // a loud error, never a quiet wrong answer.
                    if platform == RunPlatform::Android {
                        return Err(CliError::Other(
                            "runner cycle has no Android path. Cycling restarts the \
                             xcodebuild test host, and the Android runner is an \
                             instrumentation with no counterpart to restart. Use \
                             `smix runner down --platform android --device <serial>` \
                             then `smix runner up --platform android --device \
                             <serial>`. Until 6.6 this read iOS's records and told \
                             you no runner was recorded."
                                .to_string(),
                        ));
                    }
                    let port = port_flag.unwrap_or_else(runner_port);
                    smix_capsule::runner::cycle(&root, port, runner_project.as_deref())
                        .map_err(CliError::Other)?;
                }
                RunnerAction::Supervise {
                    runner_project,
                    runner_port: port,
                } => {
                    let port = port.unwrap_or_else(runner_port);
                    smix_capsule::runner::supervise(&root, port, runner_project.as_deref())
                        .map_err(CliError::Other)?;
                }
                RunnerAction::List { prune } => {
                    let leases = smix_capsule::runner::machine_leases().map_err(CliError::Other)?;
                    return Ok(std::process::ExitCode::from(runner_list::run(
                        &leases, prune,
                    )?));
                }
                RunnerAction::ListSessions { runner_port: port } => {
                    let port = port.unwrap_or_else(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 } => {
                    if let Some(target) = path {
                        runner_install_into(&target, force)?;
                    } else {
                        runner_install_default(force)?;
                    }
                }
            }
        }
        Cmd::Down { runner_port: port } => {
            let root = smix_workspace_root()?;
            down::run(&root, port.unwrap_or_else(runner_port))
                .await
                .map_err(CliError::Other)?;
        }
        Cmd::Lease { action } => {
            let leases = smix_capsule::runner::machine_leases().map_err(CliError::Other)?;
            return Ok(std::process::ExitCode::from(
                lease_cmd::run(&leases, action).await?,
            ));
        }
        Cmd::Record { action } => {
            record_cmd::run(action).await?;
        }
        Cmd::Capsule { action } => {
            let root = smix_workspace_root()?;
            let port = match &action {
                CapsuleAction::Up { runner_port: p, .. }
                | CapsuleAction::Down { runner_port: p, .. } => p.unwrap_or_else(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::capsule_supports(device_kind_of(&device), &device)
                        .map_err(CliError::Other)?;
                    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::capsule_supports(device_kind_of(&device), &device)
                        .map_err(CliError::Other)?;
                    capsule::down(&root, &udid).await.map_err(CliError::Other)?;
                }
            }
        }
        Cmd::Tap {
            selector,
            ocr_locale,
            port,
            device,
            platform,
            then_screenshot,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            match then_screenshot {
                Some(out) => act::cmd_tap_then_screenshot(selector, p, plat, &out)
                    .await
                    .map_err(|e| CliError::Other(e.to_string()))?,
                None => act::cmd_tap(selector, p, plat, ocr_locale)
                    .await
                    .map_err(|e| CliError::Other(e.to_string()))?,
            }
        }
        Cmd::Find {
            selector,
            ocr_locale,
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_find(selector, p, plat, ocr_locale)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::WaitFor {
            selector,
            ocr_locale,
            timeout,
            port,
            device,
            platform,
            absent,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_wait_for(selector, timeout, p, plat, absent, ocr_locale)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Fill {
            selector,
            text,
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_fill(selector, text, p, plat)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::PressKey {
            key,
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_press_key(key, p, plat)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Scroll {
            selector,
            direction,
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_scroll(selector, direction, p, plat)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Swipe {
            direction,
            from_point,
            to_point,
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            // Two ways in, and saying which was meant is the caller's
            // job: a swipe given both a direction and a pair of points
            // has two answers, and picking one silently is how a flow
            // ends up doing something nobody asked for.
            match (direction, from_point, to_point) {
                (Some(d), None, None) => act::cmd_swipe(d, p, plat)
                    .await
                    .map_err(|e| CliError::Other(e.to_string()))?,
                (None, Some(from), Some(to)) => act::cmd_swipe_between(&from, &to, p, plat)
                    .await
                    .map_err(|e| CliError::Other(e.to_string()))?,
                (None, None, None) => {
                    return Err(CliError::Other(
                        "swipe needs either a direction (`up` / `down` / `left` / \
                         `right`) or both `--from` and `--to`"
                            .to_string(),
                    ));
                }
                (None, Some(_), None) | (None, None, Some(_)) => {
                    return Err(CliError::Other(
                        "a coordinate swipe needs both ends: give `--from` and `--to`".to_string(),
                    ));
                }
                (Some(_), _, _) => {
                    return Err(CliError::Other(
                        "swipe takes a direction or a `--from`/`--to` pair, not both".to_string(),
                    ));
                }
            }
        }
        Cmd::HideKeyboard {
            port,
            device,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            act::cmd_hide_keyboard(p, plat)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Tree {
            json,
            port,
            device,
            platform,
            keyboard,
            reader,
        } => {
            let p = runner_dial_port(port, device.as_deref());
            // Only for the caveat, so a platform that cannot be told is not
            // a reason to refuse the tree.
            let ios = runner_dial_target(port, device.as_deref(), platform)
                .is_ok_and(|(_, plat)| plat == smix_driver::Platform::Ios);
            act::cmd_tree(json, p, keyboard, reader.to_act(), ios)
                .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,
            platform,
        } => {
            let (p, plat) = runner_dial_target(port, device.as_deref(), platform)?;
            script::cmd_run_script(&path, p, plat)
                .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());
                }
                // Forward --platform only when it was given. Left out,
                // each node reads it from its own --device, the same way
                // the single-machine path does — forwarding a guessed
                // default would override that inference downstream.
                if let Some(p) = platform {
                    passthrough.push("--platform".into());
                    passthrough.push(
                        match p {
                            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());
                }
                // Forward --platform only when it was given. Left out,
                // each node reads it from its own --device, the same way
                // the single-machine path does — forwarding a guessed
                // default would override that inference downstream.
                if let Some(p) = platform {
                    passthrough.push("--platform".into());
                    passthrough.push(
                        match p {
                            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") };
            }
            // No --device: fall back to this project's default device —
            // the pointer `smix init` recorded, keyed by the project path,
            // in the machine store. Explicit --device wins; with no pointer
            // the old behaviour stands. Never "whatever is attached" — only
            // a device the project deliberately registered.
            let device = run_device_ref(
                device.as_deref(),
                registry_path().ok().and_then(|p| {
                    SimRegistry::project_alias(&p, &project_key())
                        .ok()
                        .flatten()
                }),
            );
            // 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()));
            // Announce the run before it starts, and hold the device for
            // as long as this command lasts — every flow, every retry.
            // Released when this binding goes out of scope.
            let _run_lease = hold_run_lease(udid.as_deref())?;
            // 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)
            });
            // Read the platform from the device rather than an argument
            // that defaulted to iOS. A run with no --device has no kind
            // to read and keeps the old default; a --device the registry
            // classifies decides; a --device it cannot classify, with no
            // --platform, is an error rather than a silent iOS guess —
            // which is what sent an Android launchApp to simctl.
            let plat = match device.as_deref() {
                None => platform.unwrap_or(RunPlatform::Ios),
                Some(d) => {
                    let kind = lookup_registered(d).map(|s| s.kind);
                    match resolve_run_platform(platform, kind) {
                        Ok(p) => p,
                        Err(e) => return Err(CliError::Other(e)),
                    }
                }
            }
            .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(", ")
        );
    }
}

/// UDIDs currently reporting `Booted`.
///
/// Asked before a boot so the ledger can record whether this process is
/// the one that brought the device up.
async fn booted_udids(simctl: &smix_simctl::SimctlClient) -> Vec<String> {
    simctl
        .list_devices()
        .await
        .map(|ds| {
            ds.into_iter()
                .filter(|d| d.state == "Booted")
                .map(|d| d.udid.to_uppercase())
                .collect()
        })
        .unwrap_or_default()
}

/// Take the device's lease for one destructive command, run it, give it back.
///
/// The two commands that reach this — `sim uninstall` and
/// `sim keychain-reset` — take data away, and until now either would run
/// happily against a device somebody else's session was driving. The gate
/// is the same one the SDK uses; what is new is that the CLI goes through
/// it rather than around it via `SimctlClient`'s inherent methods.
///
/// Any settling of a previous holder's abandoned session is printed
/// rather than swallowed: a command that quietly tore down someone's
/// leftovers and then did its own destructive work would leave the person
/// unable to tell the two apart afterwards.
async fn with_device_lease<'a, F, Fut, T>(
    // Whatever drives the device, not one platform's driver.
    // `Leased::acquire` has always taken `&dyn DeviceControl`; this
    // named a concrete iOS type only because iOS was the only caller,
    // and that is what would have made the Android arm build a second
    // way of taking a lease rather than use this one.
    control: &'a dyn smix_sdk::device_control::DeviceControl,
    udid: &str,
    body: F,
) -> Result<T, CliError>
where
    F: FnOnce(smix_sdk::leased::Leased<'a>) -> Fut,
    Fut: std::future::Future<Output = Result<(T, smix_sdk::leased::Leased<'a>), CliError>>,
{
    let leases = smix_capsule::runner::machine_leases().map_err(CliError::Other)?;
    let leased = smix_sdk::leased::Leased::acquire(
        control,
        &leases,
        udid,
        &smix_capsule::reconcile::Reconciler,
    )
    .map_err(|e| CliError::Other(e.to_string()))?;
    for report in leased.settled() {
        println!("settled first: {}", report.line);
    }
    let (out, leased) = body(leased).await?;
    leased
        .release()
        .map_err(|e| CliError::Other(e.to_string()))?;
    Ok(out)
}

/// Holds a device lease for as long as a `smix run` is in progress.
///
/// A run is the longest thing the CLI does to a device, and until now it
/// announced nothing: `smix sim uninstall` aimed at the same device would
/// proceed happily alongside it, and whichever landed second won.
///
/// Released on drop. Drop cannot report a failure, so a failed release is
/// printed rather than returned — and it is not serious: an unreleased
/// lease is found by the next command, which sees the holder is gone and
/// settles it. Releasing just makes the device free sooner.
struct RunLease {
    leases: smix_lease::store::LeaseDir,
    device_id: String,
    inherited: Vec<smix_lease::Resource>,
}

impl Drop for RunLease {
    fn drop(&mut self) {
        // Keep what was inherited: an adopted runner and its forwarder
        // belong to the ledger after this run as much as before it.
        if let Err(e) = smix_lease::store::drop_process_rows_except(
            &self.leases,
            &self.device_id,
            &self.inherited,
        ) {
            eprintln!(
                "warning: device lease not released for {}: {e}",
                self.device_id
            );
        }
    }
}

/// Take the device for this run, settling an abandoned session first.
///
/// `None` device means the platform picks one later, and a lease cannot
/// be taken on a device nobody has named yet — the run proceeds
/// unannounced, exactly as it did before leases existed.
fn hold_run_lease(udid: Option<&str>) -> Result<Option<RunLease>, CliError> {
    let Some(udid) = udid else {
        return Ok(None);
    };
    // A run outside a workspace still gets a lease: the ledger is the
    // machine's.
    let Ok(leases) = smix_capsule::runner::machine_leases() else {
        return Ok(None);
    };
    let control = smix_sdk::ios_device::IosDeviceControl::new();
    let leased = smix_sdk::leased::Leased::acquire(
        &control,
        &leases,
        udid,
        &smix_capsule::reconcile::Reconciler,
    )
    .map_err(|e| CliError::Other(e.to_string()))?;
    for report in leased.settled() {
        println!("settled first: {}", report.line);
    }
    let inherited = leased.inherited().to_vec();
    Ok(Some(RunLease {
        leases,
        device_id: udid.to_string(),
        inherited,
    }))
}

/// Refuse a destructive action on a physical device that has not opted in.
///
/// Reads the class out of the registry and hands the one bit that matters
/// to `smix_lease::may_destroy`, which is where the rule lives. An
/// unregistered ref is not gated here — resolution already refused it, and
/// a second refusal with a different reason would be confusing.
/// Whether this verb can take something away from a device somebody
/// carries.
///
/// Named here, once, so the test that requires every variant to be
/// classified reads the same judgement the runtime uses. `exec` is on
/// the list because it runs an arbitrary command: whatever the worst
/// thing that command can do is, this verb can do it.
fn is_destructive(action: &SimAction) -> bool {
    // Exhaustive, for the reason `sim_verb_supports` is: a new verb has
    // to say whether it destroys something before this compiles. As a
    // `matches!` it listed four verbs and called everything else safe,
    // and `exec` — which runs an arbitrary command on the device — was
    // absent from that list for as long as it existed. A gate whose
    // default answer is "harmless" is one nobody has to remember to
    // update, which is the same as not having it.
    match action {
        SimAction::Erase { .. }
        | SimAction::Uninstall { .. }
        | SimAction::KeychainReset { .. }
        | SimAction::Exec { .. } => true,

        SimAction::List { .. }
        | SimAction::Register { .. }
        | SimAction::Resolve { .. }
        | SimAction::Migrate { .. }
        | SimAction::Unregister { .. }
        | SimAction::AllowDestructive { .. }
        | SimAction::Boot { .. }
        | SimAction::Shutdown { .. }
        | SimAction::Screenshot { .. }
        | SimAction::Launch { .. }
        | SimAction::Terminate { .. }
        | SimAction::Install { .. }
        | SimAction::Openurl { .. }
        // A route to this machine takes nothing off the device.
        | SimAction::Reverse { .. }
        // Arranging the screen and reading what is on it. The two
        // writers change a setting the same verb changes back; the two
        // readers change nothing at all.
        | SimAction::Wake { .. }
        | SimAction::StayAwake { .. }
        | SimAction::Frontmost { .. }
        | SimAction::Crashes { .. }
        // A permission grant is the app's, and revoking is the same
        // verb with the other argument. `privacy_reset_all` is the
        // destructive one, and it is not this.
        | SimAction::Permission { .. }
        | SimAction::Appearance { .. }
        | SimAction::Locale { .. } => false,
    }
}

/// The governance gate, for every verb, before any of them runs.
///
/// It used to be called inside three match arms, and the comment above
/// `guard_sim_verb` had already explained why that fails: "putting it
/// inside the arms would mean remembering it in each — and the arms
/// that most needed it are exactly the ones nobody remembered." `exec`
/// was one nobody remembered.
///
/// Before `guard_sim_verb`, deliberately. Both refuse a destructive
/// verb on a physical device, but they answer different questions —
/// this one says the rule and how to lift it, the other says simctl
/// cannot reach that device. A reader told the second learns a plumbing
/// detail and goes looking for another route; a reader told the first
/// learns the rule. The device was safe either way only because simctl
/// happens not to reach phones, which the guard's own comment noted
/// "stopped holding the day a `devicectl` path appeared".
fn guard_destructive_action(action: &SimAction) -> Result<(), CliError> {
    if !is_destructive(action) {
        return Ok(());
    }
    let Some(device) = sim_action_device(action) else {
        return Ok(());
    };
    guard_destructive(device)
}

fn guard_destructive(device_ref: &str) -> Result<(), CliError> {
    let reg = load_registry().registry;
    let Some(sim) = reg.lookup(device_ref) else {
        // Not registered, and still here — so `resolve_device` let it
        // through, which it only does for a simulator the platform
        // lists. Those were never gated: erasing one costs a minute of
        // rebuilding.
        //
        // This used to be the gate's blind spot rather than its
        // conclusion: an unregistered device of *any* kind was waved
        // through, and what stopped a phone was `simctl` refusing to
        // recognise it downstream. That is a property of the executor,
        // not of this guard, and it stopped holding the day a
        // `devicectl` path appeared.
        return Ok(());
    };
    smix_lease::may_destroy(
        device_ref,
        smix_lease::DeviceClass {
            physical: sim.kind.is_physical(),
            destructive_opt_in: sim.destructive_opt_in,
        },
    )
    .map_err(|e| CliError::Other(e.to_string()))
}

/// CLI spelling of [`smix_simctl::registry::DeviceKind`].
///
/// A separate type because clap's `ValueEnum` derive belongs to the CLI,
/// not to the registry — the registry is read by things that have no
/// command line.
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
enum DeviceKindArg {
    Simulator,
    Emulator,
    PhysicalIos,
    PhysicalAndroid,
}

impl DeviceKindArg {
    fn to_registry(self) -> smix_simctl::registry::DeviceKind {
        use smix_simctl::registry::DeviceKind as K;
        match self {
            DeviceKindArg::Simulator => K::Simulator,
            DeviceKindArg::Emulator => K::Emulator,
            DeviceKindArg::PhysicalIos => K::PhysicalIos,
            DeviceKindArg::PhysicalAndroid => K::PhysicalAndroid,
        }
    }
}

/// Which tool takes a physical iPhone's picture.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PhoneScreenshotRoute {
    /// `devicectl device capture screenshot` — nothing has to be up.
    Devicectl,
    /// The runner's `XCUIScreen` — the runner has to be up.
    Runner,
}

/// Decide it from what the phone says it offers.
///
/// `offers_capture` is whether the device lists CoreDevice's screenshot
/// capability, or `None` when devicectl could not be asked or does not
/// list the phone. Xcode 27's devicectl lists it for a connected iPhone;
/// Xcode <= 26's lists no such thing, and there the runner is the only
/// way a phone is seen. A decision on evidence, taken before anything is
/// tried — not one route attempted and the other reached by failing.
fn phone_screenshot_route(offers_capture: Option<bool>) -> PhoneScreenshotRoute {
    match offers_capture {
        Some(true) => PhoneScreenshotRoute::Devicectl,
        Some(false) | None => PhoneScreenshotRoute::Runner,
    }
}

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 SessionAction {
    /// The runner port and device this invocation resolves to, plus the
    /// runner's open sessions when it is reachable.
    State {
        /// Runner port. Overrides the flag/env/registry ladder; without
        /// it the same resolution `smix run` uses applies.
        #[arg(long)]
        port: Option<u16>,
        /// Device UDID or registry alias, used only to resolve the
        /// runner port it is registered on. Read-only.
        #[arg(long)]
        device: Option<String>,
    },
}

#[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,
        /// The runner to ask, by its port.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
}

/// `smix runner install --path <dir>`: that directory, replaced whole,
/// the previous tree kept beside it.
fn runner_install_into(target: &Path, force: bool) -> Result<(), CliError> {
    // An explicit path is one directory the caller owns:
    // replaced whole, the previous tree kept beside it.
    if !force
        && smix_runner_sources::stamp_is_current(
            smix_runner_sources::read_installed_version(target)
                .map_err(|e| CliError::Other(format!("runner install: {e}")))?
                .as_deref(),
        )
    {
        println!(
            "runner install: {} already holds v{} — nothing to do (pass --force to re-extract).",
            target.display(),
            smix_runner_sources::SOURCES_VERSION
        );
        return Ok(());
    }
    let report = smix_runner_sources::extract_to(target, true)
        .map_err(|e| CliError::Other(format!("runner install: {e}")))?;
    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
    );
    Ok(())
}

/// `smix runner install` with no path: the tree for this binary's sources
/// under the machine directory, which `runner up` would have extracted
/// anyway. `--force` removes that tree first — only this binary's; other
/// sources' trees, and a build running in one of them, are not touched.
fn runner_install_default(force: bool) -> Result<(), CliError> {
    let machine = smix_lease::store::machine_root().ok_or_else(|| {
        CliError::Other(
            "runner install: no HOME or XDG_DATA_HOME, so there is no machine directory".into(),
        )
    })?;
    let dir = smix_runner_sources::tree_dir(&machine, smix_runner_sources::RunnerPlatform::Ios);
    if force && dir.exists() {
        std::fs::remove_dir_all(&dir).map_err(|e| {
            CliError::Other(format!(
                "runner install --force: removing {}: {e}",
                dir.display()
            ))
        })?;
    }
    let ensured =
        smix_runner_sources::ensure_tree(&machine, smix_runner_sources::RunnerPlatform::Ios)
            .map_err(|e| CliError::Other(format!("runner install: {e}")))?;
    let pruned_note = if ensured.pruned.is_empty() {
        String::new()
    } else {
        format!(
            " Removed {} tree(s) of older sources, keeping the {} most recently used.",
            ensured.pruned.len(),
            smix_runner_sources::BACKUPS_KEPT
        )
    };
    if ensured.extracted {
        println!(
            "runner install: extracted v{} into {}.{pruned_note}",
            smix_runner_sources::SOURCES_VERSION,
            ensured.dir.display()
        );
    } else {
        println!(
            "runner install: {} already holds v{} — nothing to do (pass --force to re-extract).{pruned_note}",
            ensured.dir.display(),
            smix_runner_sources::SOURCES_VERSION
        );
    }
    Ok(())
}

/// 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_session(action: SessionAction) -> Result<(), CliError> {
    match action {
        SessionAction::State { port, device } => {
            let p = runner_dial_port(port, device.as_deref());
            let client = smix_runner_client::HttpRunnerClient::new(p);
            let sessions = match client.list_sessions().await {
                Ok(resp) => serde_json::to_value(&resp.sessions).unwrap_or(serde_json::Value::Null),
                // Read-only: an unreachable runner is a state to report,
                // not an error to fail on — say so rather than pretend.
                Err(e) => serde_json::json!({ "unreachable": e.to_string() }),
            };
            let report = serde_json::json!({
                "port": p,
                "device": device,
                "sessions": sessions,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&report).unwrap_or_default()
            );
            Ok(())
        }
    }
}

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,
            runner_port: port,
        } => {
            let port = port.unwrap_or_else(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: Option<&str>,
    device: Option<&str>,
    app: Option<&Path>,
) -> Result<(), CliError> {
    // Make this tree a workspace first, before anything here can refuse.
    //
    // `.smix/` is what `runner up` walks up to find, and where a run's
    // traces, cells and runner state go — checkout-scoped facts, which
    // the move of device records to the machine did not touch. It used
    // to appear as a side effect of writing the registry into it; once
    // the registry went elsewhere, nothing created it, and on a machine
    // that had never run smix `init` reported success while the next
    // command answered "no .smix/ workspace found upward". CI found it
    // on a clean runner; here every tree already had one from before.
    //
    // Before the device is resolved rather than after, because which
    // simulator you name is a separate question from whether this tree
    // is a place smix can work in. An `init` that cannot find your
    // device should still leave you somewhere to run the next one.
    let cwd = std::env::current_dir()
        .map_err(|e| CliError::Other(format!("cannot determine cwd: {e}")))?;
    let workspace = cwd.join(".smix");
    std::fs::create_dir_all(&workspace)
        .map_err(|e| CliError::Other(format!("create {}: {e}", workspace.display())))?;
    // Omitted --alias derives from the project directory's name.
    let alias = alias
        .map(str::to_string)
        .unwrap_or_else(|| init::default_project_alias(&cwd));

    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. 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()?;
    // Every alias this machine already answers to, not just the ones in
    // the book being written: an alias that collides with another
    // checkout's is a name that means two devices depending on where you
    // stand, which is the thing this scope move exists to end.
    let existing: Vec<String> = load_registry().registry.sims().keys().cloned().collect();

    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(),
            avd_name: None,
            runner_port: None,
            locale: None,
            // Same reason as `sim register`: this came from simctl, which
            // lists simulators and nothing else.
            kind: registry::DeviceKind::Simulator,
            destructive_opt_in: false,
        })
        .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}")))?;

    // Record which device this project defaults to — a pointer (the alias
    // string, keyed by the project path) in the machine store, so a later
    // `smix run` here needs no --device. The alias's facts (UDID, kind)
    // stay in the registry; only the pointer is per-project.
    SimRegistry::set_project_alias(&path, &project_key(), &plan.alias)
        .map_err(|e| CliError::Other(format!("record project device: {e}")))?;

    println!(
        "registered `{}` -> {} in {} (this project's default device)",
        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.
            // The boot is recorded like any other; it was not, and `smix
            // down` left running a simulator smix had turned on.
            let claim = boot_record::claim_before_boot(simctl, &plan.udid).await;
            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)));
            }
            boot_record::record_simulator_boot(&plan.udid, claim);
            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, port: u16) -> 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,
    };

    // Every device this machine knows, not every device this tree
    // knows. A doctor that reports on the checkout answers a question
    // nobody asked: the simulators are the machine's.
    let reg = load_registry().registry;
    let registry = (!reg.sims().is_empty()).then(|| readiness::RegistryFacts {
        aliases: reg.sims().len(),
        first_alias: reg.sims().keys().next().cloned(),
    });

    // Existence checked before opening, because `Store::open` creates
    // what it cannot find — and a health check that brings a store into
    // being has changed the thing it was asked to report on. A workspace
    // with no `.smix` yet simply has no store fact.
    let downgradeable = std::env::current_dir()
        .ok()
        .map(|cwd| cwd.join(".smix"))
        .filter(|dir| dir.join("kv").is_dir())
        .and_then(|dir| smix_store::Store::open(&dir).ok())
        .and_then(|store| store.downgradeable_to_kevy3());

    let verdict = readiness::assess(&readiness::Facts {
        simctl: simctl_facts,
        registry,
        // health-not-a-decider: doctor prints whether a runner is
        // answering. It concludes nothing and drives nothing.
        runner_up: smix_capsule::runner::health_ok(port),
        capture_server_up: capture_server_reachable(),
        downgradeable,
        adb: adb_facts(),
    });

    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(())
}

/// The adb smix runs, as doctor reports it; `None` when there is none.
fn adb_facts() -> Option<readiness::AdbFacts> {
    let (path, source) = smix_adb::adb_path();
    // The file a bare name stands for, which is the thing to know.
    let found = if path.components().count() == 1 {
        std::env::var_os("PATH").and_then(|dirs| {
            std::env::split_paths(&dirs)
                .map(|d| d.join(path))
                .find(|p| p.is_file())
        })
    } else {
        path.is_file().then(|| path.clone())
    };
    found.map(|found| readiness::AdbFacts {
        path: found.display().to_string(),
        source: source.to_string(),
        cannot_start: smix_adb::adb_usable().err(),
    })
}

/// One Android device as `adb devices -l` reports it.
struct AndroidDevice {
    serial: String,
    state: String,
    model: String,
    release: String,
    registered: bool,
}

/// Parse `adb devices -l` output.
///
/// Split out from the call so the parsing is testable without a device:
/// the shape of that output is the only thing worth asserting, and it
/// is not worth an emulator to assert it.
fn parse_adb_devices(list: &str) -> Vec<(String, String, String)> {
    list.lines()
        .skip_while(|l| l.starts_with("List of devices"))
        .filter(|l| !l.trim().is_empty())
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            let serial = fields.next()?.to_string();
            let state = fields.next()?.to_string();
            let model = fields
                .find_map(|f| f.strip_prefix("model:"))
                .unwrap_or("")
                .to_string();
            Some((serial, state, model))
        })
        .collect()
}

/// Whether `sim list` may open a shell on `serial` to read its release.
///
/// A phone that is attached and not registered is unreachable (§9#1):
/// that holds for a read as much as for an install. `adb devices -l`
/// already names it and its model, which is all a listing needs; its
/// release is left unasked.
fn may_ask_release(serial: &str, registered: bool) -> bool {
    registered || smix_simctl::registry::is_emulator_serial(serial)
}

/// Every Android device adb can see, with its OS release.
///
/// A machine with no adb has no Android devices, which is the truthful
/// answer rather than an error — the same way `simctl_knows` answers no
/// on a machine with no Xcode.
fn android_devices() -> Vec<AndroidDevice> {
    let registry = load_registry().registry;
    // An adb that cannot start has said why, once, on stderr.
    let Ok(out) = smix_adb::std_command().map(|mut adb| adb.args(["devices", "-l"]).output())
    else {
        return Vec::new();
    };
    let Ok(out) = out else {
        return Vec::new();
    };
    if !out.status.success() {
        return Vec::new();
    }
    parse_adb_devices(&String::from_utf8_lossy(&out.stdout))
        .into_iter()
        .map(|(serial, state, model)| {
            let registered = registry.lookup(&serial).is_some();
            if !may_ask_release(&serial, registered) {
                return AndroidDevice {
                    serial,
                    state,
                    model,
                    release: String::new(),
                    registered,
                };
            }
            let release = std::process::Command::new(&smix_adb::adb_path().0)
                .args([
                    "-s",
                    &serial,
                    "shell",
                    "getprop",
                    "ro.build.version.release",
                ])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                .unwrap_or_default();
            AndroidDevice {
                serial,
                state,
                model,
                release,
                registered,
            }
        })
        .collect()
}

/// List every device smix can drive — simulators and Android both.
///
/// This listed simulators only, which read as "smix has no Android
/// devices" to anyone who ran it with an emulator attached, right after
/// `sim register --kind emulator` had accepted that same emulator. A
/// catalogue command that omits half the catalogue is worse than one
/// that does not exist: it answers the question wrongly instead of
/// sending you to ask elsewhere.
///
/// The JSON stays an array and every element gains a `platform` field.
/// Android entries are not dressed in simctl's clothes — there is no
/// runtime identifier on an emulator, and inventing one would make the
/// listing agree with a schema by lying about the device.
/// The devices smix has records for, and where each record lives.
fn cmd_sim_list_registered(json: bool) -> Result<(), CliError> {
    let view = load_registry();
    let machine = SimRegistry::machine_dir();
    if json {
        let rows: Vec<serde_json::Value> = view
            .registry
            .all()
            .map(|(alias, sim)| {
                serde_json::json!({
                    "alias": alias,
                    "udid": sim.udid,
                    "name": sim.device_name,
                    "kind": sim.kind,
                    "runtime": sim.runtime,
                    "destructiveOptIn": sim.destructive_opt_in,
                    // Where the record is, not just what it says. The
                    // question this command exists to answer is whether
                    // two checkouts see the same devices, and a row
                    // that does not say where it came from cannot
                    // answer it.
                    "scope": match view.unmigrated.get(alias) {
                        Some(p) => serde_json::json!({"checkout": p.display().to_string()}),
                        None => serde_json::json!({"machine": machine.as_ref().map(|m| m.display().to_string())}),
                    },
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&rows)
                .map_err(|e| CliError::Other(format!("serialize: {e}")))?
        );
        return Ok(());
    }
    if view.registry.sims().is_empty() {
        println!("no devices recorded — `smix sim register <alias> --udid <udid>`");
        return Ok(());
    }
    println!("{:<20} {:<40} {:<10} SCOPE", "ALIAS", "UDID", "KIND");
    for (alias, sim) in view.registry.all() {
        let scope = match view.unmigrated.get(alias) {
            Some(p) => p.display().to_string(),
            None => "machine".to_string(),
        };
        println!(
            "{:<20} {:<40} {:<10} {scope}",
            alias,
            sim.udid,
            format!("{:?}", sim.kind).to_lowercase()
        );
    }
    if !view.unmigrated.is_empty() {
        println!();
        println!(
            "{} record(s) live in a checkout and are invisible from anywhere \
             else — `smix sim migrate` folds them in",
            view.unmigrated.len()
        );
    }
    Ok(())
}

/// Fold per-checkout device registries into this machine's.
fn cmd_sim_migrate(from: Vec<PathBuf>, dry_run: bool) -> Result<(), CliError> {
    let into = registry_path()?;
    let sources: Vec<PathBuf> = if from.is_empty() {
        let cwd = std::env::current_dir()
            .map_err(|e| CliError::Other(format!("cannot determine cwd: {e}")))?;
        SimRegistry::discover(&cwd).into_iter().collect()
    } else {
        from.iter()
            .map(|p| {
                if p.ends_with(".smix") {
                    p.clone()
                } else {
                    p.join(".smix")
                }
            })
            .collect()
    };
    if sources.is_empty() {
        println!(
            "nothing to migrate — no .smix registry above {}. \
             Name the checkouts to read with --from <dir>.",
            std::env::current_dir()
                .unwrap_or_else(|_| PathBuf::from("."))
                .display()
        );
        return Ok(());
    }
    // Migrating a book into itself would read every row and write it
    // back, which is harmless but reports every device as "already
    // there" and reads like the migration did nothing. Say which one it
    // is instead.
    let sources: Vec<PathBuf> = sources
        .into_iter()
        .filter(|p| {
            if p == &into {
                println!("{} is already the machine registry — skipped", p.display());
                false
            } else {
                true
            }
        })
        .collect();

    // A rehearsal reads the same books and applies the same merge
    // rules; only the write is skipped. Working the answer out a second
    // way would produce a report about the second way.
    let report = if dry_run {
        SimRegistry::migrate_dry_run(&into, &sources)
    } else {
        SimRegistry::migrate(&into, &sources)
    }
    .map_err(|e| CliError::Other(format!("migrate: {e}")))?;

    for (path, why) in &report.unreadable {
        eprintln!("  {} could not be read: {why}", path.display());
    }
    for path in &report.empty {
        println!("  {} held no devices", path.display());
    }
    for alias in &report.added {
        println!("  + {alias}");
    }
    for alias in &report.narrowed {
        println!("  ~ {alias} — destructive consent narrowed to the stricter answer");
    }
    println!(
        "{} device(s) {} in {} ({} already there)",
        report.added.len(),
        if dry_run {
            "would be recorded"
        } else {
            "now recorded"
        },
        into.display(),
        report.unchanged.len()
    );
    if !report.added.is_empty() && !dry_run {
        // The source is deliberately left in place, so the next reader
        // still finds it and still calls it unmigrated. Saying so beats
        // having somebody wonder why the note did not go away.
        println!(
            "the source registries are untouched — delete them yourself once \
             every tree you use has been migrated"
        );
    }
    Ok(())
}

async fn cmd_sim_list(simctl: &SimctlClient, json: bool) -> Result<(), CliError> {
    let devices = simctl.list_devices().await?;
    let android = android_devices();
    if json {
        let mut all: Vec<serde_json::Value> = Vec::new();
        for d in &devices {
            let mut v =
                serde_json::to_value(d).map_err(|e| CliError::Other(format!("serialize: {e}")))?;
            if let Some(obj) = v.as_object_mut() {
                obj.insert("platform".into(), "ios".into());
            }
            all.push(v);
        }
        for a in &android {
            all.push(serde_json::json!({
                "platform": "android",
                "udid": a.serial,
                "name": if a.model.is_empty() { a.serial.clone() } else { a.model.clone() },
                "state": a.state,
                "release": a.release,
                "registered": a.registered,
            }));
        }
        let out = serde_json::to_string_pretty(&all)
            .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
        );
    }
    for a in &android {
        let name = if a.model.is_empty() {
            a.serial.as_str()
        } else {
            a.model.as_str()
        };
        let release = if !may_ask_release(&a.serial, a.registered) {
            "Android (not registered; smix does not address it)".to_string()
        } else if a.release.is_empty() {
            "Android".to_string()
        } else {
            format!("Android-{}", a.release)
        };
        println!("{:<40} {:<28} {:<10} {release}", a.serial, name, a.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.
/// The device a `run` should drive, given what the caller named and
/// what the project defaults to. Explicit `--device` always wins; with
/// none, the project's recorded pointer stands in; with neither, `None`
/// keeps the old behaviour (the iOS default). It never reaches for a
/// device the project did not name — the pointer is a deliberate
/// `smix init` / `smix sim register`, not "whatever is attached".
fn run_device_ref(explicit: Option<&str>, pointer: Option<String>) -> Option<String> {
    match explicit {
        Some(d) => Some(d.to_string()),
        None => pointer,
    }
}

/// The key a project's device pointer is stored under: the workspace
/// root (the nearest ancestor with a `.smix/`), canonicalized, or the
/// cwd when there is no workspace. Lenient on purpose — a `run` outside
/// a workspace still resolves to a key, just one with no pointer, so it
/// falls through to the old behaviour rather than failing.
fn project_key() -> String {
    let cwd = std::env::current_dir().unwrap_or_default();
    let root = smix_capsule::runner::workspace_root(&cwd).unwrap_or_else(|| cwd.clone());
    std::fs::canonicalize(&root)
        .unwrap_or(root)
        .to_string_lossy()
        .into_owned()
}

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)
    })
}

/// Dial both the port and the platform a CLI verb should drive, so
/// `fill` / `find` reach the driver the flow path already uses. The port
/// keeps `runner_dial_port`'s flag → env → registry → default ladder;
/// the platform is read from the device the same way `smix run` reads it
/// (C1) — one rule at both entrances. No `--device` lets the dialed
/// port's registered holder decide (the consumer's `--port 22088`
/// usage). An unclassifiable target is an error, not a silent iOS drive
/// that would 501 on Android.
fn runner_dial_target(
    flag: Option<u16>,
    device: Option<&str>,
    platform: Option<RunPlatform>,
) -> Result<(u16, smix_driver::Platform), CliError> {
    let port = runner_dial_port(flag, device);
    // Said outright, as `smix run --platform` says it.
    if let Some(p) = platform {
        return Ok((port, p.to_driver()));
    }
    let dial = device.map(|d| match lookup_registered(d) {
        Some(sim) => DeviceDial::Registered(sim.kind),
        None => DeviceDial::Unregistered,
    });
    let holders: Vec<smix_simctl::registry::DeviceKind> = if device.is_none() {
        load_registry()
            .registry
            .all()
            .filter(|(_, sim)| sim.runner_port == Some(port))
            .map(|(_, sim)| sim.kind)
            .collect()
    } else {
        Vec::new()
    };
    let plat = dial_platform(dial, &holders).map_err(CliError::Other)?;
    Ok((port, plat.to_driver()))
}

/// 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(runner_project: bool, supervise: bool) -> Result<(), String> {
    let offenders: Vec<&str> = [
        (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 builds no Xcode project and has no \
         supervise sidecar. What applies on this platform: --runner-port, \
         --bundle (the app to leave in front), --no-launch, --force, --take-over.",
        offenders.join(" / "),
        if offenders.len() == 1 {
            "it is"
        } else {
            "they are"
        },
    ))
}

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

/// Whether this process is the one that turned an emulator on.
#[derive(Clone, Copy, Debug, PartialEq)]
enum EmulatorState {
    WasOff,
    AlreadyRunning,
}

/// What to write to the ledger after a boot.
#[derive(Clone, Copy, Debug, PartialEq)]
enum BootClaim {
    ClaimAsOurs,
    LeaveUnclaimed,
}

/// What the ledger says about who holds a device.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Ownership {
    BootedByUs,
    HeldByOther { pid: u32 },
    NoLedgerRow,
}

/// Whether this process may stop a device.
#[derive(Clone, Debug, PartialEq)]
enum ShutdownVerdict {
    Proceed,
    Refuse { message: String },
}

/// A device that was already up was turned on by somebody else, and
/// claiming it is how a later teardown comes to stop their work.
fn boot_claim(state: EmulatorState) -> BootClaim {
    match state {
        EmulatorState::WasOff => BootClaim::ClaimAsOurs,
        EmulatorState::AlreadyRunning => BootClaim::LeaveUnclaimed,
    }
}

/// What this machine's ledger says about a device, in the shape the
/// verdict below takes.
///
/// A translation of `smix_lease::assess`, not a second opinion. The
/// first draft asked only "is there a row", which cannot tell a device
/// somebody is using from one whose holder died hours ago — and a
/// stale row would then have locked the device out of smix's hands
/// permanently. The ledger already draws that line (`Admission`), and
/// drawing it twice is how the two answers start disagreeing.
fn ownership_of(serial: &str) -> Ownership {
    let Ok(leases) = smix_capsule::runner::machine_leases() else {
        return Ownership::NoLedgerRow;
    };
    let Ok(facts) = smix_lease::store::collect_facts(&leases, serial) else {
        return Ownership::NoLedgerRow;
    };
    // Booted-by-us is read off the resources rather than the admission,
    // because `Booted` is a device state and not a process: `assess`
    // deliberately does not treat it as something to probe for
    // liveness. Whether this device is ours and whether somebody's
    // session is alive on it are two questions.
    let booted_by_us = facts.existing.as_ref().is_some_and(|h| {
        h.lease
            .known_resources()
            .any(|r| matches!(r, smix_lease::Resource::Booted { by_us: true }))
    });
    match smix_lease::assess(&facts) {
        smix_lease::Admission::Denied(c) if c.holder_alive => {
            Ownership::HeldByOther { pid: c.holder.pid }
        }
        _ if booted_by_us => Ownership::BootedByUs,
        _ => Ownership::NoLedgerRow,
    }
}

/// Whoever booted it stops it.
///
/// The two refusals are kept apart because they send a reader somewhere
/// different: no ledger row means nothing here started the device and
/// there is nobody to ask; a row held by another process means
/// something did start it and may still be using it, and names who.
fn shutdown_verdict(owner: Ownership, serial: &str) -> ShutdownVerdict {
    match owner {
        Ownership::BootedByUs => ShutdownVerdict::Proceed,
        Ownership::NoLedgerRow => ShutdownVerdict::Refuse {
            message: format!(
                "{serial} is running and this machine's ledger has no record of smix \
                 booting it — whoever booted it stops it.\n\
                 \x20 if it is yours and you started it by hand, stop it the same way\n\
                 \x20 if it should be smix's, start it with `smix sim boot {serial}` \
                 and the ledger will say so"
            ),
        },
        Ownership::HeldByOther { pid } => ShutdownVerdict::Refuse {
            message: format!(
                "{serial} is held by pid {pid}, which is still alive — stopping it now \
                 takes a device out from under work that is running.\n\
                 \x20 `smix lease status {serial}` says what it has open\n\
                 \x20 `smix lease reconcile {serial}` closes it gracefully once that \
                 process is gone"
            ),
        },
    }
}

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

    // Who turned this device on, and may this process turn it off.
    //
    // The iOS path has answered both since the ledger moved to the
    // machine: `record_boot(.., !was_up)` declines to claim a device
    // that was already running, and teardown reads that claim back.
    // Android had neither, and the day this was written another
    // person's smix stopped this machine's emulator a dozen times
    // while a release was using it — nobody was doing anything wrong,
    // because nothing could be asked.

    #[test]
    fn a_device_already_running_is_not_claimed() {
        assert_eq!(
            boot_claim(EmulatorState::AlreadyRunning),
            BootClaim::LeaveUnclaimed,
            "smix did not turn this one on, and saying otherwise is how a \
             teardown later stops somebody else's work"
        );
    }

    #[test]
    fn a_device_this_process_started_is_claimed() {
        assert_eq!(boot_claim(EmulatorState::WasOff), BootClaim::ClaimAsOurs);
    }

    /// The seed of the whole version. Everything else in v6.1 is this
    /// sentence applied in another place.
    #[test]
    fn an_emulator_we_did_not_boot_is_not_ours_to_stop() {
        match shutdown_verdict(Ownership::NoLedgerRow, "emulator-5560") {
            ShutdownVerdict::Refuse { message } => {
                assert!(
                    message.contains("emulator-5560"),
                    "a refusal that does not name the device cannot be acted on: {message}"
                );
                assert!(
                    message.to_lowercase().contains("boot"),
                    "the refusal must say the rule it is applying — whoever booted it \
                     stops it: {message}"
                );
            }
            other => panic!("stopping a device smix never started was allowed: {other:?}"),
        }
    }

    #[test]
    fn an_emulator_we_booted_is_ours_to_stop() {
        assert!(matches!(
            shutdown_verdict(Ownership::BootedByUs, "emulator-5560"),
            ShutdownVerdict::Proceed
        ));
    }

    /// Held by another live process, with a ledger row that is not ours.
    /// Distinct from "no row" because the two send a reader somewhere
    /// different: no row means nothing here started it, and a row means
    /// something did and may still be using it.
    #[test]
    fn an_emulator_held_by_someone_else_names_the_holder() {
        match shutdown_verdict(Ownership::HeldByOther { pid: 4242 }, "emulator-5560") {
            ShutdownVerdict::Refuse { message } => assert!(
                message.contains("4242"),
                "the refusal must name who is holding it, or the reader has nothing \
                 to go and ask: {message}"
            ),
            other => panic!("stopping a device another process holds was allowed: {other:?}"),
        }
    }
}

#[cfg(test)]
mod platform_from_device {
    use super::*;
    use smix_simctl::registry::DeviceKind;

    // The platform used to be an argument that defaulted to iOS,
    // unrelated to the device you named — so `smix run --device
    // emulator-5560` sent its launchApp to simctl and got
    // `Invalid device: emulator-5560`. The device already says which
    // platform it is; the run should read it there, and only fall back
    // to an explicit --platform, never to a guess.

    #[test]
    fn an_explicit_platform_wins() {
        assert_eq!(
            resolve_run_platform(Some(RunPlatform::Android), Some(DeviceKind::Simulator)).unwrap(),
            RunPlatform::Android,
            "--platform is the override for a device the registry cannot classify"
        );
    }

    #[test]
    fn an_emulator_is_android_without_being_told() {
        for k in [DeviceKind::Emulator, DeviceKind::PhysicalAndroid] {
            assert_eq!(
                resolve_run_platform(None, Some(k)).unwrap(),
                RunPlatform::Android,
                "{k:?}"
            );
        }
    }

    #[test]
    fn a_simulator_is_ios_without_being_told() {
        for k in [DeviceKind::Simulator, DeviceKind::PhysicalIos] {
            assert_eq!(
                resolve_run_platform(None, Some(k)).unwrap(),
                RunPlatform::Ios,
                "{k:?}"
            );
        }
    }

    /// The bug was defaulting to iOS when nothing said otherwise. An
    /// unregistered bare name has no kind, and guessing is how an
    /// Android flow reached simctl. Refuse and name the two ways out.
    #[test]
    fn an_unclassifiable_device_refuses_rather_than_guessing() {
        let err = resolve_run_platform(None, None).unwrap_err();
        assert!(
            err.contains("--platform"),
            "the error must name the override: {err}"
        );
        assert!(
            err.to_lowercase().contains("register"),
            "and the durable fix: {err}"
        );
    }
}

#[cfg(test)]
mod phone_screenshot_routing {
    use super::{PhoneScreenshotRoute, phone_screenshot_route};

    // Which tool takes a phone's picture is decided by what the phone
    // says it offers, not by trying one and falling back to the other.
    #[test]
    fn a_phone_that_offers_capture_is_asked_itself() {
        assert_eq!(
            phone_screenshot_route(Some(true)),
            PhoneScreenshotRoute::Devicectl
        );
    }

    // Xcode <= 26's devicectl lists no such capability, and there the
    // runner's XCUIScreen is the only way a phone is seen.
    #[test]
    fn a_phone_that_does_not_is_seen_through_the_runner() {
        assert_eq!(
            phone_screenshot_route(Some(false)),
            PhoneScreenshotRoute::Runner
        );
    }

    // devicectl could not be asked, or does not list the phone: nothing
    // was learned about capture, and the runner is the route that needs
    // nothing from devicectl.
    #[test]
    fn a_phone_devicectl_cannot_speak_for_is_seen_through_the_runner() {
        assert_eq!(phone_screenshot_route(None), PhoneScreenshotRoute::Runner);
    }
}

#[cfg(test)]
mod dial_platform {
    use super::*;
    use smix_simctl::registry::DeviceKind;

    #[test]
    fn run_device_ref_prefers_explicit_then_pointer_then_none() {
        assert_eq!(
            run_device_ref(Some("emulator-5560"), Some("proj-alias".into())),
            Some("emulator-5560".to_string()),
            "explicit --device wins over the project pointer"
        );
        assert_eq!(
            run_device_ref(None, Some("proj-alias".into())),
            Some("proj-alias".to_string()),
            "no --device falls back to the project pointer"
        );
        assert_eq!(
            run_device_ref(None, None),
            None,
            "neither → None, the old iOS-default behaviour"
        );
    }

    // C3: the same capability has to reach the same driver from every
    // entrance. The CLI act verbs always built a SimctlDriver, so `fill`
    // and `find text:` were 501 on Android while the flow's inputText
    // worked on the same device. dial_platform brings C1's rule — the
    // platform is a property of the device — to the verb entrance.

    #[test]
    fn a_registered_device_decides_by_its_kind() {
        assert_eq!(
            dial_platform(Some(DeviceDial::Registered(DeviceKind::Emulator)), &[]).unwrap(),
            RunPlatform::Android,
            "an emulator names the Android driver"
        );
        assert_eq!(
            dial_platform(Some(DeviceDial::Registered(DeviceKind::Simulator)), &[]).unwrap(),
            RunPlatform::Ios,
            "a simulator names the iOS driver"
        );
        assert_eq!(
            dial_platform(
                Some(DeviceDial::Registered(DeviceKind::PhysicalAndroid)),
                &[]
            )
            .unwrap(),
            RunPlatform::Android,
        );
    }

    /// The same judgement `smix run` makes: a --device the registry does
    /// not know is an error naming the fix, not a silent iOS guess. The
    /// two entrances must not carry two rules.
    /// A device this machine has not registered is driven as the caller
    /// says, the way `smix run --platform` drives it — a consumer's fresh
    /// machine knew none of its emulators, and `wait-for` had no way to say.
    #[test]
    fn a_platform_said_outright_drives_an_unregistered_device() {
        let (port, plat) = runner_dial_target(
            Some(28999),
            Some("emulator-5998"),
            Some(RunPlatform::Android),
        )
        .unwrap();
        assert_eq!(port, 28999);
        assert_eq!(plat, smix_driver::Platform::Android);
    }

    #[test]
    fn an_unregistered_device_refuses_and_names_register() {
        let err = dial_platform(Some(DeviceDial::Unregistered), &[]).unwrap_err();
        assert!(
            err.to_lowercase().contains("register"),
            "the error must name the durable fix: {err}"
        );
    }

    /// The consumer dialed by port (`--port 22088`, no --device); 5560
    /// was registered with `--runner-port 22088`, so the port's holder
    /// classifies it.
    #[test]
    fn a_ports_single_holder_decides_when_no_device() {
        assert_eq!(
            dial_platform(None, &[DeviceKind::Emulator]).unwrap(),
            RunPlatform::Android,
        );
        assert_eq!(
            dial_platform(None, &[DeviceKind::Simulator, DeviceKind::Simulator]).unwrap(),
            RunPlatform::Ios,
            "two holders of the same platform is not a conflict",
        );
    }

    /// A bare port nobody registered keeps the old iOS default. A wrong
    /// guess here ends in a loud 501 from the Android runner, not a
    /// silent mis-drive — so the default is safe to keep.
    #[test]
    fn a_bare_port_keeps_the_ios_default() {
        assert_eq!(dial_platform(None, &[]).unwrap(), RunPlatform::Ios);
    }

    /// Two platforms on one port is a coin toss, so refuse instead.
    #[test]
    fn two_platforms_on_one_port_refuses() {
        let err = dial_platform(None, &[DeviceKind::Emulator, DeviceKind::Simulator]).unwrap_err();
        assert!(
            err.to_lowercase().contains("--device"),
            "the error must name the way out: {err}"
        );
    }
}

#[cfg(test)]
mod device_power {
    use super::*;
    use smix_simctl::registry::DeviceKind;

    // Turning a device on and off was an Apple-only idea here, and an
    // Android emulator therefore had no way to be started *by smix* —
    // so no way to be recorded as started. Every ownership question
    // above this rests on the one fact nobody could write down: who
    // turned this device on. Measured cost over one day: another person
    // driving smix on this machine took a release's emulator out from
    // under it a dozen times, and two release gates picked their device
    // instead of ours. Neither side could tell, because neither side
    // could ask.

    fn kinds(action: &SimAction) -> Vec<DeviceKind> {
        sim_verb_supports(action).expect("this verb acts on a device")
    }

    fn boot() -> SimAction {
        SimAction::Boot {
            device: String::new(),
            cold: false,
        }
    }

    fn shutdown() -> SimAction {
        SimAction::Shutdown {
            device: String::new(),
        }
    }

    #[test]
    fn booting_and_stopping_reach_emulators() {
        for action in [boot(), shutdown()] {
            let k = kinds(&action);
            assert!(
                k.contains(&DeviceKind::Emulator),
                "an emulator cannot be powered by smix, so nothing can record who did: {k:?}"
            );
            assert!(
                k.contains(&DeviceKind::Simulator),
                "the iOS path must survive the widening: {k:?}"
            );
        }
    }

    /// The half that goes quietly wrong if only the first is written.
    /// Widening a set is one edit from widening it too far, and a phone
    /// powered off by a release gate is not recovered by re-running the
    /// gate.
    #[test]
    fn no_physical_device_is_powered_here() {
        for action in [boot(), shutdown()] {
            let k = kinds(&action);
            for forbidden in [DeviceKind::PhysicalIos, DeviceKind::PhysicalAndroid] {
                assert!(
                    !k.contains(&forbidden),
                    "this path claims to reach {forbidden:?} — section 9 #1 does not put \
                     a physical device's power state on it"
                );
            }
        }
    }
}

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

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

    #[test]
    fn a_device_ref_is_classed_by_the_registry_then_by_shape() {
        use smix_simctl::registry::{DeviceKind, RegisteredSim};
        let mut reg = SimRegistry::default();
        reg.insert(
            "phone",
            RegisteredSim {
                device_name: "a phone".into(),
                kind: DeviceKind::PhysicalIos,
                destructive_opt_in: false,
                udid: "00008120-000000000000000E".into(),
                runtime: String::new(),
                device_type: String::new(),
                avd_name: None,
                locale: None,
                runner_port: None,
            },
        );
        // Registered wins over shape: that is the whole ordering.
        assert_eq!(
            classify_device(&reg, "00008120-000000000000000E"),
            DeviceKind::PhysicalIos
        );
        // Unregistered and emulator-shaped: adb names these, so the
        // shape is a fact rather than a heuristic.
        assert_eq!(classify_device(&reg, "emulator-5554"), DeviceKind::Emulator);
        // Unregistered and not emulator-shaped. Falling back to
        // Simulator is a consequence of C15, not a guess: a raw
        // identifier only gets past `resolve_device` when the platform
        // itself claims it, and the emulator case was just handled.
        assert_eq!(classify_device(&reg, UDID), DeviceKind::Simulator);
        // The uppercase spelling is not what adb answers to, so it is
        // not an emulator serial.
        assert_eq!(
            classify_device(&reg, "EMULATOR-5554"),
            DeviceKind::Simulator
        );
    }

    /// A device you can register and drive, you can also load.
    ///
    /// v4.0 made a physical Android device registrable, addressable and
    /// drivable, and left it impossible to put an app on: `Install`
    /// routed to simctl alone, while `smix-adb` had carried the call
    /// that does it the whole time. The device guard refuses the bare
    /// form and names smix as the way through, so the two pointed at
    /// each other — and a consumer moved all eight copies of that guard
    /// aside to get a build onto a phone.
    ///
    /// Shape only: `sim_verb_supports` reads nothing but its argument. A
    /// test that consulted the registry would pass or fail on whatever
    /// this machine happens to have registered, which is how the
    /// classification test went red the day device records moved.
    #[test]
    fn payload_verbs_reach_android() {
        use smix_simctl::registry::DeviceKind::{
            Emulator, PhysicalAndroid, PhysicalIos, Simulator,
        };
        let install = sim_verb_supports(&SimAction::Install {
            device: String::new(),
            app_path: std::path::PathBuf::new(),
        })
        .expect("install takes a device");
        assert!(install.contains(&Emulator), "install: {install:?}");
        assert!(install.contains(&PhysicalAndroid), "install: {install:?}");
        assert!(install.contains(&Simulator), "install: {install:?}");
        // A registered iPhone too, since `DevicectlClient::install` was
        // wired: the CLI refused it for a while afterwards because it
        // kept its own list of where each verb worked, and that list
        // still said what had been true before.
        assert!(
            install.contains(&PhysicalIos),
            "install refuses a registered iPhone and devicectl installs on one: {install:?}"
        );

        let uninstall = sim_verb_supports(&SimAction::Uninstall {
            device: String::new(),
            bundle_id: String::new(),
        })
        .expect("uninstall takes a device");
        for kind in [Simulator, PhysicalIos, Emulator, PhysicalAndroid] {
            assert!(
                uninstall.contains(&kind),
                "uninstall dropped {kind:?}: {uninstall:?}"
            );
        }
    }

    /// The five verbs that arrange or read a handset, and the kinds of
    /// device each one reaches.
    ///
    /// Shape only, for the same reason as the test above: this reads
    /// nothing but its argument.
    #[test]
    fn arranging_verbs_reach_the_kinds_that_have_a_path() {
        use smix_simctl::registry::DeviceKind;
        use smix_simctl::registry::DeviceKind::{
            Emulator, PhysicalAndroid, PhysicalIos, Simulator,
        };

        let android_only: Vec<(&str, Option<Vec<DeviceKind>>)> = vec![
            (
                "wake",
                sim_verb_supports(&SimAction::Wake {
                    device: String::new(),
                }),
            ),
            (
                "stay-awake",
                sim_verb_supports(&SimAction::StayAwake {
                    device: String::new(),
                    state: true,
                }),
            ),
            (
                "frontmost",
                sim_verb_supports(&SimAction::Frontmost {
                    device: String::new(),
                    json: false,
                }),
            ),
            (
                "crashes",
                sim_verb_supports(&SimAction::Crashes {
                    device: String::new(),
                    app: None,
                    json: false,
                }),
            ),
        ];
        for (name, kinds) in android_only {
            let kinds = kinds.unwrap_or_else(|| panic!("{name} takes a device"));
            assert!(kinds.contains(&Emulator), "{name}: {kinds:?}");
            assert!(kinds.contains(&PhysicalAndroid), "{name}: {kinds:?}");
            // Neither simctl nor devicectl has a verb for any of these,
            // and claiming one would attempt a capability that is not
            // there instead of saying so (§9 #1 ③).
            assert!(
                !kinds.contains(&Simulator),
                "{name} claims a simulator: {kinds:?}"
            );
            assert!(
                !kinds.contains(&PhysicalIos),
                "{name} claims a physical iPhone: {kinds:?}"
            );
        }

        // The odd one out: a simulator answers this through
        // `simctl privacy`, and only a physical iPhone refuses.
        let permission = sim_verb_supports(&SimAction::Permission {
            device: String::new(),
            bundle_id: String::new(),
            permission: String::new(),
            action: String::new(),
        })
        .expect("permission takes a device");
        for kind in [Simulator, Emulator, PhysicalAndroid] {
            assert!(permission.contains(&kind), "permission dropped {kind:?}");
        }
        assert!(
            !permission.contains(&PhysicalIos),
            "a device's TCC grants are its owner's: {permission:?}"
        );
    }

    /// Each of the five points at the row of the platform table that
    /// carries its refusal.
    ///
    /// Without this they fall to the generic sentence, which says the
    /// command runs through simctl — false for all five, and the kind of
    /// true-looking wrong answer a caller acts on.
    #[test]
    fn arranging_verbs_take_their_refusal_from_the_table() {
        use smix_sdk::device_control::availability;
        use smix_simctl::registry::DeviceKind::Simulator;

        let pairs = [
            (
                table_action_of(&SimAction::Wake {
                    device: String::new(),
                }),
                "wake",
            ),
            (
                table_action_of(&SimAction::StayAwake {
                    device: String::new(),
                    state: false,
                }),
                "set_stay_awake",
            ),
            (
                table_action_of(&SimAction::Permission {
                    device: String::new(),
                    bundle_id: String::new(),
                    permission: String::new(),
                    action: String::new(),
                }),
                "set_permission",
            ),
            (
                table_action_of(&SimAction::Frontmost {
                    device: String::new(),
                    json: false,
                }),
                "frontmost_app",
            ),
            (
                table_action_of(&SimAction::Crashes {
                    device: String::new(),
                    app: None,
                    json: false,
                }),
                "crash_reports",
            ),
        ];
        for (mapped, expected) in pairs {
            assert_eq!(mapped, Some(expected), "verb does not name its table row");
            // And the row is real: a name the table has never heard of
            // would map cleanly here and produce nothing to print.
            assert!(
                availability(expected, Simulator).is_some(),
                "{expected} is not a row in the platform table"
            );
        }
    }

    /// Every `smix sim` verb, one of each, for the reconciliations below.
    ///
    /// Hand-written and therefore the kind of copy that goes stale — so
    /// the test underneath it checks the list against the command tree
    /// clap builds from the enum itself. A verb that leaves this list
    /// takes its reconciliation with it, silently, which is exactly the
    /// failure the reconciliation exists to catch.
    fn every_sim_action() -> Vec<(&'static str, SimAction)> {
        let d = String::new;
        vec![
            (
                "list",
                SimAction::List {
                    json: false,
                    registered: false,
                },
            ),
            (
                "register",
                SimAction::Register {
                    alias: d(),
                    udid: d(),
                    locale: None,
                    runner_port: None,
                    kind: DeviceKindArg::Simulator,
                    name: None,
                },
            ),
            (
                "resolve",
                SimAction::Resolve {
                    device: d(),
                    json: false,
                },
            ),
            (
                "migrate",
                SimAction::Migrate {
                    dry_run: false,
                    from: Vec::new(),
                },
            ),
            ("unregister", SimAction::Unregister { alias: d() }),
            (
                "allow-destructive",
                SimAction::AllowDestructive { device: d() },
            ),
            (
                "boot",
                SimAction::Boot {
                    device: d(),
                    cold: false,
                },
            ),
            ("shutdown", SimAction::Shutdown { device: d() }),
            ("erase", SimAction::Erase { device: d() }),
            (
                "screenshot",
                SimAction::Screenshot {
                    device: d(),
                    out: std::path::PathBuf::new(),
                    runner_port: None,
                },
            ),
            (
                "launch",
                SimAction::Launch {
                    device: d(),
                    bundle_id: d(),
                    child_env: Vec::new(),
                    launch_args: Vec::new(),
                },
            ),
            (
                "terminate",
                SimAction::Terminate {
                    device: d(),
                    bundle_id: d(),
                },
            ),
            (
                "install",
                SimAction::Install {
                    device: d(),
                    app_path: std::path::PathBuf::new(),
                },
            ),
            (
                "uninstall",
                SimAction::Uninstall {
                    device: d(),
                    bundle_id: d(),
                },
            ),
            (
                "openurl",
                SimAction::Openurl {
                    device: d(),
                    url: d(),
                },
            ),
            (
                "appearance",
                SimAction::Appearance {
                    device: d(),
                    mode: Appearance::Light,
                },
            ),
            ("keychain-reset", SimAction::KeychainReset { device: d() }),
            (
                "locale",
                SimAction::Locale {
                    device: d(),
                    lang: d(),
                    reboot: false,
                },
            ),
            (
                "exec",
                SimAction::Exec {
                    device: d(),
                    verb: d(),
                    args: Vec::new(),
                },
            ),
            (
                "reverse",
                SimAction::Reverse {
                    device: d(),
                    port: 0,
                    to: None,
                    remove: false,
                },
            ),
            ("wake", SimAction::Wake { device: d() }),
            (
                "stay-awake",
                SimAction::StayAwake {
                    device: d(),
                    state: false,
                },
            ),
            (
                "permission",
                SimAction::Permission {
                    device: d(),
                    bundle_id: d(),
                    permission: d(),
                    action: d(),
                },
            ),
            (
                "frontmost",
                SimAction::Frontmost {
                    device: d(),
                    json: false,
                },
            ),
            (
                "crashes",
                SimAction::Crashes {
                    device: d(),
                    app: None,
                    json: false,
                },
            ),
        ]
    }

    /// One verb out of the list above, by the name clap knows it by.
    fn sim_verb(want: &str) -> SimAction {
        every_sim_action()
            .into_iter()
            .find(|(n, _)| *n == want)
            .map(|(_, a)| a)
            .unwrap_or_else(|| panic!("no `smix sim {want}`"))
    }

    /// The kinds of device a verb reaches. Panics for the verbs that
    /// take no device, which the callers below never ask about.
    fn verb_kinds(action: &SimAction) -> Vec<smix_simctl::registry::DeviceKind> {
        sim_verb_supports(action)
            .expect("this verb acts on a device")
            .to_vec()
    }

    /// The list above names every `sim` subcommand and no others.
    ///
    /// Read off the clap tree, which is generated from the enum, so the
    /// two cannot drift: adding a verb and forgetting to list it here
    /// fails, and so does listing one that no longer exists.
    #[test]
    fn the_enumeration_of_sim_verbs_matches_the_command_tree() {
        use clap::CommandFactory;
        use std::collections::BTreeSet;

        let cmd = Cli::command();
        let sim = cmd
            .get_subcommands()
            .find(|c| c.get_name() == "sim")
            .expect("smix sim exists");
        let from_clap: BTreeSet<&str> =
            sim.get_subcommands().map(clap::Command::get_name).collect();
        let listed: BTreeSet<&str> = every_sim_action().iter().map(|(n, _)| *n).collect();
        assert_eq!(
            listed, from_clap,
            "the hand-written verb list and the command tree disagree"
        );
    }

    /// A verb the platform table answers for supports exactly what the
    /// table says works — not a kind more, not a kind less.
    ///
    /// The CLI used to keep its own list of which devices each verb
    /// reached, and by 10.2 the two had drifted in five places, every
    /// one of them the CLI refusing something the backend carries out:
    /// `launch`, `terminate` and `openurl` were simulator-only while
    /// `AndroidDeviceControl` ran all three through `am`; `install`
    /// excluded a physical iPhone whose `DevicectlClient::install` had
    /// been wired since 10.2; `keychain-reset` claimed a phone the table
    /// refuses. A consumer met the first of those and read its refusal
    /// as a report that something had broken.
    ///
    /// Equality rather than containment: a CLI that claimed a kind the
    /// table refuses would reach a backend with nothing behind it.
    #[test]
    fn a_verb_the_table_answers_for_supports_exactly_what_the_table_says() {
        use smix_sdk::device_control::{Availability, availability};
        use smix_simctl::registry::DeviceKind;

        let mut reconciled = 0;
        for (name, action) in every_sim_action() {
            let Some(table_action) = table_action_of(&action) else {
                continue;
            };
            reconciled += 1;
            let claimed = sim_verb_supports(&action)
                .unwrap_or_else(|| panic!("{name} names a table row but takes no device"));
            // Both sides in `DeviceKind::ALL` order, so the comparison
            // is about membership and never about the order a list was
            // written in.
            let supported: Vec<_> = DeviceKind::ALL
                .iter()
                .copied()
                .filter(|k| claimed.contains(k))
                .collect();
            let works: Vec<_> = DeviceKind::ALL
                .iter()
                .copied()
                .filter(|k| availability(table_action, *k) == Some(Availability::Works))
                .collect();
            assert_eq!(
                supported, works,
                "`smix sim {name}` and the platform table disagree about {table_action}"
            );
        }
        // Exact, so that a verb quietly dropping out of the table's
        // answer shows up here rather than in a consumer's refusal.
        assert_eq!(
            reconciled, 13,
            "the number of verbs answered by the platform table changed"
        );
    }

    /// The four the consumer round found refused while the backend
    /// carried them out.
    #[test]
    fn the_verbs_the_backend_carries_out_are_not_refused() {
        use smix_simctl::registry::DeviceKind::{Emulator, PhysicalAndroid, PhysicalIos};

        for verb in ["launch", "openurl"] {
            let kinds = verb_kinds(&sim_verb(verb));
            for kind in [Emulator, PhysicalAndroid, PhysicalIos] {
                assert!(
                    kinds.contains(&kind),
                    "`smix sim {verb}` refuses {kind:?} and the backend does it: {kinds:?}"
                );
            }
        }

        let terminate = verb_kinds(&sim_verb("terminate"));
        for kind in [Emulator, PhysicalAndroid] {
            assert!(
                terminate.contains(&kind),
                "terminate refuses {kind:?} and `am force-stop` does it: {terminate:?}"
            );
        }
        assert!(
            !terminate.contains(&PhysicalIos),
            "devicectl stops by pid and cannot find one from a bundle id: {terminate:?}"
        );

        assert!(
            verb_kinds(&sim_verb("install")).contains(&PhysicalIos),
            "install refuses a registered iPhone, and DevicectlClient::install is wired"
        );
    }

    /// A verb with no row in the platform table refuses in its own
    /// words.
    ///
    /// The sentence these used to share said the command runs through
    /// simctl. True of the six that do; false of every verb that does
    /// not, and it was the false half a consumer read.
    #[test]
    fn a_verb_the_table_cannot_answer_for_refuses_without_claiming_simctl() {
        for verb in ["erase", "appearance", "locale", "exec"] {
            let action = sim_verb(verb);
            assert!(
                table_action_of(&action).is_none(),
                "{verb} has a table row now — reconcile it instead"
            );
            let said = refusal_for(
                &action,
                "emulator-5554",
                smix_simctl::registry::DeviceKind::Emulator,
            );
            assert!(
                !said.contains("runs through simctl"),
                "`smix sim {verb}` still claims simctl: {said}"
            );
            assert!(
                said.contains("iOS Simulator"),
                "`smix sim {verb}` does not say where it does work: {said}"
            );
            assert!(
                !said.contains("Android lifecycle goes through adb"),
                "a refusal carrying advice about another verb entirely: {said}"
            );
        }
    }

    /// `on` and `off`, and nothing else. A value nobody recognises must
    /// not fall through to a default — `stay-awake maybe` turning it off
    /// is the shape this rejects.
    #[test]
    fn stay_awake_takes_on_or_off_and_says_so() {
        assert_eq!(parse_on_off("on"), Ok(true));
        assert_eq!(parse_on_off("OFF"), Ok(false));
        let err = parse_on_off("maybe").expect_err("maybe is not a state");
        assert!(err.contains("on"), "{err}");
        assert!(err.contains("off"), "{err}");
        assert!(err.contains("maybe"), "says what it could not read: {err}");
    }

    #[test]
    fn a_permission_action_is_one_of_three() {
        assert_eq!(parse_permission_action("grant"), Ok("grant".to_string()));
        assert_eq!(
            parse_permission_action(" Revoke "),
            Ok("revoke".to_string())
        );
        let err = parse_permission_action("allow").expect_err("allow is not one of them");
        assert!(
            err.contains("grant") && err.contains("revoke") && err.contains("reset"),
            "{err}"
        );
    }

    #[test]
    fn sim_list_asks_an_emulator_and_a_registered_phone_and_no_other_device() {
        assert!(
            may_ask_release("emulator-5554", false),
            "an emulator is ours to read"
        );
        assert!(
            may_ask_release("R5CT10ABCDE", true),
            "a registered phone was offered to smix"
        );
        assert!(
            !may_ask_release("R5CT10ABCDE", false),
            "an attached phone nobody registered is listed from adb's own line and not addressed (§9#1)"
        );
    }

    #[test]
    fn adb_devices_output_parses_to_serial_state_and_model() {
        let out = "List of devices attached\n\
                   emulator-5554          device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:1\n\
                   R5CT10ABCDE            unauthorized usb:337641472X transport_id:2\n\
                   \n";
        let got = parse_adb_devices(out);
        assert_eq!(
            got,
            vec![
                (
                    "emulator-5554".to_string(),
                    "device".to_string(),
                    "sdk_gphone64_arm64".to_string()
                ),
                (
                    "R5CT10ABCDE".to_string(),
                    "unauthorized".to_string(),
                    String::new()
                ),
            ]
        );
    }

    #[test]
    fn a_literal_slot_is_not_asked_who_it_is() {
        // The alias path is where P1 lives: "where is my device" has to
        // be answered by identity. A caller who typed the port named the
        // port, and refusing their literal because some row mentions it
        // would make `--device emulator-5556` unusable.
        assert!(alias_needs_identity_check("sim-smix-android-01"));
        assert!(alias_needs_identity_check("phone-s22"));
        assert!(!alias_needs_identity_check("emulator-5556"));
        assert!(!alias_needs_identity_check(
            "5D087114-ECB3-443C-8DDB-40EEF9CFB90C"
        ));
    }

    #[test]
    fn adb_knows_answers_from_adbs_own_list() {
        // A serial of a shape nothing answers to. This half runs
        // everywhere, including machines with no adb at all — a missing
        // binary is truthfully "no such device".
        assert!(!adb_knows("NOSUCHSERIAL0001"));

        // The other half needs hardware, so it asserts only when there
        // is some: every serial adb reports as `device` must come back
        // true. Skipping quietly would leave a function that returns
        // `false` for everything looking exactly as healthy as one that
        // works.
        let Ok(out) = std::process::Command::new(&smix_adb::adb_path().0)
            .arg("devices")
            .output()
        else {
            return;
        };
        if !out.status.success() {
            return;
        }
        let listed: Vec<String> = String::from_utf8_lossy(&out.stdout)
            .lines()
            .filter_map(|l| l.split_once('\t'))
            .filter(|(_, state)| state.trim() == "device")
            .map(|(serial, _)| serial.to_string())
            .collect();
        for serial in listed {
            assert!(
                adb_knows(&serial),
                "adb lists {serial} as a device but adb_knows says no"
            );
        }
    }

    // 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_refuses_what_it_cannot_do() {
        assert!(reject_ios_only_up_flags(false, false).is_ok());

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

    /// `--bundle` means the same on both platforms: the app `runner up`
    /// leaves in front. On Android it used to be refused as iOS-only, so
    /// a caller had nothing to say "and bring this app back" with.
    #[test]
    fn android_runner_up_takes_the_app_under_test() {
        let cli = Cli::try_parse_from([
            "smix",
            "runner",
            "up",
            "emulator-5554",
            "--platform",
            "android",
            "--bundle",
            "dev.smix.fixture",
            "--no-launch",
        ])
        .expect("--bundle and --no-launch parse for Android runner up");
        let Cmd::Runner {
            action: RunnerAction::Up {
                bundle, no_launch, ..
            },
        } = cli.cmd
        else {
            panic!("parsed as something other than runner up");
        };
        assert_eq!(bundle.as_deref(), Some("dev.smix.fixture"));
        assert!(no_launch);
    }

    #[test]
    fn every_dropped_flag_is_named_at_once() {
        // One flag per run would make a user re-run twice to discover two
        // problems.
        let err = reject_ios_only_up_flags(true, true).expect_err("both are iOS-only");
        for flag in ["--runner-project", "--supervise"] {
            assert!(err.contains(flag), "{flag} unnamed in: {err}");
        }
        assert!(err.contains("they are"), "plural form expected in: {err}");
    }
    /// The command tree is one clap can actually build.
    ///
    /// clap checks a long list of internal contradictions only when a
    /// command is built, which happens on the first real invocation —
    /// so a malformed argument is not a compile error and not a failing
    /// unit test, it is a panic in front of whoever ran `smix` next. A
    /// `bool` positional shipped exactly that way during 10.2: clap
    /// gives `bool` the flag treatment, a positional flag takes no
    /// value, and *every* subcommand panicked, not just the new one.
    ///
    /// `debug_assert()` is clap's own name for these checks. It costs a
    /// millisecond and covers every argument anyone adds after this.
    #[test]
    fn the_command_tree_is_one_clap_can_build() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }

    /// `--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"
        );
    }
}

#[cfg(test)]
mod resolution_shape_tests {
    use super::*;
    use smix_simctl::registry::{DeviceKind, RegisteredSim, Resolved, Source};

    fn emulator() -> RegisteredSim {
        RegisteredSim {
            device_name: "sim-smix-android-01".into(),
            kind: DeviceKind::Emulator,
            destructive_opt_in: false,
            udid: "emulator-5554".into(),
            runtime: String::new(),
            device_type: String::new(),
            avd_name: Some("sim-smix-android-01".into()),
            locale: None,
            runner_port: None,
        }
    }

    /// The keys a harness reads instead of a registry file, with the book
    /// that answered — the thing a consumer lost an hour for want of.
    #[test]
    fn resolve_json_names_the_book_and_the_device() {
        let path = std::path::PathBuf::from("machine-dir/devices");
        let r = Resolved {
            id: "emulator-5556".into(),
            alias: "phone".into(),
            source: Source::Machine(path.clone()),
        };
        let sim = emulator();
        let v = resolution_json("phone", "emulator-5556", Some(&r), Some(&sim), &r.source);
        assert_eq!(v["ref"], "phone");
        assert_eq!(v["id"], "emulator-5556");
        assert_eq!(v["alias"], "phone");
        assert_eq!(v["source"]["kind"], "machine");
        assert_eq!(v["source"]["path"], "machine-dir/devices");
        assert_eq!(v["deviceKind"], "emulator");
        assert_eq!(v["avd"], "sim-smix-android-01");
    }

    #[test]
    fn the_stderr_line_says_which_book_answered() {
        let sim = emulator();
        let line = resolution_line(
            "phone",
            Some(&sim),
            &Source::Checkout("a-checkout/.smix/sims.json".into()),
        );
        assert!(
            line.contains("a-checkout/.smix/sims.json") && line.contains("legacy book"),
            "{line}"
        );
        assert!(line.contains("AVD `sim-smix-android-01`"), "{line}");
        let literal = resolution_line("emulator-5554", None, &Source::Literal);
        assert!(literal.contains("no registry was consulted"), "{literal}");
    }
}