Skip to main content

smix_simctl/
registry.rs

1//! The device registry — deterministic device addressing.
2//!
3//! Records live in the `smix-store` under `.smix/`. A pre-store
4//! `sims.json` sitting beside it is imported on open and then left
5//! alone; smix never writes that file again.
6//!
7//! Every smix device operation targets either an explicit UDID or an
8//! alias recorded in this file. Resolution never consults the live
9//! simulator set: the registry file is the only mapping source, so a
10//! given input always resolves to the same device regardless of what
11//! happens to be booted on the machine.
12
13use serde::{Deserialize, Serialize};
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use thiserror::Error;
17
18/// Failure variants for registry load / device-ref resolution.
19#[derive(Debug, Error)]
20pub enum RegistryError {
21    /// Registry file could not be read.
22    #[error("cannot read sim registry {path}: {source}")]
23    Io {
24        /// Path that failed to read.
25        path: String,
26        /// Underlying I/O error.
27        source: std::io::Error,
28    },
29    /// Registry file is not valid registry JSON.
30    #[error("malformed sim registry {path}: {detail}")]
31    Malformed {
32        /// Path that failed to parse.
33        path: String,
34        /// Parser-side detail.
35        detail: String,
36    },
37    /// Input is neither a UDID nor a recorded alias.
38    #[error(
39        "unknown device ref {device_ref:?} — pass an explicit UDID or one of \
40         the recorded aliases: {}",
41        known.join(", ")
42    )]
43    UnknownDevice {
44        /// The input that failed to resolve.
45        device_ref: String,
46        /// Alias keys and device names available in the registry.
47        known: Vec<String>,
48    },
49}
50
51/// What kind of device a registry entry names.
52///
53/// The distinction exists for one reason: what smix is allowed to do to
54/// it. A simulator can be erased and rebuilt in a minute; a phone in
55/// somebody's pocket cannot. §9#1 hangs the destructive-action guard off
56/// this field.
57///
58/// Defaults to `Simulator` when the field is absent, and that direction
59/// is deliberate. Every registry written before this field existed was
60/// written by a simulator; reading those as physical would lock a working
61/// setup behind an opt-in nobody asked for. Guessing "simulator" costs at
62/// most one missing gate on a device that never needed it — guessing
63/// "physical" breaks people who did nothing wrong.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub enum DeviceKind {
67    /// iOS Simulator.
68    #[default]
69    Simulator,
70    /// Android emulator.
71    Emulator,
72    /// A physical iPhone or iPad.
73    PhysicalIos,
74    /// A physical Android device.
75    PhysicalAndroid,
76}
77
78impl DeviceKind {
79    /// Is this a device somebody might be carrying around?
80    #[must_use]
81    pub fn is_physical(self) -> bool {
82        matches!(self, DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid)
83    }
84}
85
86/// One registered simulator.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct RegisteredSim {
89    /// Human-chosen device name (also usable as an alias).
90    #[serde(rename = "deviceName")]
91    pub device_name: String,
92    /// What kind of device this is. Absent in registries written before
93    /// physical devices were addressable — see [`DeviceKind`] for why
94    /// that reads as `Simulator`.
95    #[serde(default)]
96    pub kind: DeviceKind,
97    /// Whether destructive actions have been allowed on this device.
98    ///
99    /// Only consulted for physical devices; a simulator is never gated.
100    /// Recorded once here rather than confirmed per command, because a
101    /// confirmation that must be typed every time ends up in a script,
102    /// which is the same as not having one.
103    #[serde(default, rename = "destructiveOptIn")]
104    pub destructive_opt_in: bool,
105    /// CoreSimulator UDID.
106    pub udid: String,
107    /// Runtime identifier.
108    pub runtime: String,
109    /// Device type identifier.
110    #[serde(rename = "deviceType")]
111    pub device_type: String,
112    /// Desired BCP 47 locale tag (e.g. `"en-US"`, `"ja-JP"`). When set,
113    /// `smix sim boot` enforces it via
114    /// `defaults write -g AppleLanguages + AppleLocale` and reboots the
115    /// sim if the current locale differs. `None` (field absent) =
116    /// honor whatever locale the sim boots with, no enforcement.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub locale: Option<String>,
119    /// Desired runner port (SmixRunner FlyingFox HTTP port). When set,
120    /// `smix runner up <alias>` binds the runner to this port instead
121    /// of the CLI default 22087. Two sims can then run their own runner
122    /// in parallel without port collision
123    /// (e.g. `sim-a.runnerPort = 22087` + `sim-b.runnerPort = 22088`).
124    /// Falls through to `--runner-port` flag or `SMIX_RUNNER_PORT` env
125    /// when absent.
126    #[serde(
127        default,
128        rename = "runnerPort",
129        skip_serializing_if = "Option::is_none"
130    )]
131    pub runner_port: Option<u16>,
132}
133
134/// What [`SimRegistry::register`] did with the alias.
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum RegisterOutcome {
137    /// The alias did not exist; a new row was written.
138    Added,
139    /// The alias existed; its row was replaced.
140    Updated,
141}
142
143/// Loaded view of the registry, keyed by alias.
144#[derive(Debug, Default, Clone)]
145pub struct SimRegistry {
146    sims: BTreeMap<String, RegisteredSim>,
147}
148
149/// What a migration did, per alias.
150///
151/// Reported rather than summarised as a count. A migration is a one-way
152/// door and the thing somebody needs afterwards is the ability to look
153/// up one device by name and see what happened to it.
154#[derive(Debug, Default, Clone)]
155pub struct MigrationReport {
156    /// Aliases the destination did not have.
157    pub added: Vec<String>,
158    /// Aliases that were already there, pointing at the same device.
159    pub unchanged: Vec<String>,
160    /// Aliases that were already there and whose record changed —
161    /// which, under [`SimRegistry::merge`], can only mean consent
162    /// narrowed.
163    pub narrowed: Vec<String>,
164    /// Sources that opened and held nothing.
165    pub empty: Vec<PathBuf>,
166    /// Sources that would not open, and why.
167    pub unreadable: Vec<(PathBuf, String)>,
168}
169
170/// Every registry this machine can read, folded into one.
171#[derive(Debug, Default, Clone)]
172pub struct MergedRegistry {
173    /// The merged view. Which book a device came from is not visible
174    /// here, deliberately: a device is a device.
175    pub registry: SimRegistry,
176    /// Aliases a checkout is the only holder of, and which checkout.
177    ///
178    /// Not an error — those devices work. It is the one thing a caller
179    /// has to be able to say out loud, because a record only one tree
180    /// holds is a record the next tree cannot act on, and the whole
181    /// point of moving these was that "check who owns this runner" can
182    /// be carried out from anywhere.
183    pub unmigrated: BTreeMap<String, PathBuf>,
184}
185
186/// Whether `s` has CoreSimulator UDID form (8-4-4-4-12 hex).
187///
188/// Answers the shape question only. It used to answer more than that —
189/// UDID-form input was treated as a deliberate instruction that skipped
190/// the registry entirely, and the CLI still short-circuits alias lookup
191/// on it. What changed on 2026-08-06 is that skipping the registry no
192/// longer means skipping every check: a raw identifier now has to be one
193/// the platform itself claims, because the shape alone stopped being
194/// evidence the moment a `devicectl` path appeared that reaches phones
195/// whose CoreDevice UUIDs wear exactly this form.
196pub fn is_udid(s: &str) -> bool {
197    let bytes = s.as_bytes();
198    if bytes.len() != 36 {
199        return false;
200    }
201    for (i, b) in bytes.iter().enumerate() {
202        match i {
203            8 | 13 | 18 | 23 => {
204                if *b != b'-' {
205                    return false;
206                }
207            }
208            _ => {
209                if !b.is_ascii_hexdigit() {
210                    return false;
211                }
212            }
213        }
214    }
215    true
216}
217
218/// Why an identifier does not fit the kind it was registered under.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct IdentifierMismatch {
221    /// The identifier as given.
222    pub given: String,
223    /// What that kind's identifiers look like.
224    pub expected: &'static str,
225}
226
227impl std::fmt::Display for IdentifierMismatch {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        write!(
230            f,
231            "{:?} is not how that kind of device is identified — {}",
232            self.given, self.expected
233        )
234    }
235}
236
237/// Does this identifier fit the kind it is being registered as?
238///
239/// Shape only; whether the device exists is a separate question, asked
240/// against a different catalogue per kind, and asked by the caller.
241///
242/// The three answers differ because the world does:
243///
244/// * A **simulator** is a directory on this Mac with a CoreSimulator
245///   UDID, and `simctl` can list every one of them.
246/// * An **emulator** is named by `adb`, which calls them `emulator-<port>`
247///   and will list them too.
248/// * A **phone** has no catalogue at all. Nothing on this machine can
249///   enumerate the world's devices, so its identifier is taken as given —
250///   which is exactly why registering one has to be a deliberate act
251///   rather than a lookup. That is not a hole in the check; it is the
252///   reason the check exists.
253///
254/// # Errors
255///
256/// Returns what that kind's identifiers look like, so the message can
257/// say which of the three worlds the caller landed in the wrong one of.
258pub fn identifier_fits(kind: DeviceKind, id: &str) -> Result<(), IdentifierMismatch> {
259    let ok = match kind {
260        DeviceKind::Simulator => is_udid(id),
261        DeviceKind::Emulator => is_emulator_serial(id),
262        // No catalogue exists to check against.
263        DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid => !id.trim().is_empty(),
264    };
265    if ok {
266        return Ok(());
267    }
268    Err(IdentifierMismatch {
269        given: id.to_string(),
270        expected: match kind {
271            DeviceKind::Simulator => {
272                "a simulator has a CoreSimulator UDID (8-4-4-4-12 hex); find it with `smix sim list`"
273            }
274            DeviceKind::Emulator => {
275                "adb names an emulator `emulator-<port>`, e.g. emulator-5554; find it with `adb devices`"
276            }
277            DeviceKind::PhysicalIos | DeviceKind::PhysicalAndroid => {
278                "a physical device needs a non-empty identifier: a UDID for iOS, an adb serial for Android"
279            }
280        },
281    })
282}
283
284/// Put an identifier in the form its platform matches on.
285///
286/// Normalise what has a normal form; preserve what is matched verbatim.
287///
288/// Apple's identifiers are hex and canonically upper-case, and this is
289/// not a style preference: `devicectl` was measured on 2026-08-06 to
290/// reject the lower-case spelling of a UDID it accepts in upper-case
291/// (`ERROR: The specified device was not found`). Upper-casing therefore
292/// rescues a typed-in identifier rather than mangling it.
293///
294/// `adb` matches serials byte for byte, so there is nothing to rescue and
295/// everything to break: `EMULATOR-5554` is not a device, and neither is a
296/// vendor serial that came with lower-case letters in it.
297///
298/// Done once, here, where the kind is known — never again downstream. A
299/// value normalised twice by two different rules is how `sim resolve` came
300/// to hand out `EMULATOR-5554`.
301#[must_use]
302pub fn canonical_identifier(kind: DeviceKind, id: &str) -> String {
303    match kind {
304        DeviceKind::Simulator | DeviceKind::PhysicalIos => id.to_ascii_uppercase(),
305        DeviceKind::Emulator | DeviceKind::PhysicalAndroid => id.to_string(),
306    }
307}
308
309/// Whether `s` is an adb emulator serial.
310///
311/// `adb` is the one naming these, so this recognises rather than guesses:
312/// an emulator is `emulator-<port>`, and a physical device answers with a
313/// hardware serial that never takes that form. Case matters — `adb`
314/// matches serials verbatim and `EMULATOR-5554` is not a device.
315#[must_use]
316pub fn is_emulator_serial(s: &str) -> bool {
317    s.strip_prefix("emulator-")
318        .is_some_and(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()))
319}
320
321/// Resolve a caller-supplied path to the `.smix` directory holding the
322/// store.
323///
324/// Callers pass either form: `SMIX_SIMS_JSON` documents a file, while
325/// discovery yields a directory. Accepting both is also what lets the
326/// pre-store test suite keep exercising the legacy import path
327/// unchanged, instead of being rewritten into agreement with the code
328/// it is supposed to check.
329pub fn store_dir(path: &Path) -> PathBuf {
330    smix_dir(path)
331}
332
333fn smix_dir(path: &Path) -> PathBuf {
334    if path.extension().is_some_and(|e| e == "json") {
335        path.parent().unwrap_or(path).to_path_buf()
336    } else {
337        path.to_path_buf()
338    }
339}
340
341/// Open the store under `path` and fold in any legacy `sims.json`
342/// sitting beside it.
343///
344/// The legacy file is read, never written and never removed: a user who
345/// has to go back to a pre-store smix must still find their registry.
346fn open_store(path: &Path) -> Result<smix_store::Store, RegistryError> {
347    let dir = smix_dir(path);
348    std::fs::create_dir_all(&dir).map_err(|source| RegistryError::Io {
349        path: dir.display().to_string(),
350        source,
351    })?;
352    let store = smix_store::Store::open(&dir).map_err(|e| RegistryError::Io {
353        path: dir.display().to_string(),
354        source: std::io::Error::other(e.to_string()),
355    })?;
356    let legacy = dir.join("sims.json");
357    smix_store::import_legacy_records(&store.sims(), &legacy, "sims").map_err(|e| {
358        RegistryError::Malformed {
359            path: legacy.display().to_string(),
360            detail: e.to_string(),
361        }
362    })?;
363    Ok(store)
364}
365
366impl SimRegistry {
367    /// Write `sim` into the registry under `alias`.
368    ///
369    /// One key, not a whole file. The read-modify-write this replaces
370    /// lost an alias whenever two processes registered at once — each
371    /// read the file, each inserted its own row, and the second write
372    /// erased the first, with no error on either side.
373    pub fn register(
374        path: &Path,
375        alias: &str,
376        sim: RegisteredSim,
377    ) -> Result<RegisterOutcome, RegistryError> {
378        let store = open_store(path)?;
379        let existed = store
380            .sims()
381            .get(alias)
382            .map_err(|e| RegistryError::Malformed {
383                path: path.display().to_string(),
384                detail: e.to_string(),
385            })?
386            .is_some();
387        store
388            .sims()
389            .put_json(alias, &sim)
390            .map_err(|e| RegistryError::Io {
391                path: path.display().to_string(),
392                source: std::io::Error::other(e.to_string()),
393            })?;
394        store.sync().map_err(|e| RegistryError::Io {
395            path: path.display().to_string(),
396            source: std::io::Error::other(e.to_string()),
397        })?;
398        Ok(if existed {
399            RegisterOutcome::Updated
400        } else {
401            RegisterOutcome::Added
402        })
403    }
404
405    /// Remove one alias from the registry at `path`.
406    ///
407    /// The other half of [`Self::register`], and absent until the
408    /// records moved to machine scope made its absence permanent: a
409    /// device registered by mistake — a test that wrote to the real
410    /// book, an alias for a phone somebody no longer has — could be
411    /// added and never taken back. A registry that only grows stops
412    /// describing the machine.
413    ///
414    /// Removes the name, not the device. Another alias for the same
415    /// device keeps working, which is why this takes an alias key
416    /// rather than a device ref: "forget this device" and "forget this
417    /// name for it" are different requests, and only the second one is
418    /// unambiguous.
419    ///
420    /// # Errors
421    ///
422    /// [`RegistryError::UnknownDevice`] when no such alias exists.
423    /// Silently succeeding would let a typo read as a removal.
424    pub fn unregister(path: &Path, alias: &str) -> Result<RegisteredSim, RegistryError> {
425        let reg = Self::load(path)?;
426        let Some(sim) = reg.sims.get(alias).cloned() else {
427            return Err(RegistryError::UnknownDevice {
428                device_ref: alias.to_string(),
429                known: reg.sims.keys().cloned().collect(),
430            });
431        };
432        let store = open_store(path)?;
433        store.sims().delete(alias).map_err(|e| RegistryError::Io {
434            path: path.display().to_string(),
435            source: std::io::Error::other(e.to_string()),
436        })?;
437        store.sync().map_err(|e| RegistryError::Io {
438            path: path.display().to_string(),
439            source: std::io::Error::other(e.to_string()),
440        })?;
441        Ok(sim)
442    }
443
444    /// Allow destructive actions on one registered device, once.
445    ///
446    /// Goes through [`Self::register`] rather than rewriting the file,
447    /// for the reason that function documents: a read-modify-write of the
448    /// whole registry loses a concurrent registration silently. One key
449    /// in, one key out.
450    ///
451    /// Returns the alias it was recorded against and whether it was
452    /// already allowed — the caller can then say "already allowed"
453    /// instead of implying something changed.
454    ///
455    /// # Errors
456    ///
457    /// [`RegistryError::UnknownDevice`] when nothing matches the ref. The
458    /// opt-in is per device, so there is nothing to record it against —
459    /// and silently creating an entry would mean allowing destruction on
460    /// a device nobody registered.
461    pub fn allow_destructive(
462        path: &Path,
463        device_ref: &str,
464    ) -> Result<(String, bool), RegistryError> {
465        let reg = Self::load(path)?;
466        let Some((alias, sim)) = reg
467            .sims()
468            .iter()
469            .find(|(alias, sim)| {
470                alias.as_str() == device_ref
471                    || sim.device_name == device_ref
472                    || sim.udid.eq_ignore_ascii_case(device_ref)
473            })
474            .map(|(a, s)| (a.clone(), s.clone()))
475        else {
476            let mut known: Vec<String> = Vec::new();
477            for (alias, sim) in reg.sims() {
478                known.push(alias.clone());
479                known.push(sim.device_name.clone());
480            }
481            return Err(RegistryError::UnknownDevice {
482                device_ref: device_ref.to_string(),
483                known,
484            });
485        };
486        if sim.destructive_opt_in {
487            return Ok((alias, true));
488        }
489        let updated = RegisteredSim {
490            destructive_opt_in: true,
491            ..sim
492        };
493        Self::register(path, &alias, updated)?;
494        Ok((alias, false))
495    }
496
497    /// Read every registered sim.
498    ///
499    /// `path` may be the `.smix` directory or a legacy `sims.json`
500    /// inside it; both land on the same store.
501    pub fn load(path: &Path) -> Result<Self, RegistryError> {
502        let store = open_store(path)?;
503        let mut sims = BTreeMap::new();
504        for alias in store.sims().list() {
505            let sim: RegisteredSim = store
506                .sims()
507                .get_json(&alias)
508                .map_err(|e| RegistryError::Malformed {
509                    path: path.display().to_string(),
510                    detail: e.to_string(),
511                })?
512                .ok_or_else(|| RegistryError::Malformed {
513                    path: path.display().to_string(),
514                    detail: format!("`{alias}` vanished between listing and reading"),
515                })?;
516            sims.insert(alias, sim);
517        }
518        Ok(Self { sims })
519    }
520
521    /// Where device facts live: this machine, not this checkout.
522    ///
523    /// A simulator is an operating-system object. Its UDID, its runtime
524    /// version, whether it is booted and who booted it do not change
525    /// when you `cd` — so storing them per checkout means four trees on
526    /// one machine each hold their own answer, which is what they do
527    /// today. On 2026-08-11 two of them held a lease on the same
528    /// simulators, and a runner on port 22087 was simultaneously on the
529    /// books and invisible: the rule says check the owner before
530    /// touching a runner, and the checkout doing the checking was not
531    /// the one holding the record.
532    ///
533    /// `$XDG_DATA_HOME/smix` or `~/.local/share/smix`, which is where
534    /// the runner tree and its version stamp already live — machine
535    /// scope is not a new idea here, it was just not used for this.
536    ///
537    /// `None` when neither variable is set, which is the same condition
538    /// under which the runner tree has no home either; the caller falls
539    /// back to the checkout and says so.
540    pub fn machine_dir() -> Option<PathBuf> {
541        smix_lease::store::machine_root().map(|r| r.join("devices"))
542    }
543
544    /// Every registry a read may draw on, in precedence order.
545    ///
546    /// `SMIX_SIMS_JSON` names one registry and means exactly that one:
547    /// it is how a test works against a book of its own, and a
548    /// machine-level fallback under it would let the real one leak in.
549    ///
550    /// Otherwise the machine registry first, then whatever checkout is
551    /// underfoot. The checkout entry keeps books written before this
552    /// move working until `smix sim migrate` folds them in; nothing is
553    /// ever written back to it.
554    pub fn read_paths(start: &Path) -> Vec<PathBuf> {
555        if let Some(p) = std::env::var_os("SMIX_SIMS_JSON") {
556            return vec![PathBuf::from(p)];
557        }
558        let mut paths = Vec::new();
559        if let Some(m) = Self::machine_dir() {
560            paths.push(m);
561        }
562        if let Some(c) = Self::discover(start) {
563            paths.push(c);
564        }
565        paths
566    }
567
568    /// Read every registry that applies and fold them into one.
569    ///
570    /// A source that will not open is skipped rather than fatal: one
571    /// corrupt book must not strand the devices recorded in the others.
572    /// Which is why this returns a value and not a `Result` — there is
573    /// no failure here other than "nothing was readable anywhere", and
574    /// that is an empty registry, which reads the same as a machine
575    /// where nothing has been registered yet.
576    pub fn open_all(start: &Path) -> MergedRegistry {
577        let paths = Self::read_paths(start);
578        // Under `SMIX_SIMS_JSON` there is no machine/checkout split to
579        // report: the caller named the registry, and calling their own
580        // choice "unmigrated" would be advice to move a book they put
581        // where they wanted it.
582        let machine = if std::env::var_os("SMIX_SIMS_JSON").is_some() {
583            None
584        } else {
585            Self::machine_dir()
586        };
587        let mut loaded: Vec<Self> = Vec::new();
588        let mut unmigrated: BTreeMap<String, PathBuf> = BTreeMap::new();
589        let mut on_machine: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
590        for path in &paths {
591            let Ok(reg) = Self::load(path) else {
592                continue;
593            };
594            if machine.as_deref() == Some(path.as_path()) {
595                on_machine.extend(reg.sims.values().map(|s| s.udid.to_ascii_uppercase()));
596            } else if machine.is_some() {
597                for (alias, sim) in &reg.sims {
598                    if !on_machine.contains(&sim.udid.to_ascii_uppercase()) {
599                        unmigrated.insert(alias.clone(), path.clone());
600                    }
601                }
602            }
603            loaded.push(reg);
604        }
605        MergedRegistry {
606            registry: Self::merge(loaded),
607            unmigrated,
608        }
609    }
610
611    /// Walk up from `start` looking for a `.smix` that holds a
612    /// registry — either the store or a legacy `sims.json`.
613    pub fn discover(start: &Path) -> Option<PathBuf> {
614        let mut dir = Some(start);
615        while let Some(d) = dir {
616            let smix = d.join(".smix");
617            if smix.join("sims.json").is_file() || smix.join("kv").is_dir() {
618                return Some(smix);
619            }
620            dir = d.parent();
621        }
622        None
623    }
624
625    /// Resolve a device ref to the identifier its platform is addressed by.
626    ///
627    /// CoreSimulator-form input passes through whether or not it is
628    /// registered. Otherwise the ref must match an alias key, a
629    /// `deviceName`, or the registered identifier itself.
630    ///
631    /// That last one was missing until 2026-08-06, and [`Self::lookup`]
632    /// had it — so the two disagreed about whether a device's own
633    /// identifier names it. A real phone found the disagreement: an iOS
634    /// device UDID is 25 characters, not CoreSimulator's 36, so it fell
635    /// past the short-circuit into a search that never looked at the one
636    /// field it matched. `smix runner forward 00008120-…` answered
637    /// "unknown device ref" about a device that was registered right
638    /// there in the file it was reading.
639    pub fn resolve(&self, device_ref: &str) -> Result<String, RegistryError> {
640        if is_udid(device_ref) {
641            return Ok(device_ref.to_ascii_uppercase());
642        }
643        // Stored verbatim, returned verbatim. The value was already put
644        // in its platform's form at registration by
645        // [`canonical_identifier`]; upper-casing it a second time here is
646        // what turned a registered `emulator-5554` into the
647        // `EMULATOR-5554` that adb does not answer to.
648        if let Some(sim) = self.sims.get(device_ref) {
649            return Ok(sim.udid.clone());
650        }
651        if let Some(sim) = self
652            .sims
653            .values()
654            .find(|s| s.device_name == device_ref || s.udid.eq_ignore_ascii_case(device_ref))
655        {
656            return Ok(sim.udid.clone());
657        }
658        // Deduplicated: an alias and a device name are commonly the same
659        // word, and "one of the recorded aliases: phone, phone" reads as
660        // a bug in the tool rather than a list of choices.
661        let mut known: Vec<String> = Vec::with_capacity(self.sims.len() * 2);
662        for (alias, sim) in &self.sims {
663            for name in [alias, &sim.device_name] {
664                if !known.iter().any(|k| k == name) {
665                    known.push(name.clone());
666                }
667            }
668        }
669        Err(RegistryError::UnknownDevice {
670            device_ref: device_ref.to_string(),
671            known,
672        })
673    }
674
675    /// All registered sims, keyed by alias.
676    /// Fold several registries into one, losing nothing.
677    ///
678    /// Four checkouts on this machine each keep their own, and merging
679    /// them is a one-way door: whatever this drops, the tree that was
680    /// relying on it stops working, and nobody can tell which of the
681    /// four to look in. So the rules are chosen to be safe, not tidy.
682    ///
683    /// - **Two aliases for one device: keep both.** An alias is how
684    ///   somebody types a device's name. Dropping one breaks whatever
685    ///   script used it; a duplicate is noise.
686    /// - **Conflicting destructive consent: take the stricter.**
687    ///   Consent is a per-device authorisation (§9 #1), and merging two
688    ///   books is not a moment to widen it. Granting it again is one
689    ///   command; un-wiping a phone is not a command at all.
690    /// - **Same alias, different devices: keep both**, the later one
691    ///   under a suffixed alias. Silently overwriting means one tree's
692    ///   alias stops resolving with no way to know which.
693    ///
694    /// Order-independent for the facts that matter: four checkouts have
695    /// no natural order, and a merge that depends on read order changes
696    /// when somebody renames a directory.
697    pub fn merge(sources: impl IntoIterator<Item = Self>) -> Self {
698        let mut out: BTreeMap<String, RegisteredSim> = BTreeMap::new();
699        // Sorted, so the result cannot depend on which tree was read
700        // first.
701        let mut incoming: Vec<(String, RegisteredSim)> = sources
702            .into_iter()
703            .flat_map(|r| r.sims.into_iter())
704            .collect();
705        incoming.sort_by(|a, b| (&a.0, &a.1.udid).cmp(&(&b.0, &b.1.udid)));
706
707        for (alias, sim) in incoming {
708            match out.get_mut(&alias) {
709                None => {
710                    out.insert(alias, sim);
711                }
712                Some(existing) if existing.udid == sim.udid => {
713                    // Same device under the same name: the only thing
714                    // that can differ is consent, and it narrows.
715                    existing.destructive_opt_in =
716                        existing.destructive_opt_in && sim.destructive_opt_in;
717                }
718                Some(_) => {
719                    // Same name, different device. Both survive; the
720                    // second takes a suffix derived from its UDID so the
721                    // name is stable across merges rather than depending
722                    // on how many collisions came before it.
723                    let short = sim.udid.chars().take(8).collect::<String>().to_lowercase();
724                    out.insert(format!("{alias}-{short}"), sim);
725                }
726            }
727        }
728        Self { sims: out }
729    }
730
731    /// Fold `sources` into the registry at `into`, keeping everything.
732    ///
733    /// The merge rules are [`Self::merge`]'s; this applies them to books
734    /// on disk. What it adds to them is a promise about the sources:
735    /// they are read and left alone. Somebody who has to go back to a
736    /// smix from before device records became machine-scoped must still
737    /// find their registry where they left it — and a migration that
738    /// deletes what it has just copied has no way to be run twice by
739    /// somebody who is not sure whether it worked.
740    ///
741    /// Writes go through [`Self::register`], one key at a time, for the
742    /// reason that function documents: a whole-file rewrite loses a
743    /// concurrent registration without saying so.
744    pub fn migrate(into: &Path, sources: &[PathBuf]) -> Result<MigrationReport, RegistryError> {
745        Self::migrate_inner(into, sources, true)
746    }
747
748    /// What [`Self::migrate`] would do, having done nothing.
749    ///
750    /// The same function with the write skipped, rather than a second
751    /// one that works the answer out again — a rehearsal with its own
752    /// copy of the rules reports on its copy.
753    ///
754    /// # Errors
755    ///
756    /// As [`Self::migrate`], minus the ones only a write can raise.
757    pub fn migrate_dry_run(
758        into: &Path,
759        sources: &[PathBuf],
760    ) -> Result<MigrationReport, RegistryError> {
761        Self::migrate_inner(into, sources, false)
762    }
763
764    fn migrate_inner(
765        into: &Path,
766        sources: &[PathBuf],
767        commit: bool,
768    ) -> Result<MigrationReport, RegistryError> {
769        let mut report = MigrationReport::default();
770        let mut books = vec![Self::load(into)?];
771        let before: BTreeMap<String, String> = books[0]
772            .sims
773            .iter()
774            .map(|(a, s)| (a.clone(), s.udid.clone()))
775            .collect();
776
777        for src in sources {
778            match Self::load(src) {
779                Ok(reg) if reg.sims.is_empty() => report.empty.push(src.clone()),
780                Ok(reg) => books.push(reg),
781                // Named, not fatal. One book nobody can open must not
782                // strand the devices recorded in the others — and the
783                // path is what somebody needs in order to go look.
784                Err(e) => report.unreadable.push((src.clone(), e.to_string())),
785            }
786        }
787
788        let merged = Self::merge(books);
789        for (alias, sim) in &merged.sims {
790            match before.get(alias) {
791                Some(udid) if udid == &sim.udid => report.unchanged.push(alias.clone()),
792                Some(_) => report.narrowed.push(alias.clone()),
793                None => report.added.push(alias.clone()),
794            }
795            if commit {
796                Self::register(into, alias, sim.clone())?;
797            }
798        }
799        Ok(report)
800    }
801
802    /// Every alias and what it points at.
803    pub fn all(&self) -> impl Iterator<Item = (&str, &RegisteredSim)> {
804        self.sims.iter().map(|(k, v)| (k.as_str(), v))
805    }
806
807    /// Add or replace one entry. For merging and for tests; the
808    /// registering path goes through `register`, which also writes.
809    pub fn insert(&mut self, alias: impl Into<String>, sim: RegisteredSim) {
810        self.sims.insert(alias.into(), sim);
811    }
812
813    /// Every registered sim, keyed by alias.
814    pub fn sims(&self) -> &BTreeMap<String, RegisteredSim> {
815        &self.sims
816    }
817
818    /// Look up a [`RegisteredSim`] by alias key, device name, or UDID.
819    /// Returns `None` if no entry matches any of the three. Mirrors
820    /// [`Self::resolve`]'s match precedence so cli callers can fetch
821    /// the full spec (e.g. `locale` field) after they already resolved
822    /// the UDID.
823    pub fn lookup(&self, device_ref: &str) -> Option<&RegisteredSim> {
824        if let Some(sim) = self.sims.get(device_ref) {
825            return Some(sim);
826        }
827        self.sims
828            .values()
829            .find(|sim| sim.device_name == device_ref || sim.udid.eq_ignore_ascii_case(device_ref))
830    }
831}
832
833#[cfg(test)]
834mod kind_tests {
835    use super::*;
836
837    const UDID: &str = "47ACEAE5-36BA-4C62-811B-F09B397910D7";
838
839    #[test]
840    fn each_virtual_kind_takes_its_own_platforms_identifiers() {
841        assert!(identifier_fits(DeviceKind::Simulator, UDID).is_ok());
842        assert!(identifier_fits(DeviceKind::Emulator, "emulator-5554").is_ok());
843        // And not each other's. A UDID registered as an emulator would
844        // be an alias for something adb can never be handed.
845        assert!(identifier_fits(DeviceKind::Simulator, "emulator-5554").is_err());
846        assert!(identifier_fits(DeviceKind::Emulator, UDID).is_err());
847    }
848
849    #[test]
850    fn a_physical_identifier_is_taken_as_given() {
851        // Nothing on this machine can enumerate the world's phones, so
852        // there is no catalogue to check against — which is precisely
853        // why registering one is a deliberate act. Both spellings are
854        // legitimate: a UDID for iOS, an adb serial for Android.
855        assert!(identifier_fits(DeviceKind::PhysicalIos, "00008120-001410C11A42201E").is_ok());
856        assert!(identifier_fits(DeviceKind::PhysicalAndroid, "R5CT52DF07D").is_ok());
857        // Empty is still nothing.
858        assert!(identifier_fits(DeviceKind::PhysicalIos, "   ").is_err());
859    }
860
861    #[test]
862    fn an_emulator_serial_is_recognised_not_guessed() {
863        assert!(is_emulator_serial("emulator-5554"));
864        assert!(!is_emulator_serial("emulator-"));
865        assert!(!is_emulator_serial("emulator-abcd"));
866        // Case matters: adb matches serials verbatim, and this is not a
867        // device. The UDID path upper-cases; this one must not.
868        assert!(!is_emulator_serial("EMULATOR-5554"));
869        assert!(!is_emulator_serial("R5CT52DF07D"));
870    }
871
872    #[test]
873    fn apple_identifiers_are_normalised_and_adb_serials_are_not() {
874        // Measured, not assumed: `devicectl` rejects the lower-case
875        // spelling of a UDID it accepts in upper-case, so upper-casing
876        // an Apple identifier rescues it. `adb` matches byte for byte,
877        // so the same move would break it.
878        assert_eq!(
879            canonical_identifier(
880                DeviceKind::Simulator,
881                "47aceae5-36ba-4c62-811b-f09b397910d7"
882            ),
883            "47ACEAE5-36BA-4C62-811B-F09B397910D7"
884        );
885        assert_eq!(
886            canonical_identifier(DeviceKind::PhysicalIos, "00008120-001410c11a42201e"),
887            "00008120-001410C11A42201E"
888        );
889        assert_eq!(
890            canonical_identifier(DeviceKind::Emulator, "emulator-5554"),
891            "emulator-5554"
892        );
893        assert_eq!(
894            canonical_identifier(DeviceKind::PhysicalAndroid, "abc123xyz"),
895            "abc123xyz"
896        );
897    }
898
899    #[test]
900    fn an_alias_resolves_to_what_was_stored_not_to_an_upper_cased_copy() {
901        // The bug this pins: `sim resolve` used to upper-case whatever
902        // it returned, so a registered `emulator-5554` came back as
903        // `EMULATOR-5554` — a string adb does not answer to. Normalising
904        // happens once, at registration, where the kind is known.
905        let mut sims = BTreeMap::new();
906        sims.insert(
907            "emu".to_string(),
908            RegisteredSim {
909                device_name: "emu".into(),
910                udid: "emulator-5554".into(),
911                runtime: String::new(),
912                device_type: String::new(),
913                locale: None,
914                runner_port: None,
915                kind: DeviceKind::Emulator,
916                destructive_opt_in: false,
917            },
918        );
919        let reg = SimRegistry { sims };
920        assert_eq!(reg.resolve("emu").unwrap(), "emulator-5554");
921    }
922
923    #[test]
924    fn the_mismatch_says_what_that_kind_looks_like() {
925        // "not UDID-form" told an Android user the shape of a thing they
926        // were not registering. The message has to name the world they
927        // are actually in.
928        let e = identifier_fits(DeviceKind::Emulator, UDID).expect_err("must refuse");
929        let msg = e.to_string();
930        assert!(msg.contains("emulator-<port>"), "got: {msg}");
931        assert!(msg.contains("adb devices"), "got: {msg}");
932        assert!(!msg.contains("8-4-4-4-12"), "wrong world named: {msg}");
933    }
934
935    #[test]
936    fn a_registry_written_before_this_field_reads_as_simulator() {
937        // The compatibility case that matters: every existing registry on
938        // every machine was written without `kind`. Reading those as
939        // physical would put a working simulator setup behind an opt-in
940        // its owner never asked for.
941        let json = r#"{
942            "deviceName": "sim-smix-02",
943            "udid": "5D087114-ECB3-443C-8DDB-40EEF9CFB90C",
944            "runtime": "iOS-26-5",
945            "deviceType": "iPhone-17-Pro"
946        }"#;
947        let sim: RegisteredSim = serde_json::from_str(json).expect("old record still parses");
948        assert_eq!(sim.kind, DeviceKind::Simulator);
949        assert!(!sim.kind.is_physical());
950        assert!(!sim.destructive_opt_in, "opt-in defaults to off");
951    }
952
953    #[test]
954    fn every_kind_knows_whether_it_is_physical() {
955        assert!(!DeviceKind::Simulator.is_physical());
956        assert!(!DeviceKind::Emulator.is_physical());
957        assert!(DeviceKind::PhysicalIos.is_physical());
958        assert!(DeviceKind::PhysicalAndroid.is_physical());
959    }
960
961    #[test]
962    fn kind_roundtrips_with_its_wire_spelling_pinned() {
963        let sim = RegisteredSim {
964            device_name: "panda".into(),
965            kind: DeviceKind::PhysicalIos,
966            destructive_opt_in: true,
967            udid: "00008120-001410C11A42201E".into(),
968            runtime: "iOS-26-5".into(),
969            device_type: "iPhone15,4".into(),
970            locale: None,
971            runner_port: None,
972        };
973        let json = serde_json::to_string(&sim).expect("serialize");
974        assert!(json.contains("\"physicalIos\""), "got: {json}");
975        assert!(json.contains("\"destructiveOptIn\":true"), "got: {json}");
976        let back: RegisteredSim = serde_json::from_str(&json).expect("deserialize");
977        assert_eq!(back.kind, DeviceKind::PhysicalIos);
978        assert!(back.destructive_opt_in);
979    }
980}