Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add vphoned service profiles and the first-boot settle wait

Jacky975553e53a7b
diff --git a/Research/Guest/service_trimming.md b/Research/Guest/service_trimming.md
new file mode 100644
index 00000000..fe7e74fe
--- /dev/null
+++ b/Research/Guest/service_trimming.md
@@ -0,0 +1,185 @@
+# Trimming system services
+
+vphoned's `trimmed` service profile turns off about 140 launchd jobs a
+research VM has no use for: Siri and the intelligence daemons, Find My,
+Wallet/NFC/Secure Element, Watch, Home, health coaching, Maps background
+work, iCloud and iMessage sync, ads and recommendations, telemetry, accessory
+firmware updates and OTA. On an iOS 27.0 guest that cuts process memory by
+29%, idle host CPU by 26% and idle host writes by 60%, and no vphone feature
+was lost. The profile is applied once, in the setup boot of a machine
+template, and every clone of the template inherits it.
+
+`services.profile` and `services.profile.apply` are described in
+[`vphoned_http_api.md`](../vphoned_http_api.md); the lists are in
+`VPhoneDaemon/Daemon/GuestServiceProfile.swift`.
+
+## How it works
+
+The profile uses the override `launchctl disable` writes, which lives in
+launchd's database on the data volume
+(`/private/var/db/com.apple.xpc.launchd/disabled.plist`). launchd does not
+load a disabled job at the next boot. It is the same mechanism
+`services.disable` and the [OTA block](ota_software_update_block.md) use.
+
+- **It takes a reboot.** `services.stop` and `services.unload` answer with
+ launchd status 144 on the guest, so a running job keeps running until the
+ guest restarts.
+- **It is not a firmware patch.** The system volume and `launchd.plist` are
+ untouched, nothing goes into a patch set, and the Services panel still lists
+ every job, disabled ones marked as such.
+- **It reverts cleanly.** vphoned records the labels it disabled in
+ `/var/db/vphoned/service-profile.plist`. `profile: "none"` turns back on
+ those labels and no others. A job that was already disabled when the profile
+ ran, such as the OTA trio, is never recorded and stays disabled.
+- **The host has to ask.** The host cannot write the data volume of a guest:
+ it is encrypted with the guest's keys. So the profile is applied by vphoned
+ from inside the guest.
+
+## What `trimmed` disables
+
+| Group | Default | Labels | Why they can go |
+| --- | --- | --- | --- |
+| `base` | on | 137 | Appendix A of the measurement below. Nothing in vphone, IcliKit or the guest hooks talks to them |
+| `app_store` | on | `com.apple.appstored`, `com.apple.itunesstored` | Off with the App Store and iTunes Store apps a template removes. `appstorecomponentsd` is already in `base` |
+| `signin_followup` | on | `com.apple.followupd`, `com.apple.appleidsetupd` | The sign-in follow-up and Apple Account setup prompts. They complement `libsigninfix`'s pane suppression. A guest that went through `setup.skip` has no follow-up items, so no orphaned badge is left |
+| `accounts` | off, `groups: ["accounts"]` | `com.apple.akd`, `com.apple.amsaccountsd`, `com.apple.appleaccountd` | Only for guests that never sign in: with these off, the guest cannot sign in to an Apple Account |
+
+The `base` group, by area:
+
+| Area | Examples | Kind |
+| --- | --- | --- |
+| Siri and intelligence | assistantd, siriinferenced, intelligenceflowd, siriactionsd, modelmanagerd, corespeechd | Not used. siriactionsd also serves Shortcuts and App Intents, and corespeechd and modelmanagerd serve dictation |
+| Photos and media analysis | mediaanalysisd, photoanalysisd, photosface | mediaanalysisd alone wrote 79 MiB in a 15-minute idle window |
+| Ads, content and recommendations | amsengagementd, promotedcontentd, tipsd, weatherd, gamed | amsengagementd was the top idle CPU and write consumer |
+| Find My | findmydeviced, searchpartyd, findmylocated, fmflocatord | No Apple Account |
+| Wallet, NFC, Secure Element | passd, nfcd, seld, seserviced, coreidvd | No NFC or SE hardware |
+| Watch | nanotimekitcompaniond, nanoprefsyncd, nanobackupd | No paired watch. nanoregistryd stays (see below) |
+| Home and health | homed, homeeventsd, fitnesscoachingd, ThreadCommissionerService | HomeKit apps under test need `homed` |
+| Maps background | routined, navd, destinationd, mapspushd, mapssyncd | Not the location simulation path |
+| iCloud, iMessage, mail sync | identityservicesd, imagent, maild, remindd, replicatord, syncdefaultsd | No account. Mail, Reminders and iMessage under test need theirs |
+| Telemetry | analyticsd, triald, cloudtelemetryd, hangtelemetryd and other reporting daemons | Upload only. ReportCrash and osanalyticshelper stay, for `logs.crashes` |
+| Accessory firmware | accessoryupdaterd, uarpd and helpers | No accessories. accessoryupdaterd used 18 s of CPU at boot |
+| OTA | softwareupdateservicesd, mobile.softwareupdated, OTATaskingAgent, OTACrashCopier | Same as the [OTA block](ota_software_update_block.md) |
+| Cellular extras and prediction | WirelessRadioManager, carkitd, vmd, PowerUIAgent, duetexpertd, ospredictiond | CommCenter itself stays |
+
+Some of these are only optional: Shortcuts, dictation, HomeKit, Maps,
+Mail, Reminders, iMessage and Safari bookmark sync. A research target that
+uses one of those frameworks needs its daemon back. Pass that label in `allow`
+and apply again; the profile turns back on a recorded label it no longer
+selects.
+
+Only iOS 27 has a list. It was measured on an iPhone guest. An iOS 26 or
+iPadOS guest gets "No trimmed service list" until one is measured there.
+
+## Never disabled
+
+`GuestServiceProfile.neverDisable` lists what the profile refuses to disable,
+whatever list or group names it. Four kinds of job were measured to make the
+guest **worse** when off, and are kept out of the lists for that reason:
+
+| Job | What happens without it | Evidence |
+| --- | --- | --- |
+| `com.apple.sleepd` | SpringBoard's and mobiletimerd's HealthKit sleep clients (`HKSPXPCConnectionProvider`) reconnect to `com.apple.sleepd.sleepserver` with no back-off | 5000 log lines in 3 s, host at about 400% CPU, launchd used 115 s of CPU and wrote 385 MiB in the first two minutes |
+| `com.apple.CommCenter`, `CommCenterMobileHelper`, `CommCenterRootHelper` | SpringBoard's `SBTelephonyManager` reconnects to `com.apple.commcenter.xpc` every second and resets the idle timer each time (`updateIdleTimerForReason:"TelephonyManager:UpdateSB"`), so **the screen never turns off** | A 1 Hz loop in the log; backboardd grew from 99 to 160 MB; SpringBoard took 4418 wakeups in two minutes |
+| `com.apple.cloudd` | transparencyd (`Retrying CK account state fetch`) and ScreenTimeSettingsAgent keep retrying CloudKit | Each wrote 50–60 MiB per 15 idle minutes, against nothing on the untrimmed guest. Idle writes rose above the untrimmed guest's, to 337 MiB per 15 minutes |
+| `com.apple.nanoregistryd`, `nanoregistrylaunchd` | locationd waits synchronously on NanoRegistry's management queue | A spindump of a hung locationd showed `com.apple.nanoregistry.registry.managementqueue` in `dispatch_sync`. 27.0's locationd also hangs and crashes on its own, so this is kept out of caution |
+
+The rest of the list is what vphone's own features and the tools it drives
+rely on. Each one was traced to vphoned, IcliKit, the guest hooks or a
+research note: SpringBoard, backboardd, runningboardd, lsd,
+containermanagerd, installd, misagent, lockdownd, remoted, cryptexd,
+remotepairingdeviced, avconferenced, diskimagesiod, locationd, bluetoothd
+(locationd calls it synchronously), pasted, powerd, amfid
+(`com.apple.MobileFileIntegrity`), profiled, keybagd, cfprefsd, notifyd,
+mDNSResponder, configd, timed, tzlinkd, securityd, logd, diagnosticd,
+ReportCrash, osanalyticshelper, audiomxd, mediaplaybackd, mediaremoted,
+cameracaptured, mobileactivationd, mobileassetd and storekitd (which the OTA
+and App Store notes require), and vphoned itself. dtremotedisplayd and
+dtdeviceinfod are not launchd.plist jobs on 27.0 and are out of reach anyway.
+
+Two jobs looked like candidates and cannot be disabled this way.
+`com.apple.siri.context.service` and `com.apple.siri.acousticsignature` are
+XPC services, not LaunchDaemons, so the override is written and they run
+anyway.
+
+## Measurements
+
+These numbers come from `svctest-a`, a `--new-identity` clone of an iPhone
+27.0 (24A435) guest with cloudOS 26.4, 8 GB and 8 cores, started `--headless`
+after `setup.skip` (2026-10-07). Both runs used the same machine and disk. The
+baseline is its third untrimmed boot. Host figures are `proc_pid_rusage` of
+the VM process every 10 s. Guest figures come from `processes.list`,
+`memory.jetsam` and `/usr/bin/taskinfo`, run through a one-shot launchd job.
+
+| After 17 minutes idle | Untrimmed | Trimmed (137 + store) | Change |
+| --- | --- | --- | --- |
+| Guest process footprint, summed | 1658 MB | 1177 MB | −29% |
+| Processes | 394 | 263 | −33% |
+| `memorystatus_level` (free memory) | 62% | 73% | |
+| Host VM process CPU, idle window | 6.5% of a core | 4.8% | −26% |
+| Host writes, 15 idle minutes | 220 MiB | 89 MiB | −60% |
+| Host writes, first 100 s of boot | 572–604 MiB | 363–423 MiB | about −35% |
+| Host VM process footprint | 8.67 GB | 7.26 GB | |
+
+Boot CPU varied more between runs (72–208 s in the first 100 s untrimmed,
+44–138 s trimmed) than trimming changed it, so only the drop in boot writes is
+dependable. vphoned answered 5–14 s after start either way, because launchd
+starts it early. The host keeps most of the memory the guest frees, since the
+VM has no balloon device. The gain is headroom inside the guest.
+
+A template set up with the profile (P0, 2026-10-07) showed the same effect on
+its clones. A clone's first 100 s wrote 372–375 MiB, against 1040 MiB for a
+clone of an unprepared template.
+
+### Function checks
+
+These checks gave the same result trimmed and untrimmed: unlock, screenshot,
+`apps.list` (258), installing a small app with `apps.install` and launching it,
+Settings, clipboard, `audio.state`, starting the Camera app, uninstalling.
+SpringBoard kept the same pid through every run, and no new crash type
+appeared.
+
+Not checked:
+
+- installd's own install path (`ideviceinstaller`).
+- Xcode and DeviceHub screen viewing. The jobs they need are kept.
+- Frida.
+- A real microphone path.
+- **Location.** 27.0's locationd hangs or crashes with `EXC_ARM_PAC_FAIL` on
+ untrimmed guests too, and Location Services were off after `setup.skip`.
+ Test it again on a trimmed guest once locationd is fixed. Until then, the
+ Maps background group and `nearbyd` are only optional, not unused.
+
+Known side effect: with `weatherd` off, the default Home Screen's Weather
+widget reads "Weather Unavailable". Pass `allow: ["com.apple.weatherd"]` to
+keep it.
+
+## Applying it in a template
+
+A template is changed once, in its setup boot, and frozen; every clone
+inherits the overrides and the record. The order matters:
+
+1. `setup.skip`.
+2. `setup.settle`, until first-boot app expansion is done.
+3. Remove the system apps.
+4. `services.profile.apply {profile: "trimmed", force: true}`. The
+ `signin_followup` group belongs after the first-boot work, which step 2
+ already waited for. Every override waits for the reboot anyway, so one call
+ covers both the services and the sign-in follow-up.
+5. Reboot, and check that no job the profile owns is running
+ (`services.profile` → `running` empty).
+6. Shut down and freeze.
+
+## Reverting
+
+On a running guest:
+
+```sh
+vphone-launchpad-cli guest rpc <vm> services.profile.apply '{"profile":"none","force":true}'
+vphone-launchpad-cli vm stop <vm> && vphone-launchpad-cli vm start <vm> --wait
+```
+
+That turns back on only what the profile disabled. To keep the profile but
+bring back one job, apply `trimmed` again with that label in `allow`. To
+bring back the Apple Account daemons on a guest that had `accounts`, apply
+`trimmed` without that group.
diff --git a/Research/README.md b/Research/README.md
index 102e6943..20b77c66 100644
--- a/Research/README.md
+++ b/Research/README.md
@@ -20,7 +20,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-
| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) |
| Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) |
| Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md), [machine identity and `vm clone --new-identity`](Host/machine_identity_and_clone.md), [sharing identical disk blocks with `vm rebase`](Host/disk_rebase.md) |
-| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md), [locationd startup deadlock](Guest/locationd_startup_deadlock.md) |
+| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md), [locationd startup deadlock](Guest/locationd_startup_deadlock.md), [trimming system services](Guest/service_trimming.md) |
| Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |
`KernelSymbols/` holds symbol datasets and indexes; `Reference/` holds source references when present. They are evidence inputs, not steps for running the distributed app. The files in `History/` are preserved snapshots and may describe scripts or variants that have since been removed.
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index fd98a1a4..3bfdc7e3 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -285,12 +285,12 @@ request carries `"force": true`.
| Area | Methods |
| --- | --- |
-| Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` |
+| Device | `device.snapshot`, `device.info` (snapshot plus network, screen, rotation, brightness, volume, low power, Developer Mode, agent, `device_name` `{name, own_name}`: the pinned name and the guest's own ComputerName), `device.screen`, `device.network`, `device.ioreg {plane}`, `device.environment`, `device.basebin {archive?}` |
| Display, audio | `display.brightness {value?}`, `display.rotation {orientation?}`, `display.orientation` (`{degrees, source}`: SpringBoard's interface orientation without a screen capture, for polling; capability `display_orientation`), `display.rotation_lock {locked}`, `display.auto_lock` (`{auto_lock_seconds, never, lock_screen_minimum_seconds}`: Auto-Lock and the Lock Screen timeout vphoned keeps in step with it, see below; capability `display_auto_lock`), `screen.unlock {passcode?, timeout?}` (`{locked, screen_off, was_locked, was_screen_off}`: the display on and the Lock Screen passed, see below; capability `screen_unlock`), `audio.volume {value?, category?}`, `audio.state` |
| Input | `input.touch`, `input.hid`, `input.button {name}`, `input.key {name}`, `input.type {text, delay_ms?}`, `input.paste {text}`, `input.tap`, `input.double_tap`, `input.long_press`, `input.swipe`, `input.drag {points}`, `input.touch_sequence {events}` — gesture coordinates are screen points |
| UI | `ui.tree` (alias `accessibility.tree`), `ui.element_at`, `ui.tap_element`, `ui.wait`, `ui.wait_gone`, `ui.ocr {languages?, min_confidence?}`, `ui.describe`, `screen.screenshot` |
| Processes | `processes.list {filter?}`, `processes.kill {pid, signal?}` **force**, `memory.jetsam`, `memory.pressure` (only the three kernel memory sysctls, for polling) |
-| launchd | `services.list`, `status`, `print`, `dump`, `disabled`, `start`, `enable`, `load`; `services.stop`, `disable`, `remove`, `signal`, `unload` **force**; `launchd.getenv`, `setenv`, `unsetenv` |
+| launchd | `services.list`, `status`, `print`, `dump`, `disabled`, `start`, `enable`, `load`, `profile` (see below); `services.stop`, `disable`, `remove`, `signal`, `unload`, `profile.apply {profile, groups?, allow?}` **force**; `launchd.getenv`, `setenv`, `unsetenv` |
| Logs | `logs.syslog {seconds, process?, level?, max_lines?}` (a bounded capture of at most 60 s), `logs.crashes {bundle_id?}`, `logs.crash {path}` |
| Darwin notifications | `notify.post {name, state?}` (`postDarwinNotification`; `state` is a UInt64, as a number or a decimal string, stored before the post), `notify.state {name}` (`darwinNotificationState`) |
| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `device.name.get`, `device.name.set {name}` (see below), `network.static_names.get`, `network.static_names.set {entries}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` |
@@ -305,7 +305,7 @@ request carries `"force": true`.
| Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) |
| Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) |
| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) |
-| Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |
+| Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`); `setup.settle {timeout_s?, poll_s?, stable_polls?}` (read-only wait for first-boot work, see below); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |
`display.auto_lock` reads Settings' Auto-Lock (`maxInactivity` in profiled's
`EffectiveUserSettings.plist`) and SpringBoard's `SBMinimumLockscreenIdleTime`.
@@ -425,7 +425,76 @@ change vphoned applies configd's preferences unchanged, so configd publishes
again and `libdevicename.dylib` pins the new name at once, and posts
`com.apple.mobile.lockdown.device_name_changed`. The file outlives a reboot.
`vphone-vm` calls `set` after every connect with the VM's name. See
-`Research/Guest/device_name_pinning.md`.
+`Research/Guest/device_name_pinning.md`. `set` also returns `reboot_required`,
+true after a change: lockdown readers (Finder, `ideviceinfo`, `idevicename`) follow
+at once, but CoreDevice (Xcode, `devicectl`) reads the name once per handshake
+and the DHCP lease keeps the host name it was requested with, so both show the
+new name after the guest restarts. A clone of a template boots with the
+template's pin until `vphone-vm` connects. `device.info` carries
+`device_name: {name, own_name}`: the pinned name (null when none) and the
+guest's own `System/System/ComputerName` in configd's preferences, which a
+clone inherits.
+
+`services.profile` (capability `service_profile`) reports the service profile
+and `services.profile.apply` **force** applies one
+(`VPhoneDaemon/Daemon/GuestAPI+ServiceProfile.swift`, lists in
+`GuestServiceProfile.swift`). A profile is a set of launchd jobs turned off
+with the same override as `services.disable`; launchd honors it from the next
+boot, so the guest has to restart. `apply {profile, groups?, allow?}`:
+
+- `profile: "trimmed"` disables the default groups of the list for the
+ guest's iOS major version (`base`, the 137 labels measured on iOS 27.0;
+ `app_store`, appstored and itunesstored; `signin_followup`, followupd and
+ appleidsetupd), plus the optional groups named in `groups` (`accounts`:
+ akd, amsaccountsd, appleaccountd, after which the guest cannot sign in to an
+ Apple Account), minus the labels in `allow`. Only iOS 27 has a list; on
+ another version it fails with "No trimmed service list for iOS N".
+- `profile: "none"` turns back on only the labels the profile disabled, on any
+ version.
+- A label already disabled by somebody else (the OTA block, a user in the
+ Services panel) is skipped and never recorded, so `none` leaves it disabled.
+ A recorded label the profile no longer selects is turned back on. The jobs
+ in `GuestServiceProfile.neverDisable` (sleepd, CommCenter and its helpers,
+ cloudd, NanoRegistry, mobileassetd, storekitd, vphoned, and what vphone's
+ features use) are refused whatever names them.
+- The labels the profile owns go to `/var/db/vphoned/service-profile.plist`
+ (`Profile`, `ListVersion`, `iOSMajor`, `Groups`, `Allow`, `Labels`,
+ `Updated`). A second apply with the same arguments changes nothing.
+- It returns `{profile, ios_major, list_version, groups, disabled, enabled,
+ kept, skipped: [{label, reason}], allowed, failed: [{label, action, error}],
+ owned, reboot_required}`: `disabled` and `enabled` are what this call
+ changed, `kept` what was already the profile's, `owned` how many labels the
+ record holds. `reboot_required` is true when this call changed something or
+ a label the profile owns is still running. A failure on one label is listed
+ in `failed` and the others still apply.
+
+`services.profile` returns `{profile, ios_major, supported, supported_ios,
+list_version, groups: [{name, default, summary, labels}], never_disable,
+record, disabled, enabled_since, running, reboot_required}`: `disabled` are
+the recorded labels still disabled, `enabled_since` recorded labels somebody
+turned back on, `running` recorded labels still running until the next boot.
+See `Research/Guest/service_trimming.md`.
+
+`setup.settle` (capability `setup_settle`) waits until the guest's first-boot
+work has settled and returns, without changing anything
+(`VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift`, conditions in
+`GuestFirstBootSettle.swift`). It polls every `poll_s` seconds (default 5,
+1–30) and is settled when, over the last `stable_polls` polls (default 3,
+2–20), `/private/var/staged_system_apps` is empty or absent (installd expands
+the removable system apps from it on the first boot), the number of
+registered apps did not change, and installd used less than 0.2 s of CPU
+between polls or was not running. `timeout_s` defaults to 90 and is capped at
+110, because the host waits at most 120 s for one answer; a caller that needs
+longer calls again. A timeout is not an error: it returns `{settled, elapsed_s,
+polls, timeout_s, poll_s, stable_polls, reasons, signals}` with `settled:
+false` and `reasons` naming the conditions still unmet; `signals` holds
+`staged_system_apps` (entries, null when unreadable), `app_count`,
+`app_counts` (the window), `installd_pid`, `installd_cpu_seconds`,
+`installd_cpu_delta` and `setup_pending`.
+
+`VPhoneDaemon/Tests/run-logic-tests.sh` builds the guest-independent parts of
+these three (the lists and their bookkeeping, the settle verdict, the device
+name rule) for the Mac and checks them; it needs no guest.
`network.static_names.set` replaces the names the guest resolves locally, given
as `entries: [{address, names}]` (IPv4 only; an empty list withdraws them).
@@ -450,7 +519,7 @@ Account passwords, boot logo rendering and package installation, removal and
repository changes are deliberately not exposed. `/v1/health` lists the new
areas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,
`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,
-`app_details`, `system_control`, `system_shutdown`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `device_name`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
+`app_details`, `system_control`, `system_shutdown`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `setup_settle`, `service_profile`, `network_ipv4`, `network_hostname`, `device_name`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
panels an older agent cannot serve. icli failures reach the caller with
icli's own error `code` (`failed`, `unavailable`, `device_locked`, …) and
message.
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
index c012f66c..cc7b0c9b 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -19,6 +19,7 @@ extension GuestAPI {
info["low_power_mode"] = (try? lowPowerMode()) ?? [:]
info["developer_mode"] = (try? developerModeStatus()) ?? [:]
info["agent"] = ["binary_hash": binaryHash, "pid": getpid()]
+ info["device_name"] = deviceNameInfo()
return info
case "device.network":
return networkInfo()
@@ -205,7 +206,12 @@ extension GuestAPI {
}
/// Pin `name`, or with nil give the guest its own back. Returns the state
- /// plus `changed`.
+ /// plus `changed` and `reboot_required`: lockdown readers (Finder,
+ /// `ideviceinfo`, `idevicename`) follow a change at once, but CoreDevice (Xcode,
+ /// `devicectl`) reads the name once per handshake and the DHCP lease keeps
+ /// the host name it was requested with, so both show the new name only
+ /// after the guest restarts. A clone of a template boots with the
+ /// template's pin until `vphone-vm` connects and sets its own.
static func setDeviceName(_ name: String?) throws -> [String: Any] {
if let name {
try validateDeviceName(name)
@@ -226,21 +232,30 @@ extension GuestAPI {
}
var state = deviceNameState()
state["changed"] = changed
+ state["reboot_required"] = changed
return state
}
- /// The host's rule (`VPhoneGuestDeviceName.validate`), which the guest's
- /// (`VPDeviceNameCreateFromBytes`) accepts: not blank, at most 255 UTF-8
- /// bytes, no control character.
- private static func validateDeviceName(_ name: String) throws {
- if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
- throw GuestAPIError.invalidRequest("name must not be blank")
- }
- if name.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }) {
- throw GuestAPIError.invalidRequest("name must not contain a control character")
+ /// For `device.info`: the pinned name, and the guest's own ComputerName in
+ /// configd's preferences, which a clone inherits from its template. Two
+ /// small file reads.
+ static func deviceNameInfo() -> [String: Any] {
+ let path = "/private/var/preferences/SystemConfiguration/preferences.plist"
+ let preferences = FileManager.default.contents(atPath: path).flatMap {
+ try? PropertyListSerialization.propertyList(from: $0, format: nil) as? [String: Any]
}
- if name.utf8.count > 255 {
- throw GuestAPIError.invalidRequest("name must be at most 255 bytes in UTF-8")
+ let system = (preferences?["System"] as? [String: Any])?["System"] as? [String: Any]
+ return [
+ "name": storedDeviceName() ?? NSNull(),
+ "own_name": system?["ComputerName"] as? String ?? NSNull(),
+ ]
+ }
+
+ /// `GuestDeviceNameRule`: not blank, at most 255 UTF-8 bytes, no control
+ /// character.
+ private static func validateDeviceName(_ name: String) throws {
+ if let problem = GuestDeviceNameRule.problem(name) {
+ throw GuestAPIError.invalidRequest(problem)
}
}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index 28f91e82..2a2f81cb 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -16,6 +16,7 @@ extension GuestAPI {
executeEnvironment,
executeDeviceIdentity,
executeSetupAssistant,
+ executeFirstBoot,
executeTimeZone,
executeAudioLatency,
executeGyroscope,
diff --git a/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift b/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift
new file mode 100644
index 00000000..f4e7fe24
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+FirstBoot.swift
@@ -0,0 +1,89 @@
+import Foundation
+import IcliKit
+import IcliSystem
+import VphonedNative
+
+// MARK: - First-Boot Settle
+
+/// `setup.settle`: waits, read-only, until the guest's first-boot work has
+/// settled (`GuestFirstBootSettle` has the conditions), or until the timeout.
+/// A timeout is an answer, not an error: `settled: false` with the last
+/// signals and the conditions still unmet.
+extension GuestAPI {
+ static func executeFirstBoot(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ switch method {
+ case "setup.settle":
+ try waitForFirstBootSettle(params)
+ default:
+ nil
+ }
+ }
+
+ /// The host gives one answer at most 120 s (`VPhoneHTTPTransaction`'s
+ /// read timeout), so one call waits at most 110 s; a caller that needs
+ /// longer calls again.
+ static let settleMaximumTimeout = 110.0
+
+ private static func waitForFirstBootSettle(_ params: [String: Any]) throws -> [String: Any] {
+ for key in ["timeout_s", "poll_s", "stable_polls"] where params[key] != nil && !(params[key] is NSNumber) {
+ throw GuestAPIError.invalidRequest("\(key) must be a number")
+ }
+ let timeout = min(max(number(params, "timeout_s", default: 90), 0), settleMaximumTimeout)
+ let poll = min(max(number(params, "poll_s", default: 5), 1), 30)
+ let stablePolls = Int(min(max(number(params, "stable_polls", default: 3), 2), 20))
+
+ let start = Date()
+ var samples: [GuestFirstBootSettle.Sample] = []
+ var verdict: GuestFirstBootSettle.Verdict
+ while true {
+ samples.append(firstBootSample(time: Date().timeIntervalSince(start)))
+ verdict = GuestFirstBootSettle.evaluate(samples, stablePolls: stablePolls)
+ if verdict.settled || Date().timeIntervalSince(start) + poll > timeout {
+ break
+ }
+ Thread.sleep(forTimeInterval: poll)
+ }
+
+ let latest = samples[samples.count - 1]
+ return [
+ "settled": verdict.settled,
+ "elapsed_s": (Date().timeIntervalSince(start) * 10).rounded() / 10,
+ "polls": samples.count,
+ "timeout_s": timeout,
+ "poll_s": poll,
+ "stable_polls": stablePolls,
+ "reasons": verdict.reasons,
+ "signals": [
+ "staged_system_apps": latest.stagedSystemApps.map { $0 as Any } ?? NSNull(),
+ "app_count": latest.appCount.map { $0 as Any } ?? NSNull(),
+ "app_counts": samples.suffix(stablePolls).map { $0.appCount.map { $0 as Any } ?? NSNull() },
+ "installd_pid": latest.installdPID.map { $0 as Any } ?? NSNull(),
+ "installd_cpu_seconds": latest.installdCPUSeconds.map { $0 as Any } ?? NSNull(),
+ "installd_cpu_delta": verdict.installdCPUDelta.map { $0 as Any } ?? NSNull(),
+ "setup_pending": setupAssistantPending(),
+ ] as [String: Any],
+ ]
+ }
+
+ private static func firstBootSample(time: Double) -> GuestFirstBootSettle.Sample {
+ var sample = GuestFirstBootSettle.Sample(time: time)
+ let staged = GuestFirstBootSettle.stagedSystemAppsPath
+ if !FileManager.default.fileExists(atPath: staged) {
+ sample.stagedSystemApps = 0
+ } else if let entries = try? FileManager.default.contentsOfDirectory(atPath: staged) {
+ sample.stagedSystemApps = entries.filter { !$0.hasPrefix(".") }.count
+ }
+ if let apps = try? listApps(), let count = apps["count"] as? Int {
+ sample.appCount = count
+ }
+ let processes = (try? listProcesses(filter: "installd"))?["processes"] as? [[String: Any]] ?? []
+ if let pid = processes.first(where: { ($0["executable"] as? String)?.hasSuffix("/installd") == true })?["pid"] as? Int {
+ var usage = VPProcessUsage()
+ if vp_process_usage(Int32(pid), &usage), usage.has_task_info {
+ sample.installdPID = pid
+ sample.installdCPUSeconds = usage.cpu_seconds
+ }
+ }
+ return sample
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Service.swift b/VPhoneDaemon/Daemon/GuestAPI+Service.swift
index 74625c89..89840f7b 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Service.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Service.swift
@@ -28,6 +28,11 @@ extension GuestAPI {
return try servicesDump()
case "services.disabled":
return try disabledServiceOverrides()
+ case "services.profile":
+ return try serviceProfileState()
+ case "services.profile.apply":
+ try requireForce(params, "apply a service profile")
+ return try applyServiceProfile(params)
case "services.start":
return try startService(string(params, "label"))
case "services.enable":
diff --git a/VPhoneDaemon/Daemon/GuestAPI+ServiceProfile.swift b/VPhoneDaemon/Daemon/GuestAPI+ServiceProfile.swift
new file mode 100644
index 00000000..29312912
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+ServiceProfile.swift
@@ -0,0 +1,154 @@
+import Foundation
+import IcliKit
+import IcliSystem
+
+// MARK: - Service Profile
+
+/// `services.profile` and `services.profile.apply`, over the same launchd
+/// override as `services.disable` and `services.enable`. The lists, the
+/// never-disabled set and the bookkeeping are in `GuestServiceProfile`.
+extension GuestAPI {
+ /// One apply at a time: two would read the same record and overwrite each
+ /// other's.
+ private static let serviceProfileLock = NSLock()
+
+ private static var guestIOSMajor: Int {
+ ProcessInfo.processInfo.operatingSystemVersion.majorVersion
+ }
+
+ /// Read-only: the recorded profile, the lists for this iOS version, and
+ /// how the recorded labels stand now.
+ static func serviceProfileState() throws -> [String: Any] {
+ let major = guestIOSMajor
+ let record = GuestServiceProfile.readRecord()
+ let owned = record?.labels ?? []
+ let overrides = try disabledServiceOverrides()["disabled"] as? [String: Bool] ?? [:]
+ let running = runningServiceLabels()
+ let groups = GuestServiceProfile.groups(iosMajor: major) ?? []
+ let pending = owned.filter { running.contains($0) }
+ return [
+ "profile": record?.profile ?? GuestServiceProfile.none,
+ "ios_major": major,
+ "supported": GuestServiceProfile.groups(iosMajor: major) != nil,
+ "supported_ios": GuestServiceProfile.supportedMajors,
+ "list_version": GuestServiceProfile.listVersion,
+ "groups": groups.map { group -> [String: Any] in
+ ["name": group.name, "default": group.byDefault, "summary": group.summary, "labels": group.labels]
+ },
+ "never_disable": GuestServiceProfile.neverDisable.sorted(),
+ "record": record?.json ?? NSNull(),
+ "disabled": owned.filter { overrides[$0] == true },
+ "enabled_since": owned.filter { overrides[$0] != true },
+ "running": pending,
+ "reboot_required": !pending.isEmpty,
+ ]
+ }
+
+ /// `{profile: "trimmed"|"none", groups?, allow?}`. Disables what the
+ /// profile selects and is not yet disabled, turns back on what it disabled
+ /// earlier and no longer selects, records what it owns, and leaves every
+ /// other override alone. Idempotent: a second call changes nothing.
+ static func applyServiceProfile(_ params: [String: Any]) throws -> [String: Any] {
+ let profile = try string(params, "profile")
+ let extraGroups = try stringList(params, "groups")
+ let allow = try stringList(params, "allow")
+ for label in allow {
+ try validateServiceLabel(label)
+ }
+
+ serviceProfileLock.lock()
+ defer { serviceProfileLock.unlock() }
+
+ let major = guestIOSMajor
+ let selection: GuestServiceProfile.Selection
+ do {
+ selection = try GuestServiceProfile.select(
+ profile: profile, iosMajor: major, extraGroups: extraGroups, allow: allow,
+ )
+ } catch let failure as GuestServiceProfile.Failure {
+ throw GuestAPIError.invalidRequest(failure.description)
+ }
+ let previous = GuestServiceProfile.readRecord()
+ let overrides = try disabledServiceOverrides()["disabled"] as? [String: Bool] ?? [:]
+ let change = GuestServiceProfile.reconcile(
+ target: selection.labels, owned: previous?.labels ?? [], overrides: overrides,
+ )
+
+ var disabled: [String] = []
+ var enabled: [String] = []
+ var failed: [[String: Any]] = []
+ var failedDisable = Set<String>()
+ var failedEnable = Set<String>()
+ for label in change.disable {
+ do {
+ _ = try setServiceEnabled(label, enabled: false)
+ disabled.append(label)
+ } catch {
+ failedDisable.insert(label)
+ failed.append(["label": label, "action": "disable", "error": serviceErrorMessage(error)])
+ }
+ }
+ for label in change.enable {
+ do {
+ _ = try setServiceEnabled(label, enabled: true)
+ enabled.append(label)
+ } catch {
+ failedEnable.insert(label)
+ failed.append(["label": label, "action": "enable", "error": serviceErrorMessage(error)])
+ }
+ }
+
+ let owned = GuestServiceProfile.owned(after: change, failedDisable: failedDisable, failedEnable: failedEnable)
+ let record = GuestServiceProfile.Record(
+ profile: profile, listVersion: GuestServiceProfile.listVersion, iosMajor: major,
+ groups: selection.groups, allow: selection.allowed, labels: owned, updated: Date(),
+ )
+ do {
+ try GuestServiceProfile.writeRecord(record)
+ } catch {
+ throw GuestAPIError.operationFailed(
+ "Disabled \(disabled.count) and enabled \(enabled.count) services, but could not record them in "
+ + "\(GuestServiceProfile.recordPath): \(error.localizedDescription)",
+ )
+ }
+
+ let running = runningServiceLabels()
+ let pending = owned.filter { running.contains($0) }
+ return [
+ "profile": profile,
+ "ios_major": major,
+ "list_version": GuestServiceProfile.listVersion,
+ "groups": selection.groups,
+ "disabled": disabled,
+ "enabled": enabled,
+ "kept": change.keep,
+ "skipped": (change.skipped + selection.refused.map {
+ GuestServiceProfile.Skip(label: $0, reason: GuestServiceProfile.neverDisabledReason)
+ }).map { ["label": $0.label, "reason": $0.reason] },
+ "allowed": selection.allowed,
+ "failed": failed,
+ "owned": owned.count,
+ "reboot_required": !disabled.isEmpty || !enabled.isEmpty || !pending.isEmpty,
+ ]
+ }
+
+ /// Labels launchd reports with a pid, in either domain. Empty when the
+ /// list cannot be read; it only feeds `reboot_required`.
+ private static func runningServiceLabels() -> Set<String> {
+ let rows = (try? listServices())?["services"] as? [[String: Any]] ?? []
+ return Set(rows.compactMap { row in row["running"] as? Bool == true ? row["label"] as? String : nil })
+ }
+
+ private static func serviceErrorMessage(_ error: Error) -> String {
+ (error as? IcliError)?.message ?? String(describing: error)
+ }
+
+ /// An absent key is an empty list; anything but an array of strings is refused.
+ private static func stringList(_ params: [String: Any], _ key: String) throws -> [String] {
+ guard let value = params[key], !(value is NSNull) else { return [] }
+ guard let list = value as? [String] else {
+ throw GuestAPIError.invalidRequest("\(key) must be an array of strings")
+ }
+ return list
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 9178e084..37d7af62 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -122,6 +122,7 @@ enum GuestAPI {
"ui_inspection",
"processes",
"services",
+ "service_profile",
"logs",
"network_capture",
"app_details",
@@ -133,6 +134,7 @@ enum GuestAPI {
"environment_update",
"udid_override",
"setup_skip",
+ "setup_settle",
"network_ipv4",
"network_hostname",
"device_name",
diff --git a/VPhoneDaemon/Daemon/GuestDeviceNameRule.swift b/VPhoneDaemon/Daemon/GuestDeviceNameRule.swift
new file mode 100644
index 00000000..9137bef3
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestDeviceNameRule.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+// MARK: - Device Name Rule
+
+/// The device name rule `device.name.set` enforces: the host's
+/// (`VPhoneGuestDeviceName.validate`), which the guest's
+/// (`VPDeviceNameCreateFromBytes`) accepts. Not blank, at most 255 UTF-8
+/// bytes, no control character. SystemConfiguration takes any such string as
+/// a ComputerName and derives the DNS and mDNS names from it.
+///
+/// Nothing here touches the guest, so `VPhoneDaemon/Tests/run-logic-tests.sh`
+/// builds this file on the Mac.
+enum GuestDeviceNameRule {
+ static let maximumBytes = 255
+
+ /// Why `name` is refused, nil when it is accepted.
+ static func problem(_ name: String) -> String? {
+ if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ return "name must not be blank"
+ }
+ if name.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }) {
+ return "name must not contain a control character"
+ }
+ if name.utf8.count > maximumBytes {
+ return "name must be at most \(maximumBytes) bytes in UTF-8"
+ }
+ return nil
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift
new file mode 100644
index 00000000..abbc25d7
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestFirstBootSettle.swift
@@ -0,0 +1,96 @@
+import Foundation
+
+// MARK: - First-Boot Settle
+
+/// Decides from polled signals whether a guest's first-boot work is done, so
+/// a template can be changed and shut down without cutting it short.
+///
+/// On the first boot after a restore, installd expands the removable system
+/// apps from `/System/Library/AppPlaceholders` into data-volume containers.
+/// The ones still to do wait in `stagedSystemAppsPath`; installd empties it as
+/// it goes. Removing an app or disabling services before that ends races the
+/// expansion. Settled means, over the last `stablePolls` polls in a row:
+///
+/// - `staged_system_apps` is empty (or absent),
+/// - the number of registered apps did not change,
+/// - installd used less than `installdBusyCPUSeconds` of CPU between polls,
+/// or was not running.
+///
+/// Measured on an iOS 27.0 template (P0, 2026-10-07): 92 s after `setup.skip`
+/// all three held.
+///
+/// Nothing here touches the guest, so `VPhoneDaemon/Tests/run-logic-tests.sh`
+/// builds this file on the Mac.
+enum GuestFirstBootSettle {
+ static let stagedSystemAppsPath = "/private/var/staged_system_apps"
+ /// CPU seconds installd may use between two polls and still count as idle.
+ static let installdBusyCPUSeconds = 0.2
+
+ /// One poll.
+ struct Sample: Equatable, Sendable {
+ /// Seconds since the wait began.
+ var time: Double
+ /// Entries in `staged_system_apps`, 0 when it is absent, nil when it
+ /// could not be read.
+ var stagedSystemApps: Int?
+ /// Registered apps, nil when LaunchServices did not answer.
+ var appCount: Int?
+ /// installd's pid and CPU time, nil when it is not running.
+ var installdPID: Int?
+ var installdCPUSeconds: Double?
+ }
+
+ struct Verdict: Equatable, Sendable {
+ var settled: Bool
+ /// Why not: one line per unmet condition, empty when settled.
+ var reasons: [String]
+ /// installd's CPU between the last two polls.
+ var installdCPUDelta: Double?
+ }
+
+ /// CPU installd used from `earlier` to `later`. A new pid counts all of
+ /// its CPU so far; no installd in `later` counts as none.
+ static func installdCPUDelta(from earlier: Sample, to later: Sample) -> Double? {
+ guard let pid = later.installdPID, let cpu = later.installdCPUSeconds else { return 0 }
+ if earlier.installdPID == pid, let before = earlier.installdCPUSeconds {
+ return max(cpu - before, 0)
+ }
+ return cpu
+ }
+
+ static func evaluate(_ samples: [Sample], stablePolls: Int) -> Verdict {
+ let needed = max(stablePolls, 2)
+ let window = Array(samples.suffix(needed))
+ let lastDelta = window.count >= 2 ? installdCPUDelta(from: window[window.count - 2], to: window[window.count - 1]) : nil
+ var reasons: [String] = []
+ if window.count < needed {
+ reasons.append("\(window.count) of \(needed) polls so far")
+ }
+ if let latest = window.last {
+ switch latest.stagedSystemApps {
+ case nil:
+ reasons.append("staged_system_apps could not be read")
+ case let count? where count > 0:
+ reasons.append("staged_system_apps has \(count) entries")
+ default:
+ if window.contains(where: { ($0.stagedSystemApps ?? 1) != 0 }) {
+ reasons.append("staged_system_apps only just emptied")
+ }
+ }
+ let counts = window.map(\.appCount)
+ if counts.contains(where: { $0 == nil }) {
+ reasons.append("app count unavailable")
+ } else if Set(counts.compactMap { $0 }).count > 1 {
+ let values = counts.compactMap { $0 }.map(String.init).joined(separator: " → ")
+ reasons.append("app count changed: \(values)")
+ }
+ }
+ for (earlier, later) in zip(window, window.dropFirst()) {
+ if let delta = installdCPUDelta(from: earlier, to: later), delta >= installdBusyCPUSeconds {
+ reasons.append(String(format: "installd used %.2f s CPU between polls", delta))
+ break
+ }
+ }
+ return Verdict(settled: reasons.isEmpty, reasons: reasons, installdCPUDelta: lastDelta)
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestServiceProfile.swift b/VPhoneDaemon/Daemon/GuestServiceProfile.swift
new file mode 100644
index 00000000..fd15a0d4
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestServiceProfile.swift
@@ -0,0 +1,444 @@
+import Foundation
+
+// MARK: - Service Profiles
+
+/// A service profile is a set of launchd jobs vphoned turns off with
+/// `launchctl disable`: an override in launchd's database on the data volume
+/// (`/private/var/db/com.apple.xpc.launchd/disabled.plist`), so launchd does not
+/// load the job at the next boot. Nothing changes until the guest restarts;
+/// `launchctl stop` and `unload` return launchd status 144 on the guest.
+///
+/// `trimmed` is the set measured on an iOS 27.0 iPhone guest: memory −29%,
+/// idle host CPU −26%, idle host writes −60%, with no vphone feature lost.
+/// `none` turns back on only what the profile turned off, which it records in
+/// `recordPath`; a job somebody else disabled (the OTA block, a user in the
+/// Services panel) is never touched. See `Research/Guest/service_trimming.md`.
+///
+/// Nothing here touches the guest, so `VPhoneDaemon/Tests/run-logic-tests.sh`
+/// builds this file on the Mac.
+enum GuestServiceProfile {
+ /// Raised whenever a label list changes, and kept in the record, so a
+ /// guest shows which list its overrides came from.
+ static let listVersion = 1
+ static let recordPath = "/var/db/vphoned/service-profile.plist"
+ static let trimmed = "trimmed"
+ static let none = "none"
+
+ struct Group: Sendable {
+ let name: String
+ /// Part of `trimmed` unless the caller asks otherwise; the rest only
+ /// when named in `groups`.
+ let byDefault: Bool
+ let summary: String
+ let labels: [String]
+ }
+
+ /// The groups for an iOS major version, nil where no list was measured.
+ /// iOS 26 and iPadOS guests have none yet.
+ static func groups(iosMajor: Int) -> [Group]? {
+ iosMajor == 27 ? groups27 : nil
+ }
+
+ static let supportedMajors = [27]
+
+ // MARK: - iOS 27
+
+ static let groups27: [Group] = [
+ Group(
+ name: "base", byDefault: true,
+ summary: "Siri and intelligence, Find My, Wallet/NFC/SE, Watch, Home, health coaching, Maps background, "
+ + "iCloud/iMessage sync, ads and recommendations, telemetry, accessory firmware, OTA",
+ labels: base27,
+ ),
+ Group(
+ name: "app_store", byDefault: true,
+ summary: "App Store and iTunes Store daemons, off with the store apps; appstorecomponentsd is in base",
+ labels: ["com.apple.appstored", "com.apple.itunesstored"],
+ ),
+ Group(
+ name: "signin_followup", byDefault: true,
+ summary: "Sign-in follow-up and Apple Account setup prompts; apply after first-boot work has settled",
+ labels: ["com.apple.appleidsetupd", "com.apple.followupd"],
+ ),
+ Group(
+ name: "accounts", byDefault: false,
+ summary: "Apple Account daemons; with these off the guest cannot sign in to an Apple Account",
+ labels: ["com.apple.akd", "com.apple.amsaccountsd", "com.apple.appleaccountd"],
+ ),
+ ]
+
+ /// Appendix A of the 2026-10-07 measurement on `svctest-a` (iPhone, 27.0
+ /// 24A435): 137 LaunchDaemons that were loaded at boot and stayed unloaded
+ /// after the override, with the four traps below already taken out.
+ static let base27: [String] = [
+ "com.apple.CallHistorySyncHelper",
+ "com.apple.Maps.mapspushd",
+ "com.apple.Maps.mapssyncd",
+ "com.apple.OTACrashCopier",
+ "com.apple.OTATaskingAgent",
+ "com.apple.PerfPowerServicesExtended",
+ "com.apple.PowerUIAgent",
+ "com.apple.SafariBookmarksSyncAgent",
+ "com.apple.SensorKitALSHelper",
+ "com.apple.SiriTTSTrainingAgent",
+ "com.apple.StatusKitAgent",
+ "com.apple.ThreadCommissionerService",
+ "com.apple.WirelessRadioManager",
+ "com.apple.absd",
+ "com.apple.accessibility.heard",
+ "com.apple.accessoryupdaterd",
+ "com.apple.adid",
+ "com.apple.amsengagementd",
+ "com.apple.analyticsagent",
+ "com.apple.analyticsd",
+ "com.apple.ap.adprivacyd",
+ "com.apple.ap.promotedcontentd",
+ "com.apple.appstorecomponentsd",
+ "com.apple.askpermissiond",
+ "com.apple.assistant_cdmd",
+ "com.apple.assistant_service",
+ "com.apple.assistantd",
+ "com.apple.audioanalyticsd",
+ "com.apple.batteryintelligenced",
+ "com.apple.biomesyncd",
+ "com.apple.bookassetd",
+ "com.apple.callintelligenced",
+ "com.apple.carkitd",
+ "com.apple.cdpd",
+ "com.apple.cloudtelemetryd",
+ "com.apple.cmfsyncagent",
+ "com.apple.coreidvd",
+ "com.apple.corespeechd",
+ "com.apple.diagnosticextensionsd",
+ "com.apple.diagnosticspushd",
+ "com.apple.duetexpertd",
+ "com.apple.ecosystemanalyticsd",
+ "com.apple.email.maild",
+ "com.apple.eyereliefd",
+ "com.apple.familycircled",
+ "com.apple.financed",
+ "com.apple.findmy.findmybeaconingd",
+ "com.apple.findmy.findmylocated",
+ "com.apple.finhealthd",
+ "com.apple.fitnesscoachingd",
+ "com.apple.fitnessintelligenced",
+ "com.apple.gamed",
+ "com.apple.generativeexperiencesd",
+ "com.apple.geoanalyticsd",
+ "com.apple.hangtelemetryd",
+ "com.apple.homed",
+ "com.apple.homeeventsd",
+ "com.apple.hybridsearchd",
+ "com.apple.icloud.findmydeviced",
+ "com.apple.icloud.fmflocatord",
+ "com.apple.icloud.searchpartyd",
+ "com.apple.icloudmailagent",
+ "com.apple.identityservicesd",
+ "com.apple.imagent",
+ "com.apple.imcore.imtransferagent",
+ "com.apple.ind",
+ "com.apple.inputanalyticsd",
+ "com.apple.intelligencecontextd",
+ "com.apple.intelligenceflowd",
+ "com.apple.intelligenceplatformd",
+ "com.apple.intelligencetasksd",
+ "com.apple.itunescloudd",
+ "com.apple.jetpackassetd",
+ "com.apple.knowledgeconstructiond",
+ "com.apple.libsqlite3.dbtelemetryd",
+ "com.apple.maps.destinationd",
+ "com.apple.mediaanalysisd",
+ "com.apple.mediaanalysisd.service",
+ "com.apple.milod",
+ "com.apple.mobile.softwareupdated",
+ "com.apple.modelmanagerd",
+ "com.apple.nanobackupd",
+ "com.apple.nanoprefsyncd.2",
+ "com.apple.nanotimekitcompaniond",
+ "com.apple.navd",
+ "com.apple.ndoagent",
+ "com.apple.nearbyd",
+ "com.apple.nfcd",
+ "com.apple.ospredictiond",
+ "com.apple.parsec-fbf",
+ "com.apple.passd",
+ "com.apple.peopled",
+ "com.apple.perfpowermetricd",
+ "com.apple.photoanalysisd",
+ "com.apple.photosface",
+ "com.apple.powerexperienced",
+ "com.apple.remindd",
+ "com.apple.replicatord",
+ "com.apple.routined",
+ "com.apple.rtcreportingd",
+ "com.apple.safetyalertsd",
+ "com.apple.seld",
+ "com.apple.sensorkitd",
+ "com.apple.servicesintelligenced",
+ "com.apple.seserviced",
+ "com.apple.siri.sirireaderd",
+ "com.apple.siriactionsd",
+ "com.apple.siriinferenced",
+ "com.apple.siriknowledged",
+ "com.apple.sociallayerd",
+ "com.apple.softposreaderd",
+ "com.apple.softwareupdateservicesd",
+ "com.apple.speechmaintenanced",
+ "com.apple.spotlightknowledged",
+ "com.apple.spotlightknowledged.updater",
+ "com.apple.symptomsd-diag",
+ "com.apple.syncdefaultsd",
+ "com.apple.systemvoiceassistant",
+ "com.apple.terminusd",
+ "com.apple.textunderstandingd",
+ "com.apple.tipsd",
+ "com.apple.triald",
+ "com.apple.uarpassetmanagerd",
+ "com.apple.uarpd",
+ "com.apple.uarphidd",
+ "com.apple.uarppersonalizationd",
+ "com.apple.usbctelemetryd",
+ "com.apple.videosubscriptionsd",
+ "com.apple.visioncompaniond",
+ "com.apple.visualintelligenced",
+ "com.apple.voicebankingd",
+ "com.apple.voicemail.vmd",
+ "com.apple.watchlistd",
+ "com.apple.watchpresenced",
+ "com.apple.weatherd",
+ "com.apple.wifianalyticsd",
+ "com.apple.wirelessinsightsd",
+ ]
+
+ // MARK: - Never Disabled
+
+ /// Jobs the profile refuses to disable, whatever list or group names them.
+ ///
+ /// The first four kinds were measured to make things worse when off: without
+ /// sleepd, SpringBoard and mobiletimerd reconnect to it with no back-off
+ /// (about 400% host CPU); without CommCenter, SpringBoard reconnects every
+ /// second and resets the idle timer, so the screen never sleeps; without
+ /// cloudd, transparencyd and ScreenTimeSettingsAgent retry CloudKit and
+ /// write more than the untrimmed guest; without NanoRegistry, locationd
+ /// waits on it synchronously. The rest are what vphone's own features and
+ /// the tools it drives (Xcode, DeviceHub, ideviceinstaller, Frida, crash
+ /// logs, camera and audio) rely on.
+ static let neverDisable: Set<String> = [
+ // Worse when disabled.
+ "com.apple.sleepd",
+ "com.apple.CommCenter", "com.apple.CommCenterMobileHelper", "com.apple.CommCenterRootHelper",
+ "com.apple.cloudd",
+ "com.apple.nanoregistryd", "com.apple.nanoregistrylaunchd",
+ // Named by the OTA block and the App Store notes.
+ "com.apple.mobileassetd", "com.apple.storekitd",
+ // vphone features.
+ "com.vphone.vphoned",
+ "com.apple.SpringBoard", "com.apple.backboardd", "com.apple.runningboardd",
+ "com.apple.lsd", "com.apple.lsd.system",
+ "com.apple.containermanagerd", "com.apple.containermanagerd.system",
+ "com.apple.mobile.installd", "com.apple.misagent", "com.apple.mobile.lockdown",
+ "com.apple.remoted", "com.apple.security.cryptexd", "com.apple.dt.remotepairingdeviced",
+ "com.apple.avconferenced", "com.apple.diskimagesiod", "com.apple.diskimagesiod.ram",
+ "com.apple.locationd", "com.apple.bluetoothd",
+ "com.apple.pasteboard.pasted", "com.apple.powerd", "com.apple.MobileFileIntegrity",
+ "com.apple.managedconfiguration.profiled", "com.apple.mobile.keybagd",
+ "com.apple.cfprefsd.xpc.daemon", "com.apple.cfprefsd.xpc.daemon.system",
+ "com.apple.notifyd", "com.apple.mDNSResponder.reloaded", "com.apple.mDNSResponderHelper.reloaded",
+ "com.apple.configd", "com.apple.timed", "com.apple.tzlinkd", "com.apple.securityd",
+ "com.apple.logd", "com.apple.logd_helper", "com.apple.diagnosticd",
+ "com.apple.ReportCrash", "com.apple.osanalytics.osanalyticshelper",
+ "com.apple.audiomxd", "com.apple.mediaplaybackd", "com.apple.mediaremoted", "com.apple.cameracaptured",
+ "com.apple.mobileactivationd",
+ ]
+
+ // MARK: - Selection
+
+ enum Failure: Error, Equatable, CustomStringConvertible {
+ case unknownProfile(String)
+ case unsupported(iosMajor: Int)
+ case unknownGroup(String)
+
+ var description: String {
+ switch self {
+ case let .unknownProfile(name):
+ "profile must be \(GuestServiceProfile.trimmed) or \(GuestServiceProfile.none), not \(name)"
+ case let .unsupported(major):
+ "No trimmed service list for iOS \(major); lists exist for iOS "
+ + GuestServiceProfile.supportedMajors.map(String.init).joined(separator: ", ")
+ case let .unknownGroup(name):
+ "Unknown service group \(name)"
+ }
+ }
+ }
+
+ /// The labels a profile wants disabled.
+ struct Selection: Equatable, Sendable {
+ var groups: [String] = []
+ /// Sorted and unique, without `allow` and `neverDisable`.
+ var labels: [String] = []
+ /// Catalog labels the caller kept with `allow`.
+ var allowed: [String] = []
+ /// Catalog labels refused because they are on `neverDisable`.
+ var refused: [String] = []
+ }
+
+ /// The default groups plus `extraGroups`, minus `allow` and `neverDisable`.
+ /// `none` selects nothing on every version.
+ static func select(profile: String, iosMajor: Int, extraGroups: [String] = [], allow: [String] = []) throws -> Selection {
+ switch profile {
+ case none:
+ return Selection()
+ case trimmed:
+ break
+ default:
+ throw Failure.unknownProfile(profile)
+ }
+ guard let catalog = groups(iosMajor: iosMajor) else {
+ throw Failure.unsupported(iosMajor: iosMajor)
+ }
+ for name in extraGroups where !catalog.contains(where: { $0.name == name }) {
+ throw Failure.unknownGroup(name)
+ }
+ let chosen = catalog.filter { $0.byDefault || extraGroups.contains($0.name) }
+ let wanted = Set(chosen.flatMap(\.labels))
+ let kept = Set(allow)
+ return Selection(
+ groups: chosen.map(\.name),
+ labels: wanted.subtracting(kept).subtracting(neverDisable).sorted(),
+ allowed: wanted.intersection(kept).sorted(),
+ refused: wanted.intersection(neverDisable).subtracting(kept).sorted(),
+ )
+ }
+
+ // MARK: - Reconciliation
+
+ struct Skip: Equatable, Sendable {
+ let label: String
+ let reason: String
+ }
+
+ /// What applying a selection does, given the labels the profile disabled
+ /// before (`owned`) and launchd's overrides now (`overrides`, true =
+ /// disabled).
+ struct Change: Equatable, Sendable {
+ /// Enabled now; the profile disables them and owns them from then on.
+ var disable: [String] = []
+ /// Owned, no longer selected, still disabled: the profile turns them on.
+ var enable: [String] = []
+ /// Owned, still selected and still disabled: nothing to do.
+ var keep: [String] = []
+ /// Left alone: disabled by someone else, refused, or owned but already
+ /// back on.
+ var skipped: [Skip] = []
+ }
+
+ static let disabledElsewhere = "already disabled, not by the profile"
+ static let neverDisabledReason = "never disabled"
+ static let enabledElsewhere = "already enabled again"
+
+ static func reconcile(target: [String], owned: [String], overrides: [String: Bool]) -> Change {
+ var change = Change()
+ let ownedSet = Set(owned)
+ let targetSet = Set(target)
+ for label in targetSet.sorted() {
+ if neverDisable.contains(label) {
+ change.skipped.append(Skip(label: label, reason: neverDisabledReason))
+ } else if overrides[label] == true {
+ if ownedSet.contains(label) {
+ change.keep.append(label)
+ } else {
+ change.skipped.append(Skip(label: label, reason: disabledElsewhere))
+ }
+ } else {
+ change.disable.append(label)
+ }
+ }
+ for label in ownedSet.subtracting(targetSet).sorted() {
+ if overrides[label] == true {
+ change.enable.append(label)
+ } else {
+ change.skipped.append(Skip(label: label, reason: enabledElsewhere))
+ }
+ }
+ return change
+ }
+
+ /// The labels the profile owns once `change` ran: what it kept, what it
+ /// disabled, and what it failed to turn back on, so a later `none` tries
+ /// again.
+ static func owned(after change: Change, failedDisable: Set<String>, failedEnable: Set<String>) -> [String] {
+ (change.keep + change.disable.filter { !failedDisable.contains($0) }
+ + change.enable.filter { failedEnable.contains($0) }).sorted()
+ }
+
+ // MARK: - Record
+
+ /// What the profile last did, in `recordPath`.
+ struct Record: Equatable, Sendable {
+ var profile: String
+ var listVersion: Int
+ var iosMajor: Int
+ var groups: [String]
+ var allow: [String]
+ /// The labels this profile disabled and still owns.
+ var labels: [String]
+ var updated: Date
+
+ init(profile: String, listVersion: Int, iosMajor: Int, groups: [String], allow: [String], labels: [String], updated: Date) {
+ self.profile = profile
+ self.listVersion = listVersion
+ self.iosMajor = iosMajor
+ self.groups = groups
+ self.allow = allow
+ self.labels = labels
+ self.updated = updated
+ }
+
+ init?(propertyList: Any) {
+ guard let plist = propertyList as? [String: Any],
+ let profile = plist["Profile"] as? String,
+ let labels = plist["Labels"] as? [String]
+ else { return nil }
+ self.profile = profile
+ listVersion = (plist["ListVersion"] as? NSNumber)?.intValue ?? 0
+ iosMajor = (plist["iOSMajor"] as? NSNumber)?.intValue ?? 0
+ groups = plist["Groups"] as? [String] ?? []
+ allow = plist["Allow"] as? [String] ?? []
+ self.labels = labels
+ updated = plist["Updated"] as? Date ?? Date(timeIntervalSince1970: 0)
+ }
+
+ var propertyList: [String: Any] {
+ [
+ "Profile": profile, "ListVersion": listVersion, "iOSMajor": iosMajor,
+ "Groups": groups, "Allow": allow, "Labels": labels, "Updated": updated,
+ ]
+ }
+
+ /// The record in JSON terms, for a reply.
+ var json: [String: Any] {
+ [
+ "profile": profile, "list_version": listVersion, "ios_major": iosMajor,
+ "groups": groups, "allow": allow, "labels": labels,
+ "updated": ISO8601DateFormatter().string(from: updated),
+ ]
+ }
+ }
+
+ static func readRecord(at path: String = recordPath) -> Record? {
+ guard let data = FileManager.default.contents(atPath: path),
+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil)
+ else { return nil }
+ return Record(propertyList: plist)
+ }
+
+ /// Replaces the record in one rename.
+ static func writeRecord(_ record: Record, to path: String = recordPath) throws {
+ let directory = (path as NSString).deletingLastPathComponent
+ try FileManager.default.createDirectory(
+ atPath: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o755],
+ )
+ let data = try PropertyListSerialization.data(fromPropertyList: record.propertyList, format: .xml, options: 0)
+ try data.write(to: URL(fileURLWithPath: path), options: .atomic)
+ }
+}
diff --git a/VPhoneDaemon/Tests/LogicTests.swift b/VPhoneDaemon/Tests/LogicTests.swift
new file mode 100644
index 00000000..78a0d30b
--- /dev/null
+++ b/VPhoneDaemon/Tests/LogicTests.swift
@@ -0,0 +1,264 @@
+import Foundation
+
+// MARK: - Harness
+
+/// Checks the guest-independent parts of vphoned on the Mac: the service
+/// profile lists and bookkeeping, the first-boot settle verdict and the device
+/// name rule. `run-logic-tests.sh` builds this file with those sources.
+nonisolated(unsafe) var failures = 0
+nonisolated(unsafe) var checks = 0
+
+func expect(_ condition: Bool, _ message: @autoclosure () -> String, line: Int = #line) {
+ checks += 1
+ if !condition {
+ failures += 1
+ print("FAIL line \(line): \(message())")
+ }
+}
+
+func expectEqual<T: Equatable>(_ actual: T, _ expected: T, _ message: String = "", line: Int = #line) {
+ expect(actual == expected, "\(message) expected \(expected), got \(actual)", line: line)
+}
+
+@main
+enum LogicTests {
+ static func main() {
+ profileCatalog()
+ profileSelection()
+ neverDisableEnforcement()
+ reconciliation()
+ noneRestoresOnlyRecorded()
+ recordRoundTrip()
+ settleVerdicts()
+ deviceNameRule()
+ print("\(checks) checks, \(failures) failures")
+ exit(failures == 0 ? 0 : 1)
+ }
+
+ // MARK: - Service Profile
+
+ static let labelPattern = "^[A-Za-z0-9][A-Za-z0-9._:\\[\\]-]{0,200}$"
+
+ static func profileCatalog() {
+ let groups = GuestServiceProfile.groups27
+ expectEqual(GuestServiceProfile.base27.count, 137, "appendix A")
+ expectEqual(Set(GuestServiceProfile.base27).count, 137, "appendix A has no duplicates")
+ let all = groups.flatMap(\.labels)
+ expectEqual(Set(all).count, all.count, "no label is in two groups")
+ for label in all + GuestServiceProfile.neverDisable {
+ expect(label.range(of: labelPattern, options: .regularExpression) != nil, "\(label) is a valid label")
+ }
+ expectEqual(groups.map(\.name), ["base", "app_store", "signin_followup", "accounts"])
+ expectEqual(groups.filter(\.byDefault).map(\.name), ["base", "app_store", "signin_followup"])
+ expect(GuestServiceProfile.base27.contains("com.apple.appstorecomponentsd"), "appstorecomponentsd is in base")
+ expect(GuestServiceProfile.groups(iosMajor: 26) == nil, "no list for iOS 26")
+ expect(GuestServiceProfile.groups(iosMajor: 27) != nil, "a list for iOS 27")
+ }
+
+ static func profileSelection() {
+ let trimmed = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27)
+ expectEqual(trimmed?.labels.count, 141, "default trimmed = 137 + 2 store + 2 follow-up")
+ expectEqual(trimmed?.groups, ["base", "app_store", "signin_followup"])
+ expect(trimmed?.labels.contains("com.apple.followupd") == true, "followupd is in trimmed")
+ expect(trimmed?.labels.contains("com.apple.akd") == false, "akd is not in trimmed by default")
+ expectEqual(trimmed?.labels, trimmed?.labels.sorted(), "labels sorted")
+
+ let accounts = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27, extraGroups: ["accounts"])
+ expectEqual(accounts?.labels.count, 144, "accounts adds three")
+ expect(accounts?.labels.contains("com.apple.amsaccountsd") == true, "amsaccountsd with accounts")
+
+ let allowed = try? GuestServiceProfile.select(
+ profile: "trimmed", iosMajor: 27, allow: ["com.apple.weatherd", "com.example.not-listed"],
+ )
+ expectEqual(allowed?.labels.count, 140, "allow removes one")
+ expectEqual(allowed?.allowed, ["com.apple.weatherd"], "only catalog labels are reported as allowed")
+ expect(allowed?.labels.contains("com.apple.weatherd") == false, "weatherd kept")
+
+ expectEqual(try? GuestServiceProfile.select(profile: "none", iosMajor: 26), GuestServiceProfile.Selection())
+ expectThrows(.unsupported(iosMajor: 26)) { try GuestServiceProfile.select(profile: "trimmed", iosMajor: 26) }
+ expectThrows(.unknownGroup("bogus")) {
+ try GuestServiceProfile.select(profile: "trimmed", iosMajor: 27, extraGroups: ["bogus"])
+ }
+ expectThrows(.unknownProfile("lean")) { try GuestServiceProfile.select(profile: "lean", iosMajor: 27) }
+ }
+
+ static func expectThrows(_ expected: GuestServiceProfile.Failure, line: Int = #line, _ body: () throws -> Any) {
+ do {
+ _ = try body()
+ expect(false, "expected \(expected)", line: line)
+ } catch let failure as GuestServiceProfile.Failure {
+ expectEqual(failure, expected, line: line)
+ } catch {
+ expect(false, "unexpected \(error)", line: line)
+ }
+ }
+
+ static func neverDisableEnforcement() {
+ for group in GuestServiceProfile.groups27 {
+ let overlap = Set(group.labels).intersection(GuestServiceProfile.neverDisable)
+ expect(overlap.isEmpty, "\(group.name) names never-disabled \(overlap.sorted())")
+ }
+ for trap in [
+ "com.apple.sleepd", "com.apple.CommCenter", "com.apple.CommCenterMobileHelper",
+ "com.apple.CommCenterRootHelper", "com.apple.cloudd", "com.apple.nanoregistryd",
+ "com.apple.nanoregistrylaunchd", "com.apple.mobileassetd", "com.apple.storekitd",
+ "com.apple.cfprefsd.xpc.daemon", "com.apple.SpringBoard", "com.apple.backboardd",
+ "com.apple.mobile.installd", "com.apple.lsd", "com.apple.mobileactivationd",
+ "com.apple.locationd", "com.apple.bluetoothd", "com.vphone.vphoned",
+ ] {
+ expect(GuestServiceProfile.neverDisable.contains(trap), "\(trap) is never disabled")
+ }
+ // Even a target that names them, as a future list might, leaves them alone.
+ let change = GuestServiceProfile.reconcile(
+ target: ["com.apple.sleepd", "com.apple.tipsd"], owned: [], overrides: [:],
+ )
+ expectEqual(change.disable, ["com.apple.tipsd"])
+ expectEqual(change.skipped, [GuestServiceProfile.Skip(label: "com.apple.sleepd", reason: "never disabled")])
+ }
+
+ static func reconciliation() {
+ let overrides = [
+ "com.apple.a": true, // disabled by the profile earlier
+ "com.apple.b": true, // disabled by somebody else (the OTA block)
+ "com.apple.d": true, // owned, no longer selected
+ "com.apple.e": false, // owned, re-enabled by the user
+ ]
+ let change = GuestServiceProfile.reconcile(
+ target: ["com.apple.a", "com.apple.b", "com.apple.c"],
+ owned: ["com.apple.a", "com.apple.d", "com.apple.e"],
+ overrides: overrides,
+ )
+ expectEqual(change.keep, ["com.apple.a"])
+ expectEqual(change.disable, ["com.apple.c"])
+ expectEqual(change.enable, ["com.apple.d"])
+ expectEqual(change.skipped, [
+ GuestServiceProfile.Skip(label: "com.apple.b", reason: GuestServiceProfile.disabledElsewhere),
+ GuestServiceProfile.Skip(label: "com.apple.e", reason: GuestServiceProfile.enabledElsewhere),
+ ])
+ expectEqual(
+ GuestServiceProfile.owned(after: change, failedDisable: [], failedEnable: []),
+ ["com.apple.a", "com.apple.c"], "owned after success",
+ )
+ expectEqual(
+ GuestServiceProfile.owned(after: change, failedDisable: ["com.apple.c"], failedEnable: ["com.apple.d"]),
+ ["com.apple.a", "com.apple.d"], "a failed disable is not owned; a failed enable stays owned",
+ )
+
+ // Applying again once the overrides reflect the first apply changes nothing.
+ let after = ["com.apple.a": true, "com.apple.b": true, "com.apple.c": true, "com.apple.e": false]
+ let again = GuestServiceProfile.reconcile(
+ target: ["com.apple.a", "com.apple.b", "com.apple.c"], owned: ["com.apple.a", "com.apple.c"], overrides: after,
+ )
+ expect(again.disable.isEmpty && again.enable.isEmpty, "idempotent")
+ expectEqual(again.keep, ["com.apple.a", "com.apple.c"])
+ }
+
+ static func noneRestoresOnlyRecorded() {
+ // The OTA trio was disabled before the profile ran, so it was never owned.
+ let ota = ["com.apple.mobile.softwareupdated", "com.apple.OTATaskingAgent", "com.apple.softwareupdateservicesd"]
+ guard let trimmed = try? GuestServiceProfile.select(profile: "trimmed", iosMajor: 27) else {
+ return expect(false, "trimmed selects")
+ }
+ var overrides = Dictionary(uniqueKeysWithValues: ota.map { ($0, true) })
+ overrides["com.apple.user-choice"] = true
+ let apply = GuestServiceProfile.reconcile(target: trimmed.labels, owned: [], overrides: overrides)
+ expectEqual(apply.disable.count, 138, "141 minus the three already disabled")
+ expectEqual(apply.skipped.map(\.label), ota.sorted())
+ let owned = GuestServiceProfile.owned(after: apply, failedDisable: [], failedEnable: [])
+ for label in apply.disable {
+ overrides[label] = true
+ }
+
+ let restore = GuestServiceProfile.reconcile(target: [], owned: owned, overrides: overrides)
+ expectEqual(restore.enable, owned, "none enables exactly what the profile owned")
+ expect(Set(restore.enable).isDisjoint(with: ota), "the OTA trio stays disabled")
+ expect(!restore.enable.contains("com.apple.user-choice"), "a user's override stays")
+ expectEqual(GuestServiceProfile.owned(after: restore, failedDisable: [], failedEnable: []), [])
+ }
+
+ static func recordRoundTrip() {
+ let directory = NSTemporaryDirectory() + "vphoned-logic-\(getpid())"
+ defer { try? FileManager.default.removeItem(atPath: directory) }
+ let path = directory + "/db/service-profile.plist"
+ expect(GuestServiceProfile.readRecord(at: path) == nil, "no record yet")
+ let record = GuestServiceProfile.Record(
+ profile: "trimmed", listVersion: 1, iosMajor: 27, groups: ["base"], allow: ["com.apple.weatherd"],
+ labels: ["com.apple.tipsd"], updated: Date(timeIntervalSince1970: 1_791_331_200),
+ )
+ do {
+ try GuestServiceProfile.writeRecord(record, to: path)
+ } catch {
+ return expect(false, "write: \(error)")
+ }
+ expectEqual(GuestServiceProfile.readRecord(at: path), record, "record round-trips")
+ expect(GuestServiceProfile.Record(propertyList: ["Profile": "none"]) == nil, "a record needs Labels")
+ expectEqual(record.json["updated"] as? String, "2026-10-07T00:00:00Z")
+ }
+
+ // MARK: - First-Boot Settle
+
+ typealias Sample = GuestFirstBootSettle.Sample
+
+ static func sample(_ time: Double, staged: Int? = 0, apps: Int? = 248, pid: Int? = 90, cpu: Double? = 1.0) -> Sample {
+ Sample(time: time, stagedSystemApps: staged, appCount: apps, installdPID: pid, installdCPUSeconds: cpu)
+ }
+
+ static func settleVerdicts() {
+ let quiet = [sample(0), sample(5, cpu: 1.05), sample(10, cpu: 1.1)]
+ let verdict = GuestFirstBootSettle.evaluate(quiet, stablePolls: 3)
+ expect(verdict.settled, "quiet polls settle: \(verdict.reasons)")
+ expectEqual(verdict.installdCPUDelta.map { ($0 * 100).rounded() }, 5)
+
+ expect(!GuestFirstBootSettle.evaluate(Array(quiet.prefix(2)), stablePolls: 3).settled, "too few polls")
+ expect(GuestFirstBootSettle.evaluate(quiet, stablePolls: 1).settled, "at least two polls even when asked for one")
+
+ let staged = GuestFirstBootSettle.evaluate([sample(0), sample(5), sample(10, staged: 4)], stablePolls: 3)
+ expect(!staged.settled && staged.reasons == ["staged_system_apps has 4 entries"], "\(staged.reasons)")
+
+ let emptied = GuestFirstBootSettle.evaluate([sample(0, staged: 2), sample(5), sample(10)], stablePolls: 3)
+ expectEqual(emptied.reasons, ["staged_system_apps only just emptied"])
+
+ let unreadable = GuestFirstBootSettle.evaluate([sample(0), sample(5), sample(10, staged: nil)], stablePolls: 3)
+ expectEqual(unreadable.reasons, ["staged_system_apps could not be read"])
+
+ let growing = GuestFirstBootSettle.evaluate([sample(0, apps: 250), sample(5, apps: 258), sample(10, apps: 258)], stablePolls: 3)
+ expectEqual(growing.reasons, ["app count changed: 250 → 258 → 258"])
+
+ let unknownApps = GuestFirstBootSettle.evaluate([sample(0), sample(5, apps: nil), sample(10)], stablePolls: 3)
+ expectEqual(unknownApps.reasons, ["app count unavailable"])
+
+ let busy = GuestFirstBootSettle.evaluate([sample(0), sample(5, cpu: 3.0), sample(10, cpu: 3.1)], stablePolls: 3)
+ expectEqual(busy.reasons, ["installd used 2.00 s CPU between polls"])
+
+ // An older busy poll outside the window no longer counts.
+ let recovered = GuestFirstBootSettle.evaluate(
+ [sample(0), sample(5, cpu: 3.0), sample(10, cpu: 3.05), sample(15, cpu: 3.1)], stablePolls: 2,
+ )
+ expect(recovered.settled, "window of two: \(recovered.reasons)")
+
+ // installd exiting counts as idle; a new installd counts all of its CPU.
+ let exited = [sample(0), sample(5, pid: nil, cpu: nil), sample(10, pid: nil, cpu: nil)]
+ expect(GuestFirstBootSettle.evaluate(exited, stablePolls: 3).settled, "installd gone is idle")
+ let restarted = GuestFirstBootSettle.evaluate([sample(0), sample(5, pid: nil, cpu: nil), sample(10, pid: 120, cpu: 0.9)], stablePolls: 3)
+ expectEqual(restarted.reasons, ["installd used 0.90 s CPU between polls"])
+ let restartedIdle = GuestFirstBootSettle.evaluate([sample(0), sample(5, pid: 120, cpu: 0.05), sample(10, pid: 120, cpu: 0.06)], stablePolls: 3)
+ expect(restartedIdle.settled, "a new, idle installd: \(restartedIdle.reasons)")
+ }
+
+ // MARK: - Device Name
+
+ static func deviceNameRule() {
+ expect(GuestDeviceNameRule.problem("p0-a") == nil, "plain name")
+ expect(GuestDeviceNameRule.problem("dhtest 27 测试") == nil, "spaces and CJK")
+ expect(GuestDeviceNameRule.problem("Jacky’s iPhone") == nil, "typographic apostrophe")
+ expectEqual(GuestDeviceNameRule.problem(""), "name must not be blank")
+ expectEqual(GuestDeviceNameRule.problem(" \n\t"), "name must not be blank")
+ expectEqual(GuestDeviceNameRule.problem("a\u{7}b"), "name must not contain a control character")
+ expectEqual(GuestDeviceNameRule.problem("line\nbreak"), "name must not contain a control character")
+ expect(GuestDeviceNameRule.problem(String(repeating: "a", count: 255)) == nil, "255 bytes")
+ expectEqual(GuestDeviceNameRule.problem(String(repeating: "a", count: 256)), "name must be at most 255 bytes in UTF-8")
+ // 85 three-byte characters are 255 bytes; one more is 258.
+ expect(GuestDeviceNameRule.problem(String(repeating: "测", count: 85)) == nil, "255 bytes of CJK")
+ expect(GuestDeviceNameRule.problem(String(repeating: "测", count: 86)) != nil, "258 bytes of CJK")
+ }
+}
diff --git a/VPhoneDaemon/Tests/run-logic-tests.sh b/VPhoneDaemon/Tests/run-logic-tests.sh
new file mode 100755
index 00000000..04e1c7cd
--- /dev/null
+++ b/VPhoneDaemon/Tests/run-logic-tests.sh
@@ -0,0 +1,20 @@
+#!/bin/zsh
+set -euo pipefail
+
+# Builds the guest-independent vphoned sources with LogicTests.swift for the
+# Mac and runs them: service profile lists and bookkeeping, the first-boot
+# settle verdict, the device name rule. No guest is needed.
+
+daemon="${0:a:h:h}"
+temporary="$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/vphone-logic-tests.XXXXXX")"
+trap '/bin/rm -rf "$temporary"' EXIT
+
+/usr/bin/xcrun --sdk macosx swiftc -swift-version 6 -parse-as-library \
+ -module-cache-path "$temporary/module-cache" \
+ "$daemon/Daemon/GuestServiceProfile.swift" \
+ "$daemon/Daemon/GuestFirstBootSettle.swift" \
+ "$daemon/Daemon/GuestDeviceNameRule.swift" \
+ "$daemon/Tests/LogicTests.swift" \
+ -o "$temporary/logic-tests"
+
+"$temporary/logic-tests"