smix-cli 2.0.0

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

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Persisted handle for the host-side xcodebuild process.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunnerState {
    pub pid: u32,
    pub udid: String,
    pub port: u16,
    pub log: PathBuf,
    /// Target bundle the runner's XCUIApplication is bound to (None =
    /// runner default, com.apple.Preferences).
    #[serde(default)]
    pub bundle: Option<String>,
    /// Pid of the supervisor sidecar spawned when `runner up`
    /// was invoked with `--supervise`. `None` means no sidecar was
    /// started. `runner down` cascades a SIGTERM to this pid before
    /// tearing down xcodebuild.
    #[serde(default)]
    pub supervisor_pid: Option<u32>,
}

/// Env pairs for the xcodebuild process. Xcode forwards `TEST_RUNNER_*`
/// variables into the XCUITest runner process (prefix stripped); a
/// positional `NAME=VALUE` arg would be a build setting and never reach
/// the runner.
///
/// `record_enabled` sets `TEST_RUNNER_SMIX_RECORD_ENABLED=1`, which
/// activates the swift `EventRecorder.installSwizzle` path plus the
/// `/record/*` routes. The capsule bring-up sets this to true; the
/// bare `smix runner up` path leaves it false for backward compat.
///
/// `port` is forwarded via `TEST_RUNNER_SMIX_RUNNER_PORT=<port>` so
/// Xcode surfaces `SMIX_RUNNER_PORT` inside the swift runner process
/// and its `RunnerPortResolver` binds FlyingFox to the requested port.
/// This is what lets multiple concurrent runners share one host
/// without colliding on the default 22087 port.
pub fn runner_env(
    bundle: Option<&str>,
    record_enabled: bool,
    port: u16,
    attach_without_relaunch: bool,
) -> Vec<(String, String)> {
    let mut env = Vec::new();
    // `XCUIApplication.activate()` foregrounds an app that is already
    // running instead of restarting it, and still starts one that is
    // not — which is what "attach" has to mean for a consumer who
    // navigated somewhere before bringing the runner up. The runner has
    // resolved this mode since `LaunchModeResolver` was written; until
    // now nothing set the variable, so `launch` was the only reachable
    // behaviour.
    if attach_without_relaunch {
        env.push((
            "TEST_RUNNER_SMIX_RUNNER_LAUNCH_MODE".to_string(),
            "activate".to_string(),
        ));
    }
    if let Some(b) = bundle {
        env.push((
            "TEST_RUNNER_SMIX_RUNNER_TARGET_BUNDLE".to_string(),
            b.to_string(),
        ));
    }
    if record_enabled {
        env.push((
            "TEST_RUNNER_SMIX_RECORD_ENABLED".to_string(),
            "1".to_string(),
        ));
    }
    env.push(("TEST_RUNNER_SMIX_RUNNER_PORT".to_string(), port.to_string()));
    // Forward the CLI's compile-time version to the runner so
    // `HealthRoute.responseDetail` can echo it back on `GET /health`.
    // Rust `env!("CARGO_PKG_VERSION")` inside the CLI binary matches
    // `smix-runner-sources::SOURCES_VERSION` because the workspace pins
    // them together. The client then compares this echo against its own
    // CARGO_PKG_VERSION and refuses boot on mismatch — without this,
    // CLI-vs-runner drift makes CLI patches silently no-op against
    // stale Swift sources.
    env.push((
        "TEST_RUNNER_SMIX_RUNNER_VERSION".to_string(),
        env!("CARGO_PKG_VERSION").to_string(),
    ));
    // Forward `.smix/config.yaml interactiveProbe:` (JSON-encoded) to
    // the runner so the `launchApp` handler's interactive-fingerprint
    // probe knows the configured minIdentifierCount + ignore-list.
    // Missing config → env unset → Swift falls back to bundled
    // defaults.
    if let Some(json) = load_interactive_probe_env() {
        env.push(("TEST_RUNNER_SMIX_INTERACTIVE_PROBE_JSON".to_string(), json));
    }
    env
}

/// Read `.smix/config.yaml` looking for the `interactiveProbe:` key.
/// Returns a JSON-encoded string when present, `None` when file absent
/// OR key absent OR file unreadable. The runner side falls back to
/// bundled defaults in either case.
///
/// Yaml → JSON conversion goes via `serde_norway` into a
/// `serde_json::Value` — deliberately no explicit schema on this
/// crate's side, so the `interactiveProbe` mapping can grow without
/// smix-cli needing an update.
fn load_interactive_probe_env() -> Option<String> {
    let root = workspace_root(&std::env::current_dir().ok()?)?;
    let root_value = read_config_yaml(&root)?;
    let probe = root_value.get("interactiveProbe")?;
    serde_json::to_string(probe).ok()
}

/// Read `.smix/config.yaml` under `root` as a schemaless
/// `serde_json::Value`. `None` when the file is absent OR unreadable OR
/// not valid yaml. Deliberately no explicit schema so the config can
/// grow keys without smix-cli needing an update — `interactiveProbe`
/// and `switches` both read their slice off the same parsed value.
fn read_config_yaml(root: &Path) -> Option<serde_json::Value> {
    let text = std::fs::read_to_string(root.join(".smix/config.yaml")).ok()?;
    serde_norway::from_str(&text).ok()
}

/// The four v2 behavior switches as declared under `.smix/config.yaml`'s
/// `switches:` block. Each is `None` when the key is absent (schemaless:
/// a missing block or missing/non-bool key leaves the field `None`).
/// `None` means "config said nothing" — the CLI resolver then falls
/// through to the `SMIX_*` env var, then to the default.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SwitchesConfig {
    pub auto_ocr_fallback: Option<bool>,
    pub enable_ai_assertions: Option<bool>,
    pub assert_screenshot_no_autorecord: Option<bool>,
    pub launch_fresh_force_reinstall: Option<bool>,
}

/// Read `.smix/config.yaml`'s `switches:` block from the workspace root
/// anchored at the current dir. A missing file / missing block yields an
/// all-`None` [`SwitchesConfig`].
pub fn load_switches() -> SwitchesConfig {
    std::env::current_dir()
        .ok()
        .and_then(|cwd| workspace_root(&cwd))
        .and_then(|root| read_config_yaml(&root))
        .map(|v| switches_from_value(&v))
        .unwrap_or_default()
}

/// Pull the `switches:` block off an already-parsed config value.
/// Schemaless: each key is read via `Value::as_bool`, so a non-bool or
/// absent key stays `None`.
fn switches_from_value(root: &serde_json::Value) -> SwitchesConfig {
    let block = root.get("switches");
    let get = |key: &str| {
        block
            .and_then(|b| b.get(key))
            .and_then(serde_json::Value::as_bool)
    };
    SwitchesConfig {
        auto_ocr_fallback: get("autoOcrFallback"),
        enable_ai_assertions: get("enableAiAssertions"),
        assert_screenshot_no_autorecord: get("assertScreenshotNoAutorecord"),
        launch_fresh_force_reinstall: get("launchFreshForceReinstall"),
    }
}

/// Where a resolved switch value came from. Drives the CLI's named
/// deprecation warn: only `Env` warns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SwitchSource {
    /// `.smix/config.yaml switches.*` supplied the value.
    Config,
    /// The legacy `SMIX_*` env var supplied it (deprecated → CLI warns).
    Env,
    /// Neither config nor env set it; fell through to the default.
    Default,
}

/// A resolved switch: the effective `bool` plus where it came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedSwitch {
    pub value: bool,
    pub source: SwitchSource,
}

/// Resolve one switch with priority `config > SMIX_* env > default(false)`.
///
/// `config` is the `switches.*` value (from [`load_switches`]); `Some`
/// wins outright. Otherwise the legacy `env_name` is consulted — present
/// (any value) resolves to its truthiness and marks the source `Env` so
/// the CLI can emit a named deprecation warn. Absent env resolves to
/// `false`/`Default`. This resolver is the ONLY place the four `SMIX_*`
/// names are read on the `smix run` / `--check` path; parser and sdk keep
/// their own env reads solely as the non-CLI (`None`-injection) fallback.
pub fn resolve_switch(config: Option<bool>, env_name: &str) -> ResolvedSwitch {
    if let Some(value) = config {
        return ResolvedSwitch {
            value,
            source: SwitchSource::Config,
        };
    }
    match std::env::var(env_name) {
        Ok(raw) => ResolvedSwitch {
            value: matches!(raw.as_str(), "1" | "true" | "TRUE" | "yes"),
            source: SwitchSource::Env,
        },
        Err(_) => ResolvedSwitch {
            value: false,
            source: SwitchSource::Default,
        },
    }
}

/// Walk up from `start` to the directory containing `.smix/` — the smix
/// workspace root (same anchor the sim registry lives under).
pub fn workspace_root(start: &Path) -> Option<PathBuf> {
    let mut dir = Some(start);
    while let Some(d) = dir {
        if d.join(".smix").is_dir() {
            return Some(d.to_path_buf());
        }
        dir = d.parent();
    }
    None
}

/// argv for the runner session (after the `xcodebuild` word itself).
pub fn xcodebuild_argv(project: &Path, udid: &str) -> Vec<String> {
    // Per-udid `-derivedDataPath` avoids DerivedData contention when
    // multiple `capsule up` invocations share the default Xcode
    // DerivedData root (~/Library/Developer/Xcode/DerivedData): the same
    // project + scheme running under two concurrent xcodebuilds hits an
    // "Xcode3CommandLineBuildTool ... operation queue" lock, and the
    // second sim can hang for 5min+ before failing. Isolating each sim
    // under .smix/runner/derived-data-<udid>/ sidesteps the lock.
    let derived = format!(".smix/runner/derived-data-{udid}");
    vec![
        "test".into(),
        "-project".into(),
        project.display().to_string(),
        "-scheme".into(),
        "SmixRunner".into(),
        "-destination".into(),
        format!("platform=iOS Simulator,id={udid}"),
        "-derivedDataPath".into(),
        derived,
    ]
}

/// Bare HTTP GET /health against `localhost:<port>`; true on a 200 line.
pub fn health_ok(port: u16) -> bool {
    read_health_bytes(port, 64)
        .map(|(status_ok, _body)| status_ok)
        .unwrap_or(false)
}

/// Read `runnerVersion` from the `GET /health` body. Returns
/// `Some("<ver>")` when the runner emits the extended body (runners
/// carrying `SmixRunnerServer.swift`'s `responseDetail` wiring);
/// `None` for older runners that still return the legacy `{"ok":true}`
/// shape, or when the socket read failed / the body wasn't parseable
/// JSON. `None` MUST NOT be treated as a version-mismatch — it's the
/// "runner too old to tell me" signal, and the CLI keeps booting.
pub fn health_runner_version(port: u16) -> Option<String> {
    let (ok, body) = read_health_bytes(port, 4096).ok()?;
    if !ok {
        return None;
    }
    // Extract just the JSON body (after the blank line separator).
    let body_start = body
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .map(|i| i + 4)?;
    let json_bytes = &body[body_start..];
    let value: serde_json::Value = serde_json::from_slice(json_bytes).ok()?;
    let v = value.get("runnerVersion")?.as_str()?;
    if v.is_empty() {
        None
    } else {
        Some(v.to_string())
    }
}

/// The wire schemas the running runner says it speaks.
///
/// Empty when the runner predates the question or the read failed — which
/// means "it did not say", not "it speaks none". The two are different and
/// only one of them is a reason to stop.
pub fn health_wire_schemas(port: u16) -> Vec<u32> {
    let Ok((ok, body)) = read_health_bytes(port, 4096) else {
        return Vec::new();
    };
    if !ok {
        return Vec::new();
    }
    let Some(start) = body
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .map(|i| i + 4)
    else {
        return Vec::new();
    };
    let Ok(value) = serde_json::from_slice::<serde_json::Value>(&body[start..]) else {
        return Vec::new();
    };
    value
        .get("wireSchema")
        .and_then(|w| w.get("supports"))
        .and_then(serde_json::Value::as_array)
        .map(|xs| {
            xs.iter()
                .filter_map(serde_json::Value::as_u64)
                .filter_map(|n| u32::try_from(n).ok())
                .collect()
        })
        .unwrap_or_default()
}

/// Shared HTTP GET /health primitive. Returns `(status_is_200, raw_response_bytes)`
/// on connection success, `Err(())` on IO failure. Callers pick apart
/// the byte buffer to answer specific questions.
fn read_health_bytes(port: u16, cap: usize) -> Result<(bool, Vec<u8>), ()> {
    use std::io::{Read, Write};
    use std::net::TcpStream;
    use std::time::Duration;
    let mut s = TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), Duration::from_secs(1))
        .map_err(|_| ())?;
    s.set_read_timeout(Some(Duration::from_secs(2)))
        .map_err(|_| ())?;
    s.write_all(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .map_err(|_| ())?;
    let mut buf = vec![0u8; cap];
    let mut total = 0usize;
    while total < cap {
        match s.read(&mut buf[total..]) {
            Ok(0) => break,
            Ok(n) => total += n,
            Err(_) => break,
        }
    }
    buf.truncate(total);
    let status_ok = std::str::from_utf8(&buf)
        .ok()
        .map(|s| s.contains(" 200"))
        .unwrap_or(false);
    Ok((status_ok, buf))
}

/// Probe a live runner for the in-process soft-cycle and report the
/// outcome. `POST /soft-cycle` asks the surviving XCUITest host to bounce
/// its FlyingFox server (via the in-process restart signal) and rebind
/// the app; a `GET /health` afterwards confirms the server came back on
/// the same port. The whole path costs one app relaunch (~seconds)
/// instead of the ~36 s SIGINT-teardown + xcodebuild respawn a hard cycle
/// pays.
///
/// Only a reachable runner can be soft-cycled: if `/health` does not
/// answer up front the host is dead or wedged and the caller must hard
/// cycle. An older runner that never learned the route answers 404 →
/// [`SoftCycleProbe::Unsupported`], also a hard fallback.
fn try_soft_cycle(port: u16) -> smix_runner_client::SoftCycleProbe {
    use smix_runner_client::SoftCycleProbe;
    if !health_ok(port) {
        return SoftCycleProbe::Unreachable;
    }
    let start = std::time::Instant::now();
    match post_soft_cycle(port) {
        Ok((200, _body)) => {
            // The bounce briefly drops the listening socket; confirm the
            // reborn server answers before declaring recovery.
            if wait_health_back(port, std::time::Duration::from_secs(15)) {
                SoftCycleProbe::Recovered {
                    wall_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
                }
            } else {
                SoftCycleProbe::Failed(
                    "/soft-cycle answered 200 but /health did not return after the bounce"
                        .to_string(),
                )
            }
        }
        Ok((404, _)) | Ok((400, _)) => SoftCycleProbe::Unsupported,
        Ok((status, _)) => SoftCycleProbe::Failed(format!("/soft-cycle returned status {status}")),
        Err(()) => {
            // The response was cut mid-flight. If the server nonetheless
            // came back, the bounce did happen — treat it as recovered;
            // otherwise it genuinely failed.
            if wait_health_back(port, std::time::Duration::from_secs(15)) {
                SoftCycleProbe::Recovered {
                    wall_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
                }
            } else {
                SoftCycleProbe::Failed(
                    "/soft-cycle connection dropped and /health did not return".to_string(),
                )
            }
        }
    }
}

/// `POST /soft-cycle` over raw loopback TCP. Returns `(status, body)`.
/// The read timeout is generous because the handler performs the app
/// relaunch before it writes the response.
fn post_soft_cycle(port: u16) -> Result<(u16, Vec<u8>), ()> {
    use std::io::{Read, Write};
    use std::net::TcpStream;
    use std::time::Duration;
    let mut s = TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), Duration::from_secs(2))
        .map_err(|_| ())?;
    s.set_read_timeout(Some(Duration::from_secs(30)))
        .map_err(|_| ())?;
    s.write_all(b"POST /soft-cycle HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
        .map_err(|_| ())?;
    let mut buf = Vec::with_capacity(512);
    s.read_to_end(&mut buf).map_err(|_| ())?;
    if buf.is_empty() {
        return Err(());
    }
    let status = parse_http_status(&buf).ok_or(())?;
    Ok((status, buf))
}

/// Parse the numeric status from an HTTP response's status line
/// (`HTTP/1.1 200 OK`).
fn parse_http_status(buf: &[u8]) -> Option<u16> {
    let line_end = buf
        .windows(2)
        .position(|w| w == b"\r\n")
        .unwrap_or(buf.len());
    let line = std::str::from_utf8(&buf[..line_end]).ok()?;
    line.split_whitespace().nth(1)?.parse::<u16>().ok()
}

/// Poll `GET /health` until it answers 200 or the deadline passes.
fn wait_health_back(port: u16, timeout: std::time::Duration) -> bool {
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if health_ok(port) {
            return true;
        }
        if std::time::Instant::now() >= deadline {
            return false;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
}

/// Forget the iOS runner record. Reported rather than discarded: a
/// stale record makes the next `up` believe a runner is already there.
fn clear_state(root: &Path) {
    if let Err(e) = crate::runner_state::clear(root, crate::runner_state::Platform::Ios) {
        eprintln!("runner: {e}");
    }
}

/// The iOS runner's record. `None` is "no runner"; a record that
/// cannot be read is reported, not swallowed — the `.ok()?` this
/// replaces turned a damaged record into "no runner", and `up` would
/// then start a second one beside the first.
fn read_state(root: &Path) -> Option<RunnerState> {
    match crate::runner_state::read(root, crate::runner_state::Platform::Ios) {
        Ok(state) => state,
        Err(e) => {
            eprintln!("runner: {e}");
            None
        }
    }
}

/// `ps -p <pid> -o command=` — None if the pid is gone.
fn pid_command(pid: u32) -> Option<String> {
    let out = std::process::Command::new("ps")
        .args(["-p", &pid.to_string(), "-o", "command="])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let cmd = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if cmd.is_empty() { None } else { Some(cmd) }
}

fn signal(pid: u32, sig: &str) {
    let _ = std::process::Command::new("kill")
        .args([sig, &pid.to_string()])
        .status();
}

fn tail_log(log: &Path, lines: usize) -> String {
    let Ok(text) = std::fs::read_to_string(log) else {
        return String::new();
    };
    let all: Vec<&str> = text.lines().collect();
    let start = all.len().saturating_sub(lines);
    all[start..].join("\n")
}

/// Resolve the SmixRunner.xcodeproj path via a 4-step cascade. First
/// match wins:
///
/// 1. `override` — explicit `--runner-project <path>` from CLI. Wins.
/// 2. `$SMIX_RUNNER_PROJECT` env — semi-explicit.
/// 3. Install-shipped default (with auto-sync — see below):
///    - `$XDG_DATA_HOME/smix/runner/` when set
///    - `~/.local/share/smix/runner/` (macOS + Linux XDG fallback)
/// 4. `<root>/swift-bridge/SmixRunner.xcodeproj` — smix-dev-repo fallback
///    so `cd smix; cargo run --bin smix -- runner up ...` still works
///    from a fresh checkout.
///
/// The install-shipped step is auto-syncing. Before returning the
/// install-shipped path, we compare the on-disk version file
/// (`~/.local/share/smix/runner/.smix-runner-version`) against the CLI
/// version. On drift OR missing, we extract the embedded
/// `smix-runner-sources` tarball, preserving the previous tree as a
/// timestamped backup. Without this, `cargo install smix` would ship
/// only the Rust binary and the Swift runner project would silently
/// stay frozen at whatever revision first landed on disk.
///
/// Returns the first existing path, or the last candidate's error
/// (which prints as "runner project missing: `<path>`") so users see the
/// most-likely-intended location.
pub fn resolve_runner_project(
    root: &Path,
    override_path: Option<&Path>,
) -> Result<PathBuf, String> {
    // Explicit override (either --runner-project or $SMIX_RUNNER_PROJECT)
    // is a *strict* override: if set, that path MUST exist; we do NOT
    // silently fall back. This matches unix `--config` conventions —
    // when a user tells you where to look, believe them.
    let explicit_flag = override_path.map(Path::to_path_buf);
    let explicit_env = std::env::var_os("SMIX_RUNNER_PROJECT").map(PathBuf::from);
    if let Some(p) = explicit_flag.or(explicit_env) {
        if p.exists() {
            return Ok(p);
        }
        return Err(format!(
            "runner project missing: {}\n\
             explicit override (--runner-project or $SMIX_RUNNER_PROJECT) \
             does not point to an existing SmixRunner.xcodeproj — \
             fix the path, or unset the override to fall back to \
             install-shipped / repo-local defaults.",
            p.display()
        ));
    }

    // Auto-sync install-shipped sources on version drift. Runs before
    // the existence check so a first-run consumer with an
    // empty ~/.local/share/smix/ gets sources extracted transparently.
    if let Some(installed_dir) = installed_runner_dir() {
        match ensure_installed_runner_synced(&installed_dir) {
            Ok(SyncOutcome::AlreadyCurrent) => {}
            Ok(SyncOutcome::Extracted {
                previous_version, ..
            }) => {
                let from = previous_version.as_deref().unwrap_or("<none>");
                eprintln!(
                    "smix-runner: synced runner sources → {} (was {}) at {}",
                    smix_runner_sources::SOURCES_VERSION,
                    from,
                    installed_dir.display()
                );
            }
            Err(err) => {
                // Don't fail the whole resolve — fall through to the
                // repo-local candidate. A dev running from the repo
                // still works; a consumer without $HOME hits the same
                // "runner project missing" error they'd have hit before
                // auto-sync existed.
                eprintln!(
                    "smix-runner: auto-sync failed at {}: {err}",
                    installed_dir.display()
                );
            }
        }
    }

    // No explicit override — try install-shipped, then repo-local.
    let candidates: Vec<PathBuf> = std::iter::empty()
        .chain(installed_runner_project())
        .chain(std::iter::once(
            root.join("swift-bridge/SmixRunner.xcodeproj"),
        ))
        .collect();

    for cand in &candidates {
        if cand.exists() {
            return Ok(cand.clone());
        }
    }

    let last = candidates
        .last()
        .cloned()
        .unwrap_or_else(|| PathBuf::from("<no candidates — this should not happen>"));
    let attempted = candidates
        .iter()
        .map(|p| format!("  - {}", p.display()))
        .collect::<Vec<_>>()
        .join("\n");
    Err(format!(
        "runner project missing: {}\n\
         tried:\n{attempted}\n\
         fix: (a) `smix runner install` to populate ~/.local/share/smix/runner/, \
         or (b) pass `--runner-project <path>` on `smix runner up`, \
         or (c) set $SMIX_RUNNER_PROJECT",
        last.display()
    ))
}

/// Install-shipped runner *project* path — the SmixRunner.xcodeproj
/// under [`installed_runner_dir`]. Returns `None` when `$HOME` is unset.
fn installed_runner_project() -> Option<PathBuf> {
    installed_runner_dir().map(|d| d.join("SmixRunner.xcodeproj"))
}

/// Install-shipped runner *directory* (parent of SmixRunner.xcodeproj).
/// Follows XDG basedir when `$XDG_DATA_HOME` is set; falls back to
/// `~/.local/share/smix/runner/` on macOS + Linux. Returns `None` when
/// `$HOME` is unset (rare).
pub(crate) fn installed_runner_dir() -> Option<PathBuf> {
    let base = std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))?;
    Some(base.join("smix/runner"))
}

/// Outcome of an [`ensure_installed_runner_synced`] call.
#[derive(Debug)]
pub(crate) enum SyncOutcome {
    /// The on-disk `.smix-runner-version` already matched the CLI
    /// version — no extract performed.
    AlreadyCurrent,
    /// Sources were extracted. Callers should emit an info banner.
    Extracted {
        /// Version string previously on disk (if any).
        previous_version: Option<String>,
        /// Backup path where the previous tree was moved, `None` when
        /// the destination was empty.
        #[allow(dead_code)]
        backup: Option<PathBuf>,
    },
}

/// Ensure `dir` contains runner sources whose `.smix-runner-version`
/// matches the CLI's [`smix_runner_sources::SOURCES_VERSION`]. Extracts
/// the embedded tarball on mismatch or missing, backing up any prior
/// contents. Idempotent: a second call with the same version is a
/// cheap file read.
///
/// This is what keeps the Swift sources in step with the CLI: they are
/// baked into the CLI binary and re-materialise on every `smix runner
/// up` when the CLI version has moved forward (typically after
/// `cargo install smix` / `brew upgrade smix`).
pub(crate) fn ensure_installed_runner_synced(
    dir: &Path,
) -> Result<SyncOutcome, smix_runner_sources::ExtractError> {
    let previous = smix_runner_sources::read_installed_version(dir)?;
    if previous.as_deref() == Some(smix_runner_sources::SOURCES_VERSION) {
        return Ok(SyncOutcome::AlreadyCurrent);
    }
    // Version drift OR missing → extract with force. `force=true` is
    // safe: extract_to backs up any existing tree to a timestamped
    // sibling directory before writing, so a consumer's local
    // modifications (rare — the install dir is meant to be
    // CLI-managed) are preserved for post-mortem inspection.
    let report = smix_runner_sources::extract_to(dir, true)?;
    Ok(SyncOutcome::Extracted {
        previous_version: previous,
        backup: report.backup,
    })
}

/// What `runner up` should do beyond starting the process.
///
/// These were trailing positional bools; a third one would have made
/// `up(_, _, _, _, false, _, false, true)` the call site.
#[derive(Clone, Copy, Debug, Default)]
pub struct UpOptions {
    /// Let the runner record events (`capsule up` wants this; bare
    /// `runner up` does not).
    pub record_enabled: bool,
    /// Spawn the `runner supervise` sidecar once `/health` answers.
    pub supervise: bool,
    /// Foreground the target app instead of relaunching it.
    ///
    /// Bringing the runner up restarts the app, which drops whatever
    /// screen had been navigated to — and then reports the next flow's
    /// failure as `ELEMENT_NOT_FOUND` against a splash screen.
    pub attach_without_relaunch: bool,
}

/// Bring the runner up on `udid`. Blocks until `/health` answers 200 or
/// the timeout (env `SMIX_RUNNER_UP_TIMEOUT_SECS`, default 300 — first
/// run includes a full Swift build) expires.
///
/// `runner_project` — optional explicit path to `SmixRunner.xcodeproj`.
/// When `None`, uses [`resolve_runner_project`] cascade against `root`.
///
/// With `opts.supervise`, after `/health` returns 200 spawn a detached
/// `smix runner supervise` process, record its pid in state.json, and
/// return. `runner down` cascades a SIGTERM to that pid before tearing
/// down xcodebuild.
pub fn up(
    root: &Path,
    udid: &str,
    port: u16,
    bundle: Option<&str>,
    runner_project: Option<&Path>,
    opts: UpOptions,
) -> Result<(), String> {
    let UpOptions {
        record_enabled,
        supervise,
        attach_without_relaunch,
    } = opts;
    // Refuse to boot without --bundle unless the caller explicitly
    // opts in via SMIX_RUNNER_UP_ALLOW_DEFAULT_BUNDLE=1. The runner's
    // built-in default `com.apple.Preferences` silently latches every
    // `/tree` call to Preferences and every `takeScreenshot` to the
    // wrong app, which surfaces as baffling "empty tree" results —
    // so it's explicit-or-error.
    match bundle {
        Some(b) => {
            println!("[runner] target bundle-id: {b}");
        }
        None => {
            let bypass = std::env::var("SMIX_RUNNER_UP_ALLOW_DEFAULT_BUNDLE")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false);
            if !bypass {
                return Err("no --bundle passed; the runner would latch to the \
                     built-in default (com.apple.Preferences) and every \
                     subsequent /tree call would report Preferences as the \
                     app.\n\n\
                     fix: pass --bundle <your-app-bundle-id>, e.g.\n\
                       smix runner up <device> --bundle com.example.app\n\n\
                     to keep the legacy default (v1.0.3 behavior), export\n\
                       SMIX_RUNNER_UP_ALLOW_DEFAULT_BUNDLE=1\n\
                     — but expect empty a11y trees until you re-attach a \
                     real target."
                    .to_string());
            }
            eprintln!(
                "[runner] warning: no --bundle passed and \
                 SMIX_RUNNER_UP_ALLOW_DEFAULT_BUNDLE=1 set; latching to \
                 default com.apple.Preferences"
            );
        }
    }
    if health_ok(port) {
        match read_state(root) {
            Some(st) if st.udid == udid && st.bundle.as_deref() == bundle => {
                println!("runner already up: udid={udid} port={port} pid={}", st.pid);
                return Ok(());
            }
            Some(st) => {
                return Err(format!(
                    "port {port} already serves a runner recorded for udid={} \
                     bundle={:?} — run `smix runner down` first",
                    st.udid, st.bundle
                ));
            }
            None => {
                return Err(format!(
                    "port {port} already serves /health but the store has no \
                     record of that runner — not killing blindly; investigate \
                     (pgrep -fl xcodebuild), then `smix runner down`"
                ));
            }
        }
    }

    let project = resolve_runner_project(root, runner_project)?;
    let runner_dir = root.join(".smix/runner");
    std::fs::create_dir_all(&runner_dir).map_err(|e| format!("mkdir .smix/runner: {e}"))?;
    let log = runner_dir.join(format!("runner-{udid}.log"));
    let log_file =
        std::fs::File::create(&log).map_err(|e| format!("create {}: {e}", log.display()))?;
    let log_err = log_file
        .try_clone()
        .map_err(|e| format!("clone log handle: {e}"))?;

    let mut cmd = std::process::Command::new("xcodebuild");
    cmd.args(xcodebuild_argv(&project, udid))
        .envs(runner_env(
            bundle,
            record_enabled,
            port,
            attach_without_relaunch,
        ))
        .stdin(std::process::Stdio::null())
        .stdout(log_file)
        .stderr(log_err);
    // Own process group so the session outlives this CLI invocation and a
    // ctrl-C on smix doesn't tear the runner down implicitly.
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    let mut child = cmd.spawn().map_err(|e| format!("spawn xcodebuild: {e}"))?;
    let pid = child.id();

    let st = RunnerState {
        pid,
        udid: udid.to_string(),
        port,
        log: log.clone(),
        bundle: bundle.map(str::to_string),
        supervisor_pid: None,
    };
    crate::runner_state::write(root, crate::runner_state::Platform::Ios, &st)?;

    let timeout_secs: u64 = std::env::var("SMIX_RUNNER_UP_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(300);
    // Detect cold vs warm rebuild by inspecting whether the per-udid
    // derived-data dir is already populated. Cold rebuilds after a
    // version bump can take 5-10 min (full swift stdlib copy + linker +
    // code sign). Print an explicit banner so callers know to budget the
    // wait and don't set a spawnSync timeout too aggressively.
    let derived_dir = root.join(format!(".smix/runner/derived-data-{udid}"));
    let is_cold = !derived_dir.is_dir()
        || std::fs::read_dir(&derived_dir)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true);
    if is_cold {
        println!(
            "runner starting: udid={udid} port={port} pid={pid} \
             — COLD REBUILD expected up to 10 minutes (first run after \
             upgrade compiles the XCUITest bundle for smix {}). \
             Log: {}. Timeout {timeout_secs}s.",
            env!("CARGO_PKG_VERSION"),
            log.display()
        );
    } else {
        println!(
            "runner starting: udid={udid} port={port} pid={pid} \
             (warm rebuild ~3 s expected; log {}, timeout {timeout_secs}s)",
            log.display()
        );
    }
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
    // Heartbeat every 30 s during a cold rebuild so anyone watching
    // stdout sees progress instead of a stall.
    let started_at = std::time::Instant::now();
    let mut last_heartbeat = started_at;
    while std::time::Instant::now() < deadline {
        if is_cold && last_heartbeat.elapsed() >= std::time::Duration::from_secs(30) {
            let elapsed_s = started_at.elapsed().as_secs();
            println!("runner up: xcodebuild still working ({elapsed_s}s elapsed)");
            use std::io::Write;
            let _ = std::io::stdout().flush();
            last_heartbeat = std::time::Instant::now();
        }
        if let Ok(Some(status)) = child.try_wait() {
            clear_state(root);
            return Err(format!(
                "xcodebuild exited early ({status}) — log tail:\n{}",
                tail_log(&log, 25)
            ));
        }
        if health_ok(port) {
            // Version-mismatch gate. Ask the runner what version it
            // thinks it is; if it disagrees with the CLI, refuse boot
            // with an actionable message. This is the last line of
            // defense against CLI-vs-runner drift silently no-oping CLI
            // patches — if `ensure_installed_runner_synced` failed for
            // any reason (unwritable XDG dir, custom
            // SMIX_RUNNER_PROJECT, stale supervisor cache), this check
            // catches it before the user runs into a mysterious 404.
            let cli_version = env!("CARGO_PKG_VERSION");
            // Ask about the wire before asking about the version. A runner
            // that has been up across a CLI upgrade is not a problem unless
            // the shape between them moved, and demanding identical semvers
            // called every such runner broken.
            let theirs = health_wire_schemas(port);
            if !theirs.is_empty() {
                match smix_runner_wire::negotiate_wire_schema(
                    smix_runner_wire::WIRE_SCHEMA_SUPPORTED,
                    &theirs,
                ) {
                    Some(schema) => {
                        let v = health_runner_version(port).unwrap_or_default();
                        println!(
                            "runner up: http://localhost:{port}/health = 200 \
                             (runner v{v}, wire schema {schema})"
                        );
                        return Ok(());
                    }
                    None => {
                        clear_state(root);
                        signal(pid, "-TERM");
                        let ours = smix_runner_wire::WIRE_SCHEMA_SUPPORTED;
                        return Err(format!(
                            "no wire schema in common: this CLI speaks {ours:?} and the \
                             running SmixRunner speaks {theirs:?}. Nothing they could say \
                             to each other would mean the same thing. Fix: \
                             `smix runner install --force` to re-extract the runner \
                             sources this CLI ships with, then retry `smix runner up`."
                        ));
                    }
                }
            }
            match health_runner_version(port) {
                Some(v) if v == cli_version => {
                    println!("runner up: http://localhost:{port}/health = 200 (runner v{v})");
                }
                Some(v) => {
                    clear_state(root);
                    signal(pid, "-TERM");
                    return Err(format!(
                        "runner version mismatch: CLI is v{cli_version} but the \
                         running SmixRunner reports v{v}. This means the on-disk \
                         runner project used by xcodebuild is out of sync with the \
                         installed CLI — the v1.0.4-v1.0.9 distribution gap the \
                         v1.0.10 auto-sync closes. Fix: `smix runner install --force` \
                         to re-extract the embedded runner sources, then retry \
                         `smix runner up`. If you're using an explicit \
                         --runner-project / $SMIX_RUNNER_PROJECT, either update \
                         that path to a v{cli_version} runner or drop the override."
                    ));
                }
                None => {
                    // Older runner (legacy `{\"ok\":true}` body).
                    // Don't refuse boot — that would break every user
                    // who has an older runner they haven't re-installed.
                    // Warn instead. On next `runner install`/upgrade the
                    // warning goes away.
                    eprintln!(
                        "runner up: warning — runner /health returned legacy body \
                         (no `runnerVersion` field). This runner predates v1.0.10 \
                         and cannot self-report its version. If you see missing \
                         routes (e.g. `/session/open` 404), run \
                         `smix runner install --force` to sync sources to v{cli_version}."
                    );
                    println!("runner up: http://localhost:{port}/health = 200 (legacy body)");
                }
            }
            // Sidecar mode.
            if supervise {
                match spawn_supervisor(root, runner_project) {
                    Ok(sup_pid) => {
                        // Rewrite state.json with the supervisor pid.
                        if let Some(mut current) = read_state(root) {
                            current.supervisor_pid = Some(sup_pid);
                            // Not discarded: losing the supervisor pid
                            // means `runner down` never cascades SIGTERM
                            // to the sidecar, and the sidecar outlives
                            // the runner it was watching.
                            if let Err(e) = crate::runner_state::write(
                                root,
                                crate::runner_state::Platform::Ios,
                                &current,
                            ) {
                                eprintln!("runner supervise: {e}");
                            }
                            println!(
                                "runner supervise: spawned pid={sup_pid} \
                                 (log: .smix/runner/supervise-{udid}.log)"
                            );
                        }
                    }
                    Err(e) => {
                        eprintln!(
                            "runner supervise: spawn failed: {e} — runner \
                             is up but no sidecar attached"
                        );
                    }
                }
            }
            return Ok(());
        }
        std::thread::sleep(std::time::Duration::from_secs(2));
    }
    signal(pid, "-INT");
    clear_state(root);
    Err(format!(
        "runner did not become healthy within {timeout_secs}s — sent SIGINT; log tail:\n{}",
        tail_log(&log, 25)
    ))
}

/// Tear the runner down. SIGINT first — xcodebuild cancels the XCUITest
/// session cleanly via testmanagerd; a hard kill SIGABRTs the runner app
/// and macOS pops a crash-report dialog that steals user focus.
///
/// If state.json records a supervisor pid, cascade a SIGTERM to it
/// BEFORE tearing down xcodebuild. Otherwise the sidecar
/// would flap into a `TEST INTERRUPTED` trigger the moment we send
/// SIGINT to xcodebuild and try to re-cycle a runner we just killed.
pub fn down(root: &Path, port: u16) -> Result<(), String> {
    let mut acted = false;
    if let Some(st) = read_state(root) {
        // Supervisor teardown first. Skip when we are
        // the supervisor calling down() (avoid killing ourselves
        // mid-cycle — the re-entrant case).
        if let Some(sup_pid) = st.supervisor_pid
            && sup_pid != std::process::id()
            && let Some(cmd) = pid_command(sup_pid)
            && (cmd.contains("smix") || cmd.contains("supervise"))
        {
            println!("stopping supervisor: pid={sup_pid}");
            signal(sup_pid, "-TERM");
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            while pid_command(sup_pid).is_some() && std::time::Instant::now() < deadline {
                std::thread::sleep(std::time::Duration::from_millis(250));
            }
            if pid_command(sup_pid).is_some() {
                eprintln!("supervisor pid {sup_pid} ignored SIGTERM for 5s — SIGKILL");
                signal(sup_pid, "-9");
            }
        }
        match pid_command(st.pid) {
            Some(cmd) if cmd.contains("xcodebuild") => {
                println!("stopping runner: pid={} udid={}", st.pid, st.udid);
                signal(st.pid, "-INT");
                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
                while pid_command(st.pid).is_some() && std::time::Instant::now() < deadline {
                    std::thread::sleep(std::time::Duration::from_millis(500));
                }
                if pid_command(st.pid).is_some() {
                    eprintln!(
                        "warning: pid {} ignored SIGINT for 30s — escalating to \
                         SIGKILL (expect a macOS crash-report dialog from the \
                         runner app)",
                        st.pid
                    );
                    signal(st.pid, "-9");
                }
                acted = true;
            }
            Some(other) => {
                eprintln!(
                    "stale handle: pid {} is now {:?} (not xcodebuild) — \
                     dropping state without killing",
                    st.pid, other
                );
            }
            None => {
                println!("runner pid {} already gone — dropping stale handle", st.pid);
            }
        }
        clear_state(root);
    }

    // Fallback: sessions started outside `smix runner up` (no handle).
    let swept = std::process::Command::new("pkill")
        .args(["-INT", "-f", "xcodebuild.*SmixRunner"])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if swept {
        println!("swept unrecorded xcodebuild SmixRunner session(s)");
        acted = true;
    }

    if acted {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
        while health_ok(port) && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
    }
    if health_ok(port) {
        return Err(format!(
            "port {port} still answers /health after teardown — inspect \
             `pgrep -fl xcodebuild`"
        ));
    }
    println!("runner down: port {port} closed");
    Ok(())
}

/// `smix runner cycle`.
///
/// Reads the current runner state, tears the runner down (SIGINT +
/// wait), and brings it back up on the SAME device + port + bundle. The
/// per-udid derived-data directory (`.smix/runner/derived-data-<udid>/`)
/// is preserved by both [`down`] and [`up`], so the second `xcodebuild
/// test-without-building` boots in ~3 s instead of the ~15 s cold path.
///
/// When the XCTest test-host observes `** TEST INTERRUPTED **`, the
/// safest recovery is to cycle. This verb exposes cycle explicitly, and
/// is also invoked internally by the runner supervisor.
///
/// Errors if no state.json exists — cycle only cycles known runners;
/// use `smix runner up` for a cold start.
pub fn cycle(root: &Path, port: u16, runner_project: Option<&Path>) -> Result<(), String> {
    let st = read_state(root).ok_or_else(|| {
        "no runner recorded — cycle only cycles a known runner; \
         run `smix runner up <device> [--bundle <id>]` for a cold start"
            .to_string()
    })?;
    let udid = st.udid.clone();
    let bundle = st.bundle.clone();
    let cycle_port = st.port;
    // Carry the supervise flag across the cycle so the
    // sidecar re-attaches to the new xcodebuild after `up` returns.
    // Otherwise `runner cycle` from inside a supervisor-managed runner
    // would silently drop supervision.
    let had_supervisor = st.supervisor_pid.is_some();
    if cycle_port != port {
        eprintln!(
            "note: the recorded port {cycle_port} differs from --runner-port {port}; \
             cycling on state.json's {cycle_port}"
        );
    }
    println!("cycling runner: udid={udid} port={cycle_port} bundle={bundle:?}");

    // Try the in-process soft-cycle first: if the XCUITest host is alive
    // and answering /health, it can bounce its server + relaunch the app
    // in seconds without the ~36 s SIGINT-teardown + xcodebuild respawn.
    // Anything else (host dead, wedged, or an older runner that never
    // learned /soft-cycle) falls back to the byte-identical hard cycle,
    // preserving the N=1 / no-supervisor contract.
    match smix_runner_client::soft_cycle_plan(try_soft_cycle(cycle_port)) {
        smix_runner_client::CyclePlan::Soft { wall_ms } => {
            println!(
                "runner soft-cycled: recovered in {wall_ms}ms on port {cycle_port} \
                 (host survived, no xcodebuild respawn)"
            );
            Ok(())
        }
        smix_runner_client::CyclePlan::HardFallback { reason } => {
            println!("soft-cycle unavailable ({reason}); hard-cycling via xcodebuild");
            down(root, cycle_port)?;
            up(
                root,
                &udid,
                cycle_port,
                bundle.as_deref(),
                runner_project,
                UpOptions {
                    supervise: had_supervisor,
                    ..Default::default()
                },
            )
        }
    }
}

/// Collect ±`context_size` lines surrounding the first occurrence of
/// `match_line` inside the log file. Best-effort: returns empty on
/// file-read failure, or on partial matches (log rotated between
/// trigger + read). Emitted inside the supervisor's `RunnerCycled` JSON
/// event so callers get cycle-cascade classification data without
/// needing a separate `grep` pass.
fn collect_log_context(log_path: &Path, match_line: &str, context_size: usize) -> Vec<String> {
    let Ok(text) = std::fs::read_to_string(log_path) else {
        return Vec::new();
    };
    let trimmed = match_line.trim();
    let lines: Vec<&str> = text.lines().collect();
    let Some(idx) = lines.iter().position(|l| l.contains(trimmed)) else {
        return Vec::new();
    };
    let start = idx.saturating_sub(context_size);
    let end = (idx + context_size + 1).min(lines.len());
    lines[start..end].iter().map(|l| l.to_string()).collect()
}

/// Spawn the supervisor as a detached child process after
/// `runner up --supervise`. Redirects stdout/stderr to
/// `.smix/runner/supervise-<UDID>.log`. Uses its own process group so
/// a ctrl-C on the CLI doesn't tear the supervisor down. Returns the
/// child pid on success.
fn spawn_supervisor(root: &Path, runner_project: Option<&Path>) -> Result<u32, String> {
    let st = read_state(root)
        .ok_or_else(|| "internal: no state.json to attach supervisor to".to_string())?;
    let udid = st.udid.clone();
    let runner_dir = root.join(".smix/runner");
    std::fs::create_dir_all(&runner_dir).map_err(|e| format!("mkdir .smix/runner: {e}"))?;
    let log = runner_dir.join(format!("supervise-{udid}.log"));
    let log_file =
        std::fs::File::create(&log).map_err(|e| format!("create {}: {e}", log.display()))?;
    let log_err = log_file
        .try_clone()
        .map_err(|e| format!("clone supervise log handle: {e}"))?;

    let self_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    let mut cmd = std::process::Command::new(&self_exe);
    cmd.arg("runner").arg("supervise");
    if let Some(p) = runner_project {
        cmd.arg("--runner-project").arg(p);
    }
    cmd.stdin(std::process::Stdio::null())
        .stdout(log_file)
        .stderr(log_err);
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    let child = cmd.spawn().map_err(|e| format!("spawn supervise: {e}"))?;
    Ok(child.id())
}

/// Host-side XCTest supervisor.
///
/// Tails the runner log at `.smix/runner/runner-<UDID>.log` and looks
/// for interrupt patterns (`** TEST INTERRUPTED **`,
/// `SchemeActionResultOperation started unexpectedly`). On match:
/// invokes [`cycle`] to tear the runner down and bring it back up on
/// the same device/port/bundle. Session persistence preserves the
/// client's `Session-Id` across the cycle.
///
/// Backoff: at most one cycle per 60 s (a spurious hit during boot is
/// common). If 5 cycles fire inside 10 minutes the supervisor exits
/// non-zero so a monitoring layer can escalate.
///
/// Runs foreground; SIGINT / SIGTERM to the supervisor cleanly shuts
/// it down. `smix runner down` invoked separately still tears the
/// runner itself down.
pub fn supervise(root: &Path, runner_project: Option<&Path>) -> Result<(), String> {
    let st = read_state(root).ok_or_else(|| {
        "no runner recorded — supervise attaches to a known runner; \
         run `smix runner up <device> --bundle <id>` first"
            .to_string()
    })?;
    let log_path = st.log.clone();
    let port = st.port;
    println!(
        "smix runner supervise: attached\n  udid={} port={} log={}",
        st.udid,
        st.port,
        log_path.display()
    );

    let mut position: u64 = std::fs::metadata(&log_path).map(|m| m.len()).unwrap_or(0);
    let mut last_cycle_at: Option<std::time::Instant> = None;
    let mut cycle_times: Vec<std::time::Instant> = Vec::new();
    let interrupt_patterns: &[&str] = &[
        "** TEST INTERRUPTED **",
        "SchemeActionResultOperation started unexpectedly",
    ];
    let cycle_cooldown = std::time::Duration::from_secs(60);
    let storm_window = std::time::Duration::from_secs(600);
    let storm_threshold = 5;

    // Health-unreachable trigger. The log-marker triggers only fire
    // when xcodebuild prints a recognizable death banner, but a runner
    // can die with NO marker at all (e.g. warm derived-data reuse after
    // a downgrade sync), which the supervisor would otherwise sit
    // through. Probe GET /health every ~10 s; 3 consecutive failures
    // (~30 s unreachable) is a cycle trigger through the same cooldown +
    // storm accounting as the log markers.
    let health_probe_every = 20; // × 500 ms sleep = ~10 s cadence
    let health_fail_threshold = 3;
    let mut loop_ticks: u64 = 0;
    let mut health_consecutive_fails: u32 = 0;

    fn probe_health(port: u16) -> bool {
        use std::io::{Read, Write};
        let addr = format!("127.0.0.1:{port}");
        let timeout = std::time::Duration::from_secs(3);
        let Ok(mut stream) = std::net::TcpStream::connect_timeout(
            &match addr.parse() {
                Ok(a) => a,
                Err(_) => return false,
            },
            timeout,
        ) else {
            return false;
        };
        let _ = stream.set_read_timeout(Some(timeout));
        let _ = stream.set_write_timeout(Some(timeout));
        if stream
            .write_all(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
            .is_err()
        {
            return false;
        }
        let mut buf = [0u8; 64];
        match stream.read(&mut buf) {
            Ok(n) if n > 0 => {
                // Any HTTP response line counts as alive; /health
                // never legitimately errors on a healthy runner.
                buf[..n].starts_with(b"HTTP/1.1 200") || buf[..n].starts_with(b"HTTP/1.0 200")
            }
            _ => false,
        }
    }

    let mut carry = String::new();
    loop {
        // Sleep between polls; keeps CPU low.
        std::thread::sleep(std::time::Duration::from_millis(500));

        // Periodic health probe (see above).
        loop_ticks += 1;
        if loop_ticks.is_multiple_of(health_probe_every) {
            if probe_health(port) {
                health_consecutive_fails = 0;
            } else {
                health_consecutive_fails += 1;
                eprintln!(
                    "supervise: /health unreachable ({health_consecutive_fails}/{health_fail_threshold})"
                );
                if health_consecutive_fails >= health_fail_threshold {
                    health_consecutive_fails = 0;
                    let now = std::time::Instant::now();
                    let in_cooldown = last_cycle_at
                        .map(|prev| now.duration_since(prev) < cycle_cooldown)
                        .unwrap_or(false);
                    if in_cooldown {
                        eprintln!(
                            "supervise: health trigger within {:?} of last cycle — skipping (cooldown)",
                            cycle_cooldown
                        );
                    } else {
                        cycle_times.retain(|t| now.duration_since(*t) < storm_window);
                        if cycle_times.len() >= storm_threshold {
                            return Err(format!(
                                "supervise: {} cycles inside {:?} — bailing so a monitoring \
                                 layer can escalate",
                                cycle_times.len(),
                                storm_window
                            ));
                        }
                        use std::io::Write;
                        let mut out = std::io::stdout().lock();
                        let _ = writeln!(
                            out,
                            r#"{{"event":"RunnerCycled","reasonMatched":"health-unreachable x{}","context":[],"atMs":{}}}"#,
                            health_fail_threshold,
                            std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .map(|d| d.as_millis())
                                .unwrap_or(0)
                        );
                        let _ = out.flush();
                        match cycle(root, port, runner_project) {
                            Ok(()) => {
                                cycle_times.push(now);
                                last_cycle_at = Some(now);
                                position = 0;
                                carry.clear();
                            }
                            Err(e) => {
                                return Err(format!("supervise: cycle failed: {e}"));
                            }
                        }
                    }
                }
            }
        }

        let meta = match std::fs::metadata(&log_path) {
            Ok(m) => m,
            Err(_) => continue,
        };
        let current_len = meta.len();
        if current_len < position {
            // Log rotated — reset to start of file.
            position = 0;
            carry.clear();
        }
        if current_len == position {
            continue;
        }
        // Read new bytes.
        use std::io::{Read, Seek, SeekFrom};
        let mut f = match std::fs::File::open(&log_path) {
            Ok(f) => f,
            Err(_) => continue,
        };
        if f.seek(SeekFrom::Start(position)).is_err() {
            continue;
        }
        let mut buf = String::new();
        if f.read_to_string(&mut buf).is_err() {
            // Non-UTF8 chunk — skip and advance.
            position = current_len;
            continue;
        }
        position = current_len;
        carry.push_str(&buf);
        // Match line-by-line so an interrupt marker split across chunks
        // still fires correctly on the reassembled line.
        let mut lines: Vec<&str> = carry.lines().collect();
        // If the last line doesn't end with \n the current position may
        // land mid-line — keep it as carry for the next iter.
        let keep_last = !carry.ends_with('\n');
        let tail = if keep_last {
            lines.pop().unwrap_or("").to_string()
        } else {
            String::new()
        };
        for line in &lines {
            let matched = interrupt_patterns.iter().any(|p| line.contains(p));
            if !matched {
                continue;
            }
            let now = std::time::Instant::now();
            if last_cycle_at.is_some_and(|prev| now.duration_since(prev) < cycle_cooldown) {
                eprintln!(
                    "supervise: interrupt hit within {:?} of last cycle — \
                     skipping (cooldown)",
                    cycle_cooldown
                );
                continue;
            }
            // Storm check: prune expired timestamps, then check count.
            cycle_times.retain(|t| now.duration_since(*t) < storm_window);
            if cycle_times.len() >= storm_threshold {
                return Err(format!(
                    "supervise: {} cycles inside {:?} — bailing so a monitoring \
                     layer can escalate",
                    cycle_times.len(),
                    storm_window
                ));
            }
            // Flush after every JSON event so anything parsing
            // supervisor stdout sees the event immediately even when
            // the outer flow crashes fast right after.
            //
            // Attach the surrounding ±5 lines of runner log context so
            // the cycle can be classified without a separate grep.
            // Context is best-effort — if the log file has been rotated
            // between the trigger and the read we still emit the event
            // with an empty context.
            let context: Vec<String> = collect_log_context(&log_path, line, 5);
            use std::io::Write;
            let mut out = std::io::stdout().lock();
            let context_json = context
                .iter()
                .map(|l| format!("{:?}", l))
                .collect::<Vec<_>>()
                .join(",");
            let _ = writeln!(
                out,
                r#"{{"event":"RunnerCycled","reasonMatched":{:?},"context":[{}],"atMs":{}}}"#,
                line.trim(),
                context_json,
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_millis())
                    .unwrap_or(0)
            );
            let _ = out.flush();
            match cycle(root, port, runner_project) {
                Ok(()) => {
                    cycle_times.push(now);
                    last_cycle_at = Some(now);
                    // After cycle succeeds the log path is truncated
                    // (up recreates the file). Reset our position.
                    position = 0;
                    carry.clear();
                    break;
                }
                Err(e) => {
                    return Err(format!("supervise: cycle failed: {e}"));
                }
            }
        }
        carry = tail;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::Mutex;

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

    /// Serialize the resolver tests that mutate process-global env. Each
    /// uses a test-only var name, but `set_var`/`remove_var` still churn
    /// the shared environ table, so they hold this lock while doing so.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn xcodebuild_argv_targets_explicit_udid() {
        let argv = xcodebuild_argv(Path::new("/repo/swift-bridge/SmixRunner.xcodeproj"), UDID);
        assert_eq!(argv[0], "test");
        assert!(argv.contains(&"SmixRunner".to_string()));
        assert!(
            argv.iter()
                .any(|a| a == &format!("platform=iOS Simulator,id={UDID}"))
        );
        assert!(!argv.iter().any(|a| a.contains("name=")));
        // Per-udid derivedDataPath keeps concurrent runners from
        // contending on the shared Xcode DerivedData lock.
        let derived_pos = argv
            .iter()
            .position(|a| a == "-derivedDataPath")
            .expect("argv missing -derivedDataPath");
        assert_eq!(
            argv[derived_pos + 1],
            format!(".smix/runner/derived-data-{UDID}")
        );
    }

    #[test]
    fn runner_state_round_trips() {
        let st = RunnerState {
            pid: 4242,
            udid: UDID.into(),
            port: 22087,
            log: PathBuf::from("/tmp/runner.log"),
            bundle: Some("com.example.app".into()),
            supervisor_pid: None,
        };
        let json = serde_json::to_string(&st).unwrap();
        let back: RunnerState = serde_json::from_str(&json).unwrap();
        assert_eq!(back, st);
    }

    /// `capsule up` and `runner up` bring the runner up by binding it
    /// to a bundle, and binding launched — which restarts the app and
    /// drops whatever screen had been navigated to. The runner has
    /// understood `activate` since `LaunchModeResolver` was written and
    /// nothing on this side ever set it, so the mode was unreachable.
    #[test]
    fn attaching_asks_the_runner_to_activate_rather_than_relaunch() {
        let relaunching = runner_env(Some("com.example.app"), false, 22087, false);
        assert!(
            !relaunching
                .iter()
                .any(|(k, _)| k == "TEST_RUNNER_SMIX_RUNNER_LAUNCH_MODE"),
            "the default must stay launch, or every existing flow changes"
        );

        let attaching = runner_env(Some("com.example.app"), false, 22087, true);
        let mode = attaching
            .iter()
            .find(|(k, _)| k == "TEST_RUNNER_SMIX_RUNNER_LAUNCH_MODE")
            .map(|(_, v)| v.as_str());
        assert_eq!(
            mode,
            Some("activate"),
            "the `TEST_RUNNER_` prefix is what makes xcodebuild surface \
             `SMIX_RUNNER_LAUNCH_MODE` inside the runner process"
        );
    }

    #[test]
    fn runner_env_uses_test_runner_prefix() {
        let env = runner_env(Some("com.example.app"), false, 22087, false);
        let map: std::collections::HashMap<String, String> = env.iter().cloned().collect();
        assert_eq!(
            map.get("TEST_RUNNER_SMIX_RUNNER_TARGET_BUNDLE")
                .map(String::as_str),
            Some("com.example.app")
        );
        assert_eq!(
            map.get("TEST_RUNNER_SMIX_RUNNER_PORT").map(String::as_str),
            Some("22087")
        );
        let env_no_bundle = runner_env(None, false, 22090, false);
        // The version is unconditionally forwarded.
        assert_eq!(env_no_bundle.len(), 2);
        assert!(
            env_no_bundle
                .iter()
                .any(|(k, v)| k == "TEST_RUNNER_SMIX_RUNNER_PORT" && v == "22090")
        );
    }

    #[test]
    fn runner_env_forwards_cli_version_for_health_echo() {
        // The CLI's own version reaches the runner via
        // TEST_RUNNER_SMIX_RUNNER_VERSION so /health can echo it and
        // the client can refuse boot on mismatch.
        let env = runner_env(None, false, 22087, false);
        let map: std::collections::HashMap<String, String> = env.into_iter().collect();
        assert_eq!(
            map.get("TEST_RUNNER_SMIX_RUNNER_VERSION")
                .map(String::as_str),
            Some(env!("CARGO_PKG_VERSION"))
        );
    }

    #[test]
    fn runner_env_with_record_adds_enabled_var() {
        let env = runner_env(Some("com.example.app"), true, 22087, false);
        let map: std::collections::HashMap<String, String> = env.into_iter().collect();
        assert_eq!(
            map.get("TEST_RUNNER_SMIX_RUNNER_TARGET_BUNDLE")
                .map(String::as_str),
            Some("com.example.app")
        );
        assert_eq!(
            map.get("TEST_RUNNER_SMIX_RECORD_ENABLED")
                .map(String::as_str),
            Some("1")
        );
    }

    // Auto-sync regression tests. These lock in the behavior that
    // closes the CLI-vs-runner distribution gap: on version drift OR
    // missing version file, ensure_installed_runner_synced MUST extract
    // the embedded tarball; on matching version it MUST be a no-op.

    #[test]
    fn ensure_installed_runner_synced_extracts_on_missing_version_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let outcome = ensure_installed_runner_synced(dir.path()).expect("sync");
        matches!(
            outcome,
            SyncOutcome::Extracted {
                previous_version: None,
                ..
            }
        )
        .then_some(())
        .expect("expected first-run extract with no previous version");
        assert!(
            dir.path().join(".smix-runner-version").exists(),
            "version file must be written"
        );
        assert!(
            dir.path()
                .join("SmixRunner.xcodeproj/project.pbxproj")
                .exists(),
            "xcodeproj must land on disk after sync"
        );
    }

    #[test]
    fn ensure_installed_runner_synced_reextracts_on_stale_version() {
        let dir = tempfile::tempdir().expect("tempdir");
        // Simulate a consumer whose runner tree was populated by an
        // earlier CLI. The stale sentinel version 0.0.0-stale MUST NOT
        // survive the sync call.
        fs::write(dir.path().join(".smix-runner-version"), "0.0.0-stale\n")
            .expect("seed stale version");
        fs::write(dir.path().join("stale-marker.txt"), b"old contents").expect("seed stale marker");

        let outcome = ensure_installed_runner_synced(dir.path()).expect("sync");
        match outcome {
            SyncOutcome::Extracted {
                previous_version,
                backup,
            } => {
                assert_eq!(previous_version.as_deref(), Some("0.0.0-stale"));
                let backup = backup.expect("backup path present");
                assert!(backup.exists(), "backup dir must exist");
                assert!(
                    backup.join("stale-marker.txt").exists(),
                    "backup must preserve prior tree contents"
                );
            }
            SyncOutcome::AlreadyCurrent => panic!("stale must not be treated as current"),
        }
        // Fresh sources landed; stale marker is NOT in the new tree.
        assert!(!dir.path().join("stale-marker.txt").exists());
        assert_eq!(
            std::fs::read_to_string(dir.path().join(".smix-runner-version"))
                .unwrap()
                .trim(),
            smix_runner_sources::SOURCES_VERSION
        );
    }

    #[test]
    fn ensure_installed_runner_synced_is_noop_when_current() {
        let dir = tempfile::tempdir().expect("tempdir");
        // First call: extracts.
        ensure_installed_runner_synced(dir.path()).expect("first sync");
        // Second call: same version file → no-op.
        let outcome = ensure_installed_runner_synced(dir.path()).expect("second sync");
        matches!(outcome, SyncOutcome::AlreadyCurrent)
            .then_some(())
            .expect("second call must be AlreadyCurrent, not Extracted");
    }

    #[test]
    fn switches_from_value_reads_only_present_keys() {
        // Schemaless read: only `autoOcrFallback` is set → the other
        // three stay `None`.
        let yaml = "switches:\n  autoOcrFallback: true\n";
        let value: serde_json::Value = serde_norway::from_str(yaml).unwrap();
        let sw = switches_from_value(&value);
        assert_eq!(sw.auto_ocr_fallback, Some(true));
        assert_eq!(sw.enable_ai_assertions, None);
        assert_eq!(sw.assert_screenshot_no_autorecord, None);
        assert_eq!(sw.launch_fresh_force_reinstall, None);
    }

    #[test]
    fn switches_from_value_empty_when_no_block() {
        let value: serde_json::Value =
            serde_norway::from_str("interactiveProbe:\n  minIdentifierCount: 3\n").unwrap();
        assert_eq!(switches_from_value(&value), SwitchesConfig::default());
    }

    #[test]
    fn resolve_switch_config_wins_over_env() {
        let _g = ENV_LOCK.lock().unwrap();
        let name = "SMIX_TEST_RESOLVE_CONFIG_WINS";
        // SAFETY: ENV_LOCK serializes env churn; the var name is unique
        // to this test.
        unsafe { std::env::set_var(name, "1") };
        // config=Some(false) must beat env=1, source Config, no warn.
        let r = resolve_switch(Some(false), name);
        assert!(!r.value);
        assert_eq!(r.source, SwitchSource::Config);
        unsafe { std::env::remove_var(name) };
    }

    #[test]
    fn resolve_switch_env_used_when_no_config() {
        let _g = ENV_LOCK.lock().unwrap();
        let name = "SMIX_TEST_RESOLVE_ENV_USED";
        // SAFETY: as above.
        unsafe { std::env::set_var(name, "1") };
        let r = resolve_switch(None, name);
        assert!(r.value);
        assert_eq!(r.source, SwitchSource::Env);
        unsafe { std::env::remove_var(name) };
    }

    #[test]
    fn resolve_switch_default_when_neither() {
        let _g = ENV_LOCK.lock().unwrap();
        let name = "SMIX_TEST_RESOLVE_DEFAULT";
        // SAFETY: as above — ensure the var is unset for this thread.
        unsafe { std::env::remove_var(name) };
        let r = resolve_switch(None, name);
        assert!(!r.value);
        assert_eq!(r.source, SwitchSource::Default);
    }

    #[test]
    fn workspace_root_walks_up_to_smix_dir() {
        let root = std::env::temp_dir().join(format!("smix-runner-ws-{}", std::process::id()));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(root.join(".smix")).unwrap();
        let nested = root.join("crates/smix-cli");
        fs::create_dir_all(&nested).unwrap();
        assert_eq!(workspace_root(&nested).unwrap(), root);
        let outside =
            std::env::temp_dir().join(format!("smix-runner-no-ws-{}", std::process::id()));
        let _ = fs::remove_dir_all(&outside);
        fs::create_dir_all(&outside).unwrap();
        assert!(workspace_root(&outside).is_none());
    }
}