smix-sdk 1.0.6

smix-sdk — user-facing public surface for the smix Rust library. App + ergonomic selector helpers + matchers. Wraps SimctlDriver + SimctlClient + HttpRunnerClient.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
//! smix-sdk — user-facing public surface for the smix Rust library.
//!
//! Wraps [`SimctlDriver`] + [`SimctlClient`] + [`HttpRunnerClient`] with
//! an ergonomic Rust API.
//!
//! ```no_run
//! use smix_sdk::{App, text};
//! use std::time::Duration;
//!
//! # async fn demo() -> Result<(), smix_sdk::ExpectationFailure> {
//! let app = App::connect_to_runner(22087).await?;
//! app.launch("com.example.app").await?;
//! app.wait_for(&text("Login"), Duration::from_secs(5)).await?;
//! app.tap(&text("Login")).await?;
//! app.fill(&text("Email"), "user@example.com").await?;
//! app.press_key(smix_sdk::KeyName::Return).await?;
//! # Ok(())
//! # }
//! ```

#![doc(html_root_url = "https://docs.smix.dev/smix-sdk")]

/// Visual regression perceptual hash (dhash 64-bit). Crate-internal:
/// `compute_dhash` + `hamming_distance` back the public
/// `App::assert_screenshot`, not part of the SDK surface.
pub(crate) mod screenshot_hash;

pub mod issued_ledger;
pub use issued_ledger::{IssuedAction, IssuedKind, IssuedLedger};

// DeviceControl trait + cross-platform Permission enum + iOS impl.
// Two-trait architecture pair with smix-driver::Driver.
pub mod device_control;
pub mod ios_device;
pub use device_control::{DeviceControl, Permission};
pub use ios_device::IosDeviceControl;

// Android DeviceControl impl backed by smix-adb.
pub mod android_device;
pub use android_device::AndroidDeviceControl;

pub mod capsule;
pub use capsule::{
    CapsuleReconciliation, DEFAULT_RECONCILE_WINDOW_MS, FOCUS_CHANGE_RAW_CODE, reconcile,
};

use std::time::Duration;

/// Unix epoch in milliseconds — used by the issued-action ledger timestamps.
fn now_ms() -> f64 {
    chrono::Utc::now().timestamp_millis() as f64
}

// -- re-exports for downstream user convenience ------------------------

pub use smix_driver::{
    HttpRunnerClient, IncludeScope, OcrFrame, RunnerScrollSelector, RunnerTransportError,
    SimctlDriver, SystemPopup, TapMode,
};
pub use smix_error::{
    ExpectationFailure, FailureCode, FailureInit, build_suggestions, edit_distance, similarity,
};
pub use smix_input::{KeyName, SwipeDirection};
pub use smix_screen::{
    A11yNode, Bounds, ElementSummary, Rect, Role, ScreenDescription, collect_visible_summaries,
    is_visible_enough, summarize_node, visible_area,
};
pub use smix_selector::{
    AnchorBox, IndexModifiers, Modifiers, Pattern, Selector, True, describe_selector, match_text,
    match_text_compiled,
};
pub use smix_simctl::{Appearance, LaunchResult, SimctlClient, SimctlError, SimctlPermission};

/// Nucleus of `App::assert_screenshot`. Wraps fs IO + the dhash algorithm
/// without any `App` dependency, so it can be exercised in host-side
/// unit tests. Helper fn — not a user-facing capability.
pub fn assert_screenshot_inner(
    png_bytes: &[u8],
    baseline_path: &std::path::Path,
    max_hamming: u32,
    strict: bool,
) -> Result<AssertScreenshotOutcome, ExpectationFailure> {
    use std::io::ErrorKind;
    let baseline_bytes = match std::fs::read(baseline_path) {
        Ok(b) => b,
        Err(e) if e.kind() == ErrorKind::NotFound => {
            if strict {
                return Err(ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::DriverError),
                    message: format!(
                        "assert_screenshot: baseline missing at {} and SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD=1 set; record a baseline first",
                        baseline_path.display()
                    ),
                    suggestions: vec![
                        "Run once without SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD to auto-record"
                            .into(),
                    ],
                    ..Default::default()
                }));
            }
            // auto-record: ensure parent dir exists + write current PNG.
            if let Some(parent) = baseline_path.parent()
                && !parent.as_os_str().is_empty()
            {
                std::fs::create_dir_all(parent).map_err(|e| {
                    ExpectationFailure::new(FailureInit {
                        code: Some(FailureCode::DriverError),
                        message: format!(
                            "assert_screenshot: failed to create baseline parent dir {}: {e}",
                            parent.display()
                        ),
                        ..Default::default()
                    })
                })?;
            }
            std::fs::write(baseline_path, png_bytes).map_err(|e| {
                ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::DriverError),
                    message: format!(
                        "assert_screenshot: failed to write baseline {}: {e}",
                        baseline_path.display()
                    ),
                    ..Default::default()
                })
            })?;
            return Ok(AssertScreenshotOutcome::Recorded {
                path: baseline_path.to_path_buf(),
            });
        }
        Err(e) => {
            return Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!(
                    "assert_screenshot: failed to read baseline {}: {e}",
                    baseline_path.display()
                ),
                ..Default::default()
            }));
        }
    };

    let h_current = screenshot_hash::compute_dhash(png_bytes)?;
    let h_baseline = screenshot_hash::compute_dhash(&baseline_bytes)?;
    let hamming = screenshot_hash::hamming_distance(h_current, h_baseline);
    if hamming <= max_hamming {
        Ok(AssertScreenshotOutcome::Matched { hamming })
    } else {
        Err(ExpectationFailure::new(FailureInit {
            code: Some(FailureCode::AssertionFailed),
            message: format!(
                "assertScreenshot: dhash hamming distance {hamming} exceeds threshold {max_hamming} (baseline {})",
                baseline_path.display()
            ),
            suggestions: vec![
                "Re-record baseline (delete the file) if the UI intentionally changed".into(),
                "Or pin/wait for animations to settle before assertScreenshot".into(),
            ],
            ..Default::default()
        }))
    }
}

/// Outcome of [`App::assert_screenshot`]. Distinguishes the
/// first-run "auto-record baseline" path (which writes the captured PNG to
/// disk and treats as Ok) from the steady-state diff path (which compares
/// dhash hamming distance against the recorded baseline).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AssertScreenshotOutcome {
    /// First run — baseline did not exist, captured PNG was written to
    /// `path`. Subsequent runs will diff against this file.
    Recorded {
        /// Absolute path written.
        path: std::path::PathBuf,
    },
    /// Baseline existed and matched within tolerance; `hamming` is the
    /// observed dhash distance (≤ max_hamming).
    Matched {
        /// dhash hamming distance against baseline.
        hamming: u32,
    },
}

/// Maestro `setOrientation: <variant>` literal enum.
/// `landscape` yaml alias normalizes to `LandscapeLeft` at the parser
/// layer (same as maestro default). 1:1 mirrors `smix_driver::Orientation`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MaestroOrientation {
    /// Standard upright portrait.
    Portrait,
    /// Upside-down portrait.
    PortraitUpsideDown,
    /// Landscape with home indicator to the right (the default for
    /// `landscape` alias).
    LandscapeLeft,
    /// Landscape with home indicator to the left.
    LandscapeRight,
}

impl MaestroOrientation {
    /// 1:1 forward into the driver-level [`smix_driver::Orientation`].
    pub fn to_driver(self) -> smix_driver::Orientation {
        match self {
            Self::Portrait => smix_driver::Orientation::Portrait,
            Self::PortraitUpsideDown => smix_driver::Orientation::PortraitUpsideDown,
            Self::LandscapeLeft => smix_driver::Orientation::LandscapeLeft,
            Self::LandscapeRight => smix_driver::Orientation::LandscapeRight,
        }
    }
}

/// Maestro yaml `permissions:` action — controls iOS privacy state per bundle.
/// Maestro yaml parity:
/// - `Grant`  ↔ maestro yaml `"allow"` ↔ simctl `privacy grant`
/// - `Revoke` ↔ maestro yaml `"deny"`  ↔ simctl `privacy revoke`
/// - `Reset`  ↔ maestro yaml `"unset"` ↔ simctl `privacy reset`
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PermissionAction {
    Grant,
    Revoke,
    Reset,
}

/// Typed shape of maestro yaml `launchApp:` mapping. Adapter assembles this
/// from yaml fields; SDK consumes it in [`App::launch_app_with_options`].
/// Covers maestro `launchApp.permissions / arguments / stopApp`.
#[derive(Clone, Debug, PartialEq)]
pub struct LaunchAppOptions {
    pub bundle_id: String,
    pub clear_state: bool,
    pub clear_keychain: bool,
    /// Process-level argv passed via `simctl launch -- <args>`.
    pub arguments: Vec<String>,
    /// Permission directives applied in declaration order BEFORE launch.
    pub permissions: Vec<(SimctlPermission, PermissionAction)>,
    /// App bundle path for clear_state / clear_keychain wipe — mirrors the
    /// `launch_fresh::app_path` parameter; usually populated by the
    /// adapter from `SMIX_APP_PATH_<NORMALIZED_BUNDLE>` env.
    pub app_path: Option<String>,
}

// -------------------- selector helpers (ergonomic factories) --------

/// `text("Login")` shortcut. Mirrors TS `{ text: 'Login' }` shorthand.
#[must_use]
pub fn text<S: Into<String>>(s: S) -> Selector {
    Selector::Text {
        text: Pattern::text(s),
        modifiers: Modifiers::default(),
    }
}

/// `text_regex("^Lo")` shortcut.
#[must_use]
pub fn text_regex<S: Into<String>>(p: S) -> Selector {
    Selector::Text {
        text: Pattern::regex(p),
        modifiers: Modifiers::default(),
    }
}

/// `id("btn-x")` shortcut.
#[must_use]
pub fn id<S: Into<String>>(s: S) -> Selector {
    Selector::Id {
        id: s.into(),
        modifiers: Modifiers::default(),
    }
}

/// `label("Settings")` shortcut.
#[must_use]
pub fn label<S: Into<String>>(s: S) -> Selector {
    Selector::Label {
        label: s.into(),
        modifiers: Modifiers::default(),
    }
}

/// `role(Role::Button)` shortcut.
#[must_use]
pub fn role(r: Role) -> Selector {
    Selector::Role {
        role: r,
        name: None,
        modifiers: Modifiers::default(),
    }
}

/// `role_named(Role::Button, "Submit")` shortcut.
#[must_use]
pub fn role_named<S: Into<String>>(r: Role, name: S) -> Selector {
    Selector::Role {
        role: r,
        name: Some(Pattern::text(name)),
        modifiers: Modifiers::default(),
    }
}

/// `focused()` shortcut.
#[must_use]
pub fn focused() -> Selector {
    Selector::Focused {
        focused: True(true),
    }
}

/// Atomic op in the [`App::launch_fresh`] orchestration plan. Exposed
/// so the plan is testable as a pure function (no `SimctlClient` stub
/// — and a stub wouldn't help much since `SimctlClient` is a ZST).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LaunchFreshOp {
    /// `simctl terminate` on the target — clean SIGTERM, no crash-report
    /// daemon interpretation.
    Terminate,
    /// `simctl uninstall` on the target. As of v1.0.4 §D12 this is
    /// used only when `SMIX_LAUNCH_FRESH_FORCE_REINSTALL=1` is set;
    /// the default clear-state path uses [`SandboxClearInPlace`] to
    /// avoid the iOS 26.5 XCUITest binding loss (feedback §F) and
    /// ReportCrash "Insight quit unexpectedly" dialog (feedback §H).
    Uninstall,
    /// `simctl install <path>` — reinstalls the .app bundle. Same
    /// v1.0.4 §D12 note as [`Uninstall`]: only used on the
    /// force-reinstall path.
    Install(String),
    /// `simctl privacy reset all` — wipes granted permissions
    /// without touching the app's data. Companion to
    /// [`SandboxClearInPlace`]; both make up the default in-place
    /// clear-state path.
    ///
    /// Since smix 1.0.4.
    PrivacyResetAll,
    /// v1.0.4 §D12 — wipe the app's sandbox
    /// (`Documents/`, `Library/`, `tmp/`) via NSFileManager
    /// on the running sim, without `simctl uninstall`. Preserves
    /// the XCUITest binding (fixes feedback §F) and does not trip
    /// ReportCrash (fixes feedback §H). Argument is the target bundle-id.
    SandboxClearInPlace(String),
    KeychainReset,
    Launch,
}

/// Pure planner for [`App::launch_fresh`] — computes the simctl op
/// sequence + warnings from `(clear_state, clear_keychain, app_path)`.
///
/// Maestro `launchApp.clearState` semantic is "wipe app data without
/// removing other apps", and iOS exposes no native per-app data wipe
/// API. The closest aligned host-side path is `simctl uninstall`
/// followed by `simctl install <app_path>`. So `clear_state=true`
/// only triggers a real wipe when `app_path` is supplied (typically
/// by the adapter reading `SMIX_APP_PATH_<BUNDLE_NORMALIZED>`);
/// otherwise it gracefully falls back to the non-clear path
/// (`terminate + launch`) with a warning.
#[must_use]
pub fn plan_launch_fresh_calls(
    clear_state: bool,
    clear_keychain: bool,
    app_path: Option<&str>,
) -> (Vec<LaunchFreshOp>, Vec<String>) {
    plan_launch_fresh_calls_v2(clear_state, clear_keychain, app_path, false)
}

/// v1.0.4 §D12 — extended planner with an explicit `force_reinstall`
/// switch. When `false` (the new default), `clear_state=true` runs
/// the in-place sandbox clear + privacy reset instead of
/// `simctl uninstall + install`. This avoids the iOS 26.5 XCUITest
/// binding loss (feedback §F) and the ReportCrash "Insight quit
/// unexpectedly" system dialog (feedback §H) — both of which stem
/// from the uninstall+install sequence.
///
/// When `force_reinstall=true` (opt-in via
/// `SMIX_LAUNCH_FRESH_FORCE_REINSTALL=1`), the pre-v1.0.4 path is
/// preserved for cases where a bit-for-bit reinstall is required.
///
/// Since smix 1.0.4.
#[must_use]
pub fn plan_launch_fresh_calls_v2(
    clear_state: bool,
    clear_keychain: bool,
    app_path: Option<&str>,
    force_reinstall: bool,
) -> (Vec<LaunchFreshOp>, Vec<String>) {
    // Terminate is always first — clean SIGTERM before any wipe.
    let mut ops = vec![LaunchFreshOp::Terminate];
    let mut warnings = Vec::new();
    if clear_state {
        if force_reinstall {
            match app_path {
                Some(path) => {
                    ops.push(LaunchFreshOp::Uninstall);
                    ops.push(LaunchFreshOp::Install(path.to_string()));
                }
                None => {
                    warnings.push(
                        "launch_fresh: force_reinstall=1 but app_path missing — cannot \
                         reinstall; falling back to in-place clear"
                            .to_string(),
                    );
                    ops.push(LaunchFreshOp::PrivacyResetAll);
                    ops.push(LaunchFreshOp::SandboxClearInPlace(String::new()));
                }
            }
        } else {
            // v1.0.4 default: in-place sandbox clear + privacy reset.
            // No uninstall/install → XCUITest binding preserved
            // (feedback §F fix) + no ReportCrash dialog (§H fix).
            //
            // The SandboxClearInPlace op receives an empty string
            // here; the executor fills it in from the target bundle-id
            // that App::launch_fresh already knows.
            ops.push(LaunchFreshOp::PrivacyResetAll);
            ops.push(LaunchFreshOp::SandboxClearInPlace(String::new()));
            if app_path.is_some() {
                warnings.push(
                    "launch_fresh: app_path set but in-place clear used (v1.0.4 default); \
                     set SMIX_LAUNCH_FRESH_FORCE_REINSTALL=1 to fall back to \
                     uninstall+install for a bit-for-bit reinstall"
                        .to_string(),
                );
            }
        }
    }
    if clear_keychain {
        ops.push(LaunchFreshOp::KeychainReset);
    }
    ops.push(LaunchFreshOp::Launch);
    (ops, warnings)
}

// -------------------- App ------------------------------------------------

/// Top-level surface for test authors. Mirrors Playwright's `page`
/// deliberately — AI authoring quality is highest when names overlap
/// with corpus the AI was trained on.
///
/// Every method is async — no chaining shortcuts, no fluent builder
/// pattern. One step, one await, one observable side effect (CLAUDE.md
/// §9 #5).
/// v1.0.3 — a runner-side session guard. Obtained via
/// v1.0.4 §D7 — Session state exposed to consumers via
/// [`Session::state`]. Additive over v1.0.3; the runner's
/// `X-Sim-Health` response header drives transitions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SessionState {
    /// All observed signals inside envelope.
    Healthy = 0,
    /// At least one signal degraded (screenshot slow, /health stale).
    Degraded = 1,
    /// Runner is mid-cycle (supervisor auto-restart in progress).
    Cycling = 2,
    /// Runner or a watched subprocess (SimRenderServer / xcodebuild)
    /// is gone.
    Dead = 3,
}

impl SessionState {
    /// Round-trip from the AtomicU8 storage; unknown wire values map
    /// to `Healthy` (optimistic) so a new future state doesn't crash.
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Degraded,
            2 => Self::Cycling,
            3 => Self::Dead,
            _ => Self::Healthy,
        }
    }
}

/// [`App::open_session`]; drop the value or call [`Session::close`] to
/// release. While a session is open the wrapped `App` sends the
/// `Session-Id` header on every request, and the runner uses the
/// session's cached `XCUIApplication` binding — no per-request
/// activation storm.
///
/// The type is deliberately `!Clone` and takes ownership of the
/// `App`. Consumer flow:
///
/// ```ignore
/// use smix_sdk::App;
/// # async fn demo() -> Result<(), smix_sdk::ExpectationFailure> {
/// let mut app = App::connect_to_runner(22087).await?;
/// let mut session = app.open_session("com.example.app", true).await?;
/// session.app_mut().tap(&smix_sdk::text("Sign In")).await?;
/// session.close().await?;
/// # Ok(())
/// # }
/// ```
///
/// If `Session::close` is not called, `Drop` releases the reference
/// but cannot await the network `POST /session/close` — a background
/// task is spawned best-effort. Prefer `close()` explicitly.
pub struct Session {
    /// `Some` until `close()` moves the App out; `None` afterwards.
    /// Every accessor asserts `Some` — using a Session after `close`
    /// panics.
    app: Option<App>,
    session_id: String,
    /// v1.0.4 §D7 — sim-health state observed via `X-Sim-Health`
    /// response header on the last runner response. Updated
    /// automatically by [`HttpRunnerClient`] when the header is
    /// present; defaults to `Healthy` at open time. Consumers read
    /// via [`Session::state`].
    state: std::sync::Arc<std::sync::atomic::AtomicU8>,
}

impl Session {
    /// Immutable access to the underlying `App`. Every call goes out
    /// with the `Session-Id` header. Panics if called after
    /// [`Session::close`].
    pub fn app(&self) -> &App {
        self.app.as_ref().expect("Session used after close()")
    }

    /// Mutable access to the underlying `App`. Panics if called after
    /// [`Session::close`].
    pub fn app_mut(&mut self) -> &mut App {
        self.app.as_mut().expect("Session used after close()")
    }

    /// The runner-issued session id. Opaque; useful only for logging.
    pub fn session_id(&self) -> &str {
        &self.session_id
    }

    /// v1.0.4 §D7 — current sim-health classification observed via
    /// the `X-Sim-Health` response header on the most recent runner
    /// request. `Healthy` at open time (optimistic — the open call
    /// itself succeeded); transitions to `Degraded` / `Cycling` / `Dead`
    /// as the runner emits them.
    pub fn state(&self) -> SessionState {
        SessionState::from_u8(
            self.state.load(std::sync::atomic::Ordering::Acquire),
        )
    }

    /// v1.0.5 §D1 — probe the runner's `/session/list` and return
    /// `true` iff this session's id is still known. Consumers wire
    /// this after a `Session::state` transition to `Cycling` or `Dead`
    /// to decide whether to keep using the session (still valid across
    /// the cycle thanks to §D1 persistence) or reopen a fresh one.
    ///
    /// Runner errors return `Err` — treat as "unknown"; consumers
    /// typically bail on that path anyway.
    pub async fn still_valid(&self) -> Result<bool, ExpectationFailure> {
        let app = self.app();
        let runner = app.http_runner_client().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "session still_valid: driver has no HTTP runner client".into(),
                ..Default::default()
            })
        })?;
        let resp = runner.list_sessions().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("session still_valid: {e}"),
                ..Default::default()
            })
        })?;
        Ok(resp.sessions.iter().any(|s| s.session_id == self.session_id))
    }

    /// v1.0.4 §D14 — instruct the runner to `terminate()` + `launch()`
    /// the session's cached `XCUIApplication` in place. Preserves the
    /// session id and XCUITest binding. Consumers wire this after
    /// observing an app crash (via [`Self::state`] transitioning to
    /// `Degraded`/`Dead` with the runner itself Healthy) to auto-
    /// recover without cycling the runner.
    ///
    /// Returns the wall-clock milliseconds the terminate + launch
    /// cycle took, as reported by the runner.
    pub async fn relaunch_app(&self) -> Result<u64, ExpectationFailure> {
        let app = self.app();
        let runner = app.http_runner_client().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "session relaunch_app: driver has no HTTP runner client".into(),
                ..Default::default()
            })
        })?;
        let req = smix_runner_client::SessionRelaunchAppRequest {
            session_id: self.session_id.clone(),
        };
        runner
            .relaunch_session_app(&req)
            .await
            .map(|r| r.wall_ms)
            .map_err(|e| {
                ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::DriverError),
                    message: format!("session relaunch_app: {e}"),
                    ..Default::default()
                })
            })
    }

    /// Ask the runner to re-issue `.activate()` on the session's
    /// cached binding. Subject to the runner's per-session 2 s rate
    /// limit; when rate-limited returns `Ok(false)`. When the runner
    /// no longer has the session id in its table (evicted / restart)
    /// returns an error.
    pub async fn renew_activation(&self) -> Result<bool, ExpectationFailure> {
        let app = self.app();
        let runner = app.http_runner_client().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "session renew_activation: driver has no HTTP runner client".into(),
                ..Default::default()
            })
        })?;
        let req = smix_runner_client::SessionRenewActivationRequest {
            session_id: self.session_id.clone(),
        };
        runner
            .renew_session_activation(&req)
            .await
            .map(|r| r.activated)
            .map_err(|e| {
                ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::DriverError),
                    message: format!("session renew_activation: {e}"),
                    ..Default::default()
                })
            })
    }

    /// Release the session — sends `POST /session/close` and clears
    /// the `Session-Id` header from the client. Returns the wrapped
    /// `App` so the caller can keep issuing requests via the legacy
    /// per-request path.
    pub async fn close(mut self) -> Result<App, ExpectationFailure> {
        let mut app = self.app.take().expect("Session::close called twice");
        // Best-effort: an error here means the runner is gone or the
        // session id has already been evicted. Neither is fatal; the
        // client-side header clear is the meaningful action.
        if let Some(runner) = app.http_runner_client() {
            let req = smix_runner_client::SessionCloseRequest {
                session_id: self.session_id.clone(),
            };
            let _ = runner.close_session(&req).await;
        }
        app.driver.set_session_id(None);
        Ok(app)
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // Best-effort clear of the session header. Network
        // `POST /session/close` is skipped — we can't `await` in Drop;
        // prefer explicit `close()` when the release contract matters.
        if let Some(app) = self.app.as_mut() {
            app.driver.set_session_id(None);
        }
    }
}

pub struct App {
    /// Sense+act trait stored as `Box<dyn>` for cross-platform
    /// dispatch. iOS impl = `IosDriver`; Android impl = `AndroidDriver`.
    driver: Box<dyn smix_driver::Driver>,
    /// Sim/host control trait stored as `Box<dyn>` for cross-platform
    /// dispatch. iOS impl = `IosDeviceControl`; Android impl =
    /// `AndroidDeviceControl`.
    device: Box<dyn DeviceControl>,
    udid: Option<String>,
    /// Capsule SDK issued-action ledger. Each `tap` / `tap_with_mode` /
    /// `fill` / `tap_at_coord` records an entry before the driver call,
    /// which is reconciled against EventRecorder 1018 focus-change events.
    /// Capacity LRU 1024.
    ledger: IssuedLedger,
}

impl App {
    /// Construct from a fully-wired driver + simctl client. Use this when
    /// you already manage Cell / UDID lifecycle externally.
    ///
    /// Back-compat constructor: still accepts `SimctlDriver` (alias to
    /// `IosDriver`) and `SimctlClient`; internally wraps into
    /// `Box<dyn Driver>` and `Box::new(IosDeviceControl::with_client(...))`.
    pub fn new(driver: SimctlDriver, simctl: SimctlClient) -> Self {
        App {
            driver: Box::new(driver),
            device: Box::new(IosDeviceControl::with_client(simctl)),
            udid: None,
            ledger: IssuedLedger::new(),
        }
    }

    /// Generic constructor for cross-platform tests. Use this when
    /// constructing with non-iOS `Driver` / `DeviceControl` impls.
    pub fn new_with(driver: Box<dyn smix_driver::Driver>, device: Box<dyn DeviceControl>) -> Self {
        App {
            driver,
            device,
            udid: None,
            ledger: IssuedLedger::new(),
        }
    }

    /// v1.0.3 — accessor for the underlying HTTP runner client, used by
    /// [`Session`] to drive the `/session/*` routes. Returns `None`
    /// when the driver is not backed by an HTTP runner (e.g. mock
    /// driver in tests).
    pub fn http_runner_client(&self) -> Option<&HttpRunnerClient> {
        self.driver.as_ios_driver().map(|ios| ios.runner())
    }

    /// v1.0.3 — open a runner-side session bound to `bundle_id`.
    /// Subsequent requests via the returned [`Session`] send the
    /// `Session-Id` header and skip per-request activation entirely.
    ///
    /// `activate = true` causes the runner to `.activate()` the target
    /// once as part of the open (idiomatic when the target may not be
    /// foregrounded yet). `activate = false` opens a passive binding
    /// suitable when the caller has already ensured foreground state.
    ///
    /// This is the recommended surface for long-running gates. See the
    /// [`Session`] docs for the lifecycle contract.
    pub async fn open_session(
        mut self,
        bundle_id: &str,
        activate: bool,
    ) -> Result<Session, ExpectationFailure> {
        let runner = self.http_runner_client().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "open_session: driver has no HTTP runner client".into(),
                ..Default::default()
            })
        })?;
        let req = smix_runner_client::SessionOpenRequest {
            bundle_id: bundle_id.to_string(),
            activate,
        };
        let resp = runner.open_session(&req).await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("open_session wire: {e}"),
                ..Default::default()
            })
        })?;
        let sid = resp.session_id.clone();
        self.driver.set_session_id(Some(sid.clone()));
        // v1.0.4 §D7 — hook the state atomic into the client so future
        // X-Sim-Health header transitions are visible to consumers via
        // Session::state(). Optimistic Healthy at open time.
        let state = std::sync::Arc::new(std::sync::atomic::AtomicU8::new(
            SessionState::Healthy as u8,
        ));
        if let Some(runner) = self.http_runner_client() {
            runner.attach_session_state(state.clone());
        }
        Ok(Session {
            app: Some(self),
            session_id: sid,
            state,
        })
    }

    /// Convenience: connect to a runner on `127.0.0.1:{port}` and probe
    /// `GET /health` once. Returns App ready for sense+act calls.
    pub async fn connect_to_runner(port: u16) -> Result<Self, ExpectationFailure> {
        let client = HttpRunnerClient::new(port);
        client.ensure_reachable().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("runner unreachable: {e}"),
                hint: Some(format!("check SmixRunner started on port {port}")),
                ..Default::default()
            })
        })?;
        Ok(App {
            driver: Box::new(SimctlDriver::new(client)),
            device: Box::new(IosDeviceControl::new()),
            udid: None,
            ledger: IssuedLedger::new(),
        })
    }

    /// Connect to an Android Kotlin runner on `127.0.0.1:{port}`
    /// (the host-forwarded port that proxies to the device-side
    /// runner instrumentation). Returns App ready for cross-platform
    /// sense+act calls dispatched via AndroidDriver + AndroidDeviceControl.
    pub async fn connect_to_runner_android(port: u16) -> Result<Self, ExpectationFailure> {
        use smix_driver::AndroidDriver;
        let client = HttpRunnerClient::new(port);
        client.ensure_reachable().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("Android runner unreachable: {e}"),
                hint: Some(format!(
                    "check smix-android-runner instrument is up on port {port}"
                )),
                ..Default::default()
            })
        })?;
        Ok(App {
            driver: Box::new(AndroidDriver::new(client)),
            device: Box::new(AndroidDeviceControl::new()),
            udid: None,
            ledger: IssuedLedger::new(),
        })
    }

    /// Bind a UDID for lifecycle operations (launch/terminate/install/etc.).
    pub fn with_udid<S: Into<String>>(mut self, udid: S) -> Self {
        self.udid = Some(udid.into());
        self
    }

    /// Thread the target bundle id down to the driver, which forwards
    /// it to the runner via the `App-Bundle-Id` HTTP header. The iOS
    /// runner rebinds `XCUIApplication(bundleIdentifier:)` per request
    /// so calls stay pinned to the right app even when something else
    /// briefly claims foreground.
    #[must_use]
    pub fn with_bundle_id<S: Into<String>>(mut self, bundle: S) -> Self {
        let s: String = bundle.into();
        self.driver.set_target_bundle_id(&s);
        self
    }

    /// Enable auto-activate on every request. Runner side
    /// `.activate()`s the resolved target before operating. Costs one
    /// XCUITest activate call per request (~50-100ms); opt-in.
    #[must_use]
    pub fn with_auto_activate(mut self, activate: bool) -> Self {
        self.driver.set_auto_activate(activate);
        self
    }

    /// Force key-event dispatch mode on text-input verbs. Sends
    /// `Input-Dispatch-Mode: key-events` header on every request.
    /// Covers the RN hidden-input pattern where a11y-focus lookup
    /// returns nothing. Also opt-in via `smix run --force-key-events`.
    #[must_use]
    pub fn with_force_key_events(mut self, force: bool) -> Self {
        self.driver.set_force_key_events(force);
        self
    }

    pub fn udid(&self) -> Option<&str> {
        self.udid.as_deref()
    }

    /// Direct access to underlying `Driver` trait object.
    /// Use `app.driver()` for cross-platform calls; downcast to
    /// `IosDriver` only if iOS-specific behavior needed.
    pub fn driver(&self) -> &dyn smix_driver::Driver {
        self.driver.as_ref()
    }

    /// Back-compat `&SimctlClient` accessor. **iOS-only.**
    /// Panics on Android (use `app.device()` instead).
    pub fn simctl(&self) -> &SimctlClient {
        self.device.as_ios_simctl().expect(
            "App::simctl() called on non-iOS App; use app.device() for cross-platform access",
        )
    }

    /// Cross-platform sim/host control trait object.
    pub fn device(&self) -> &dyn DeviceControl {
        self.device.as_ref()
    }

    fn require_udid(&self) -> Result<&str, ExpectationFailure> {
        self.udid.as_deref().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "App not bound to a UDID; use .with_udid(...) first".into(),
                ..Default::default()
            })
        })
    }

    // ---- lifecycle (simctl-bound, requires UDID) ----------------------

    pub async fn launch(&self, bundle_id: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .launch(udid, bundle_id)
            .await
            .map(|_| ())
            .map_err(simctl_to_failure)
    }

    pub async fn terminate(&self, bundle_id: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .terminate(udid, bundle_id)
            .await
            .map_err(simctl_to_failure)
    }

    pub async fn install(&self, app_path: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .install(udid, app_path)
            .await
            .map_err(simctl_to_failure)
    }

    pub async fn uninstall(&self, bundle_id: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .uninstall(udid, bundle_id)
            .await
            .map_err(simctl_to_failure)
    }

    /// Launch the app with optional state / keychain wipe before launch.
    /// See [`plan_launch_fresh_calls`] for the op sequence semantics.
    /// Returns the warnings produced by the planner (graceful fallback
    /// path is taken when `clear_state=true` but `app_path` is `None`).
    /// The caller should append these warnings to its own collector
    /// (e.g. `RunReport::warnings` in the maestro adapter).
    /// `launch_arguments` is process-level argv (`simctl launch --
    /// <args>`). Empty `&[]` skips argv injection.
    pub async fn launch_fresh(
        &self,
        bundle_id: &str,
        clear_state: bool,
        clear_keychain: bool,
        app_path: Option<&str>,
        launch_arguments: &[String],
    ) -> Result<Vec<String>, ExpectationFailure> {
        let udid = self.require_udid()?;
        // v1.0.4 §D12 — probe SMIX_LAUNCH_FRESH_FORCE_REINSTALL env
        // for the pre-v1.0.4 uninstall+install path. Default is the
        // new in-place clear that preserves XCUITest binding + does
        // not trip ReportCrash.
        let force_reinstall = std::env::var("SMIX_LAUNCH_FRESH_FORCE_REINSTALL")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        let (ops, warnings) = plan_launch_fresh_calls_v2(
            clear_state,
            clear_keychain,
            app_path,
            force_reinstall,
        );
        for op in &ops {
            match op {
                LaunchFreshOp::Terminate => {
                    let _ = self.device.terminate(udid, bundle_id).await;
                }
                LaunchFreshOp::Uninstall => {
                    self.device
                        .uninstall(udid, bundle_id)
                        .await
                        .map_err(simctl_to_failure)?;
                }
                LaunchFreshOp::Install(path) => {
                    self.device
                        .install(udid, path)
                        .await
                        .map_err(simctl_to_failure)?;
                }
                LaunchFreshOp::PrivacyResetAll => {
                    self.device
                        .privacy_reset_all(udid, bundle_id)
                        .await
                        .map_err(simctl_to_failure)?;
                }
                LaunchFreshOp::SandboxClearInPlace(_) => {
                    // Planner passes empty string; App knows the real
                    // bundle-id already (function arg).
                    self.device
                        .clear_app_sandbox(udid, bundle_id)
                        .await
                        .map_err(simctl_to_failure)?;
                }
                LaunchFreshOp::KeychainReset => {
                    self.device
                        .keychain_reset(udid)
                        .await
                        .map_err(simctl_to_failure)?;
                }
                LaunchFreshOp::Launch => {
                    self.device
                        .launch_with_args(udid, bundle_id, launch_arguments)
                        .await
                        .map(|_| ())
                        .map_err(simctl_to_failure)?;
                }
            }
        }
        Ok(warnings)
    }

    /// Apply a permission action to a bundle.
    /// Maps maestro yaml `permissions: { camera: allow|deny|unset }` to simctl
    /// privacy. **§12.1 three-layer architecture**: sense+act live in
    /// core; the adapter only translates maestro yaml strings to the
    /// `PermissionAction` enum.
    pub async fn set_permission(
        &self,
        bundle_id: &str,
        permission: SimctlPermission,
        action: PermissionAction,
    ) -> Result<(), ExpectationFailure> {
        // Delegate to DeviceControl::set_permission with the cross-platform
        // Permission enum. Round-trip via Permission::from_simctl.
        let udid = self.require_udid()?;
        let xperm = Permission::from_simctl(permission);
        self.device
            .set_permission(udid, bundle_id, xperm, action)
            .await
            .map_err(simctl_to_failure)
    }

    /// Typed launch entry: apply permissions in declaration order, then
    /// dispatch to [`Self::launch_fresh`] (when clear_state /
    /// clear_keychain) or `simctl terminate + launch_with_args`
    /// (otherwise). Maps maestro yaml `launchApp: { ... }` in full
    /// (permissions / arguments / clearState / clearKeychain). Returns
    /// warnings emitted by `launch_fresh` (caller appends to its own
    /// collector).
    pub async fn launch_app_with_options(
        &self,
        opts: &LaunchAppOptions,
    ) -> Result<Vec<String>, ExpectationFailure> {
        let udid = self.require_udid()?;
        for (perm, action) in &opts.permissions {
            self.set_permission(&opts.bundle_id, *perm, *action).await?;
        }
        let warnings = if opts.clear_state || opts.clear_keychain {
            self.launch_fresh(
                &opts.bundle_id,
                opts.clear_state,
                opts.clear_keychain,
                opts.app_path.as_deref(),
                &opts.arguments,
            )
            .await?
        } else {
            // stop+launch path: maestro `launchApp` defaults to
            // stopApp=true — terminate first, then launch_with_args.
            // terminate failure is tolerated (the app may already be
            // dead); launch must succeed.
            let _ = self.device.terminate(udid, &opts.bundle_id).await;
            self.device
                .launch_with_args(udid, &opts.bundle_id, &opts.arguments)
                .await
                .map(|_| ())
                .map_err(simctl_to_failure)?;
            Vec::new()
        };
        Ok(warnings)
    }

    pub async fn open_url(&self, url: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .open_url(udid, url)
            .await
            .map_err(simctl_to_failure)
    }

    /// Deliver an APNS payload to `bundle_id` via `simctl push`.
    /// The payload file must contain a JSON dictionary with at least an
    /// `aps` key (per Apple's spec). Mirrors maestro yaml `sendPush:`
    /// once that command lands upstream — there is no public maestro
    /// yaml `sendPush` today, so this is SDK-only surface.
    pub async fn send_push(
        &self,
        bundle_id: &str,
        apns_json_path: &str,
    ) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .send_push(udid, bundle_id, apns_json_path)
            .await
            .map_err(simctl_to_failure)
    }

    pub async fn screenshot(&self) -> Result<Vec<u8>, ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .screenshot(udid)
            .await
            .map_err(simctl_to_failure)
    }

    /// Register a fixture-side action anchor in the SDK ledger so that
    /// the `capsule_reconcile` window can attribute the
    /// `kAXFirstResponderChangedNotification` (1018) the fixture's
    /// UIKit modal present is about to emit. Use this immediately
    /// before triggering a fixture-owned present path
    /// (UIActivityViewController, UIDocumentPickerViewController,
    /// SpringBoard system popup) that `smix-driver` would otherwise
    /// leave unattributed — without it, the phantom focus change
    /// inflates `unattributed_count`.
    pub fn mark_fixture_action(&self, action_id: &str) {
        self.ledger
            .record_fixture_action(now_ms(), action_id.to_string());
    }

    // ---- sense (driver-bound) -----------------------------------------

    pub async fn tree(&self) -> Result<A11yNode, ExpectationFailure> {
        self.driver.tree(None).await
    }

    pub async fn describe(&self) -> Result<ScreenDescription, ExpectationFailure> {
        // describe() is App-layer aggregation (not on the Driver trait
        // per cross-platform design). Inlined: driver.tree() +
        // collect_visible_summaries.
        let tree = self.driver.tree(None).await?;
        Ok(ScreenDescription {
            screenshot: None,
            elements: collect_visible_summaries(&tree, smix_screen::DEFAULT_VISIBLE_LIMIT),
            front_app: String::new(),
            summary: String::new(),
            captured_at: 0.0,
        })
    }

    pub async fn find_one(
        &self,
        selector: &Selector,
    ) -> Result<Option<A11yNode>, ExpectationFailure> {
        self.driver.find_one(selector, None).await
    }

    pub async fn find_all(&self, selector: &Selector) -> Result<Vec<A11yNode>, ExpectationFailure> {
        self.driver.find_all(selector, None).await
    }

    pub async fn find(&self, selector: &Selector) -> Result<bool, ExpectationFailure> {
        self.driver.find(selector, None).await
    }

    pub async fn system_popups(&self) -> Result<Vec<SystemPopup>, ExpectationFailure> {
        self.driver.system_popups(None).await
    }

    /// Tap a button on a previously enumerated system popup. `popup_id`
    /// and `button_id` round-trip from `system_popups()` — the runner
    /// walks the same scan order so callers don't need to manage an id
    /// map. Returns `Ok(true)` when matched and tapped, `Ok(false)` when
    /// the runner returned 404 not_found (popup or button id stale).
    /// Paired with `system_popups()` to close the sense/act loop on
    /// iOS system popups.
    pub async fn system_popup_action(
        &self,
        popup_id: &str,
        button_id: &str,
    ) -> Result<bool, ExpectationFailure> {
        // Anchor the popup-action tap in the SDK ledger so any
        // kAXFirstResponderChangedNotification 1018 the SpringBoard alert
        // dismissal emits attributes to this action (was previously
        // unattributed because system_popup_action skipped record_tap).
        self.ledger.record_tap(
            now_ms(),
            Some(format!(
                "system_popup_action(popup={popup_id} btn={button_id})"
            )),
        );
        self.driver.system_popup_action(popup_id, button_id).await
    }

    // ---- act (driver-bound) -------------------------------------------

    pub async fn tap(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        self.ledger
            .record_tap(now_ms(), Some(format!("{selector:?}")));
        self.driver.tap(selector, None).await
    }

    /// Tap a selector via an explicit dispatch mode. Use
    /// `TapMode::DaemonProxySynthesize` for RN Pressable buttons that
    /// don't fire `onPress` with the default `tap()` Apple-native-event
    /// -chain dispatch. All other selectors should use `tap(selector)`
    /// (no mode) — the default host-resolve plus `tap_at_norm_coord`
    /// path is faster and works for non-RN-Pressable elements.
    pub async fn tap_with_mode(
        &self,
        selector: &Selector,
        mode: TapMode,
    ) -> Result<(), ExpectationFailure> {
        self.ledger
            .record_tap(now_ms(), Some(format!("{selector:?}")));
        self.driver.tap_with_mode(selector, mode, None).await
    }

    pub async fn fill(&self, selector: &Selector, text: &str) -> Result<(), ExpectationFailure> {
        self.ledger
            .record_fill(now_ms(), Some(format!("{selector:?}")));
        self.driver.fill(selector, text, None).await
    }

    pub async fn clear(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        self.driver.clear(selector, None).await
    }

    pub async fn press_key(&self, key: KeyName) -> Result<(), ExpectationFailure> {
        self.driver.press_key(key).await
    }

    pub async fn scroll(
        &self,
        selector: &Selector,
        direction: SwipeDirection,
    ) -> Result<(), ExpectationFailure> {
        self.driver.scroll(selector, direction).await
    }

    pub async fn swipe_once(&self, direction: SwipeDirection) -> Result<(), ExpectationFailure> {
        self.driver.swipe_once(direction).await
    }

    pub async fn hide_keyboard(&self) -> Result<(), ExpectationFailure> {
        self.driver.hide_keyboard().await
    }

    pub async fn go_back(&self) -> Result<(), ExpectationFailure> {
        self.driver.back().await
    }

    /// Tap at normalized (nx, ny) coordinates — escape hatch for
    /// coord-based maestro yaml port and other no-a11y-semantic
    /// scenarios. (nx, ny) MUST be in [0, 1] (normalized to viewport).
    ///
    /// **§9 #3 lift (v3.16, escape hatch)**: the Selector surface still
    /// forbids xpath/coord — this method is NOT a Selector, it is the
    /// direct Apple-native-event-chain wire entry. Only `tap` is exposed;
    /// `swipe_at_coord` / `fill_at_coord` / `anchor_at_coord` are
    /// intentionally NOT provided and would require an independent
    /// CLAUDE.md §10 decision.
    ///
    /// Prefer `tap(&selector)` for any path with a11y semantic. Use this
    /// only for yaml-port edge cases (e.g. maestro `point: "X%,Y%"`).
    pub async fn tap_at_coord(&self, nx: f64, ny: f64) -> Result<(), ExpectationFailure> {
        self.ledger.record_tap_at_coord(now_ms(), nx, ny);
        self.driver.tap_at_norm_coord(nx, ny).await
    }

    /// Tap via `XCUIElement.tap()` over the XCTest gesture-recognizer
    /// chain instead of the default host-HID-at-coord path. The id
    /// selector is resolved runner-side via
    /// `XCUIApplication.descendants(matching: .any)
    /// .matching(identifier:).firstMatch.tap()`.
    ///
    /// **Why this exists**: SwiftUI `.sheet` / `.alert` /
    /// `.confirmationDialog` / `.fullScreenCover` dismiss buttons
    /// present in a separate modal window scene. The default
    /// `tap(&selector)` resolves the button frame and injects an IOKit
    /// event at that coord, but iOS routes the touch to the underlying
    /// scene's hit-target, so SwiftUI's onTap closure for the
    /// modal-window button never fires. `XCUIElement.tap()` operates on
    /// the resolved element handle and reaches the binding regardless
    /// of window topology.
    ///
    /// Use `tap(&selector)` for everything else — the default path is faster
    /// and works on non-modal SwiftUI / UIKit hierarchies.
    pub async fn tap_xcui(&self, id: &str) -> Result<(), ExpectationFailure> {
        self.ledger
            .record_tap(now_ms(), Some(format!("tap_xcui id={id}")));
        self.driver.tap_by_id(id).await
    }

    /// Apple Vision OCR find. Returns the matching text observation's
    /// bounding box (UIKit normalized) or `None`. `locales` are BCP-47
    /// language subtags; empty defaults to the SDK's current locale
    /// (`["en"]` if unset). Covers "lib without testID but with
    /// visible text" scenarios.
    ///
    /// Find a selector's centroid as viewport-normalized `(nx, ny)`.
    /// Used by adapter AnchorRelative dispatch. Returns `None` when
    /// the selector resolves no node / empty frame.
    pub async fn find_norm_coord(
        &self,
        selector: &Selector,
    ) -> Result<Option<(f64, f64)>, ExpectationFailure> {
        self.driver.find_norm_coord(selector).await
    }

    /// Eval JS against the app-side WKWebView bridge. Returns the JS
    /// result as a JSON Value. Bridge must be running in the target app.
    pub async fn webview_eval(&self, js: &str) -> Result<serde_json::Value, ExpectationFailure> {
        self.driver.webview_eval(js).await
    }

    pub async fn find_by_text_ocr(
        &self,
        text: &str,
        locales: &[String],
    ) -> Result<Option<OcrFrame>, ExpectationFailure> {
        let owned_default;
        let locales_slice: &[String] = if locales.is_empty() {
            owned_default = vec!["en".to_string()];
            &owned_default
        } else {
            locales
        };
        self.driver
            .find_text_by_ocr(text, locales_slice, "accurate")
            .await
    }

    /// Find by OCR + tap at frame center via IOHID synthesize.
    /// Convenience for the common OCR fallback path (OCR keyword → tap).
    /// Returns `ElementNotFound` when OCR finds no match.
    pub async fn tap_by_text_ocr(
        &self,
        text: &str,
        locales: &[String],
    ) -> Result<(), ExpectationFailure> {
        match self.find_by_text_ocr(text, locales).await? {
            Some(frame) => {
                self.ledger
                    .record_tap(now_ms(), Some(format!("tap_by_text_ocr text={text}")));
                self.driver
                    .tap_at_norm_coord(frame.mid_x(), frame.mid_y())
                    .await
            }
            None => Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::ElementNotFound),
                message: format!("tap_by_text_ocr: OCR found no match for \"{text}\""),
                hint: Some(
                    "Apple Vision OCR returned 0 matching observations; check spelling \
                     / recognition language / surface contrast"
                        .into(),
                ),
                ..Default::default()
            })),
        }
    }

    /// Swipe between two normalized coordinate points — escape hatch for
    /// coord-based maestro yaml port (`swipe: { from: "X%,Y%", to: "X%,Y%" }`).
    /// Both points MUST be in [0, 1].
    ///
    /// **§9 #3 lift (escape hatch)**: companion to
    /// [`Self::tap_at_coord`]. The Selector surface still forbids
    /// xpath/coord — this method is NOT a Selector, it is the direct
    /// Apple-native-event-chain wire entry. Only `tap` and `swipe` coord
    /// forms are exposed; `fill_at_coord` / `anchor_at_coord` /
    /// `hover_at_coord` are intentionally NOT provided and would each
    /// require an independent CLAUDE.md §10 decision.
    pub async fn swipe_at_coord(
        &self,
        from: (f64, f64),
        to: (f64, f64),
    ) -> Result<(), ExpectationFailure> {
        self.ledger.record_swipe_at_coord(now_ms(), from, to);
        self.driver.swipe_at_norm_coord(from, to).await
    }

    /// Viewport scroll one swipe in the given direction — no selector required.
    /// Maps to maestro yaml `scroll:` (bare, no args, defaults to down).
    ///
    /// Implementation: a single normalized-coord swipe from the viewport
    /// center to one edge (sense+act layer). [`Self::scroll`] is the
    /// scroll-until-visible composite and is orthogonal; `scroll_screen`
    /// is a pure act primitive.
    pub async fn scroll_screen(&self, direction: SwipeDirection) -> Result<(), ExpectationFailure> {
        let (from, to) = match direction {
            SwipeDirection::Down => ((0.5, 0.7), (0.5, 0.3)),
            SwipeDirection::Up => ((0.5, 0.3), (0.5, 0.7)),
            SwipeDirection::Left => ((0.7, 0.5), (0.3, 0.5)),
            SwipeDirection::Right => ((0.3, 0.5), (0.7, 0.5)),
        };
        self.swipe_at_coord(from, to).await
    }

    /// Assert that the selector is NOT visible. Dual of
    /// [`Self::assert_visible`]. Maps to maestro yaml `assertNotVisible:`.
    ///
    /// Assertion is a core sense+assertion primitive, not an
    /// adapter-only synthesis. Uses a single non-waiting
    /// [`Self::find`] probe; if the selector matches, raise
    /// `AssertionFailed`.
    /// Wait until the selector is NOT visible. Dual of [`Self::wait_for`].
    /// Polls [`Self::find`] at 250ms intervals; returns Ok the first instant
    /// the element is absent. Returns `AssertionFailed` if the element is
    /// still visible after `timeout` elapses.
    ///
    /// The assertion+sense composite is a core platform capability,
    /// not adapter-only synthesis. Maps to maestro yaml
    /// `extendedWaitUntil: { notVisible: ... , timeout: N }`.
    pub async fn wait_for_not_visible(
        &self,
        selector: &Selector,
        timeout: Duration,
    ) -> Result<(), ExpectationFailure> {
        let start = std::time::Instant::now();
        let poll_interval = Duration::from_millis(250);
        loop {
            if !self.find(selector).await? {
                return Ok(());
            }
            if start.elapsed() >= timeout {
                return Err(ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::AssertionFailed),
                    message: format!(
                        "wait_for_not_visible: element still visible after {}ms — {}",
                        timeout.as_millis(),
                        describe_selector(selector)
                    ),
                    selector: Some(selector.clone()),
                    ..Default::default()
                }));
            }
            tokio::time::sleep(poll_interval).await;
        }
    }

    /// Assert the current sim screenshot matches a recorded baseline
    /// PNG via 64-bit dhash perceptual diff. Maestro
    /// `assertScreenshot: <baseline-path>`.
    ///
    /// **Baseline lifecycle** (same as maestro):
    /// - Baseline missing → write the captured PNG + return
    ///   `Recorded { path }` (auto-record default).
    /// - `SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD=1` env → strict mode:
    ///   missing baseline = `DriverError`.
    /// - Baseline present → dhash(baseline) vs dhash(current) → hamming
    ///   distance; `≤ max_hamming` = `Matched { hamming }`, otherwise
    ///   `AssertionFailed`.
    ///
    /// `max_hamming` typically ≤ 10 (adapter runtime arm pins 5).
    pub async fn assert_screenshot(
        &self,
        baseline_path: &std::path::Path,
        max_hamming: u32,
    ) -> Result<AssertScreenshotOutcome, ExpectationFailure> {
        let png = self.screenshot().await?;
        let strict = std::env::var_os("SMIX_ASSERT_SCREENSHOT_NO_AUTORECORD").is_some();
        assert_screenshot_inner(&png, baseline_path, max_hamming, strict)
    }

    pub async fn assert_not_visible(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        if self.find(selector).await? {
            Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::AssertionFailed),
                message: format!(
                    "expect.toNotBeVisible: element is visible — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                ..Default::default()
            }))
        } else {
            Ok(())
        }
    }

    /// Write `text` to the iOS Simulator device pasteboard via
    /// `xcrun simctl pbcopy <udid>`. Maps to maestro yaml
    /// `setClipboard: "literal"`.
    ///
    /// Clipboard set is a core act primitive. Uses the simctl host-side
    /// path (device-scoped, explicit UDID) rather than the swift sim-side
    /// UIPasteboard wire — [`SimctlClient::pasteboard_set`] already has
    /// a stable wire, no need to add a new swift route.
    pub async fn set_clipboard(&self, text: &str) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .pasteboard_set(udid, text)
            .await
            .map_err(simctl_to_failure)
    }

    /// Read the current iOS Simulator device pasteboard via
    /// `xcrun simctl pbpaste <udid>`. Returns the raw string (may be empty).
    pub async fn get_clipboard(&self) -> Result<String, ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .pasteboard_get(udid)
            .await
            .map_err(simctl_to_failure)
    }

    /// Paste `text` into the currently-focused input field.
    /// Maps maestro yaml `pasteText: "literal"` (text-bearing form) and
    /// bare `- pasteText` (None form, reads current clipboard first).
    ///
    /// Both forms preserve the clipboard side-effect maestro yaml users
    /// implicitly rely on (literal form writes clipboard so the post-flow
    /// pasteboard mirrors the typed text — same as native "paste from
    /// clipboard" UX).
    pub async fn paste_text(&self, text: Option<&str>) -> Result<(), ExpectationFailure> {
        let to_type = match text {
            Some(t) => {
                self.set_clipboard(t).await?;
                t.to_string()
            }
            None => self.get_clipboard().await?,
        };
        self.fill(&focused(), &to_type).await
    }

    /// Double-tap an element. Maps to maestro yaml
    /// `doubleTapOn: <selector>`. Backed by XCUIElement.doubleTap() on
    /// the swift sim side.
    pub async fn double_tap(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        self.ledger.record_tap(
            now_ms(),
            Some(format!("double:{}", describe_selector(selector))),
        );
        self.driver.double_tap(selector, None).await
    }

    /// Long-press an element for `duration`. Maps to maestro yaml
    /// `longPressOn` (optional `duration:` ms, default 500 on the
    /// adapter side). Backed by XCUIElement.press(forDuration:) on
    /// the swift sim side.
    pub async fn long_press(
        &self,
        selector: &Selector,
        duration: Duration,
    ) -> Result<(), ExpectationFailure> {
        self.ledger.record_tap(
            now_ms(),
            Some(format!(
                "longpress({}ms):{}",
                duration.as_millis(),
                describe_selector(selector)
            )),
        );
        self.driver.long_press(selector, duration, None).await
    }

    /// Set sim location. Maestro `setLocation: { latitude, longitude }`.
    pub async fn set_location(
        &self,
        latitude: f64,
        longitude: f64,
    ) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .location_set(udid, latitude, longitude)
            .await
            .map_err(simctl_to_failure)
    }

    /// Interpolate sim location along waypoints. Maestro `travel`.
    /// **Fire-and-return**: simctl injects scenario and returns immediately;
    /// sim continues interpolation in background. Caller must explicitly
    /// `waitForAnimationToEnd` / sleep if downstream logic depends on
    /// playback completion.
    pub async fn travel(
        &self,
        points: &[(f64, f64)],
        speed_mps: Option<f64>,
    ) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .location_start(udid, points, speed_mps)
            .await
            .map_err(simctl_to_failure)
    }

    /// Add photos / videos / contacts to the sim library. Maestro
    /// `addMedia: <path>` (scalar) or `addMedia: [paths]` (array;
    /// adapter flattens to Vec).
    pub async fn add_media(&self, paths: &[String]) -> Result<(), ExpectationFailure> {
        let udid = self.require_udid()?;
        self.device
            .add_media(udid, paths)
            .await
            .map_err(simctl_to_failure)
    }

    /// Start recording the sim display to `path`. Maestro
    /// `startRecording: <path>`. Spawns `xcrun simctl io recordVideo` as
    /// a long-running child; returns immediately. Errors if a recording
    /// is already in progress (call `stop_recording` first — no silent
    /// no-op).
    pub async fn start_recording(&self, path: &str) -> Result<(), ExpectationFailure> {
        // Recording state owned by IosDeviceControl (was on App).
        // Trait method returns Result<(), SimctlError>; double-start
        // surfaces as SimctlError::NonZeroExit (mapped here to
        // ExpectationFailure).
        let udid = self.require_udid()?;
        self.device
            .start_recording(udid, std::path::Path::new(path))
            .await
            .map_err(|e| {
                ExpectationFailure::new(FailureInit {
                    code: Some(FailureCode::DriverError),
                    message: format!("start_recording: {e}"),
                    suggestions: vec!["Call stop_recording before starting a new one".to_string()],
                    ..Default::default()
                })
            })
    }

    /// Stop the active recording (SIGINT-and-wait simctl child; flushes
    /// mp4 trailer). Maestro `stopRecording`. Errors if no recording is
    /// active — explicit DriverError + hint, not a silent no-op.
    pub async fn stop_recording(&self) -> Result<(), ExpectationFailure> {
        // Delegate to DeviceControl::stop_recording.
        self.device.stop_recording().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("stop_recording: {e}"),
                suggestions: vec![
                    "Add a `- startRecording: <path>` step before this `stopRecording`".to_string(),
                ],
                ..Default::default()
            })
        })
    }

    /// Rotate sim. Maestro `setOrientation: portrait |
    /// portraitUpsideDown | landscapeLeft | landscapeRight`.
    /// Walks `driver.set_orientation` → POST /set-orientation → swift
    /// `XCUIDevice.shared.orientation`.
    pub async fn set_orientation(
        &self,
        orientation: MaestroOrientation,
    ) -> Result<(), ExpectationFailure> {
        self.driver.set_orientation(orientation.to_driver()).await
    }

    /// Batch permission setter. Maestro `setPermissions: { camera:
    /// allow, location: deny, ... }` (top-level command, distinct from
    /// `launchApp.permissions`). Reuses `set_permission` per entry
    /// (sequential apply; fail-fast on first error).
    pub async fn set_permissions(
        &self,
        bundle_id: &str,
        permissions: &[(SimctlPermission, PermissionAction)],
    ) -> Result<(), ExpectationFailure> {
        for (perm, action) in permissions {
            self.set_permission(bundle_id, *perm, *action).await?;
        }
        Ok(())
    }

    /// Read text content from the matched element and write it to the
    /// device pasteboard. Maps to maestro yaml `copyTextFrom:
    /// <selector>`. Field priority follows the maestro iOS driver:
    /// `value → text → label`. All three empty raises
    /// `AssertionFailed` — no silent no-op.
    pub async fn copy_text_from(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        let node = self.find_one(selector).await?.ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::ElementNotFound),
                message: format!(
                    "copy_text_from: no element matched — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                ..Default::default()
            })
        })?;
        let extracted = node
            .value
            .clone()
            .or_else(|| node.text.clone())
            .or_else(|| node.label.clone())
            .unwrap_or_default();
        if extracted.is_empty() {
            return Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::AssertionFailed),
                message: format!(
                    "copy_text_from: matched element carries no extractable text \
                     (value/text/label all empty) — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                ..Default::default()
            }));
        }
        self.set_clipboard(&extracted).await
    }

    // ---- Capsule helper ----------------------

    /// Start Capsule recording — triggers the UITest runner
    /// `EventRecorder.installSwizzle` registration path (if
    /// `TEST_RUNNER_SMIX_RECORD_ENABLED=1` is set in the env) and
    /// clears the SDK-internal issued-action ledger. **The runner
    /// must be started with `TEST_RUNNER_SMIX_RECORD_ENABLED=1`**;
    /// otherwise swift-side `recordEnabled` is false, `installSwizzle`
    /// is skipped, and `/record/start` returns 404.
    pub async fn start_capsule_recording(&self) -> Result<(), ExpectationFailure> {
        // Capsule recording uses HttpRunnerClient::start_record which
        // is iOS-specific (XCUITest EventRecorder swizzle path).
        // Android impl will use a different mechanism.
        let ios = self.driver.as_ios_driver().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "start_capsule_recording: iOS-only API".into(),
                ..Default::default()
            })
        })?;
        ios.runner().start_record().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("start_record failed: {e}"),
                hint: Some(
                    "ensure the runner was started with TEST_RUNNER_SMIX_RECORD_ENABLED=1".into(),
                ),
                ..Default::default()
            })
        })?;
        self.ledger.clear();
        // start_capsule_recording is itself an SDK-decision-layer act;
        // record it as an anchor so reconciliation attributes any
        // 1018 focus-change events during fixture lifecycle settle
        // (firstResponder reset after swizzle install, etc.) to this
        // action within the window, avoiding spurious unattributed
        // reports.
        self.ledger.record_capsule_start(now_ms());
        Ok(())
    }

    /// Stop recording and reconcile. `window_ms = None` uses
    /// [`DEFAULT_RECONCILE_WINDOW_MS`] (500 ms). Returned
    /// [`CapsuleReconciliation`] includes the full
    /// `unattributed_events` detail.
    pub async fn stop_capsule_recording_and_reconcile(
        &self,
        window_ms: Option<u64>,
    ) -> Result<CapsuleReconciliation, ExpectationFailure> {
        // iOS-only via Driver::as_ios_driver downcast.
        let ios = self.driver.as_ios_driver().ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: "stop_capsule_recording_and_reconcile: iOS-only API".into(),
                ..Default::default()
            })
        })?;
        let events = ios.runner().stop_record().await.map_err(|e| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::DriverError),
                message: format!("stop_record failed: {e}"),
                ..Default::default()
            })
        })?;
        let issued = self.ledger.get_all();
        Ok(reconcile(
            &issued,
            &events,
            window_ms.unwrap_or(DEFAULT_RECONCILE_WINDOW_MS),
        ))
    }

    pub async fn foreground(&self, bundle_id: &str) -> Result<(), ExpectationFailure> {
        self.driver.foreground(bundle_id).await
    }

    pub async fn wait_for(
        &self,
        selector: &Selector,
        timeout: Duration,
    ) -> Result<A11yNode, ExpectationFailure> {
        self.driver.wait_for(selector, timeout, None).await
    }

    // ---- assertion matchers -------------------------------------------

    /// Assert that the selector matches a visible element. Re-uses
    /// `wait_for` semantics (5s default budget) with `NotVisible`
    /// failure code.
    pub async fn assert_visible(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        match self
            .driver
            .wait_for(selector, Duration::from_secs(5), None)
            .await
        {
            Ok(_) => Ok(()),
            Err(e) if e.code == FailureCode::Timeout => Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::NotVisible),
                message: format!(
                    "expect.toBeVisible: not visible — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                visible_elements: e.visible_elements,
                suggestions: e.suggestions,
                ..Default::default()
            })),
            Err(e) => Err(e),
        }
    }

    /// Assert that the matched element has `enabled = true`.
    pub async fn assert_enabled(&self, selector: &Selector) -> Result<(), ExpectationFailure> {
        let node = self.driver.find_one(selector, None).await?.ok_or_else(|| {
            ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::ElementNotFound),
                message: format!(
                    "expect.toBeEnabled: not found — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                ..Default::default()
            })
        })?;
        if !node.enabled {
            return Err(ExpectationFailure::new(FailureInit {
                code: Some(FailureCode::NotEnabled),
                message: format!(
                    "expect.toBeEnabled: disabled — {}",
                    describe_selector(selector)
                ),
                selector: Some(selector.clone()),
                ..Default::default()
            }));
        }
        Ok(())
    }

    /// Assert that the screen contains at least one element whose text /
    /// label / 6-field OR scan matches the literal. Useful for "page
    /// rendered" smoke checks without crafting a full selector tree.
    pub async fn assert_text(&self, literal: &str) -> Result<(), ExpectationFailure> {
        self.assert_visible(&text(literal)).await
    }
}

// -------------------- error mapping -----------------------------------

fn simctl_to_failure(e: SimctlError) -> ExpectationFailure {
    let (code, hint) = match &e {
        SimctlError::Spawn(_) => (
            FailureCode::DriverError,
            Some("xcrun not found — install Xcode command-line tools".into()),
        ),
        SimctlError::NonZeroExit { .. } => (FailureCode::DriverError, None),
        SimctlError::Malformed { .. } => (FailureCode::DriverError, None),
        SimctlError::Timeout { ms, .. } => (
            FailureCode::Timeout,
            Some(format!("subprocess timeout after {ms}ms")),
        ),
        SimctlError::CaptureBackpressure { retry_after } => (
            FailureCode::DriverError,
            Some(format!(
                "screenshot pacer circuit open — SimRenderServer under load; retry after {}ms",
                retry_after.as_millis()
            )),
        ),
    };
    ExpectationFailure::new(FailureInit {
        code: Some(code),
        message: format!("{e}"),
        hint,
        ..Default::default()
    })
}