smix-cli 0.2.5

smix — AI-native iOS Simulator automation CLI (cement). v3.1 c12 MVP: doctor + sim subcommands. record/run/repl/watch land in c13/c-final.
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
//! smix — AI-native iOS Simulator automation CLI (cement, binary entry).
//!
//! Ported from now-retired TS source: `src/cli/index.ts` + `src/cli/commands/{doctor,sim}.ts`
//! (MVP subset). v3.1 c12.
//!
//! v5.0: `smix sim` is the sole device-control surface — raw `simctl`
//! retires from workflows. Every device argument accepts an explicit
//! UDID or an alias recorded in `.smix/sims.json` (resolved
//! deterministically by `smix_simctl::registry`; never against the live
//! simulator set). Unwrapped long-tail subcommands go through
//! `smix sim exec`, which keeps simctl's original argument shape and
//! injects the resolved UDID.

mod act;
mod capsule;
mod down;
mod runner;
mod script;
mod selftest_multi;
mod selftest_single;

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

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

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

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

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

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

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

#[derive(Subcommand, Debug)]
enum Cmd {
    /// Probe environment health: xcrun simctl availability + sim listing.
    Doctor,
    /// Manage simulators. `<DEVICE>` = explicit UDID, or an alias / deviceName
    /// recorded in .smix/sims.json (env SMIX_SIMS_JSON overrides discovery).
    Sim {
        #[command(subcommand)]
        action: SimAction,
    },
    /// Manage the XCUITest runner session (host-side xcodebuild handle).
    Runner {
        #[command(subcommand)]
        action: RunnerAction,
    },
    /// Tear down every smix-owned residual process and recycle registered
    /// sims (per-UDID; never touches sims outside .smix/sims.json).
    Down,
    /// v5.1 c4 — Cap3 硬胶囊 / 软胶囊 端到端 wire(无头 boot + capture +
    /// runner --record)。哨兵默认拒带窗;`--soft` 显式接受降级。
    Capsule {
        #[command(subcommand)]
        action: CapsuleAction,
    },
    /// v5.1 c7 — selftest 跑表面。
    Selftest {
        #[command(subcommand)]
        action: SelftestAction,
    },
    /// v5.8 c4 — host-resolve + dispatch tap on the running runner. Reads
    /// `SMIX_RUNNER_PORT` env (default 22087). Selector shorthand:
    /// `id:<a11y-id>` / `text:<plain>` / `label:<acc-label>` / `role:<role>`.
    Tap {
        /// Selector in `<kind>:<value>` shorthand.
        selector: String,
        /// Runner port override (defaults to SMIX_RUNNER_PORT env or 22087).
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.8 c4 — boolean existence probe (POST /find). Prints `exists=<bool>`.
    /// Same selector shorthand as `smix tap`.
    Find {
        selector: String,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.8 c4 — poll `/find` every 250ms until the selector resolves or
    /// `--timeout` expires. Mirrors SDK `App::wait_for` semantics; useful in
    /// shell loops driving the runner from outside Rust.
    WaitFor {
        selector: String,
        /// Timeout in seconds (default 5).
        #[arg(long, default_value_t = 5)]
        timeout: u64,
        #[arg(long)]
        port: Option<u16>,
    },
    /// Type text into the matched field. Equivalent to the flow yaml
    /// `inputText:` verb. Selector shorthand same as `smix tap`.
    Fill {
        selector: String,
        #[arg(long)]
        text: String,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c1 — issue a hardware / IME key press. Key shorthand: `return`
    /// (alias `enter`), `delete` (alias `backspace`), `tab`, `space`,
    /// `escape` / `esc`, `arrowUp` / `up`, `arrowDown` / `down`,
    /// `arrowLeft` / `left`, `arrowRight` / `right`, `home`, `lock`,
    /// `volumeUp` / `volume-up`, `volumeDown` / `volume-down`.
    PressKey {
        /// KeyName shorthand (see help text).
        key: String,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c1 — scroll until the selector becomes visible. Direction:
    /// `up` / `down` / `left` / `right`.
    Scroll {
        selector: String,
        #[arg(long)]
        direction: String,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c1 — dismiss the soft keyboard if visible.
    HideKeyboard {
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c3 — print the runner's current a11y tree. `--json` emits
    /// wire JSON; default emits an indented text outline.
    Tree {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c3 — print the runner's high-level ScreenDescription
    /// (title / interactive elements / status bar / etc.).
    Describe {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
    },
    /// v5.9 c3 — print the runner's current SpringBoard system-popup list.
    SystemPopups {
        #[arg(long)]
        json: bool,
        #[arg(long)]
        port: Option<u16>,
    },
    /// Sequential script driver. Reads a yaml file describing ordered
    /// smix subcommand invocations (see `crates/smix-cli/src/script.rs`
    /// for the schema). Lightweight shell-friendly alternative to
    /// chaining `smix tap … && smix fill …`. smix-native dialect — NOT
    /// the maestro yaml flow format (for that, use `smix run`).
    RunScript {
        /// Path to the script yaml file.
        path: PathBuf,
        #[arg(long)]
        port: Option<u16>,
    },
    /// 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 sim-smix-02 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 {
        /// v0.2.5 §Phase A — path(s) to flow yaml file(s). One or more
        /// files can be listed; 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. See insight-roadmap.md §D.
        #[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>,
        /// Bundle id / Android package for `App::foreground` (skipped
        /// with --no-launch). Overridden by `appId:` / `app:` in the
        /// yaml header.
        #[arg(long)]
        bundle_id: Option<String>,
        /// Runner port. iOS default 22087, Android 28080 by convention.
        #[arg(long, env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
        /// Skip the initial foreground call. Use when the app is
        /// already on screen (e.g. launched via `smix sim launch` or
        /// `adb shell am start`). Saves 3-5s cold-start latency.
        #[arg(long, default_value_t = false)]
        no_launch: bool,
        /// Target platform.
        #[arg(long, value_enum, env = "SMIX_PLATFORM", default_value_t = RunPlatform::Ios)]
        platform: RunPlatform,
        /// Path to `smix-apps.yaml` cross-platform app resolver config.
        /// When the yaml header uses `app: <logicalKey>`, this resolver
        /// maps to platform-specific bundle id / Android package.
        #[arg(long, env = "SMIX_APPS_CONFIG")]
        apps_config: Option<PathBuf>,
        /// gol-611 §2 (v0.2.0) — env var for yaml `${NAME}`
        /// interpolation. Repeatable: `--env A=1 --env B=2`. Wins over
        /// inherited process env (which is the fallback). Match 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)>,
        /// gol-611 §2 (v0.2.0) — 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>,
        /// gol-611 §2 (v0.2.0) — verbose logging (debug-level tracing
        /// on adapter/sdk/driver crates).
        #[arg(long, default_value_t = false)]
        verbose: bool,
        /// gol-611 §3 (v0.2.0) — 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,
        /// gol-611-v0.2.1 §Phase C (v0.2.1) — 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. See docs/ai-guide/gol-611-v0.2.1-response.md.
        #[arg(long, default_value_t = false)]
        activate: bool,
        /// v0.2.5 §Phase A A4 — 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. See insight-roadmap.md §D.
        #[arg(long, default_value_t = false)]
        fail_fast: bool,
    },
    /// v0.2.5 §Phase B — 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 preserved verbatim
    /// with a WARN line to stderr. See insight-roadmap.md §E.
    ///
    /// 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 in the input are lost (yaml codemod limitation).
    Migrate {
        /// One or more input yaml paths. When empty, reads from stdin.
        #[arg(num_args = 0..)]
        paths: Vec<PathBuf>,
        /// v0.2.5 §Phase B B4 — 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,
    },
}

/// gol-611 §3 (v0.2.0) — output-format enum mirroring
/// [`smix_adapter_maestro::OutputFormat`].
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum RunOutputFormat {
    Human,
    Json,
}

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

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

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

#[derive(Subcommand, Debug)]
enum SelftestAction {
    /// v5.1 c8 — single-sim 跑 selftest scenario(等效 `cargo run --example
    /// selftest_full_surface --`,但走 smix CLI 入口)。前置:`smix capsule up
    /// <DEVICE>` 起好 runner;或裸 `smix runner up <DEVICE>`(裸跑模式下
    /// `capsule_reconcile` 字段留空)。
    Single {
        /// UDID 或 .smix/sims.json 里的 alias / deviceName。
        device: String,
    },
    /// v5.1 c7 — multi-sim 并发跑 selftest scenario,各自独立 result.json +
    /// 聚合 summary.json。前置:每个 UDID 用 `smix capsule up <UDID>
    /// --runner-port <PORT>` 起好。c8+ 集成 capsule up/down 自调度。
    Multi {
        /// 一组 `<UDID>:<PORT>` 元组,N ≥ 1。
        #[arg(required = true)]
        targets: Vec<String>,
    },
}

#[derive(Subcommand, Debug)]
enum CapsuleAction {
    /// Bring up sim + start capture + start runner in record mode.
    Up {
        device: String,
        /// Accept带窗降级到软胶囊(Simulator.app 在场时必带,否则被哨兵拒)。
        #[arg(long)]
        soft: bool,
        /// v5.6 c2 — 跳过 `/api/capture/start` 调用 (跳过 smix-server 端的
        /// /live HLS capture pipeline)。selftest gate / scenario 内嵌
        /// simctl io recordVideo (v2_recording_basic seg) 需要此 flag 避开
        /// "Host recording is already in progress" EBUSY 16 互斥 (v5.6 c1
        /// root cause)。EventRecorder swizzle (capsule_reconcile 用的)
        /// 不受影响,仍 enabled。
        #[arg(long)]
        no_capture: bool,
    },
    /// Reverse teardown: runner down + capture stop + sim shutdown.
    Down { device: String },
}

#[derive(Subcommand, Debug)]
enum RunnerAction {
    /// Start the runner on a device; blocks until /health answers.
    Up {
        device: String,
        /// Bundle id the runner binds its XCUIApplication to (default:
        /// the runner's built-in default, com.apple.Preferences).
        #[arg(long)]
        bundle: Option<String>,
        /// Explicit path to `SmixRunner.xcodeproj`. Wins over
        /// `$SMIX_RUNNER_PROJECT` env and the install-shipped default
        /// at `~/.local/share/smix/runner/`. See resolve_runner_project
        /// cascade in runner.rs. gol-611 §1 fix.
        #[arg(long = "runner-project", env = "SMIX_RUNNER_PROJECT")]
        runner_project: Option<PathBuf>,
        /// v0.2.5 §Phase C — bind the runner to an explicit port.
        /// Priority (high → low): this flag → `.smix/sims.json`
        /// `runnerPort` field → `SMIX_RUNNER_PORT` env → 22087 default.
        /// Two sims with distinct `runnerPort` in sims.json can run
        /// their own runner concurrently without collision. See
        /// insight-roadmap.md §I.
        #[arg(long = "runner-port", env = "SMIX_RUNNER_PORT")]
        runner_port: Option<u16>,
    },
    /// Stop the runner (SIGINT-first to avoid the crash-report dialog).
    Down,
}

#[derive(Subcommand, Debug)]
enum SimAction {
    /// List available simulators (Rust port: `xcrun simctl list devices -j`).
    List {
        /// Output as JSON instead of human-readable table.
        #[arg(long)]
        json: bool,
    },
    /// Print the UDID a device ref resolves to.
    Resolve { device: String },
    /// Boot a simulator.
    Boot { device: String },
    /// Shutdown a simulator.
    Shutdown { device: String },
    /// Erase a simulator's data.
    Erase { device: String },
    /// Take a screenshot (PNG). Pass `-` to write raw PNG to stdout.
    Screenshot { device: String, out: PathBuf },
    /// Launch an app by bundle id; prints the pid. Accepts repeatable
    /// `--child-env KEY=VAL` flags to inject `SIMCTL_CHILD_KEY=VAL` envp
    /// onto the simctl process — the launched app reads it back via
    /// `ProcessInfo().environment["KEY"]`. Used to prelaunch an app
    /// before any `openLink` so iOS treats the URL as in-app routing
    /// (sidesteps the SpringBoard "Open in '`<App>`'?" dialog;
    /// insight gol-611 §4).
    Launch {
        device: String,
        bundle_id: String,
        /// v6.8 c2 — `--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)>,
        /// v6.9 c2 — process-level launch arguments forwarded after a
        /// `--` separator to `xcrun simctl launch ... -- <args>`. Mirrors
        /// maestro yaml `launchApp.arguments`. Conventionally an
        /// alternating `-key value` shape, but treated as opaque argv.
        #[arg(last = true)]
        launch_args: Vec<String>,
    },
    /// Terminate an app by bundle id.
    Terminate { device: String, bundle_id: String },
    /// Install an .app bundle.
    Install { device: String, app_path: PathBuf },
    /// Uninstall an app by bundle id.
    Uninstall { device: String, bundle_id: String },
    /// Open a URL on the simulator.
    Openurl { device: String, url: String },
    /// Set simulator UI appearance (light / dark).
    Appearance {
        device: String,
        #[arg(value_parser = parse_appearance)]
        mode: Appearance,
    },
    /// Reset keychain on a simulator.
    KeychainReset { device: String },
    /// gol-611 §5 (v0.2.0) — set the sim's locale (`AppleLanguages` +
    /// `AppleLocale` NSGlobalDomain). By default writes the values but
    /// does NOT reboot; running apps cache locale at process-start so
    /// they'll continue in the old locale until relaunched. Pass
    /// `--reboot` to have smix shut the sim down and boot it back up
    /// so the next app launch picks up the new locale cleanly.
    ///
    /// Note: `.smix/sims.json` `locale:` field is applied at *next
    /// sim boot* (by `smix runner up` / `smix sim boot`); this command
    /// covers the "sim is already booted, want to change locale now"
    /// gap.
    Locale {
        device: String,
        /// BCP-47 tag (e.g. `en`, `en-US`, `ja`, `zh-Hans`).
        lang: String,
        /// Shut the sim down and boot it back up after writing the
        /// locale, so the change is visible to apps launched next.
        #[arg(long)]
        reboot: bool,
    },
    /// Passthrough for simctl subcommands smix has not wrapped yet:
    /// `smix sim exec <DEVICE> <VERB> [ARGS...]` runs
    /// `xcrun simctl <VERB> <UDID> [ARGS...]` with simctl's original
    /// argument shape. If any arg is the literal `{udid}`, the resolved
    /// UDID substitutes there instead of being injected after the verb.
    Exec {
        device: String,
        verb: String,
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
}

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

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

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

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

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

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

async fn run(cli: Cli) -> Result<ExitCode, CliError> {
    let simctl = SimctlClient::new();
    match cli.cmd {
        Cmd::Doctor => cmd_doctor(&simctl).await?,
        Cmd::Sim { action } => match action {
            SimAction::List { json } => cmd_sim_list(&simctl, json).await?,
            SimAction::Resolve { device } => {
                println!("{}", resolve_device(&device)?);
            }
            SimAction::Boot { device } => {
                let udid = resolve_device(&device)?;
                simctl.boot(&udid).await?;
                println!("booted: {udid}");
                // v6.10 c2 — 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. Closes
                // insight gol-611 §3 (zh-Hans default vs English yaml).
                if let Some(spec) = lookup_registered(&device)
                    && let Some(desired) = spec.locale.as_ref()
                {
                    let current = simctl.current_locale(&udid).await.ok().flatten();
                    if current.as_deref() == Some(desired.as_str()) {
                        println!("locale: {desired} ok");
                    } else {
                        eprintln!(
                            "locale: enforcing {desired} (current {})",
                            current.as_deref().unwrap_or("<unset>")
                        );
                        simctl.set_locale(&udid, desired).await?;
                        // Defaults apply at process start — must reboot.
                        simctl.shutdown(&udid).await?;
                        simctl
                            .boot_and_wait(&udid, std::time::Duration::from_secs(60))
                            .await?;
                        println!("locale: {desired} enforced + sim re-booted");
                    }
                }
            }
            SimAction::Shutdown { device } => {
                let udid = resolve_device(&device)?;
                simctl.shutdown(&udid).await?;
                println!("shutdown: {udid}");
            }
            SimAction::Erase { device } => {
                let udid = resolve_device(&device)?;
                simctl.erase(&udid).await?;
                println!("erased: {udid}");
            }
            SimAction::Screenshot { device, out } => {
                let udid = resolve_device(&device)?;
                let png = simctl.screenshot(&udid).await?;
                if out.as_os_str() == "-" {
                    use std::io::Write;
                    std::io::stdout()
                        .write_all(&png)
                        .map_err(|e| CliError::Other(format!("write stdout: {e}")))?;
                } else {
                    std::fs::write(&out, &png)
                        .map_err(|e| CliError::Other(format!("write {}: {e}", out.display())))?;
                    println!(
                        "screenshot: {udid}{} ({} bytes)",
                        out.display(),
                        png.len()
                    );
                }
            }
            SimAction::Launch {
                device,
                bundle_id,
                child_env,
                launch_args,
            } => {
                let udid = resolve_device(&device)?;
                let pairs: Vec<(&str, &str)> = child_env
                    .iter()
                    .map(|(k, v)| (k.as_str(), v.as_str()))
                    .collect();
                let LaunchResult { pid } = simctl
                    .launch_with_args_and_env(&udid, &bundle_id, &launch_args, &pairs)
                    .await?;
                println!("launched: {bundle_id} on {udid} (pid {pid})");
            }
            SimAction::Terminate { device, bundle_id } => {
                let udid = resolve_device(&device)?;
                simctl.terminate(&udid, &bundle_id).await?;
                println!("terminated: {bundle_id} on {udid}");
            }
            SimAction::Install { device, app_path } => {
                let udid = resolve_device(&device)?;
                simctl
                    .install(&udid, &app_path.display().to_string())
                    .await?;
                println!("installed: {} on {udid}", app_path.display());
            }
            SimAction::Uninstall { device, bundle_id } => {
                let udid = resolve_device(&device)?;
                simctl.uninstall(&udid, &bundle_id).await?;
                println!("uninstalled: {bundle_id} on {udid}");
            }
            SimAction::Openurl { device, url } => {
                let udid = resolve_device(&device)?;
                simctl.open_url(&udid, &url).await?;
                println!("opened: {url} on {udid}");
            }
            SimAction::Appearance { device, mode } => {
                let udid = resolve_device(&device)?;
                simctl.set_appearance(&udid, mode).await?;
                println!("appearance: {udid}{}", mode.as_str());
            }
            SimAction::KeychainReset { device } => {
                let udid = resolve_device(&device)?;
                simctl.keychain_reset(&udid).await?;
                println!("keychain reset: {udid}");
            }
            SimAction::Locale {
                device,
                lang,
                reboot,
            } => {
                let udid = resolve_device(&device)?;
                // Read current locale first — no-op if already desired.
                let current = simctl.current_locale(&udid).await.ok().flatten();
                if current.as_deref() == Some(lang.as_str()) {
                    println!("locale already: {lang}");
                    return Ok(ExitCode::SUCCESS);
                }
                simctl.set_locale(&udid, &lang).await?;
                if reboot {
                    println!("locale: written {lang} — rebooting sim to apply");
                    simctl.shutdown(&udid).await?;
                    simctl.boot(&udid).await?;
                    println!("locale: {lang} enforced (sim rebooted)");
                } else {
                    println!(
                        "locale: written {lang}\n\
                         note: running apps cache locale at process-start — \
                         restart the target app, or re-run with `--reboot` to \
                         cycle the sim so subsequent launches see the new locale."
                    );
                }
            }
            SimAction::Exec { device, verb, args } => {
                return cmd_sim_exec(&device, &verb, &args).await;
            }
        },
        Cmd::Runner { action } => {
            let root = smix_workspace_root()?;
            match action {
                RunnerAction::Up {
                    device,
                    bundle,
                    runner_project,
                    runner_port: port_flag,
                } => {
                    // v0.2.5 §Phase C — port priority chain:
                    //   1. `--runner-port` flag / SMIX_RUNNER_PORT env
                    //   2. `.smix/sims.json` `runnerPort` field for this alias
                    //   3. 22087 default (CLI convention)
                    let sims_port = lookup_registered(&device)
                        .and_then(|s| s.runner_port);
                    let port = port_flag.or(sims_port).unwrap_or(22087);
                    let udid = resolve_device(&device)?;
                    // 裸 `smix runner up` 默认 record_enabled=false;Cap3 走
                    // capsule::up,会再设置 true 走 TEST_RUNNER_SMIX_RECORD_ENABLED=1。
                    runner::up(
                        &root,
                        &udid,
                        port,
                        bundle.as_deref(),
                        false,
                        runner_project.as_deref(),
                    )
                    .map_err(CliError::Other)?;
                }
                RunnerAction::Down => {
                    let port = runner_port();
                    runner::down(&root, port).map_err(CliError::Other)?;
                }
            }
        }
        Cmd::Down => {
            let root = smix_workspace_root()?;
            down::run(&root, runner_port())
                .await
                .map_err(CliError::Other)?;
        }
        Cmd::Selftest { action } => match action {
            SelftestAction::Single { device } => {
                let udid = resolve_device(&device)?;
                let port = runner_port();
                return Ok(selftest_single::run(udid, port).await);
            }
            SelftestAction::Multi { targets } => {
                return Ok(selftest_multi::run(targets).await);
            }
        },
        Cmd::Capsule { action } => {
            let root = smix_workspace_root()?;
            let port = runner_port();
            let capture_endpoint = std::env::var("SMIX_CAPTURE_ENDPOINT")
                .unwrap_or_else(|_| "http://127.0.0.1:8787".to_string());
            match action {
                CapsuleAction::Up {
                    device,
                    soft,
                    no_capture,
                } => {
                    let udid = resolve_device(&device)?;
                    capsule::up(capsule::UpOptions {
                        root: &root,
                        udid: &udid,
                        runner_port: port,
                        capture_endpoint: &capture_endpoint,
                        bundle: Some("dev.smix.SelftestFixture"),
                        soft,
                        no_capture,
                    })
                    .await
                    .map_err(CliError::Other)?;
                }
                CapsuleAction::Down { device } => {
                    let udid = resolve_device(&device)?;
                    capsule::down(&root, &udid).await.map_err(CliError::Other)?;
                }
            }
        }
        Cmd::Tap { selector, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_tap(selector, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Find { selector, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_find(selector, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::WaitFor {
            selector,
            timeout,
            port,
        } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_wait_for(selector, timeout, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Fill {
            selector,
            text,
            port,
        } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_fill(selector, text, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::PressKey { key, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_press_key(key, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Scroll {
            selector,
            direction,
            port,
        } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_scroll(selector, direction, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::HideKeyboard { port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_hide_keyboard(p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Tree { json, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_tree(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Describe { json, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_describe(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::SystemPopups { json, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            act::cmd_system_popups(json, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::RunScript { path, port } => {
            let p = port.unwrap_or_else(act::runner_port_from_env);
            script::cmd_run_script(&path, p)
                .await
                .map_err(|e| CliError::Other(e.to_string()))?;
        }
        Cmd::Run {
            flows,
            device,
            bundle_id,
            runner_port,
            no_launch,
            platform,
            apps_config,
            env,
            debug_output,
            verbose,
            format,
            activate,
            fail_fast,
        } => {
            // gol-611 §2 (v0.2.0) — verbose flag sets SMIX_LOG=debug
            // for this process only. tracing_subscriber (initialized
            // in whichever binary set it up) will pick it up.
            if verbose && std::env::var_os("SMIX_LOG").is_none() {
                // SAFETY: process is single-threaded here (before any
                // adapter/sdk async setup). setting env is safe.
                unsafe { std::env::set_var("SMIX_LOG", "debug") };
            }
            // Resolve device alias if registry has it; else pass raw.
            let udid = device
                .as_deref()
                .map(|d| resolve_device(d).unwrap_or_else(|_| d.to_string()));
            let bundle = bundle_id.unwrap_or_else(|| "com.focusai.app.mobile".to_string());
            let port = runner_port.unwrap_or(22087);
            let plat = platform.to_flow();
            let out_fmt = format.to_adapter();

            // v0.2.5 §Phase A — 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() {
                // v0.2.5 A2 — per-flow debug-output subdir when running
                // multiple flows. Single-flow batches keep the raw dir
                // for v0.2.0 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()
                    );
                }
                let exit = smix_adapter_maestro::run_flow(smix_adapter_maestro::FlowArgs {
                    flow: flow_path.clone(),
                    udid: udid.clone(),
                    bundle_id: bundle.clone(),
                    runner_port: port,
                    no_launch,
                    platform: plat,
                    apps_config: apps_config.clone(),
                    env_vars: env.clone(),
                    debug_output: per_flow_debug,
                    verbose,
                    format: out_fmt,
                    auto_activate: activate,
                })
                .await;
                // Extract per-flow exit code. ExitCode's numeric surface
                // isn't public; use Debug repr as a stable extraction path
                // (the Rust nightly `to_i32` isn't stable). We already own
                // the u8 via the adapter API — see ExitCode::from(u8).
                let code = exit_code_to_u8(exit);
                worst_exit = worst_exit.max(code);
                if fail_fast && code != 0 {
                    eprintln!(
                        "smix run: --fail-fast — aborting batch on first failure (exit={code})"
                    );
                    break;
                }
            }
            return Ok(ExitCode::from(worst_exit));
        }
        Cmd::Migrate { paths, in_place } => {
            return cmd_migrate(paths, in_place).await;
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// v0.2.5 §Phase B — 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>");
                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;
        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());
                    if in_place {
                        // v0.2.5 B4 — 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;
                        }
                        if paths.len() > 1 {
                            eprintln!(
                                "smix migrate: rewrote {} ({} renames)",
                                path.display(),
                                report.renamed.len()
                            );
                        }
                    } else {
                        print!("{out}");
                        std::io::stdout().flush().ok();
                    }
                }
                Err(e) => {
                    eprintln!("smix migrate: {}: {e}", path.display());
                    worst = worst.max(2);
                }
            }
        }
        Ok(ExitCode::from(worst))
    }
}

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

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

/// v0.2.5 §Phase A — 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.
fn exit_code_to_u8(code: std::process::ExitCode) -> u8 {
    let dbg = format!("{code:?}");
    // e.g. "ExitCode(unix_exit_status(3))"
    dbg.rsplit_once('(')
        .and_then(|(_, tail)| tail.trim_end_matches("))").parse::<u8>().ok())
        .unwrap_or(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}")))?;
    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).
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)?;
    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}")))
}

async fn cmd_doctor(simctl: &SimctlClient) -> Result<(), CliError> {
    println!("smix doctor");
    println!("============");

    // 1. xcrun simctl reachable + runtimes listable.
    let runtimes = simctl.list_runtimes().await.map_err(|e| {
        CliError::Other(format!(
            "xcrun simctl unavailable — check Xcode command-line tools install: {e}"
        ))
    })?;
    let avail = runtimes.iter().filter(|r| r.is_available).count();
    println!(
        "✓ xcrun simctl reachable; {} runtimes detected ({} available)",
        runtimes.len(),
        avail
    );

    // 2. Device inventory.
    let devices = simctl.list_devices().await?;
    let avail_dev = devices.iter().filter(|d| d.is_available).count();
    let booted = devices.iter().filter(|d| d.state == "Booted").count();
    println!(
        "{} devices total ({} available, {} booted)",
        devices.len(),
        avail_dev,
        booted
    );

    // 3. iOS-only enforcement reminder (CLAUDE.md §9 #1).
    println!("ℹ smix supports iOS Simulator only — real-device automation is");
    println!("  explicitly out of scope per CLAUDE.md §9.");

    Ok(())
}

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

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

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

impl From<SimctlError> for CliError {
    fn from(e: SimctlError) -> 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 {}

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

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

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

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

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

    // v6.8 c2 — `--child-env KEY=VAL` repeatable flag on `sim launch`
    // composes `SIMCTL_CHILD_*` envp at dispatch time. Insight gol-611 §4
    // prelaunch pattern.
    #[test]
    fn sim_launch_parses_repeated_child_env_flags() {
        let cli = Cli::try_parse_from([
            "smix",
            "sim",
            "launch",
            "02",
            "com.example.app",
            "--child-env",
            "INSIGHT_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![
                (
                    "INSIGHT_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());
    }

    // v6.9 c2 — 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", "sim-smix-02"],
            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}"));
        }
    }
}