smix-simctl 12.0.0

smix-simctl — xcrun simctl child_process wrapper (outer crate).
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
//! The device registry — deterministic device addressing.
//!
//! Records live in the `smix-store` under `.smix/`. A pre-store
//! `sims.json` sitting beside it is imported on open and then left
//! alone; smix never writes that file again.
//!
//! Every smix device operation targets either an explicit UDID or an
//! alias recorded in this file. Resolution never consults the live
//! simulator set: the registry file is the only mapping source, so a
//! given input always resolves to the same device regardless of what
//! happens to be booted on the machine.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Failure variants for registry load / device-ref resolution.
#[derive(Debug, Error)]
pub enum RegistryError {
    /// Registry file could not be read.
    #[error("cannot read sim registry {path}: {source}")]
    Io {
        /// Path that failed to read.
        path: String,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Registry file is not valid registry JSON.
    #[error("malformed sim registry {path}: {detail}")]
    Malformed {
        /// Path that failed to parse.
        path: String,
        /// Parser-side detail.
        detail: String,
    },
    /// Input is neither a UDID nor a recorded alias.
    #[error(
        "unknown device ref {device_ref:?} — pass an explicit UDID or one of \
         the recorded aliases: {}",
        known.join(", ")
    )]
    UnknownDevice {
        /// The input that failed to resolve.
        device_ref: String,
        /// Alias keys and device names available in the registry.
        known: Vec<String>,
    },
    /// This machine's registry and a checkout's legacy book give one alias
    /// to two different devices.
    #[error("{}", diverged_message(alias, machine, checkouts))]
    Diverged {
        /// The alias both books claim.
        alias: String,
        /// The machine registry's path and the identifier it holds.
        machine: (PathBuf, String),
        /// Each checkout book that disagrees, and the identifier it holds.
        checkouts: Vec<(PathBuf, String)>,
    },
}

fn diverged_message(
    alias: &str,
    machine: &(PathBuf, String),
    checkouts: &[(PathBuf, String)],
) -> String {
    let others = checkouts
        .iter()
        .map(|(p, id)| format!("{} says {id}", p.display()))
        .collect::<Vec<_>>()
        .join("; ");
    format!(
        "`{alias}` names two devices: this machine's registry ({}) says {}, and {others}. \
         A checkout's book is read, never written, and it does not get to decide which \
         device an alias drives — so nothing was driven. Make them agree: correct that \
         file (smix does not edit it), or record the device on this machine with \
         `smix sim register --udid <id> {alias}`.",
        machine.0.display(),
        machine.1
    )
}

/// The shape of a pre-store `.smix/sims.json`.
#[derive(Deserialize)]
struct LegacyBook {
    #[serde(default)]
    sims: BTreeMap<String, RegisteredSim>,
}

/// One alias, two devices: this machine's answer and each checkout book
/// that disagrees with it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Divergence {
    /// The machine registry's path and the identifier it holds.
    pub machine: (PathBuf, String),
    /// Each checkout book that disagrees, and the identifier it holds.
    pub checkouts: Vec<(PathBuf, String)>,
}

/// Which book an answer came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// This machine's registry — where device facts live (§9 #9).
    Machine(PathBuf),
    /// A checkout's book that the machine registry does not also hold.
    Checkout(PathBuf),
    /// The one registry `SMIX_SIMS_JSON` names.
    Named(PathBuf),
    /// No book: the reference was the identifier itself.
    Literal,
}

/// A device reference answered, with the book the answer came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    /// The identifier the platform addresses the device by.
    pub id: String,
    /// The alias the reference matched (the reference itself for a raw id).
    pub alias: String,
    /// Which book answered.
    pub source: Source,
}

/// What kind of device a registry entry names.
///
/// The distinction exists for one reason: what smix is allowed to do to
/// it. A simulator can be erased and rebuilt in a minute; a phone in
/// somebody's pocket cannot. §9#1 hangs the destructive-action guard off
/// this field.
///
/// Defaults to `Simulator` when the field is absent, and that direction
/// is deliberate. Every registry written before this field existed was
/// written by a simulator; reading those as physical would lock a working
/// setup behind an opt-in nobody asked for. Guessing "simulator" costs at
/// most one missing gate on a device that never needed it — guessing
/// "physical" breaks people who did nothing wrong.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DeviceKind {
    /// iOS Simulator.
    #[default]
    Simulator,
    /// Android emulator.
    Emulator,
    /// A physical iPhone or iPad.
    PhysicalIos,
    /// A physical Android device.
    PhysicalAndroid,
}

impl DeviceKind {
    /// Every kind, so nothing has to keep its own copy of the list.
    ///
    /// It lived as a local `const ALL` inside a CLI helper, which meant a
    /// fifth kind would have compiled everywhere and been silently
    /// missing from that one table. The list belongs beside the enum it
    /// lists (`code/derive-dont-copy`).
    pub const ALL: [DeviceKind; 4] = [
        DeviceKind::Simulator,
        DeviceKind::Emulator,
        DeviceKind::PhysicalIos,
        DeviceKind::PhysicalAndroid,
    ];

    /// Is this a device somebody might be carrying around?
    #[must_use]
    pub fn is_physical(self) -> bool {
        match self {
            DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid => true,
            DeviceKind::Simulator | DeviceKind::Emulator => false,
        }
    }
}

/// One registered simulator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisteredSim {
    /// Human-chosen device name (also usable as an alias).
    #[serde(rename = "deviceName")]
    pub device_name: String,
    /// What kind of device this is. Absent in registries written before
    /// physical devices were addressable — see [`DeviceKind`] for why
    /// that reads as `Simulator`.
    #[serde(default)]
    pub kind: DeviceKind,
    /// Whether destructive actions have been allowed on this device.
    ///
    /// Only consulted for physical devices; a simulator is never gated.
    /// Recorded once here rather than confirmed per command, because a
    /// confirmation that must be typed every time ends up in a script,
    /// which is the same as not having one.
    #[serde(default, rename = "destructiveOptIn")]
    pub destructive_opt_in: bool,
    /// CoreSimulator UDID.
    pub udid: String,
    /// Runtime identifier.
    pub runtime: String,
    /// Device type identifier.
    ///
    /// Apple's `SimDeviceType` for a simulator. For an emulator this is
    /// where the AVD name used to live, and rows written before
    /// [`Self::avd_name`] existed still keep it there — read it through
    /// that method rather than from here, which is named after the
    /// other half of its rows.
    #[serde(rename = "deviceType")]
    pub device_type: String,
    /// Which AVD an emulator row names.
    ///
    /// The serial is a slot: `emulator-5554` belongs to whoever booted
    /// first, so a row holding only a serial names a stranger the moment
    /// somebody else takes that port. The AVD name survives a reboot and
    /// a slot change, and it is the name `smix sim boot` already starts
    /// the device by.
    #[serde(default, rename = "avdName", skip_serializing_if = "Option::is_none")]
    pub avd_name: Option<String>,
    /// Desired BCP 47 locale tag (e.g. `"en-US"`, `"ja-JP"`). When set,
    /// `smix sim boot` enforces it via
    /// `defaults write -g AppleLanguages + AppleLocale` and reboots the
    /// sim if the current locale differs. `None` (field absent) =
    /// honor whatever locale the sim boots with, no enforcement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    /// Desired runner port (SmixRunner FlyingFox HTTP port). When set,
    /// `smix runner up <alias>` binds the runner to this port instead
    /// of the CLI default 22087. Two sims can then run their own runner
    /// in parallel without port collision
    /// (e.g. `sim-a.runnerPort = 22087` + `sim-b.runnerPort = 22088`).
    /// Falls through to `--runner-port` flag or `SMIX_RUNNER_PORT` env
    /// when absent.
    #[serde(
        default,
        rename = "runnerPort",
        skip_serializing_if = "Option::is_none"
    )]
    pub runner_port: Option<u16>,
}

impl RegisteredSim {
    /// The AVD this row names, when it names one.
    ///
    /// Reads the field, then the place the value lived before that field
    /// existed. One reader, so the two spellings cannot drift apart —
    /// and only for emulators: `deviceType` on a simulator row carries
    /// Apple's device type, and reading that as an identity would invent
    /// an AVD named `com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro`.
    pub fn avd_name(&self) -> Option<&str> {
        if self.kind != DeviceKind::Emulator {
            return None;
        }
        self.avd_name
            .as_deref()
            .or(Some(self.device_type.as_str()))
            .filter(|a| !a.is_empty())
    }
}

/// What [`SimRegistry::register`] did with the alias.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegisterOutcome {
    /// The alias did not exist; a new row was written.
    Added,
    /// The alias existed; its row was replaced.
    Updated,
}

/// Loaded view of the registry, keyed by alias.
#[derive(Debug, Default, Clone)]
pub struct SimRegistry {
    sims: BTreeMap<String, RegisteredSim>,
}

/// What a migration did, per alias.
///
/// Reported rather than summarised as a count. A migration is a one-way
/// door and the thing somebody needs afterwards is the ability to look
/// up one device by name and see what happened to it.
#[derive(Debug, Default, Clone)]
pub struct MigrationReport {
    /// Aliases the destination did not have.
    pub added: Vec<String>,
    /// Aliases that were already there, pointing at the same device.
    pub unchanged: Vec<String>,
    /// Aliases that were already there and whose record changed —
    /// which, under [`SimRegistry::merge`], can only mean consent
    /// narrowed.
    pub narrowed: Vec<String>,
    /// Sources that opened and held nothing.
    pub empty: Vec<PathBuf>,
    /// Sources that would not open, and why.
    pub unreadable: Vec<(PathBuf, String)>,
}

/// Every registry this machine can read, folded into one.
#[derive(Debug, Default, Clone)]
pub struct MergedRegistry {
    /// The merged view, with this machine's registry as the authority.
    ///
    /// This used to say that which book a device came from was not
    /// visible here, deliberately, because a device is a device. Two
    /// things came of that on 2026-09-24: a checkout's legacy book that
    /// gave an alias to another device won whenever its UDID sorted
    /// first, and a consumer lost an hour to a harness reading a book
    /// smix no longer answered from, with nothing saying which book
    /// smix did answer from. [`Self::sources`] and [`Self::diverged`]
    /// are the answer to both.
    pub registry: SimRegistry,
    /// Aliases a checkout is the only holder of, and which checkout.
    ///
    /// Not an error — those devices work. It is the one thing a caller
    /// has to be able to say out loud, because a record only one tree
    /// holds is a record the next tree cannot act on, and the whole
    /// point of moving these was that "check who owns this runner" can
    /// be carried out from anywhere.
    pub unmigrated: BTreeMap<String, PathBuf>,
    /// Which book each alias in [`Self::registry`] came from.
    pub sources: BTreeMap<String, Source>,
    /// Aliases the machine and a checkout give to different devices.
    pub diverged: BTreeMap<String, Divergence>,
}

impl MergedRegistry {
    /// Resolve a device reference, naming the book that answered.
    ///
    /// An alias the machine and a checkout give to different devices is
    /// refused rather than answered: the checkout's book may stop a
    /// decision and be named as evidence, and nothing more (§9 #9).
    pub fn resolve_ref(&self, device_ref: &str) -> Result<Resolved, RegistryError> {
        let alias = self.matched_alias(device_ref);
        if let Some(a) = alias.as_deref().or(Some(device_ref))
            && let Some(d) = self.diverged.get(a)
        {
            return Err(RegistryError::Diverged {
                alias: a.to_string(),
                machine: d.machine.clone(),
                checkouts: d.checkouts.clone(),
            });
        }
        let id = self.registry.resolve(device_ref)?;
        let (alias, source) = match alias {
            Some(a) => {
                let src = self.sources.get(&a).cloned().unwrap_or(Source::Literal);
                (a, src)
            }
            None => (device_ref.to_string(), Source::Literal),
        };
        Ok(Resolved { id, alias, source })
    }

    /// The alias a reference names: the key itself, or the entry whose
    /// device name or identifier it is.
    fn matched_alias(&self, device_ref: &str) -> Option<String> {
        let sims = self.registry.sims();
        if sims.contains_key(device_ref) {
            return Some(device_ref.to_string());
        }
        sims.iter()
            .find(|(_, s)| s.device_name == device_ref || s.udid.eq_ignore_ascii_case(device_ref))
            .map(|(a, _)| a.clone())
    }
}

/// Whether `s` has CoreSimulator UDID form (8-4-4-4-12 hex).
///
/// Answers the shape question only. It used to answer more than that —
/// UDID-form input was treated as a deliberate instruction that skipped
/// the registry entirely, and the CLI still short-circuits alias lookup
/// on it. What changed on 2026-08-06 is that skipping the registry no
/// longer means skipping every check: a raw identifier now has to be one
/// the platform itself claims, because the shape alone stopped being
/// evidence the moment a `devicectl` path appeared that reaches phones
/// whose CoreDevice UUIDs wear exactly this form.
pub fn is_udid(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.len() != 36 {
        return false;
    }
    for (i, b) in bytes.iter().enumerate() {
        match i {
            8 | 13 | 18 | 23 => {
                if *b != b'-' {
                    return false;
                }
            }
            _ => {
                if !b.is_ascii_hexdigit() {
                    return false;
                }
            }
        }
    }
    true
}

/// Where an emulator alias actually points today.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmulatorAddress {
    /// The recorded AVD is running on the slot it was registered with.
    At {
        /// The serial to address it by.
        serial: String,
    },
    /// The recorded AVD is running, on a different slot than recorded.
    MovedTo {
        /// The serial it answers on today.
        serial: String,
        /// The serial the registry recorded.
        recorded: String,
    },
    /// The recorded AVD is not running anywhere.
    NotRunning {
        /// The AVD the row records.
        avd: String,
        /// Which AVD holds the recorded slot now, when one does.
        slot_now: Option<String>,
    },
    /// The row records a slot and nothing else.
    NoIdentityRecorded {
        /// The slot the row records.
        serial: String,
    },
}

impl EmulatorAddress {
    /// How many answers there are.
    pub const VARIANTS: usize = 4;
}

/// Which emulator an alias names today, given what was recorded and
/// what is running.
///
/// `emulator-<port>` is a slot, not a device: whoever boots first takes
/// 5554. So a row that records only a serial names whichever emulator
/// happens to be answering there — on 2026-09-23 that was a consumer's
/// `qip-consumer-36`, and every alias-driven action would have installed
/// onto their device. The AVD name is what survives a reboot and a slot
/// change, and registration has been writing it down since the start;
/// nothing read it.
///
/// The order matters. Identity is asked for first, and the running list
/// is not consulted without one: letting an empty slot stand in for an
/// unknown identity is precisely how a slot becomes an identity.
pub fn emulator_address(
    recorded_avd: Option<&str>,
    recorded_serial: &str,
    live: &[(String, String)],
) -> EmulatorAddress {
    let Some(avd) = recorded_avd.filter(|a| !a.is_empty()) else {
        return EmulatorAddress::NoIdentityRecorded {
            serial: recorded_serial.to_string(),
        };
    };
    // Byte for byte: `adb` and `emulator -avd` both match verbatim, so a
    // case fold here would hand back a device neither of them answers to.
    if let Some((serial, _)) = live.iter().find(|(_, name)| name == avd) {
        return if serial == recorded_serial {
            EmulatorAddress::At {
                serial: serial.clone(),
            }
        } else {
            EmulatorAddress::MovedTo {
                serial: serial.clone(),
                recorded: recorded_serial.to_string(),
            }
        };
    }
    EmulatorAddress::NotRunning {
        avd: avd.to_string(),
        // Only for the sentence: the reader needs to know the slot is
        // not merely empty, it belongs to someone. It takes no part in
        // choosing.
        slot_now: live
            .iter()
            .find(|(serial, _)| serial == recorded_serial)
            .map(|(_, name)| name.clone()),
    }
}

/// Why an identifier does not fit the kind it was registered under.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentifierMismatch {
    /// The identifier as given.
    pub given: String,
    /// What that kind's identifiers look like.
    pub expected: &'static str,
}

impl std::fmt::Display for IdentifierMismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:?} is not how that kind of device is identified — {}",
            self.given, self.expected
        )
    }
}

/// Does this identifier fit the kind it is being registered as?
///
/// Shape only; whether the device exists is a separate question, asked
/// against a different catalogue per kind, and asked by the caller.
///
/// The three answers differ because the world does:
///
/// * A **simulator** is a directory on this Mac with a CoreSimulator
///   UDID, and `simctl` can list every one of them.
/// * An **emulator** is named by `adb`, which calls them `emulator-<port>`
///   and will list them too.
/// * A **phone** has no catalogue at all. Nothing on this machine can
///   enumerate the world's devices, so its identifier is taken as given —
///   which is exactly why registering one has to be a deliberate act
///   rather than a lookup. That is not a hole in the check; it is the
///   reason the check exists.
///
/// # Errors
///
/// Returns what that kind's identifiers look like, so the message can
/// say which of the three worlds the caller landed in the wrong one of.
pub fn identifier_fits(kind: DeviceKind, id: &str) -> Result<(), IdentifierMismatch> {
    let ok = match kind {
        DeviceKind::Simulator => is_udid(id),
        DeviceKind::Emulator => is_emulator_serial(id),
        // No catalogue exists to check against.
        DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid => !id.trim().is_empty(),
    };
    if ok {
        return Ok(());
    }
    Err(IdentifierMismatch {
        given: id.to_string(),
        expected: match kind {
            DeviceKind::Simulator => {
                "a simulator has a CoreSimulator UDID (8-4-4-4-12 hex); find it with `smix sim list`"
            }
            DeviceKind::Emulator => {
                "adb names an emulator `emulator-<port>`, e.g. emulator-5554; find it with `adb devices`"
            }
            DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid => {
                "a physical device needs a non-empty identifier: a UDID for iOS, an adb serial for Android"
            }
        },
    })
}

/// Put an identifier in the form its platform matches on.
///
/// Normalise what has a normal form; preserve what is matched verbatim.
///
/// Apple's identifiers are hex and canonically upper-case, and this is
/// not a style preference: `devicectl` was measured on 2026-08-06 to
/// reject the lower-case spelling of a UDID it accepts in upper-case
/// (`ERROR: The specified device was not found`). Upper-casing therefore
/// rescues a typed-in identifier rather than mangling it.
///
/// `adb` matches serials byte for byte, so there is nothing to rescue and
/// everything to break: `EMULATOR-5554` is not a device, and neither is a
/// vendor serial that came with lower-case letters in it.
///
/// Done once, here, where the kind is known — never again downstream. A
/// value normalised twice by two different rules is how `sim resolve` came
/// to hand out `EMULATOR-5554`.
#[must_use]
pub fn canonical_identifier(kind: DeviceKind, id: &str) -> String {
    match kind {
        DeviceKind::Simulator | DeviceKind::PhysicalIos => id.to_ascii_uppercase(),
        DeviceKind::Emulator | DeviceKind::PhysicalAndroid => id.to_string(),
    }
}

/// Whether `s` is an adb emulator serial.
///
/// `adb` is the one naming these, so this recognises rather than guesses:
/// an emulator is `emulator-<port>`, and a physical device answers with a
/// hardware serial that never takes that form. Case matters — `adb`
/// matches serials verbatim and `EMULATOR-5554` is not a device.
#[must_use]
pub fn is_emulator_serial(s: &str) -> bool {
    s.strip_prefix("emulator-")
        .is_some_and(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()))
}

/// Resolve a caller-supplied path to the `.smix` directory holding the
/// store.
///
/// Callers pass either form: `SMIX_SIMS_JSON` documents a file, while
/// discovery yields a directory. Accepting both is also what lets the
/// pre-store test suite keep exercising the legacy import path
/// unchanged, instead of being rewritten into agreement with the code
/// it is supposed to check.
pub fn store_dir(path: &Path) -> PathBuf {
    smix_dir(path)
}

fn smix_dir(path: &Path) -> PathBuf {
    if path.extension().is_some_and(|e| e == "json") {
        path.parent().unwrap_or(path).to_path_buf()
    } else {
        path.to_path_buf()
    }
}

/// Open the store under `path` and fold in any legacy `sims.json`
/// sitting beside it.
///
/// The legacy file is read, never written and never removed: a user who
/// has to go back to a pre-store smix must still find their registry.
fn open_store(path: &Path) -> Result<smix_store::Store, RegistryError> {
    let dir = smix_dir(path);
    std::fs::create_dir_all(&dir).map_err(|source| RegistryError::Io {
        path: dir.display().to_string(),
        source,
    })?;
    let store = smix_store::Store::open(&dir).map_err(|e| RegistryError::Io {
        path: dir.display().to_string(),
        source: std::io::Error::other(e.to_string()),
    })?;
    let legacy = dir.join("sims.json");
    smix_store::import_legacy_records(&store.sims(), &legacy, "sims").map_err(|e| {
        RegistryError::Malformed {
            path: legacy.display().to_string(),
            detail: e.to_string(),
        }
    })?;
    Ok(store)
}

impl SimRegistry {
    /// Write `sim` into the registry under `alias`.
    ///
    /// One key, not a whole file. The read-modify-write this replaces
    /// lost an alias whenever two processes registered at once — each
    /// read the file, each inserted its own row, and the second write
    /// erased the first, with no error on either side.
    pub fn register(
        path: &Path,
        alias: &str,
        sim: RegisteredSim,
    ) -> Result<RegisterOutcome, RegistryError> {
        let store = open_store(path)?;
        let existed = store
            .sims()
            .get(alias)
            .map_err(|e| RegistryError::Malformed {
                path: path.display().to_string(),
                detail: e.to_string(),
            })?
            .is_some();
        store
            .sims()
            .put_json(alias, &sim)
            .map_err(|e| RegistryError::Io {
                path: path.display().to_string(),
                source: std::io::Error::other(e.to_string()),
            })?;
        store.sync().map_err(|e| RegistryError::Io {
            path: path.display().to_string(),
            source: std::io::Error::other(e.to_string()),
        })?;
        Ok(if existed {
            RegisterOutcome::Updated
        } else {
            RegisterOutcome::Added
        })
    }

    /// Record which alias a project defaults to, keyed by the project's
    /// path. The value is the alias string only — a pointer into the
    /// registered devices, never a device fact. What the alias resolves
    /// to (UDID, kind, opt-in) stays in the machine registry; this says
    /// only "this project drives that one", which is a project's to
    /// decide and safe to keep per-project (§9 #9: the pointer may live
    /// with the project, the facts may not).
    ///
    /// # Errors
    /// [`RegistryError::Io`] if the store cannot be opened or written.
    pub fn set_project_alias(
        path: &Path,
        project_key: &str,
        alias: &str,
    ) -> Result<(), RegistryError> {
        let store = open_store(path)?;
        store
            .project_devices()
            .put(project_key, alias.as_bytes())
            .map_err(|e| RegistryError::Io {
                path: path.display().to_string(),
                source: std::io::Error::other(e.to_string()),
            })?;
        store.sync().map_err(|e| RegistryError::Io {
            path: path.display().to_string(),
            source: std::io::Error::other(e.to_string()),
        })
    }

    /// The alias a project defaults to, or `None` if it has never set
    /// one. Read-only counterpart of [`Self::set_project_alias`].
    ///
    /// # Errors
    /// [`RegistryError::Io`] if the store cannot be opened or read.
    pub fn project_alias(path: &Path, project_key: &str) -> Result<Option<String>, RegistryError> {
        let store = open_store(path)?;
        let raw = store
            .project_devices()
            .get(project_key)
            .map_err(|e| RegistryError::Io {
                path: path.display().to_string(),
                source: std::io::Error::other(e.to_string()),
            })?;
        Ok(raw.map(|bytes| String::from_utf8_lossy(&bytes).into_owned()))
    }

    /// Remove one alias from the registry at `path`.
    ///
    /// The other half of [`Self::register`], and absent until the
    /// records moved to machine scope made its absence permanent: a
    /// device registered by mistake — a test that wrote to the real
    /// book, an alias for a phone somebody no longer has — could be
    /// added and never taken back. A registry that only grows stops
    /// describing the machine.
    ///
    /// Removes the name, not the device. Another alias for the same
    /// device keeps working, which is why this takes an alias key
    /// rather than a device ref: "forget this device" and "forget this
    /// name for it" are different requests, and only the second one is
    /// unambiguous.
    ///
    /// # Errors
    ///
    /// [`RegistryError::UnknownDevice`] when no such alias exists.
    /// Silently succeeding would let a typo read as a removal.
    pub fn unregister(path: &Path, alias: &str) -> Result<RegisteredSim, RegistryError> {
        let reg = Self::load(path)?;
        let Some(sim) = reg.sims.get(alias).cloned() else {
            return Err(RegistryError::UnknownDevice {
                device_ref: alias.to_string(),
                known: reg.sims.keys().cloned().collect(),
            });
        };
        let store = open_store(path)?;
        store.sims().delete(alias).map_err(|e| RegistryError::Io {
            path: path.display().to_string(),
            source: std::io::Error::other(e.to_string()),
        })?;
        store.sync().map_err(|e| RegistryError::Io {
            path: path.display().to_string(),
            source: std::io::Error::other(e.to_string()),
        })?;
        Ok(sim)
    }

    /// Allow destructive actions on one registered device, once.
    ///
    /// Goes through [`Self::register`] rather than rewriting the file,
    /// for the reason that function documents: a read-modify-write of the
    /// whole registry loses a concurrent registration silently. One key
    /// in, one key out.
    ///
    /// Returns the alias it was recorded against and whether it was
    /// already allowed — the caller can then say "already allowed"
    /// instead of implying something changed.
    ///
    /// # Errors
    ///
    /// [`RegistryError::UnknownDevice`] when nothing matches the ref. The
    /// opt-in is per device, so there is nothing to record it against —
    /// and silently creating an entry would mean allowing destruction on
    /// a device nobody registered.
    pub fn allow_destructive(
        path: &Path,
        device_ref: &str,
    ) -> Result<(String, bool), RegistryError> {
        let reg = Self::load(path)?;
        let Some((alias, sim)) = reg
            .sims()
            .iter()
            .find(|(alias, sim)| {
                alias.as_str() == device_ref
                    || sim.device_name == device_ref
                    || sim.udid.eq_ignore_ascii_case(device_ref)
            })
            .map(|(a, s)| (a.clone(), s.clone()))
        else {
            let mut known: Vec<String> = Vec::new();
            for (alias, sim) in reg.sims() {
                known.push(alias.clone());
                known.push(sim.device_name.clone());
            }
            return Err(RegistryError::UnknownDevice {
                device_ref: device_ref.to_string(),
                known,
            });
        };
        if sim.destructive_opt_in {
            return Ok((alias, true));
        }
        let updated = RegisteredSim {
            destructive_opt_in: true,
            ..sim
        };
        Self::register(path, &alias, updated)?;
        Ok((alias, false))
    }

    /// Read every registered sim.
    ///
    /// `path` may be the `.smix` directory or a legacy `sims.json`
    /// inside it; both land on the same store.
    pub fn load(path: &Path) -> Result<Self, RegistryError> {
        let store = open_store(path)?;
        let mut sims = BTreeMap::new();
        for alias in store.sims().list() {
            let sim: RegisteredSim = store
                .sims()
                .get_json(&alias)
                .map_err(|e| RegistryError::Malformed {
                    path: path.display().to_string(),
                    detail: e.to_string(),
                })?
                .ok_or_else(|| RegistryError::Malformed {
                    path: path.display().to_string(),
                    detail: format!("`{alias}` vanished between listing and reading"),
                })?;
            sims.insert(alias, sim);
        }
        Ok(Self { sims })
    }

    /// Where device facts live: this machine, not this checkout.
    ///
    /// A simulator is an operating-system object. Its UDID, its runtime
    /// version, whether it is booted and who booted it do not change
    /// when you `cd` — so storing them per checkout means four trees on
    /// one machine each hold their own answer, which is what they do
    /// today. On 2026-08-11 two of them held a lease on the same
    /// simulators, and a runner on port 22087 was simultaneously on the
    /// books and invisible: the rule says check the owner before
    /// touching a runner, and the checkout doing the checking was not
    /// the one holding the record.
    ///
    /// `$XDG_DATA_HOME/smix` or `~/.local/share/smix`, which is where
    /// the runner tree and its version stamp already live — machine
    /// scope is not a new idea here, it was just not used for this.
    ///
    /// `None` when neither variable is set, which is the same condition
    /// under which the runner tree has no home either; the caller falls
    /// back to the checkout and says so.
    pub fn machine_dir() -> Option<PathBuf> {
        smix_lease::store::machine_root().map(|r| r.join("devices"))
    }

    /// Every registry a read may draw on, in precedence order.
    ///
    /// `SMIX_SIMS_JSON` names one registry and means exactly that one:
    /// it is how a test works against a book of its own, and a
    /// machine-level fallback under it would let the real one leak in.
    ///
    /// Otherwise the machine registry first, then whatever checkout is
    /// underfoot. The checkout entry keeps books written before this
    /// move working until `smix sim migrate` folds them in; nothing is
    /// ever written back to it.
    pub fn read_paths(start: &Path) -> Vec<PathBuf> {
        if let Some(p) = std::env::var_os("SMIX_SIMS_JSON") {
            return vec![PathBuf::from(p)];
        }
        let mut paths = Vec::new();
        if let Some(m) = Self::machine_dir() {
            paths.push(m);
        }
        if let Some(c) = Self::discover(start) {
            paths.push(c);
        }
        paths
    }

    /// Read every registry that applies and fold them into one.
    ///
    /// A source that will not open is skipped rather than fatal: one
    /// corrupt book must not strand the devices recorded in the others.
    /// Which is why this returns a value and not a `Result` — there is
    /// no failure here other than "nothing was readable anywhere", and
    /// that is an empty registry, which reads the same as a machine
    /// where nothing has been registered yet.
    pub fn open_all(start: &Path) -> MergedRegistry {
        // `SMIX_SIMS_JSON` names one registry and means exactly that one:
        // there is no machine/checkout split to report, and calling the
        // caller's own choice "unmigrated" would be advice to move a book
        // they put where they wanted it.
        if let Some(p) = std::env::var_os("SMIX_SIMS_JSON") {
            let path = PathBuf::from(p);
            let registry = Self::load(&path).unwrap_or_default();
            let sources = registry
                .sims
                .keys()
                .map(|a| (a.clone(), Source::Named(path.clone())))
                .collect();
            return MergedRegistry {
                registry,
                unmigrated: BTreeMap::new(),
                sources,
                diverged: BTreeMap::new(),
            };
        }
        let machine = Self::machine_dir();
        let checkouts: Vec<PathBuf> = Self::discover(start).into_iter().collect();
        Self::open_books(machine.as_deref(), &checkouts)
    }

    /// Fold this machine's registry and the checkout books named here.
    ///
    /// The machine is the authority (§9 #9). Checkout books are merged
    /// among themselves the way they always were — they have no order —
    /// and then may add only aliases the machine does not hold. An alias
    /// both hold for the same device keeps the machine's row, with
    /// destructive consent narrowed if the checkout withheld it (a stop,
    /// which is a power a checkout keeps). An alias both hold for
    /// different devices goes into [`MergedRegistry::diverged`] and is
    /// refused at resolution; the checkout's row does not enter the view
    /// under any name, because a suffixed alias is a name nobody gave.
    ///
    /// A book that will not open is skipped: one corrupt file must not
    /// strand the devices recorded in the others.
    pub fn open_books(machine: Option<&Path>, checkouts: &[PathBuf]) -> MergedRegistry {
        let machine = machine.and_then(|m| Self::load(m).ok().map(|r| (m.to_path_buf(), r)));
        let mut books: Vec<(PathBuf, Self)> = checkouts
            .iter()
            .flat_map(|c| Self::checkout_books(c))
            .collect();
        books.sort_by(|a, b| a.0.cmp(&b.0));
        Self::combine(machine, books)
    }

    /// The books a checkout's `.smix` holds, read without writing.
    ///
    /// A pre-store `sims.json` and a store written by an older smix are
    /// two books, read separately so a disagreement can name the file.
    /// Neither is opened for writing: reading one used to create a store
    /// in the checkout and import the JSON into it, which put device
    /// facts back into a checkout on every read.
    fn checkout_books(path: &Path) -> Vec<(PathBuf, Self)> {
        let dir = smix_dir(path);
        let mut out = Vec::new();
        if dir.join("kv").is_dir()
            && let Ok(store) = smix_store::Store::open(&dir)
        {
            let mut sims = BTreeMap::new();
            for alias in store.sims().list() {
                if let Ok(Some(sim)) = store.sims().get_json::<RegisteredSim>(&alias) {
                    sims.insert(alias, sim);
                }
            }
            out.push((dir.clone(), Self { sims }));
        }
        let legacy = dir.join("sims.json");
        if let Ok(bytes) = std::fs::read(&legacy)
            && let Ok(doc) = serde_json::from_slice::<LegacyBook>(&bytes)
        {
            out.push((legacy, Self { sims: doc.sims }));
        }
        out
    }

    /// The pure half of [`Self::open_books`]: already-read books in,
    /// one view out.
    fn combine(machine: Option<(PathBuf, Self)>, books: Vec<(PathBuf, Self)>) -> MergedRegistry {
        let (mpath, mut mreg) = match machine {
            Some((p, r)) => (Some(p), r),
            None => (None, Self::default()),
        };
        let mut sources: BTreeMap<String, Source> = BTreeMap::new();
        if let Some(p) = &mpath {
            for alias in mreg.sims.keys() {
                sources.insert(alias.clone(), Source::Machine(p.clone()));
            }
        }
        let mut diverged: BTreeMap<String, Divergence> = BTreeMap::new();
        let mut rest: Vec<Self> = Vec::new();
        let mut rest_paths: Vec<(PathBuf, Self)> = Vec::new();
        for (path, book) in books {
            let mut kept = BTreeMap::new();
            for (alias, sim) in book.sims {
                match (mreg.sims.get_mut(&alias), &mpath) {
                    (Some(own), _) if own.udid.eq_ignore_ascii_case(&sim.udid) => {
                        own.destructive_opt_in = own.destructive_opt_in && sim.destructive_opt_in;
                    }
                    (Some(own), Some(mp)) => {
                        diverged
                            .entry(alias)
                            .or_insert_with(|| Divergence {
                                machine: (mp.clone(), own.udid.clone()),
                                checkouts: Vec::new(),
                            })
                            .checkouts
                            .push((path.clone(), sim.udid));
                    }
                    _ => {
                        kept.insert(alias, sim);
                    }
                }
            }
            rest_paths.push((path.clone(), Self { sims: kept.clone() }));
            rest.push(Self { sims: kept });
        }
        let checkout_only = Self::merge(rest);
        let on_machine: std::collections::BTreeSet<String> = mreg
            .sims
            .values()
            .map(|s| s.udid.to_ascii_uppercase())
            .collect();
        let mut unmigrated = BTreeMap::new();
        for (alias, sim) in checkout_only.sims {
            let from = rest_paths
                .iter()
                .find(|(_, b)| {
                    b.sims
                        .values()
                        .any(|s| s.udid.eq_ignore_ascii_case(&sim.udid))
                })
                .map(|(p, _)| p.clone())
                .unwrap_or_default();
            if mpath.is_some() && !on_machine.contains(&sim.udid.to_ascii_uppercase()) {
                unmigrated.insert(alias.clone(), from.clone());
            }
            sources.insert(alias.clone(), Source::Checkout(from));
            mreg.sims.insert(alias, sim);
        }
        MergedRegistry {
            registry: mreg,
            unmigrated,
            sources,
            diverged,
        }
    }

    /// Walk up from `start` looking for a `.smix` that holds a
    /// registry — either the store or a legacy `sims.json`.
    pub fn discover(start: &Path) -> Option<PathBuf> {
        let mut dir = Some(start);
        while let Some(d) = dir {
            let smix = d.join(".smix");
            if smix.join("sims.json").is_file() || smix.join("kv").is_dir() {
                return Some(smix);
            }
            dir = d.parent();
        }
        None
    }

    /// Resolve a device ref to the identifier its platform is addressed by.
    ///
    /// CoreSimulator-form input passes through whether or not it is
    /// registered. Otherwise the ref must match an alias key, a
    /// `deviceName`, or the registered identifier itself.
    ///
    /// That last one was missing until 2026-08-06, and [`Self::lookup`]
    /// had it — so the two disagreed about whether a device's own
    /// identifier names it. A real phone found the disagreement: an iOS
    /// device UDID is 25 characters, not CoreSimulator's 36, so it fell
    /// past the short-circuit into a search that never looked at the one
    /// field it matched. `smix runner forward 00008120-…` answered
    /// "unknown device ref" about a device that was registered right
    /// there in the file it was reading.
    pub fn resolve(&self, device_ref: &str) -> Result<String, RegistryError> {
        if is_udid(device_ref) {
            return Ok(device_ref.to_ascii_uppercase());
        }
        // Stored verbatim, returned verbatim. The value was already put
        // in its platform's form at registration by
        // [`canonical_identifier`]; upper-casing it a second time here is
        // what turned a registered `emulator-5554` into the
        // `EMULATOR-5554` that adb does not answer to.
        if let Some(sim) = self.sims.get(device_ref) {
            return Ok(sim.udid.clone());
        }
        if let Some(sim) = self
            .sims
            .values()
            .find(|s| s.device_name == device_ref || s.udid.eq_ignore_ascii_case(device_ref))
        {
            return Ok(sim.udid.clone());
        }
        // Deduplicated: an alias and a device name are commonly the same
        // word, and "one of the recorded aliases: phone, phone" reads as
        // a bug in the tool rather than a list of choices.
        let mut known: Vec<String> = Vec::with_capacity(self.sims.len() * 2);
        for (alias, sim) in &self.sims {
            for name in [alias, &sim.device_name] {
                if !known.iter().any(|k| k == name) {
                    known.push(name.clone());
                }
            }
        }
        Err(RegistryError::UnknownDevice {
            device_ref: device_ref.to_string(),
            known,
        })
    }

    /// All registered sims, keyed by alias.
    /// Fold several registries into one, losing nothing.
    ///
    /// Four checkouts on this machine each keep their own, and merging
    /// them is a one-way door: whatever this drops, the tree that was
    /// relying on it stops working, and nobody can tell which of the
    /// four to look in. So the rules are chosen to be safe, not tidy.
    ///
    /// - **Two aliases for one device: keep both.** An alias is how
    ///   somebody types a device's name. Dropping one breaks whatever
    ///   script used it; a duplicate is noise.
    /// - **Conflicting destructive consent: take the stricter.**
    ///   Consent is a per-device authorisation (§9 #1), and merging two
    ///   books is not a moment to widen it. Granting it again is one
    ///   command; un-wiping a phone is not a command at all.
    /// - **Same alias, different devices: keep both**, the later one
    ///   under a suffixed alias. Silently overwriting means one tree's
    ///   alias stops resolving with no way to know which.
    ///
    /// Order-independent for the facts that matter: four checkouts have
    /// no natural order, and a merge that depends on read order changes
    /// when somebody renames a directory.
    pub fn merge(sources: impl IntoIterator<Item = Self>) -> Self {
        let mut out: BTreeMap<String, RegisteredSim> = BTreeMap::new();
        // Sorted, so the result cannot depend on which tree was read
        // first.
        let mut incoming: Vec<(String, RegisteredSim)> = sources
            .into_iter()
            .flat_map(|r| r.sims.into_iter())
            .collect();
        incoming.sort_by(|a, b| (&a.0, &a.1.udid).cmp(&(&b.0, &b.1.udid)));

        for (alias, sim) in incoming {
            match out.get_mut(&alias) {
                None => {
                    out.insert(alias, sim);
                }
                Some(existing) if existing.udid == sim.udid => {
                    // Same device under the same name: the only thing
                    // that can differ is consent, and it narrows.
                    existing.destructive_opt_in =
                        existing.destructive_opt_in && sim.destructive_opt_in;
                }
                Some(_) => {
                    // Same name, different device. Both survive; the
                    // second takes a suffix derived from its UDID so the
                    // name is stable across merges rather than depending
                    // on how many collisions came before it.
                    let short = sim.udid.chars().take(8).collect::<String>().to_lowercase();
                    out.insert(format!("{alias}-{short}"), sim);
                }
            }
        }
        Self { sims: out }
    }

    /// Fold `sources` into the registry at `into`, keeping everything.
    ///
    /// The merge rules are [`Self::merge`]'s; this applies them to books
    /// on disk. What it adds to them is a promise about the sources:
    /// they are read and left alone. Somebody who has to go back to a
    /// smix from before device records became machine-scoped must still
    /// find their registry where they left it — and a migration that
    /// deletes what it has just copied has no way to be run twice by
    /// somebody who is not sure whether it worked.
    ///
    /// Writes go through [`Self::register`], one key at a time, for the
    /// reason that function documents: a whole-file rewrite loses a
    /// concurrent registration without saying so.
    pub fn migrate(into: &Path, sources: &[PathBuf]) -> Result<MigrationReport, RegistryError> {
        Self::migrate_inner(into, sources, true)
    }

    /// What [`Self::migrate`] would do, having done nothing.
    ///
    /// The same function with the write skipped, rather than a second
    /// one that works the answer out again — a rehearsal with its own
    /// copy of the rules reports on its copy.
    ///
    /// # Errors
    ///
    /// As [`Self::migrate`], minus the ones only a write can raise.
    pub fn migrate_dry_run(
        into: &Path,
        sources: &[PathBuf],
    ) -> Result<MigrationReport, RegistryError> {
        Self::migrate_inner(into, sources, false)
    }

    fn migrate_inner(
        into: &Path,
        sources: &[PathBuf],
        commit: bool,
    ) -> Result<MigrationReport, RegistryError> {
        let mut report = MigrationReport::default();
        let mut books = vec![Self::load(into)?];
        let before: BTreeMap<String, String> = books[0]
            .sims
            .iter()
            .map(|(a, s)| (a.clone(), s.udid.clone()))
            .collect();

        for src in sources {
            match Self::load(src) {
                Ok(reg) if reg.sims.is_empty() => report.empty.push(src.clone()),
                Ok(reg) => books.push(reg),
                // Named, not fatal. One book nobody can open must not
                // strand the devices recorded in the others — and the
                // path is what somebody needs in order to go look.
                Err(e) => report.unreadable.push((src.clone(), e.to_string())),
            }
        }

        let merged = Self::merge(books);
        for (alias, sim) in &merged.sims {
            match before.get(alias) {
                Some(udid) if udid == &sim.udid => report.unchanged.push(alias.clone()),
                Some(_) => report.narrowed.push(alias.clone()),
                None => report.added.push(alias.clone()),
            }
            if commit {
                Self::register(into, alias, sim.clone())?;
            }
        }
        Ok(report)
    }

    /// Every alias and what it points at.
    pub fn all(&self) -> impl Iterator<Item = (&str, &RegisteredSim)> {
        self.sims.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// Add or replace one entry. For merging and for tests; the
    /// registering path goes through `register`, which also writes.
    pub fn insert(&mut self, alias: impl Into<String>, sim: RegisteredSim) {
        self.sims.insert(alias.into(), sim);
    }

    /// Every registered sim, keyed by alias.
    pub fn sims(&self) -> &BTreeMap<String, RegisteredSim> {
        &self.sims
    }

    /// Look up a [`RegisteredSim`] by alias key, device name, or UDID.
    /// Returns `None` if no entry matches any of the three. Mirrors
    /// [`Self::resolve`]'s match precedence so cli callers can fetch
    /// the full spec (e.g. `locale` field) after they already resolved
    /// the UDID.
    pub fn lookup(&self, device_ref: &str) -> Option<&RegisteredSim> {
        if let Some(sim) = self.sims.get(device_ref) {
            return Some(sim);
        }
        self.sims
            .values()
            .find(|sim| sim.device_name == device_ref || sim.udid.eq_ignore_ascii_case(device_ref))
    }
}

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

    const UDID: &str = "47ACEAE5-36BA-4C62-811B-F09B397910D7";

    #[test]
    fn each_virtual_kind_takes_its_own_platforms_identifiers() {
        assert!(identifier_fits(DeviceKind::Simulator, UDID).is_ok());
        assert!(identifier_fits(DeviceKind::Emulator, "emulator-5554").is_ok());
        // And not each other's. A UDID registered as an emulator would
        // be an alias for something adb can never be handed.
        assert!(identifier_fits(DeviceKind::Simulator, "emulator-5554").is_err());
        assert!(identifier_fits(DeviceKind::Emulator, UDID).is_err());
    }

    #[test]
    fn a_physical_identifier_is_taken_as_given() {
        // Nothing on this machine can enumerate the world's phones, so
        // there is no catalogue to check against — which is precisely
        // why registering one is a deliberate act. Both spellings are
        // legitimate: a UDID for iOS, an adb serial for Android.
        assert!(identifier_fits(DeviceKind::PhysicalIos, "00008120-001410C11A42201E").is_ok());
        assert!(identifier_fits(DeviceKind::PhysicalAndroid, "R5CT52DF07D").is_ok());
        // Empty is still nothing.
        assert!(identifier_fits(DeviceKind::PhysicalIos, "   ").is_err());
    }

    #[test]
    fn an_emulator_serial_is_recognised_not_guessed() {
        assert!(is_emulator_serial("emulator-5554"));
        assert!(!is_emulator_serial("emulator-"));
        assert!(!is_emulator_serial("emulator-abcd"));
        // Case matters: adb matches serials verbatim, and this is not a
        // device. The UDID path upper-cases; this one must not.
        assert!(!is_emulator_serial("EMULATOR-5554"));
        assert!(!is_emulator_serial("R5CT52DF07D"));
    }

    #[test]
    fn apple_identifiers_are_normalised_and_adb_serials_are_not() {
        // Measured, not assumed: `devicectl` rejects the lower-case
        // spelling of a UDID it accepts in upper-case, so upper-casing
        // an Apple identifier rescues it. `adb` matches byte for byte,
        // so the same move would break it.
        assert_eq!(
            canonical_identifier(
                DeviceKind::Simulator,
                "47aceae5-36ba-4c62-811b-f09b397910d7"
            ),
            "47ACEAE5-36BA-4C62-811B-F09B397910D7"
        );
        assert_eq!(
            canonical_identifier(DeviceKind::PhysicalIos, "00008120-001410c11a42201e"),
            "00008120-001410C11A42201E"
        );
        assert_eq!(
            canonical_identifier(DeviceKind::Emulator, "emulator-5554"),
            "emulator-5554"
        );
        assert_eq!(
            canonical_identifier(DeviceKind::PhysicalAndroid, "abc123xyz"),
            "abc123xyz"
        );
    }

    #[test]
    fn an_alias_resolves_to_what_was_stored_not_to_an_upper_cased_copy() {
        // The bug this pins: `sim resolve` used to upper-case whatever
        // it returned, so a registered `emulator-5554` came back as
        // `EMULATOR-5554` — a string adb does not answer to. Normalising
        // happens once, at registration, where the kind is known.
        let mut sims = BTreeMap::new();
        sims.insert(
            "emu".to_string(),
            RegisteredSim {
                device_name: "emu".into(),
                udid: "emulator-5554".into(),
                runtime: String::new(),
                device_type: String::new(),
                avd_name: None,
                locale: None,
                runner_port: None,
                kind: DeviceKind::Emulator,
                destructive_opt_in: false,
            },
        );
        let reg = SimRegistry { sims };
        assert_eq!(reg.resolve("emu").unwrap(), "emulator-5554");
    }

    #[test]
    fn the_mismatch_says_what_that_kind_looks_like() {
        // "not UDID-form" told an Android user the shape of a thing they
        // were not registering. The message has to name the world they
        // are actually in.
        let e = identifier_fits(DeviceKind::Emulator, UDID).expect_err("must refuse");
        let msg = e.to_string();
        assert!(msg.contains("emulator-<port>"), "got: {msg}");
        assert!(msg.contains("adb devices"), "got: {msg}");
        assert!(!msg.contains("8-4-4-4-12"), "wrong world named: {msg}");
    }

    #[test]
    fn a_registry_written_before_this_field_reads_as_simulator() {
        // The compatibility case that matters: every existing registry on
        // every machine was written without `kind`. Reading those as
        // physical would put a working simulator setup behind an opt-in
        // its owner never asked for.
        let json = r#"{
            "deviceName": "sim-smix-02",
            "udid": "5D087114-ECB3-443C-8DDB-40EEF9CFB90C",
            "runtime": "iOS-26-5",
            "deviceType": "iPhone-17-Pro"
        }"#;
        let sim: RegisteredSim = serde_json::from_str(json).expect("old record still parses");
        assert_eq!(sim.kind, DeviceKind::Simulator);
        assert!(!sim.kind.is_physical());
        assert!(!sim.destructive_opt_in, "opt-in defaults to off");
    }

    #[test]
    fn every_kind_knows_whether_it_is_physical() {
        assert!(!DeviceKind::Simulator.is_physical());
        assert!(!DeviceKind::Emulator.is_physical());
        assert!(DeviceKind::PhysicalIos.is_physical());
        assert!(DeviceKind::PhysicalAndroid.is_physical());
    }

    #[test]
    fn kind_roundtrips_with_its_wire_spelling_pinned() {
        let sim = RegisteredSim {
            device_name: "panda".into(),
            kind: DeviceKind::PhysicalIos,
            destructive_opt_in: true,
            udid: "00008120-001410C11A42201E".into(),
            runtime: "iOS-26-5".into(),
            device_type: "iPhone15,4".into(),
            avd_name: None,
            locale: None,
            runner_port: None,
        };
        let json = serde_json::to_string(&sim).expect("serialize");
        assert!(json.contains("\"physicalIos\""), "got: {json}");
        assert!(json.contains("\"destructiveOptIn\":true"), "got: {json}");
        let back: RegisteredSim = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.kind, DeviceKind::PhysicalIos);
        assert!(back.destructive_opt_in);
    }
}

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

    fn live(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(s, a)| ((*s).to_string(), (*a).to_string()))
            .collect()
    }

    #[test]
    fn an_avd_still_in_the_slot_it_was_registered_on_is_addressed_there() {
        let out = emulator_address(
            Some("a-01"),
            "emulator-5554",
            &live(&[("emulator-5554", "a-01")]),
        );
        assert_eq!(
            out,
            EmulatorAddress::At {
                serial: "emulator-5554".into()
            }
        );
    }

    #[test]
    fn an_avd_that_moved_slots_is_followed_not_looked_up_by_slot() {
        // This machine, 2026-09-23: the row says 5554, the AVD is on
        // 5556, and 5554 now hosts somebody else's emulator.
        let out = emulator_address(
            Some("a-01"),
            "emulator-5554",
            &live(&[
                ("emulator-5554", "qip-consumer-36"),
                ("emulator-5556", "a-01"),
            ]),
        );
        assert_eq!(
            out,
            EmulatorAddress::MovedTo {
                serial: "emulator-5556".into(),
                recorded: "emulator-5554".into()
            }
        );
    }

    #[test]
    fn an_avd_that_is_not_running_says_who_holds_the_slot_it_used_to_have() {
        let out = emulator_address(
            Some("a-01"),
            "emulator-5554",
            &live(&[("emulator-5554", "qip-consumer-36")]),
        );
        assert_eq!(
            out,
            EmulatorAddress::NotRunning {
                avd: "a-01".into(),
                slot_now: Some("qip-consumer-36".into())
            }
        );
    }

    #[test]
    fn nothing_running_is_not_running_with_nobody_in_the_slot() {
        let out = emulator_address(Some("a-01"), "emulator-5554", &live(&[]));
        assert_eq!(
            out,
            EmulatorAddress::NotRunning {
                avd: "a-01".into(),
                slot_now: None
            }
        );
    }

    #[test]
    fn a_row_with_no_identity_says_so_whatever_is_in_the_slot() {
        // Both directions: an empty slot does not turn "we do not know
        // which device this is" into "we do". That step is exactly how a
        // slot quietly becomes an identity.
        let expected = EmulatorAddress::NoIdentityRecorded {
            serial: "emulator-5554".into(),
        };
        assert_eq!(
            emulator_address(None, "emulator-5554", &live(&[])),
            expected
        );
        assert_eq!(
            emulator_address(
                None,
                "emulator-5554",
                &live(&[("emulator-5554", "somebody-else")])
            ),
            expected
        );
        // An empty string is an absence that was written down, not a name.
        assert_eq!(
            emulator_address(Some(""), "emulator-5554", &live(&[])),
            expected
        );
    }

    #[test]
    fn avd_names_are_matched_byte_for_byte() {
        // `adb` and `emulator -avd` both match verbatim, so a case fold
        // here would address a device neither of them would.
        let out = emulator_address(
            Some("A-01"),
            "emulator-5554",
            &live(&[("emulator-5554", "a-01")]),
        );
        assert_eq!(
            out,
            EmulatorAddress::NotRunning {
                avd: "A-01".into(),
                slot_now: Some("a-01".into())
            }
        );
    }

    #[test]
    fn there_are_four_answers_and_each_carries_a_different_sentence() {
        // A count, not a walk: folding one answer into another is how a
        // refusal turns into a different refusal's wording and stops
        // being about what happened.
        assert_eq!(EmulatorAddress::VARIANTS, 4);
    }
}
#[cfg(test)]
mod avd_name_tests {
    use super::*;

    fn row(kind: DeviceKind, device_type: &str, avd_name: Option<&str>) -> RegisteredSim {
        RegisteredSim {
            device_name: "d".into(),
            kind,
            destructive_opt_in: false,
            udid: "emulator-5554".into(),
            runtime: String::new(),
            device_type: device_type.into(),
            avd_name: avd_name.map(str::to_string),
            locale: None,
            runner_port: None,
        }
    }

    #[test]
    fn the_new_field_is_absent_from_the_wire_until_it_is_set() {
        // An older reader has to keep reading these files.
        let json = serde_json::to_string(&row(DeviceKind::Emulator, "", None)).expect("serialize");
        assert!(!json.contains("avdName"), "got: {json}");
        let json =
            serde_json::to_string(&row(DeviceKind::Emulator, "", Some("a-01"))).expect("serialize");
        assert!(json.contains("\"avdName\":\"a-01\""), "got: {json}");
        let back: RegisteredSim = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.avd_name(), Some("a-01"));
    }

    #[test]
    fn an_emulator_row_written_before_the_field_existed_keeps_its_identity() {
        // Registration has written the AVD name into `deviceType` since
        // emulators became registrable. Those rows are not identityless;
        // their identity is in a field named after somebody else's idea.
        let sim = row(DeviceKind::Emulator, "sim-smix-android-01", None);
        assert_eq!(sim.avd_name(), Some("sim-smix-android-01"));
    }

    #[test]
    fn a_simulators_device_type_is_not_an_avd_name() {
        // The same field carries Apple's device type for simulators.
        // Reading that as an identity would invent an AVD called
        // `com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro`.
        let sim = row(
            DeviceKind::Simulator,
            "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
            None,
        );
        assert_eq!(sim.avd_name(), None);
        let phone = row(DeviceKind::PhysicalAndroid, "SM-S9010", None);
        assert_eq!(phone.avd_name(), None);
    }

    #[test]
    fn the_new_field_wins_when_both_are_there() {
        let sim = row(DeviceKind::Emulator, "old-name", Some("new-name"));
        assert_eq!(sim.avd_name(), Some("new-name"));
    }
}