From 45fcf4b208eddd5d0d91b22f4ac5e095fb3840f5 Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:44:12 -0700
Subject: [PATCH 01/32] feat(swift): dependency-free Swift port, scaffold and
core model
Start the Swift port in swift/ (SwiftPM, no third-party packages) so
simslim can be built with the Xcode toolchain alone.
Scaffold:
- closed list of absolute-path executables behind a fakeable runner
- scripts/verify-deps.sh (make verify-deps): fails on packages,
non-allowlisted imports, network APIs, remote reads, process spawning
outside Subprocess.swift, fetching build files, non-system linked
libraries, network symbols, and test hooks in the release binary
Core model (ported from profiles.go, features.go, profile_file.go):
- allowlist of 16 categories / 179 labels, descriptions and 27 features,
generated from the Go source by swift/Tools/gen_catalog.py
(make swift-gen / swift-gen-check)
- Profile.desired, platform rules, delta scoped to the managed set,
feature diagnosis, profile file load/validate/marshal
- 53 tests, including the Go safety invariants (forbidden daemons,
managed-only mutation, required-enabled services)
Only --version works so far; commands arrive in later milestones.
docs/swift-port-plan.md records the plan and the deferred work.
---
.gitignore | 1 +
Makefile | 16 +-
docs/swift-port-plan.md | 166 +++++
scripts/verify-deps.sh | 253 +++++++
swift/Package.swift | 19 +
swift/Sources/SimSlimKit/Catalog.swift | 105 +++
swift/Sources/SimSlimKit/Device.swift | 45 ++
swift/Sources/SimSlimKit/Errors.swift | 11 +
swift/Sources/SimSlimKit/Features.swift | 114 ++++
.../SimSlimKit/Generated/CatalogData.swift | 623 ++++++++++++++++++
swift/Sources/SimSlimKit/Profile.swift | 54 ++
swift/Sources/SimSlimKit/ProfileFile.swift | 227 +++++++
swift/Sources/SimSlimKit/Subprocess.swift | 66 ++
swift/Sources/SimSlimKit/Version.swift | 2 +
swift/Sources/simslim/main.swift | 13 +
.../Tests/SimSlimKitTests/FeaturesTests.swift | 122 ++++
.../Generated/ForbiddenLabels.swift | 20 +
.../SimSlimKitTests/ProfileFileTests.swift | 197 ++++++
.../Tests/SimSlimKitTests/ProfilesTests.swift | 300 +++++++++
.../SimSlimKitTests/SubprocessTests.swift | 31 +
swift/Tools/gen_catalog.py | 264 ++++++++
swift/expected-libs.txt | 11 +
22 files changed, 2659 insertions(+), 1 deletion(-)
create mode 100644 docs/swift-port-plan.md
create mode 100755 scripts/verify-deps.sh
create mode 100644 swift/Package.swift
create mode 100644 swift/Sources/SimSlimKit/Catalog.swift
create mode 100644 swift/Sources/SimSlimKit/Device.swift
create mode 100644 swift/Sources/SimSlimKit/Errors.swift
create mode 100644 swift/Sources/SimSlimKit/Features.swift
create mode 100644 swift/Sources/SimSlimKit/Generated/CatalogData.swift
create mode 100644 swift/Sources/SimSlimKit/Profile.swift
create mode 100644 swift/Sources/SimSlimKit/ProfileFile.swift
create mode 100644 swift/Sources/SimSlimKit/Subprocess.swift
create mode 100644 swift/Sources/SimSlimKit/Version.swift
create mode 100644 swift/Sources/simslim/main.swift
create mode 100644 swift/Tests/SimSlimKitTests/FeaturesTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
create mode 100644 swift/Tests/SimSlimKitTests/ProfileFileTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/ProfilesTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/SubprocessTests.swift
create mode 100644 swift/Tools/gen_catalog.py
create mode 100644 swift/expected-libs.txt
diff --git a/.gitignore b/.gitignore
index efd9a05..1bb2a21 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@
*.tar.gz
.DS_Store
/build/
+/swift/.build/
diff --git a/Makefile b/Makefile
index 36a43ac..9f6be14 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: app cli check format test
+.PHONY: app cli check format test swift-test swift-gen swift-gen-check verify-deps
VERSION ?= $(shell git describe --tags --always --dirty)
@@ -20,3 +20,17 @@ check: test
format:
gofmt -w *.go
xcrun swift-format format --in-place --recursive gui
+
+swift-test:
+ cd swift && swift test
+
+# Regenerate (or check) swift/.../Generated from the Go catalog. Needs python3; transition-period tool.
+swift-gen:
+ python3 swift/Tools/gen_catalog.py
+
+swift-gen-check:
+ python3 swift/Tools/gen_catalog.py --check
+
+# Manual dependency audit of the Swift port (not part of `check`).
+verify-deps:
+ ./scripts/verify-deps.sh
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
new file mode 100644
index 0000000..7bd3bca
--- /dev/null
+++ b/docs/swift-port-plan.md
@@ -0,0 +1,166 @@
+# simslim Swift port: plan
+
+Status: draft for review. Nothing in this plan is implemented yet.
+Branch: `swift-port` (no upstream). Go code stays untouched as the reference until the port reaches parity.
+
+## 1. Goal and non-goals
+
+**Goal.** A `simslim` CLI built only with the Xcode toolchain already on the Mac, with no Go toolchain and no third-party code, whose dependencies can be verified by a short script anyone can run. It keeps the existing `--json` contract, so `gui/*.swift` keeps working unchanged.
+
+**Non-goals.**
+- Changing behavior or adding features during the port.
+- Linux or CI portability (the tool is macOS-only already).
+- Replacing the SwiftUI app. Only its bundled CLI changes.
+
+## 2. Size of the job (from the Go source)
+
+| Area | Go files | Lines |
+|---|---|---|
+| CLI commands and dispatch | `cmd/simslim/main.go`, `app.go` | ~1350 |
+| Live TUI (`top`) | `cmd/simslim/top.go` | ~650 |
+| Profile wizard | `cmd/simslim/wizard.go` | ~360 |
+| Clone / repair-clone | `clone.go` | ~880 |
+| simctl wrapper | `simctl.go` | ~675 |
+| Disk cleanup / inventory | `disk_cleanup.go`, `disk_inventory.go`, `disk.go` | ~740 |
+| Allowlist, categories, descriptions | `profiles.go`, `service_descriptions.go`, `features.go` | ~810 |
+| Slim engine | `slim.go`, `disabled_store.go`, `launchd_batch.go`, `verify.go` | ~710 |
+| watch | `watch.go`, `watch_dirs_darwin.go` | ~520 |
+| live enable/disable, profiles on disk | `live.go`, `profile_file.go`, `profile_save.go` | ~640 |
+| measure / fleet / output | `measure.go`, `fleet.go`, `output.go` | ~420 |
+| **Total non-test** | | **~12.7k** |
+| Tests | 40 `_test.go` files | ~4.9k |
+
+Expect roughly 9 to 12k lines of Swift. This is an estimate, not a measurement.
+
+## 3. Dependency policy: controlled and independently verifiable
+
+### 3.1 The rule
+
+The only code the Swift tool may use is:
+
+1. The Swift standard library.
+2. Apple system modules: `Foundation`, `Darwin`, `Dispatch` (CLI); additionally `AppKit` and `SwiftUI` (the existing GUI).
+3. Test-only, toolchain-bundled: `XCTest` or `Testing`, plus `swift-format` from Xcode for lint.
+
+No Swift packages, no vendored source, no downloaded binaries, no plugins, no build scripts that fetch anything. Every item in this list ships inside Xcode, so approving Xcode approves it.
+
+### 3.2 Layout choices that keep this checkable
+
+- **SwiftPM with an empty dependency list.** `swift/Package.swift` declares `dependencies: []`. This gives `swift build` and `swift test` without any third-party code. The GUI keeps its current bare-`swiftc` build in `scripts/build-app.sh`.
+- **Three targets:** `SimSlimKit` (library, all logic), `simslim` (executable, argument parsing and printing only), `SimSlimKitTests`. This mirrors the Go split where the library never writes to stdout.
+- **One place for subprocesses.** All `Process` use lives in `Subprocess.swift`. Each executable is an absolute path from a closed enum: `/usr/bin/xcrun`, `/usr/bin/plutil`, `/usr/bin/du`, `/usr/bin/pgrep`, `/bin/ps`, `/usr/bin/top`, `/usr/sbin/lsof`, `/bin/stty`. No `PATH` lookup. This is stricter than the Go version, which resolves most of them through `PATH`.
+- **One place for the filesystem roots it may mutate**, with the same guards as `requireDescendant` / `requireResolvedDescendant`.
+
+### 3.3 Verification gate: `scripts/verify-deps.sh`
+
+A single script, run by `make check` and runnable by the security team on a clean checkout. It must pass or the build fails.
+
+| # | Check | How |
+|---|---|---|
+| 1 | No packages | `swift/Package.swift` has `dependencies: []`; `Package.resolved` absent; no `Packages/`, `vendor/`, `.build/checkouts` |
+| 2 | Imports are allowlisted | grep every `import` in `swift/` and `gui/`; any module outside the allowlist fails |
+| 3 | No network APIs | grep for `URLSession`, `URLRequest`, `URL(string:` with a scheme, `NWConnection`, `CFNetwork`, `Network` import, sockets |
+| 4 | Subprocess closure | every `Process()` is in `Subprocess.swift`; every executable path is in the enum |
+| 5 | Linked libraries | `otool -L` on the release binary; every entry must be under `/usr/lib` or `/System/Library`; compared to a committed `expected-libs.txt` |
+| 6 | Symbols | `nm` / `strings` on the release binary must show no network symbols |
+| 7 | No fetching in the build | grep `Package.swift`, `Makefile`, and scripts for `curl`, `wget`, `git clone`, `http(s)://` |
+| 8 | Test hooks absent from release | the release binary does not contain the test-override env var names (see 4.2) |
+| 9 | Runtime network check (optional) | run `list`, `status`, `--json` commands under `sandbox-exec` with `(deny network*)` and confirm they still work |
+
+`docs/DEPENDENCIES.md` records the result in plain words: the allowlist, the expected `otool -L` output, and "third-party packages: none". It is generated, so it cannot drift from the code.
+
+### 3.4 Reproducibility and provenance
+
+- Build with `-file-prefix-map` so paths do not leak into the binary. Build twice and compare hashes. Treat byte-identical output as a goal and report if it isn't achieved (Swift determinism is not guaranteed).
+- `scripts/sbom.sh` prints the toolchain version, the allowlisted modules, and the linked system libraries. It will say "third-party: none".
+- Ad-hoc codesign as today. Notarization is a separate decision and needs an Apple developer identity.
+
+## 4. Test strategy
+
+### 4.1 Layer 1: pure unit tests (run anywhere, in `make check`)
+
+Port the Go tests that encode safety or contract:
+- `profiles_test`: allowlist invariants, `forbiddenLabels`, every category has a positive memory estimate, descriptions cover every label.
+- `features_test`, `profile_file_test`, `profile_save_test`.
+- Delta logic scoped to the managed set (the "only managed labels are ever mutated" invariant).
+- Parsing: `simctl list -j`, `print-disabled`, `launchctl list`, `disabled.plist`.
+- Disk-cleanup path guards, including the symlink cases.
+- `--confirm` refusal.
+
+### 4.2 Layer 2: component tests with a fake `xcrun`
+
+Mirrors `simctl_test.go`. `SimctlRunning` is a protocol, and unit tests inject a fake. For black-box CLI tests there is a debug-only override of the executable paths, compiled under `#if DEBUG`. The release binary must not contain it (gate check 8).
+
+### 4.3 Layer 3: contract tests against the GUI
+
+`gui/Models.swift` already decodes the CLI's JSON. A test compiles `Models.swift` into the test target and decodes the Swift CLI's `--json` output for every command. If a field is renamed or dropped, the build breaks, instead of the GUI breaking at runtime. A second check compares the key sets of each JSON output with the Go tool's, using fixtures recorded once from the Go binary on a machine that has Go.
+
+### 4.4 Layer 4: integration tests on real simulators (opt-in)
+
+Enabled only with `SIMSLIM_INTEGRATION=1`; never part of `make check`.
+
+Safety rules:
+- Run in an **isolated device set** (`--set `), never the default set.
+- Create a dedicated throwaway device with `simctl create`, record its UDID, and **refuse to touch any UDID that is not in that record**.
+- Always clean up in teardown, including on failure. Delete only the recorded UDID.
+- Abort before doing anything if the device cannot be created.
+
+Scenarios: list and status on a clean device; `on` then `verify`; reboot and confirm persistence; `off`; `on --no-reboot`; live `enable` and `disable` with `--save`; offline fast path; `doctor`; `measure`; `clone` and `repair-clone`; `disk-plan` (read-only) and `disk-clean --confirm` on the throwaway device only; `watch` seeing a new device.
+
+### 4.5 Side-by-side parity (needs Go, so the personal Mac)
+
+For the same throwaway device, run the Go and Swift tools and compare: `--json` output (modulo timing fields), and the resulting disabled-label set. Xcode 27.2 is newer than the Xcode 26.6 the upstream CI pins, so any difference is first checked against plain `simctl` before blaming the port.
+
+## 5. Milestones
+
+Each milestone ends with: gate script green, unit tests green, and a short written note of what was verified and what was not.
+
+- **M0 Scaffold.** `swift/` package, empty dependencies, `verify-deps.sh`, `DEPENDENCIES.md` generation, CI wiring, fake-xcrun harness.
+- **M1 Core model.** Allowlist (`profiles.go`, `service_descriptions.go`, `features.go`) as data, delta logic, profile files. All invariant tests ported first.
+- **M2 simctl and read-only commands.** `Subprocess`, `simctl` wrapper, `list`, `profiles`, `status`, `verify`, `doctor`, `measure`, `size`, `disk-categories`, `disk-plan`, with JSON contract tests.
+- **M3 Slimming.** `on`, `off`, `on --no-reboot`, the `launchctl` pool (8 workers), `disabled.plist` offline fast path, `unloadInBatch`, launchd retry delays.
+- **M4 Live and management.** `enable`, `disable`, `--save`, `boot`, `shutdown`, `rename`, `erase`, `delete`, `clone`, `repair-clone`, `disk-clean`. The destructive ones get the most review.
+- **M5 watch.** kqueue directory watch, pre-slim of new devices, `watch --json` events.
+- **M6 Interactive.** `top` live view (plain ANSI redraw, no TUI library) and the `profile` wizard (`stty` raw mode).
+- **M7 Integration and parity.** Layer 4 and 4.5 runs, fix differences.
+- **M8 Cutover.** `build-app.sh` bundles the Swift CLI, Go removed from the app build, README and `CLAUDE.md` updated. The Go tree stays until you decide to remove it.
+
+## 6. Risks
+
+- **Undocumented behavior.** `disabled.plist` location and format is a CoreSimulator internal. The Go tool already treats it as best effort and falls back to `launchctl`; the port keeps that fallback.
+- **Xcode 27 differences.** `simctl` output or runtime layout may differ from what upstream tested. Surfaces in M2 and M7.
+- **Concurrency.** Go's goroutines and contexts map to Swift concurrency. The pool, timeouts (`BootTimeout`, `SpawnTimeout`, `ShutdownTimeout`) and cancellation (`slimPass`) need careful porting, with tests.
+- **`top` and wizard.** Reimplementing terminal UI without a library is the most visible behavior change. Scope can be cut here if needed.
+- **Fork drift.** After the port, upstream Go fixes do not flow in automatically.
+- **Licensing.** The port is a derivative of MIT code; keep `LICENSE` and the copyright notice.
+- **Security-team acceptance.** Self-built code from this repo is a policy question for your team, not something this plan assumes.
+
+## 7. Decisions (resolved)
+
+1. **Scope: reduced first.** The priority is the RAM effect when running many simulators. The first release covers the CLI commands that produce it: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`, `on` (including `--no-reboot` and `--profile`), `off`, `enable`/`disable` (with `--save`), `boot`, `shutdown`, and `watch`. See section 8 for what is deferred.
+2. **Location:** `swift/` inside this repo.
+3. **Go tree:** kept until cutover only, as the parity reference. At cutover, tag the last Go commit and remove the tree. Upstream stays reachable through a git remote. Reason: `go.mod` and `go.sum` would otherwise keep the 19 third-party modules in the tree and weaken the "no third-party code" claim.
+4. **Dependency gate:** run by hand with `make verify-deps`. No CI wiring for now; revisit later.
+5. **Independent review: yes**, scoped to the mutating core (slim engine, `live.go`, `disabled_store.go`, `profile_save.go`) and, later, to any deferred destructive code before it is ported.
+
+## 8. Deferred (follow-up tasks)
+
+These are not in the first release. The SwiftUI app depends on several of them, so the app keeps bundling the Go CLI until they are ported. No cutover of the app happens before then.
+
+| Item | Why deferred | Notes |
+|---|---|---|
+| `top` live view | Not needed for the RAM effect; the one-shot `measure` covers the numbers | Terminal redraw without a TUI library. Keep `--json` one-shot. |
+| `profile` wizard | Profiles can be written by hand or via `enable --save` | Needs `stty` raw mode. |
+| `clone`, `repair-clone` | File writes in device data | Needs destructive-code review first. |
+| `rename`, `erase`, `delete` | Modify or remove whole simulators | Used by the GUI. Needs review first. |
+| `size`, `disk-categories`, `disk-plan`, `disk-clean` | `disk-clean` calls `RemoveAll` | Read-only parts may come first. `disk-clean` needs review first. |
+| App cutover to the Swift CLI | Requires all of the above | Then remove the Go tree. |
+
+## 9. Revised milestones for the first release
+
+- **M0** Scaffold: package, subprocess layer, dependency gate, `make verify-deps`.
+- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first.
+- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`.
+- **M3** Slimming: `on`, `off`, `on --no-reboot`, offline fast path, `boot`, `shutdown`, `enable`/`disable`, `--save`.
+- **M4** `watch`.
+- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/scripts/verify-deps.sh b/scripts/verify-deps.sh
new file mode 100755
index 0000000..af443bf
--- /dev/null
+++ b/scripts/verify-deps.sh
@@ -0,0 +1,253 @@
+#!/bin/zsh
+# Verifies that the Swift port uses no third-party code and no network.
+# Read-only except for building into swift/.build. Run it by hand:
+#
+# make verify-deps # all checks
+# scripts/verify-deps.sh --update-libs # rewrite swift/expected-libs.txt, then review the diff
+# scripts/verify-deps.sh --no-binary # source-level checks only (no build)
+#
+# Exit status is non-zero if any check fails.
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+SWIFT_DIR="$ROOT_DIR/swift"
+GUI_DIR="$ROOT_DIR/gui"
+SELF="scripts/verify-deps.sh"
+EXPECTED_LIBS="$SWIFT_DIR/expected-libs.txt"
+
+UPDATE_LIBS=0
+CHECK_BINARY=1
+for arg in "$@"; do
+ case "$arg" in
+ --update-libs) UPDATE_LIBS=1 ;;
+ --no-binary) CHECK_BINARY=0 ;;
+ *) echo "unknown argument: $arg" >&2; exit 64 ;;
+ esac
+done
+
+# Never name a zsh loop variable `path`: it is tied to PATH.
+for tool in find grep awk sort diff otool nm strings swift; do
+ command -v "$tool" >/dev/null 2>&1 || { print -u2 -- "verify-deps: required tool not found: $tool"; exit 70 }
+done
+
+# grep that treats "no match" (1) as empty output but any real error (>1) as fatal,
+# so a broken search can never read as a clean result.
+hits() {
+ local rc=0
+ grep "$@" || rc=$?
+ if (( rc > 1 )); then
+ print -u2 -- "verify-deps: grep failed (status $rc): grep $*"
+ exit 70
+ fi
+ return 0
+}
+
+FAILED=0
+fail() { print -u2 -- " FAIL: $*"; FAILED=1 }
+ok() { print -- " ok: $*" }
+section() { print -- "\n[$1]" }
+
+# Modules each tree may import. Everything here ships with Xcode.
+ALLOWED_SOURCES=(Foundation Darwin Dispatch SimSlimKit)
+ALLOWED_TESTS=(Foundation Darwin Dispatch SimSlimKit XCTest Testing)
+ALLOWED_GUI=(Foundation AppKit SwiftUI)
+
+# Prints ": " for each import in the given directory.
+list_imports() {
+ local dir="$1" file
+ [[ -d "$dir" ]] || return 0
+ find "$dir" -name '*.swift' -not -path '*/.build/*' | sort | while read -r file; do
+ awk -v f="${file#$ROOT_DIR/}" '
+ /^[[:space:]]*(@[A-Za-z_]+[[:space:]]+)*((public|internal|package)[[:space:]]+)?import[[:space:]]/ {
+ n = split($0, w, /[[:space:]]+/)
+ for (i = 1; i <= n; i++) if (w[i] == "import") { j = i + 1; break }
+ if (w[j] ~ /^(struct|class|enum|protocol|typealias|func|var|let)$/) j++
+ split(w[j], m, ".")
+ print f ": " m[1]
+ }' "$file"
+ done
+}
+
+check_imports() {
+ local label="$1" dir="$2"; shift 2
+ local -a allowed=("$@")
+ local line module bad=0
+ while read -r line; do
+ [[ -n "$line" ]] || continue
+ module="${line##*: }"
+ if (( ${allowed[(Ie)$module]} == 0 )); then
+ fail "$label imports '$module' (${line%%:*}); allowed: ${allowed[*]}"
+ bad=1
+ fi
+ done < <(list_imports "$dir")
+ (( bad )) || ok "$label imports only: ${allowed[*]}"
+}
+
+# ------------------------------------------------------------------ canary
+# Prove the searches can see the code: these patterns must match known lines.
+section "0. Canary (the searches can see the code)"
+[[ -n "$(hits -rn 'enum Executable' "$SWIFT_DIR/Sources")" ]] \
+ && ok "found enum Executable in swift/Sources" || fail "canary: enum Executable not found"
+[[ -n "$(hits -rn 'import Foundation' "$SWIFT_DIR/Sources")" ]] \
+ && ok "found import Foundation in swift/Sources" || fail "canary: no imports found"
+[[ -n "$(list_imports "$GUI_DIR")" ]] \
+ && ok "list_imports sees the gui imports" || fail "canary: list_imports returned nothing for gui"
+(( FAILED )) && { print -u2 -- "verify-deps: canary failed, aborting"; exit 70 }
+
+# ---------------------------------------------------------------- 1 packages
+section "1. No packages, vendored code, or plugins"
+PKG="$SWIFT_DIR/Package.swift"
+if [[ ! -f "$PKG" ]]; then
+ fail "missing $PKG"
+else
+ pkg_hits="$(hits -nE '\.package\(|\.binaryTarget|\.plugin|\.systemLibrary' "$PKG")"
+ if [[ -n "$pkg_hits" ]]; then
+ print -u2 -- "$pkg_hits"
+ fail "Package.swift declares a package, binary target, plugin, or system library"
+ else
+ ok "Package.swift declares no packages, binary targets, or plugins"
+ fi
+fi
+artifacts_ok=1
+for artifact in "$SWIFT_DIR/Package.resolved" "$SWIFT_DIR/Packages" "$SWIFT_DIR/vendor" \
+ "$ROOT_DIR/Package.swift" "$ROOT_DIR/Package.resolved" \
+ "$ROOT_DIR/Podfile" "$ROOT_DIR/Cartfile"; do
+ if [[ -e "$artifact" ]]; then fail "unexpected dependency artifact: ${artifact#$ROOT_DIR/}"; artifacts_ok=0; fi
+done
+# SwiftPM creates an empty checkouts directory even with no dependencies.
+if [[ -d "$SWIFT_DIR/.build/checkouts" && -n "$(ls -A "$SWIFT_DIR/.build/checkouts")" ]]; then
+ fail "swift/.build/checkouts is not empty: SwiftPM fetched something"; artifacts_ok=0
+fi
+(( artifacts_ok )) && ok "no Package.resolved, checkouts, Packages/, vendor/, Podfile, or Cartfile"
+
+# ---------------------------------------------------------------- 2 imports
+section "2. Imports are on the allowlist"
+check_imports "swift/Sources" "$SWIFT_DIR/Sources" "${ALLOWED_SOURCES[@]}"
+check_imports "swift/Tests" "$SWIFT_DIR/Tests" "${ALLOWED_TESTS[@]}"
+check_imports "gui" "$GUI_DIR" "${ALLOWED_GUI[@]}"
+
+# ---------------------------------------------------------------- 3 network
+section "3. No network APIs in source"
+NET_PATTERN='URLSession|URLRequest|NSURLConnection|NWConnection|NWListener|NWPathMonitor|CFNetwork|CFSocket|CFStream|InputStream|OutputStream|WKWebView|getaddrinfo|socket\(|connect\(|URL\(string:|http://|https://|ftp://'
+net_hits="$(hits -rnE "$NET_PATTERN" "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift')"
+if [[ -n "$net_hits" ]]; then
+ print -u2 -- "$net_hits"
+ fail "network-capable API or URL found in source (above)"
+else
+ ok "no URLSession, sockets, Network framework, or URLs in source"
+fi
+
+# Data(contentsOf:) and friends fetch remote URLs too. Only local reads are
+# allowed, which means the line must build its URL with fileURLWithPath.
+remote_read_hits="$(hits -rnE '(Data|String|NSData|NSString|NSDictionary|NSArray|XMLDocument)\((contentsOf|contentsOfURL):|dataTask|downloadTask' "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift' \
+ | hits -v 'fileURLWithPath')"
+if [[ -n "$remote_read_hits" ]]; then
+ print -u2 -- "$remote_read_hits"
+ fail "contentsOf:/download call that is not a fileURLWithPath read (above)"
+else
+ ok "every contentsOf: read is a local fileURLWithPath"
+fi
+
+# ---------------------------------------------------------------- 4 subprocess
+section "4. Subprocesses go through Subprocess.swift only"
+SUBPROC="$SWIFT_DIR/Sources/SimSlimKit/Subprocess.swift"
+spawn_hits="$(hits -rnE '\bProcess\(|NSTask|posix_spawn|\bpopen\(|\bsystem\(|\bexecv|\bfork\(|/bin/(ba|z)?sh' \
+ "$SWIFT_DIR/Sources" --include='*.swift' --exclude=Subprocess.swift)"
+if [[ -n "$spawn_hits" ]]; then
+ print -u2 -- "$spawn_hits"
+ fail "process spawning outside Subprocess.swift (above)"
+else
+ ok "Process/posix_spawn/popen/system only in Subprocess.swift"
+fi
+path_hits="$(hits -rnE '"/(usr/(s)?bin|bin|sbin|opt|Applications)/' "$SWIFT_DIR/Sources" --include='*.swift' \
+ --exclude=Subprocess.swift)"
+if [[ -n "$path_hits" ]]; then
+ print -u2 -- "$path_hits"
+ fail "hard-coded executable path outside Subprocess.swift (above)"
+else
+ ok "no executable paths outside the Executable enum"
+fi
+if [[ -n "$(hits -nE 'getenv|environment\[|\.environment|/usr/bin/env|"PATH"' "$SUBPROC")" ]]; then
+ fail "Subprocess.swift reads the environment or PATH"
+else
+ ok "Subprocess.swift reads no environment and does no PATH lookup"
+fi
+
+# ---------------------------------------------------------------- 7 fetching
+section "5. Build files fetch nothing"
+fetch_hits="$(cd "$ROOT_DIR" && hits -nE 'curl|wget|git clone|git submodule|http://|https://|brew install|pip install|npm install' \
+ swift/Package.swift Makefile scripts/build-app.sh | hits -v '^[^:]*:[0-9]*:[[:space:]]*echo ')"
+if [[ -n "$fetch_hits" ]]; then
+ print -u2 -- "$fetch_hits"
+ fail "build files reference a download or installer (above)"
+else
+ ok "swift/Package.swift, Makefile, and scripts/build-app.sh fetch nothing"
+fi
+
+# ------------------------------------------------------------ binary checks
+if (( CHECK_BINARY )); then
+ section "6. Release binary"
+ (cd "$SWIFT_DIR" && swift build -c release >/dev/null 2>&1) || { fail "swift build -c release failed"; }
+ BIN="$SWIFT_DIR/.build/release/simslim"
+ if [[ ! -x "$BIN" ]]; then
+ fail "release binary not found at ${BIN#$ROOT_DIR/}"
+ else
+ # Linked libraries must all be system libraries.
+ libs="$(otool -L "$BIN" | tail -n +2 | awk '{print $1}' | sort)"
+ non_system="$(print -r -- "$libs" | hits -vE '^(/usr/lib/|/System/Library/)')"
+ if [[ -n "$non_system" ]]; then
+ print -u2 -- "$non_system"
+ fail "binary links a non-system library (above)"
+ else
+ ok "every linked library is under /usr/lib or /System/Library"
+ fi
+ if (( UPDATE_LIBS )); then
+ print -r -- "$libs" > "$EXPECTED_LIBS"
+ ok "rewrote ${EXPECTED_LIBS#$ROOT_DIR/} (review the diff)"
+ elif [[ -f "$EXPECTED_LIBS" ]]; then
+ if diff <(print -r -- "$libs") "$EXPECTED_LIBS" >/dev/null; then
+ ok "linked libraries match swift/expected-libs.txt"
+ else
+ diff <(print -r -- "$libs") "$EXPECTED_LIBS" >&2 || true
+ fail "linked libraries differ from swift/expected-libs.txt"
+ fi
+ else
+ fail "swift/expected-libs.txt is missing (run with --update-libs, then review it)"
+ fi
+
+ # Undefined symbols that would indicate networking.
+ NET_SYMBOLS='NSURLSession|NSURLConnection|CFNetwork|nw_connection|nw_listener|_getaddrinfo|_socket$|_connect$'
+ net_syms="$(nm -u "$BIN" | hits -E "$NET_SYMBOLS")"
+ if [[ -n "$net_syms" ]]; then
+ print -u2 -- "$net_syms"
+ fail "binary imports network symbols (above)"
+ else
+ ok "no network symbols among the binary's imports"
+ fi
+
+ # Test-only hooks must never ship. By convention they are named SIMSLIM_TEST_*.
+ if [[ -n "$(strings -a "$BIN" | hits 'SIMSLIM_TEST_')" ]]; then
+ fail "release binary contains a SIMSLIM_TEST_ hook"
+ else
+ ok "no SIMSLIM_TEST_ hooks in the release binary"
+ fi
+
+ # Behavior check: the binary still works with all network access denied.
+ if command -v sandbox-exec >/dev/null 2>&1; then
+ if out="$(sandbox-exec -p '(version 1)(allow default)(deny network*)' "$BIN" --version 2>&1)"; then
+ ok "runs with network denied: $out"
+ else
+ fail "binary failed under sandbox-exec with network denied: $out"
+ fi
+ else
+ print -- " skip: sandbox-exec not available"
+ fi
+ fi
+fi
+
+print -- ""
+if (( FAILED )); then
+ print -u2 -- "verify-deps: FAILED"
+ exit 1
+fi
+print -- "verify-deps: all checks passed"
diff --git a/swift/Package.swift b/swift/Package.swift
new file mode 100644
index 0000000..a037473
--- /dev/null
+++ b/swift/Package.swift
@@ -0,0 +1,19 @@
+// swift-tools-version:6.0
+import PackageDescription
+
+// No third-party packages, ever. `scripts/verify-deps.sh` fails the check if
+// `dependencies` is anything other than an empty list.
+let package = Package(
+ name: "simslim",
+ platforms: [.macOS(.v14)],
+ products: [
+ .executable(name: "simslim", targets: ["simslim"])
+ ],
+ dependencies: [],
+ targets: [
+ .target(name: "SimSlimKit"),
+ .executableTarget(name: "simslim", dependencies: ["SimSlimKit"]),
+ .testTarget(name: "SimSlimKitTests", dependencies: ["SimSlimKit"]),
+ ],
+ swiftLanguageModes: [.v5]
+)
diff --git a/swift/Sources/SimSlimKit/Catalog.swift b/swift/Sources/SimSlimKit/Catalog.swift
new file mode 100644
index 0000000..42fefae
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Catalog.swift
@@ -0,0 +1,105 @@
+import Foundation
+
+/// Shown alongside a category for transparency but never part of a slim
+/// profile. Earlier versions may have disabled it, so it stays in the mutation
+/// allowlist solely to repair that legacy state.
+public struct AlwaysEnabledService: Codable, Equatable, Sendable {
+ public let label: String
+ public let reason: String
+
+ public init(label: String, reason: String) {
+ self.label = label
+ self.reason = reason
+ }
+}
+
+/// Raw, generated category data (see Generated/CatalogData.swift).
+struct CategorySeed {
+ let id: String
+ let name: String
+ let description: String
+ let downside: String
+ let approxMemoryMB: Int
+ let labels: [String]
+ let alwaysEnabled: [AlwaysEnabledService]
+}
+
+/// Groups launchd daemon labels that a slim boot disables together.
+///
+/// The JSON shape is a contract with the SwiftUI app (`gui/Models.swift`).
+public struct Category: Codable, Equatable, Sendable {
+ public let id: String
+ public let name: String
+ public let description: String
+ public let downside: String
+ public let approxMemoryMB: Int
+ public let labels: [String]
+ public let serviceDescriptions: [String: String]
+ public let alwaysEnabled: [AlwaysEnabledService]
+
+ init(seed: CategorySeed) {
+ id = seed.id
+ name = seed.name
+ description = seed.description
+ downside = seed.downside
+ approxMemoryMB = seed.approxMemoryMB
+ labels = seed.labels
+ // A label without a description maps to "", exactly like the Go map
+ // lookup; the tests reject any such label.
+ serviceDescriptions = Dictionary(
+ uniqueKeysWithValues: seed.labels.map { ($0, serviceDescriptionByLabel[$0] ?? "") }
+ )
+ alwaysEnabled = seed.alwaysEnabled
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case id, name, description, downside, approxMemoryMB, labels, serviceDescriptions, alwaysEnabled
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(id, forKey: .id)
+ try c.encode(name, forKey: .name)
+ try c.encode(description, forKey: .description)
+ try c.encode(downside, forKey: .downside)
+ try c.encode(approxMemoryMB, forKey: .approxMemoryMB)
+ try c.encode(labels, forKey: .labels)
+ try c.encode(serviceDescriptions, forKey: .serviceDescriptions)
+ // Go's `omitempty`: absent when there are none.
+ if !alwaysEnabled.isEmpty { try c.encode(alwaysEnabled, forKey: .alwaysEnabled) }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(String.self, forKey: .id)
+ name = try c.decode(String.self, forKey: .name)
+ description = try c.decode(String.self, forKey: .description)
+ downside = try c.decode(String.self, forKey: .downside)
+ approxMemoryMB = try c.decode(Int.self, forKey: .approxMemoryMB)
+ labels = try c.decode([String].self, forKey: .labels)
+ serviceDescriptions = try c.decode([String: String].self, forKey: .serviceDescriptions)
+ alwaysEnabled = try c.decodeIfPresent([AlwaysEnabledService].self, forKey: .alwaysEnabled) ?? []
+ }
+}
+
+/// The complete allowlist of daemons a profile may disable.
+///
+/// Categories may overlap: a label lives in every category whose feature needs
+/// it, and an excepted category keeps all its labels enabled even when a
+/// slimmed category also lists them. `approxMemoryMB` values are rounded median
+/// increases in phys_footprint, not additive.
+public enum Catalog {
+ public static let categories: [Category] = categorySeeds.map(Category.init(seed:))
+
+ public static func category(id: String) -> Category? {
+ categories.first { $0.id == id }
+ }
+
+ /// Every label a service profile may disable.
+ public static let slimmableSet: Set = Set(categories.flatMap(\.labels))
+
+ /// The complete mutation allowlist. Most labels are slimmable; required
+ /// labels may only transition back to enabled, for compatibility.
+ public static let managedSet: Set =
+ slimmableSet.union(categories.flatMap(\.alwaysEnabled).map(\.label))
+}
diff --git a/swift/Sources/SimSlimKit/Device.swift b/swift/Sources/SimSlimKit/Device.swift
new file mode 100644
index 0000000..e79aaa3
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Device.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+/// A simulator. The JSON keys are a contract with the SwiftUI app; `dataPath`
+/// and `runtimeID` are deliberately not part of it.
+public struct Device: Codable, Equatable, Sendable {
+ public var udid: String
+ public var name: String
+ public var state: String // "Booted" or "Shutdown"
+ public var platform: String // "iOS", "tvOS", "watchOS", or "visionOS"
+ public var osVersion: String
+ public var set: String
+ public var dataPath: String = ""
+ public var runtimeID: String = ""
+
+ public init(
+ udid: String,
+ name: String = "",
+ state: String = "",
+ platform: String = "",
+ osVersion: String = "",
+ set: String = "",
+ dataPath: String = "",
+ runtimeID: String = ""
+ ) {
+ self.udid = udid
+ self.name = name
+ self.state = state
+ self.platform = platform
+ self.osVersion = osVersion
+ self.set = set
+ self.dataPath = dataPath
+ self.runtimeID = runtimeID
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case udid, name, state, platform, osVersion, set
+ }
+
+ /// Preserves the iOS default for callers that build a Device without
+ /// platform metadata.
+ public var platformName: String { platform.isEmpty ? "iOS" : platform }
+
+ /// The platform and version shown in human-readable output.
+ public var runtimeName: String { platformName + " " + osVersion }
+}
diff --git a/swift/Sources/SimSlimKit/Errors.swift b/swift/Sources/SimSlimKit/Errors.swift
new file mode 100644
index 0000000..a20b49d
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Errors.swift
@@ -0,0 +1,11 @@
+import Foundation
+
+/// An error whose message is meant to be shown to the user as-is.
+public struct SimSlimError: Error, LocalizedError, CustomStringConvertible, Equatable {
+ public let message: String
+
+ public init(_ message: String) { self.message = message }
+
+ public var description: String { message }
+ public var errorDescription: String? { message }
+}
diff --git a/swift/Sources/SimSlimKit/Features.swift b/swift/Sources/SimSlimKit/Features.swift
new file mode 100644
index 0000000..5fa4435
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Features.swift
@@ -0,0 +1,114 @@
+import Foundation
+
+/// A user-facing capability backed by specific launchd daemons. Every label
+/// must also be managed by a Category (enforced in the tests), including
+/// required services that earlier versions could have turned off.
+public struct Feature: Codable, Equatable, Sendable {
+ public let id: String
+ public let name: String
+ public let labels: [String]
+
+ public init(id: String, name: String, labels: [String]) {
+ self.id = id
+ self.name = name
+ self.labels = labels
+ }
+}
+
+/// One feature's verdict: the daemons it needs that are down.
+public struct FeatureStatus: Codable, Equatable, Sendable {
+ public let id: String
+ public let name: String
+ public let ok: Bool
+ public let disabled: [String]
+
+ public init(id: String, name: String, ok: Bool, disabled: [String]) {
+ self.id = id
+ self.name = name
+ self.ok = ok
+ self.disabled = disabled
+ }
+
+ private enum CodingKeys: String, CodingKey { case id, name, ok, disabled }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(id, forKey: .id)
+ try c.encode(name, forKey: .name)
+ try c.encode(ok, forKey: .ok)
+ if !disabled.isEmpty { try c.encode(disabled, forKey: .disabled) } // Go omitempty
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(String.self, forKey: .id)
+ name = try c.decode(String.self, forKey: .name)
+ ok = try c.decode(Bool.self, forKey: .ok)
+ disabled = try c.decodeIfPresent([String].self, forKey: .disabled) ?? []
+ }
+}
+
+/// Whether each required feature survives the device's current slimming. `ok`
+/// is false when any required feature has a disabled daemon.
+public struct DoctorOutput: Codable, Equatable, Sendable {
+ public var udid: String
+ public var ok: Bool
+ public var features: [FeatureStatus]
+
+ public init(udid: String = "", ok: Bool, features: [FeatureStatus]) {
+ self.udid = udid
+ self.ok = ok
+ self.features = features
+ }
+
+ private enum CodingKeys: String, CodingKey { case udid, ok, features }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ if !udid.isEmpty { try c.encode(udid, forKey: .udid) } // Go omitempty
+ try c.encode(ok, forKey: .ok)
+ try c.encode(features, forKey: .features)
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ udid = try c.decodeIfPresent(String.self, forKey: .udid) ?? ""
+ ok = try c.decode(Bool.self, forKey: .ok)
+ features = try c.decode([FeatureStatus].self, forKey: .features)
+ }
+}
+
+extension Catalog {
+ /// Commonly required capabilities mapped to the daemons they need running.
+ public static let features: [Feature] = featureList
+
+ public static func feature(id: String) -> Feature? {
+ features.first { $0.id == id }
+ }
+
+ /// Maps requested IDs to their Features, failing on the first unknown one so
+ /// a typo in `--requires` fails loudly instead of passing silently.
+ public static func resolveFeatures(_ ids: [String]) throws -> [Feature] {
+ try ids.map { id in
+ guard let feature = feature(id: id) else {
+ throw SimSlimError("unknown feature \"\(id)\" (see `simslim doctor --list`)")
+ }
+ return feature
+ }
+ }
+
+ /// Reports, for each feature, which of its daemons the device currently has
+ /// disabled. A feature is OK only when none of them are.
+ public static func diagnoseFeatures(_ features: [Feature], disabled: Set) -> DoctorOutput
+ {
+ var allOK = true
+ var statuses: [FeatureStatus] = []
+ for feature in features {
+ let down = feature.labels.filter { disabled.contains($0) }
+ let ok = down.isEmpty
+ allOK = allOK && ok
+ statuses.append(FeatureStatus(id: feature.id, name: feature.name, ok: ok, disabled: down))
+ }
+ return DoctorOutput(ok: allOK, features: statuses)
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Generated/CatalogData.swift b/swift/Sources/SimSlimKit/Generated/CatalogData.swift
new file mode 100644
index 0000000..c6049e5
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Generated/CatalogData.swift
@@ -0,0 +1,623 @@
+// Generated by swift/Tools/gen_catalog.py from profiles.go, service_descriptions.go
+// and features.go. Do not edit by hand; rerun the tool.
+
+let categorySeeds: [CategorySeed] = [
+ CategorySeed(
+ id: "widgets",
+ name: "Widgets & Wallpaper",
+ description: "Home and lock screen posters, widgets, and Live Activities.",
+ downside: "Home and Lock Screen widgets, wallpaper posters, and Live Activities stop updating.",
+ approxMemoryMB: 675,
+ labels: [
+ "com.apple.PosterBoard",
+ "com.apple.chronod",
+ "com.apple.liveactivitiesd",
+ "com.apple.navd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "siri",
+ name: "Siri & Intelligence",
+ description: "Siri, Apple Intelligence, speech, and on-device ML model services.",
+ downside: "Siri, speech features, and Apple Intelligence services are unavailable.",
+ approxMemoryMB: 265,
+ labels: [
+ "com.apple.assistant_cdmd",
+ "com.apple.assistant_service",
+ "com.apple.siriactionsd",
+ "com.apple.siriinferenced",
+ "com.apple.siriknowledged",
+ "com.apple.sirittsd",
+ "com.apple.siri.context.service",
+ "com.apple.siri.acousticsignature",
+ "com.apple.corespeechd",
+ "com.apple.voiced",
+ "com.apple.voicebankingd",
+ "com.apple.speechmodeltrainingd",
+ "com.apple.intelligenceplatformd",
+ "com.apple.intelligencecontextd",
+ "com.apple.intelligenceflowd",
+ "com.apple.intelligencetasksd",
+ "com.apple.generativeexperiencesd",
+ "com.apple.knowledgeconstructiond",
+ "com.apple.naturallanguaged",
+ "com.apple.textunderstandingd",
+ "com.apple.modelcatalogd",
+ "com.apple.modelmanagerd",
+ "com.apple.mlhostd",
+ "com.apple.mlruntimed",
+ "com.apple.suggestd",
+ "com.apple.parsecd",
+ "com.apple.parsec-fbf",
+ "com.apple.proactiveeventtrackerd",
+ ],
+ alwaysEnabled: [
+ AlwaysEnabledService(label: "com.apple.assistantd", reason: "Hosts the dictation service; without it the system Spotlight app leaks memory."),
+ ]
+ ),
+ CategorySeed(
+ id: "search",
+ name: "Spotlight & Search",
+ description: "On-device Spotlight and in-Settings search services.",
+ downside: "Spotlight and Settings search return no results, and Recents in Files and the document picker fails to load.",
+ approxMemoryMB: 50,
+ labels: [
+ "com.apple.searchd",
+ "com.apple.searchtoold",
+ "com.apple.spotlightknowledged",
+ "com.apple.spotlightknowledged.updater",
+ "com.apple.corespotlightservice",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "icloud",
+ name: "iCloud & Apple Account",
+ description: "iCloud sync, Apple Account, keychain, and backup services.",
+ downside: "iCloud sync, Apple Account, Keychain, and backup workflows will not work.",
+ approxMemoryMB: 100,
+ labels: [
+ "com.apple.appleaccountd",
+ "com.apple.appleaccounttransparencyd",
+ "com.apple.appleidsetupd",
+ "com.apple.akd",
+ "com.apple.amsaccountsd",
+ "com.apple.amsengagementd",
+ "com.apple.amsondevicestoraged",
+ "com.apple.cloudd",
+ "com.apple.cloudphotod",
+ "com.apple.ckdiscretionaryd",
+ "com.apple.cloudsettingssyncagent",
+ "com.apple.bird",
+ "com.apple.syncdefaultsd",
+ "com.apple.cdpd",
+ "com.apple.sosd",
+ "com.apple.SecureBackupDaemon",
+ "com.apple.TrustedPeersHelper",
+ "com.apple.protectedcloudstorage.protectedcloudkeysyncing",
+ "com.apple.icloudmailagent",
+ "com.apple.icloudsubscriptionoptimizerd",
+ "com.apple.communicationtrustd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "store",
+ name: "App Store, Push & Media",
+ description: "App Store, push notification, StoreKit, and media services.",
+ downside: "Remote push notifications and StoreKit or App Store testing will not work.",
+ approxMemoryMB: 80,
+ labels: [
+ "com.apple.appstored",
+ "com.apple.appstorecomponentsd",
+ "com.apple.apsd",
+ "com.apple.itunescloudd",
+ "com.apple.itunesstored",
+ "com.apple.storekitd",
+ "com.apple.amsaccountsd",
+ "com.apple.amsengagementd",
+ "com.apple.amsondevicestoraged",
+ "com.apple.passd",
+ "com.apple.financed",
+ "com.apple.videosubscriptionsd",
+ "com.apple.assetsubscriptiond",
+ "com.apple.musicd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "pim",
+ name: "Mail, Calendar & Contacts",
+ description: "Mail, Calendar, Contacts, Reminders, and related sync services.",
+ downside: "Contacts, Calendar, Reminders, and Mail-backed pickers or sync may fail.",
+ approxMemoryMB: 80,
+ labels: [
+ "com.apple.email.maild",
+ "com.apple.exchangesyncd",
+ "com.apple.dataaccess.dataaccessd",
+ "com.apple.calaccessd",
+ "com.apple.remindd",
+ "com.apple.contactsd",
+ "com.apple.contacts.postersyncd",
+ "com.apple.peopled",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "web",
+ name: "Safari Sync & Web Services",
+ description: "Safari sync, web push, privacy, and universal-link services.",
+ downside: "Universal links and Safari sync or background web services will not work.",
+ approxMemoryMB: 50,
+ labels: [
+ "com.apple.SafariBookmarksSyncAgent",
+ "com.apple.Safari.History",
+ "com.apple.Safari.passwordbreachd",
+ "com.apple.Safari.SafeBrowsing.Service",
+ "com.apple.safarifetcherd",
+ "com.apple.WebBookmarks.webbookmarksd",
+ "com.apple.webkit.adattributiond",
+ "com.apple.webkit.webpushd",
+ "com.apple.webprivacyd",
+ "com.apple.swcd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "family",
+ name: "Family & Screen Time",
+ description: "Family Sharing, Screen Time, and usage tracking.",
+ downside: "Family Sharing, Screen Time, and usage tracking stop working.",
+ approxMemoryMB: 65,
+ labels: [
+ "com.apple.familycircled",
+ "com.apple.FamilyControlsAgent",
+ "com.apple.familynotification",
+ "com.apple.askpermissiond",
+ "com.apple.asktod",
+ "com.apple.ScreenTimeAgent",
+ "com.apple.ScreenTimeSettingsAgent",
+ "com.apple.UsageTrackingAgent",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "health",
+ name: "Health, Home & Fitness",
+ description: "HealthKit, HomeKit, and Fitness services.",
+ downside: "HealthKit, HomeKit, and Fitness integrations will not work.",
+ approxMemoryMB: 135,
+ labels: [
+ "com.apple.healthd",
+ "com.apple.healthappd",
+ "com.apple.healthcontentd",
+ "com.apple.healtheventsd",
+ "com.apple.healthrecordsd",
+ "com.apple.finhealthd",
+ "com.apple.homed",
+ "com.apple.homeeventsd",
+ "com.apple.fitcore",
+ "com.apple.fitcore.session",
+ "com.apple.fitnesscoachingd",
+ "com.apple.fitnessintelligenced",
+ "com.apple.activityawardsd",
+ "com.apple.activitysharingd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "photos",
+ name: "Photos & Media Analysis",
+ description: "Photos library, photo analysis, and media analysis services.",
+ downside: "Photo picker, Photos-library workflows, and media analysis may fail.",
+ approxMemoryMB: 60,
+ labels: [
+ "com.apple.photoanalysisd",
+ "com.apple.photosface",
+ "com.apple.mediaanalysisd",
+ "com.apple.mediaanalysisd.service",
+ "com.apple.mediastream.mstreamd",
+ "com.apple.medialibraryd",
+ "com.apple.assetsd",
+ "com.apple.assetsd.nebulad",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "apps",
+ name: "News, Weather, Maps & Games",
+ description: "News, Weather, Maps, Tips, and game services.",
+ downside: "News, Weather, Maps background data, and game-controller services are unavailable.",
+ approxMemoryMB: 90,
+ labels: [
+ "com.apple.newsd",
+ "com.apple.weatherd",
+ "com.apple.Maps.mapssyncd",
+ "com.apple.Maps.mapspushd",
+ "com.apple.Maps.geocorrectiond",
+ "com.apple.maps.destinationd",
+ "com.apple.MapKit.SnapshotService",
+ "com.apple.jetpackassetd",
+ "com.apple.tipsd",
+ "com.apple.gamesaved",
+ "com.apple.GameController.gamecontrollerd",
+ ],
+ alwaysEnabled: [
+ AlwaysEnabledService(label: "com.apple.gamed", reason: "Required for timely XCUITest app launches (DTServiceHub / GameKit)."),
+ ]
+ ),
+ CategorySeed(
+ id: "messaging",
+ name: "Messaging & FaceTime",
+ description: "iMessage, FaceTime, call, and identity services.",
+ downside: "iMessage, FaceTime, and related identity services will not work.",
+ approxMemoryMB: 60,
+ labels: [
+ "com.apple.identityservicesd",
+ "com.apple.ids_simd",
+ "com.apple.imautomatichistorydeletionagent",
+ "com.apple.imcore.imtransferagent",
+ "com.apple.imdpersistence.IMDPersistenceAgent",
+ "com.apple.facetimemessagestored",
+ "com.apple.telephonyutilities.callservicesd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "connectivity",
+ name: "Sharing & Device Connectivity",
+ description: "AirDrop, Continuity, CarPlay, Watch, and Find My services.",
+ downside: "AirDrop, Continuity, CarPlay, Watch, and Find My connectivity will not work.",
+ approxMemoryMB: 65,
+ labels: [
+ "com.apple.rapportd",
+ "com.apple.companiond",
+ "com.apple.carkitd",
+ "com.apple.wcd",
+ "com.apple.tvremoted",
+ "com.apple.avatarsd",
+ "com.apple.stickersd",
+ "com.apple.sociallayerd",
+ "com.apple.announced",
+ "com.apple.navd",
+ "com.apple.findmy.findmylocated",
+ ],
+ alwaysEnabled: [
+ AlwaysEnabledService(label: "com.apple.sharingd", reason: "Required for system share sheets."),
+ ]
+ ),
+ CategorySeed(
+ id: "telemetry",
+ name: "Ads, Diagnostics & Telemetry",
+ description: "DeviceCheck, ad privacy, analytics, diagnostics, and feedback services.",
+ downside: "DeviceCheck plus analytics, diagnostics, and feedback services are unavailable.",
+ approxMemoryMB: 105,
+ labels: [
+ "com.apple.ap.adprivacyd",
+ "com.apple.ap.promotedcontentd",
+ "com.apple.diagnosticextensionsd",
+ "com.apple.feedbackd",
+ "com.apple.rtcreportingd",
+ "com.apple.securityuploadd",
+ "com.apple.geoanalyticsd",
+ "com.apple.triald",
+ "com.apple.followupd",
+ "com.apple.purplebuddy.budd",
+ "com.apple.devicecheckd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "mdm",
+ name: "Device Management",
+ description: "Declarative device management and managed asset services.",
+ downside: "Declarative device management, and MDM or configuration-profile workflows that use it, will not work.",
+ approxMemoryMB: 10,
+ labels: [
+ "com.apple.remotemanagementd",
+ "com.apple.RemoteManagementAgent",
+ "com.apple.managedassetsd",
+ ],
+ alwaysEnabled: []
+ ),
+ CategorySeed(
+ id: "other",
+ name: "Other Background Services",
+ description: "Wallet, App Clips, business services, assets, and miscellaneous background daemons.",
+ downside: "Wallet, App Clips, accessibility asset downloads, merchant, business, and miscellaneous background services are unavailable.",
+ approxMemoryMB: 225,
+ labels: [
+ "com.apple.financed",
+ "com.apple.passd",
+ "com.apple.merchantd",
+ "com.apple.coreidvd",
+ "com.apple.businessservicesd",
+ "com.apple.deviceaccessd",
+ "com.apple.replicatord",
+ "com.apple.linkd",
+ "com.apple.ind",
+ "com.apple.storagedatad",
+ "com.apple.StatusKitAgent",
+ "com.apple.countryd",
+ "com.apple.mobileassetd",
+ "com.apple.managedconfiguration.passcodenagd",
+ "com.apple.accessibility.axassetsd",
+ "com.apple.ClipServices.clipserviced",
+ ],
+ alwaysEnabled: []
+ ),
+]
+
+let serviceDescriptionByLabel: [String: String] = [
+ "com.apple.PosterBoard": "Renders Home and Lock Screen wallpaper scenes.",
+ "com.apple.chronod": "Refreshes widgets and complications on schedule.",
+ "com.apple.liveactivitiesd": "Updates Live Activities and Dynamic Island content.",
+ "com.apple.assistant_cdmd": "Routes commands and intents submitted to Siri.",
+ "com.apple.assistant_service": "Provides supporting services for Siri requests.",
+ "com.apple.siriactionsd": "Executes Siri actions and App Intents.",
+ "com.apple.siriinferenced": "Runs Siri inference and intent predictions.",
+ "com.apple.siriknowledged": "Maintains knowledge and context used by Siri.",
+ "com.apple.sirittsd": "Generates Siri's spoken responses.",
+ "com.apple.siri.context.service": "Builds device context for Siri requests.",
+ "com.apple.siri.acousticsignature": "Processes acoustic signatures for voice features.",
+ "com.apple.corespeechd": "Provides speech recognition and voice-trigger services.",
+ "com.apple.voiced": "Manages system voices and speech assets.",
+ "com.apple.voicebankingd": "Supports Personal Voice and voice banking.",
+ "com.apple.speechmodeltrainingd": "Adapts on-device speech recognition models.",
+ "com.apple.intelligenceplatformd": "Coordinates Apple Intelligence services.",
+ "com.apple.intelligencecontextd": "Collects local context for intelligence features.",
+ "com.apple.intelligenceflowd": "Orchestrates Apple Intelligence workflows.",
+ "com.apple.intelligencetasksd": "Runs background Apple Intelligence tasks.",
+ "com.apple.generativeexperiencesd": "Supports generative intelligence experiences.",
+ "com.apple.knowledgeconstructiond": "Builds on-device knowledge used by suggestions.",
+ "com.apple.naturallanguaged": "Performs natural-language analysis.",
+ "com.apple.textunderstandingd": "Extracts meaning and entities from text.",
+ "com.apple.modelcatalogd": "Tracks machine-learning models available to the system.",
+ "com.apple.modelmanagerd": "Downloads and manages on-device models.",
+ "com.apple.mlhostd": "Hosts system machine-learning services.",
+ "com.apple.mlruntimed": "Executes on-device machine-learning models.",
+ "com.apple.suggestd": "Generates system suggestions and predictions.",
+ "com.apple.parsecd": "Provides network-backed Siri and Spotlight suggestions.",
+ "com.apple.parsec-fbf": "Collects feedback for Siri and Spotlight suggestions.",
+ "com.apple.proactiveeventtrackerd": "Tracks events used by proactive suggestions.",
+ "com.apple.searchd": "Coordinates system search queries.",
+ "com.apple.searchtoold": "Runs helper tasks for system search.",
+ "com.apple.spotlightknowledged": "Builds knowledge used by Spotlight results.",
+ "com.apple.spotlightknowledged.updater": "Refreshes Spotlight's knowledge data.",
+ "com.apple.corespotlightservice": "Indexes and searches app-provided content.",
+ "com.apple.appleaccountd": "Maintains Apple Account state on the device.",
+ "com.apple.appleaccounttransparencyd": "Checks Apple Account security records.",
+ "com.apple.appleidsetupd": "Handles Apple Account setup workflows.",
+ "com.apple.akd": "Provides Apple Account authentication tokens.",
+ "com.apple.amsaccountsd": "Manages App Store and media account state.",
+ "com.apple.amsengagementd": "Handles App Store and media engagement messages.",
+ "com.apple.amsondevicestoraged": "Stores Apple media-service data on the device.",
+ "com.apple.cloudd": "Synchronizes CloudKit databases and records.",
+ "com.apple.cloudphotod": "Synchronizes the iCloud Photos library.",
+ "com.apple.ckdiscretionaryd": "Schedules non-urgent CloudKit transfers.",
+ "com.apple.cloudsettingssyncagent": "Synchronizes supported system settings through iCloud.",
+ "com.apple.bird": "Synchronizes iCloud Drive files.",
+ "com.apple.syncdefaultsd": "Synchronizes supported preferences between devices.",
+ "com.apple.cdpd": "Handles iCloud data-protection setup and recovery.",
+ "com.apple.sosd": "Synchronizes iCloud Keychain secure items.",
+ "com.apple.SecureBackupDaemon": "Handles secure backup and account recovery data.",
+ "com.apple.TrustedPeersHelper": "Maintains trusted peers for iCloud Keychain.",
+ "com.apple.protectedcloudstorage.protectedcloudkeysyncing": "Synchronizes protected cloud encryption keys.",
+ "com.apple.icloudmailagent": "Runs background services for iCloud Mail.",
+ "com.apple.icloudsubscriptionoptimizerd": "Evaluates iCloud storage subscription recommendations.",
+ "com.apple.communicationtrustd": "Maintains communication trust and safety state.",
+ "com.apple.appstored": "Installs and updates apps from the App Store.",
+ "com.apple.appstorecomponentsd": "Provides background components used by the App Store.",
+ "com.apple.apsd": "Receives Apple Push Notification service messages.",
+ "com.apple.itunescloudd": "Synchronizes purchased and cloud media libraries.",
+ "com.apple.itunesstored": "Handles media-store accounts and purchases.",
+ "com.apple.storekitd": "Processes StoreKit products and transactions.",
+ "com.apple.videosubscriptionsd": "Manages video subscriptions and TV providers.",
+ "com.apple.assetsubscriptiond": "Manages subscribed media assets and downloads.",
+ "com.apple.musicd": "Runs background Music library and playback services.",
+ "com.apple.email.maild": "Fetches, indexes, and sends Mail account data.",
+ "com.apple.exchangesyncd": "Synchronizes Microsoft Exchange account data.",
+ "com.apple.dataaccess.dataaccessd": "Synchronizes CalDAV, CardDAV, and related accounts.",
+ "com.apple.calaccessd": "Provides access to Calendar event data.",
+ "com.apple.remindd": "Stores and synchronizes reminders.",
+ "com.apple.contactsd": "Provides access to the Contacts database.",
+ "com.apple.contacts.postersyncd": "Synchronizes Contact Posters.",
+ "com.apple.peopled": "Builds people and relationship suggestions.",
+ "com.apple.SafariBookmarksSyncAgent": "Synchronizes Safari bookmarks through iCloud.",
+ "com.apple.Safari.History": "Maintains and synchronizes Safari history.",
+ "com.apple.Safari.passwordbreachd": "Checks saved passwords for known data leaks.",
+ "com.apple.Safari.SafeBrowsing.Service": "Checks sites against unsafe browsing data.",
+ "com.apple.safarifetcherd": "Fetches Safari content in the background.",
+ "com.apple.WebBookmarks.webbookmarksd": "Maintains web bookmarks, clips, and Reading List data.",
+ "com.apple.webkit.adattributiond": "Processes privacy-preserving web ad attribution.",
+ "com.apple.webkit.webpushd": "Receives push notifications for websites.",
+ "com.apple.webprivacyd": "Maintains Safari privacy-protection data.",
+ "com.apple.swcd": "Matches universal links with installed apps.",
+ "com.apple.familycircled": "Maintains Family Sharing membership and state.",
+ "com.apple.FamilyControlsAgent": "Applies parental and Family Controls restrictions.",
+ "com.apple.familynotification": "Delivers Family Sharing invitations and notices.",
+ "com.apple.askpermissiond": "Handles Ask to Buy permission requests.",
+ "com.apple.asktod": "Routes family approval prompts and responses.",
+ "com.apple.ScreenTimeAgent": "Enforces Screen Time limits and reports usage.",
+ "com.apple.ScreenTimeSettingsAgent": "Connects Screen Time data to Settings.",
+ "com.apple.UsageTrackingAgent": "Tracks app and website usage duration.",
+ "com.apple.healthd": "Stores and serves HealthKit data.",
+ "com.apple.healthappd": "Runs background tasks for the Health app.",
+ "com.apple.healthcontentd": "Provides educational and recommended health content.",
+ "com.apple.healtheventsd": "Processes health events and related notifications.",
+ "com.apple.healthrecordsd": "Synchronizes clinical health records.",
+ "com.apple.finhealthd": "Analyzes Wallet transactions and financial-health data.",
+ "com.apple.homed": "Manages HomeKit accessories, rooms, and automations. Kept enabled on watchOS.",
+ "com.apple.homeeventsd": "Processes HomeKit events and automation triggers.",
+ "com.apple.fitcore": "Runs Apple Fitness content and background services.",
+ "com.apple.fitcore.session": "Manages active Apple Fitness sessions.",
+ "com.apple.fitnesscoachingd": "Provides Fitness coaching recommendations.",
+ "com.apple.fitnessintelligenced": "Generates personalized Fitness insights.",
+ "com.apple.activityawardsd": "Tracks Activity awards and achievements.",
+ "com.apple.activitysharingd": "Synchronizes shared Activity and Fitness data.",
+ "com.apple.photoanalysisd": "Analyzes photos for scenes, people, and search.",
+ "com.apple.photosface": "Performs face detection for the Photos library.",
+ "com.apple.mediaanalysisd": "Analyzes image, video, and audio content.",
+ "com.apple.mediaanalysisd.service": "Runs isolated media-analysis work.",
+ "com.apple.mediastream.mstreamd": "Synchronizes shared and streamed photo content.",
+ "com.apple.medialibraryd": "Maintains the system media library database.",
+ "com.apple.assetsd": "Provides access to Photos library assets.",
+ "com.apple.assetsd.nebulad": "Handles cloud-backed Photos asset transfers.",
+ "com.apple.newsd": "Downloads and refreshes Apple News content.",
+ "com.apple.weatherd": "Fetches forecasts and weather data.",
+ "com.apple.Maps.mapssyncd": "Synchronizes Maps favorites, guides, and history.",
+ "com.apple.Maps.mapspushd": "Receives background updates for Maps.",
+ "com.apple.Maps.geocorrectiond": "Improves and corrects map location data.",
+ "com.apple.maps.destinationd": "Predicts and maintains suggested destinations.",
+ "com.apple.MapKit.SnapshotService": "Renders static map snapshots for apps.",
+ "com.apple.jetpackassetd": "Downloads assets used by Apple content apps.",
+ "com.apple.tipsd": "Selects and refreshes content for the Tips app.",
+ "com.apple.gamesaved": "Synchronizes supported game save data.",
+ "com.apple.GameController.gamecontrollerd": "Discovers controllers and routes their input.",
+ "com.apple.identityservicesd": "Maintains identities used by iMessage and FaceTime.",
+ "com.apple.ids_simd": "Provides simulator support for Apple identity services.",
+ "com.apple.imautomatichistorydeletionagent": "Removes Messages history according to retention settings.",
+ "com.apple.imcore.imtransferagent": "Transfers Messages attachments and media.",
+ "com.apple.imdpersistence.IMDPersistenceAgent": "Stores Messages conversations and metadata.",
+ "com.apple.facetimemessagestored": "Stores FaceTime messages and related data.",
+ "com.apple.telephonyutilities.callservicesd": "Coordinates FaceTime and system call state.",
+ "com.apple.rapportd": "Discovers nearby devices for Continuity features.",
+ "com.apple.companiond": "Coordinates communication with paired companion devices.",
+ "com.apple.carkitd": "Provides CarPlay connection and vehicle services.",
+ "com.apple.wcd": "Handles connectivity with a paired Apple Watch.",
+ "com.apple.tvremoted": "Provides Apple TV discovery and remote control.",
+ "com.apple.avatarsd": "Maintains avatars and Memoji assets.",
+ "com.apple.stickersd": "Maintains sticker packs and recently used stickers.",
+ "com.apple.sociallayerd": "Supports social sharing and activity features.",
+ "com.apple.announced": "Supports announced notifications and audio messages.",
+ "com.apple.navd": "Coordinates background navigation state.",
+ "com.apple.findmy.findmylocated": "Provides device location data to Find My.",
+ "com.apple.ap.adprivacyd": "Maintains advertising privacy preferences and state.",
+ "com.apple.ap.promotedcontentd": "Fetches and manages promoted Apple content.",
+ "com.apple.diagnosticextensionsd": "Runs system diagnostic data collectors.",
+ "com.apple.feedbackd": "Collects and submits system feedback reports.",
+ "com.apple.rtcreportingd": "Reports diagnostics for real-time communications.",
+ "com.apple.securityuploadd": "Uploads security and trust telemetry.",
+ "com.apple.geoanalyticsd": "Collects Maps and location-quality analytics.",
+ "com.apple.triald": "Manages system feature experiments and configurations.",
+ "com.apple.followupd": "Schedules account and setup follow-up notices.",
+ "com.apple.purplebuddy.budd": "Maintains Setup Assistant completion state.",
+ "com.apple.devicecheckd": "Provides DeviceCheck and app-attestation services.",
+ "com.apple.remotemanagementd": "Applies declarative device management configurations.",
+ "com.apple.RemoteManagementAgent": "Applies per-user declarative management configurations.",
+ "com.apple.managedassetsd": "Downloads assets referenced by management declarations.",
+ "com.apple.financed": "Provides Wallet transaction and finance services.",
+ "com.apple.passd": "Manages Wallet passes and Apple Pay state.",
+ "com.apple.merchantd": "Looks up merchant details for Wallet transactions.",
+ "com.apple.coreidvd": "Manages supported digital identity credentials.",
+ "com.apple.businessservicesd": "Supports Apple business messaging and services.",
+ "com.apple.deviceaccessd": "Coordinates app access to supported accessories.",
+ "com.apple.replicatord": "Replicates supported system data between services.",
+ "com.apple.linkd": "Indexes App Intents and shortcut suggestions.",
+ "com.apple.ind": "Receives background iCloud notifications.",
+ "com.apple.storagedatad": "Calculates storage usage shown by the system.",
+ "com.apple.StatusKitAgent": "Shares Focus, presence, and status between devices.",
+ "com.apple.countryd": "Determines regional availability for system features.",
+ "com.apple.mobileassetd": "Downloads and manages system asset packages. Kept enabled on visionOS.",
+ "com.apple.managedconfiguration.passcodenagd": "Enforces managed passcode requirements.",
+ "com.apple.accessibility.axassetsd": "Downloads accessibility assets such as speech voices.",
+ "com.apple.ClipServices.clipserviced": "Downloads, launches, and manages App Clips.",
+]
+
+let featureList: [Feature] = [
+ Feature(id: "push", name: "Push notifications", labels: [
+ "com.apple.apsd",
+ ]),
+ Feature(id: "storekit", name: "StoreKit / in-app purchase", labels: [
+ "com.apple.storekitd",
+ "com.apple.itunesstored",
+ "com.apple.amsaccountsd",
+ "com.apple.amsengagementd",
+ "com.apple.amsondevicestoraged",
+ "com.apple.passd",
+ "com.apple.financed",
+ ]),
+ Feature(id: "app-store", name: "App Store", labels: [
+ "com.apple.appstored",
+ "com.apple.itunesstored",
+ ]),
+ Feature(id: "universal-links", name: "Universal links / associated domains", labels: [
+ "com.apple.swcd",
+ ]),
+ Feature(id: "spotlight", name: "Spotlight & Settings search", labels: [
+ "com.apple.searchd",
+ "com.apple.searchtoold",
+ ]),
+ Feature(id: "files-recents", name: "Files & document picker Recents", labels: [
+ "com.apple.searchd",
+ ]),
+ Feature(id: "siri", name: "Siri & speech", labels: [
+ "com.apple.assistantd",
+ "com.apple.corespeechd",
+ ]),
+ Feature(id: "icloud", name: "iCloud sync", labels: [
+ "com.apple.cloudd",
+ ]),
+ Feature(id: "keychain-sync", name: "iCloud Keychain", labels: [
+ "com.apple.akd",
+ ]),
+ Feature(id: "contacts", name: "Contacts", labels: [
+ "com.apple.contactsd",
+ ]),
+ Feature(id: "calendar", name: "Calendar", labels: [
+ "com.apple.calaccessd",
+ ]),
+ Feature(id: "reminders", name: "Reminders", labels: [
+ "com.apple.remindd",
+ ]),
+ Feature(id: "mail", name: "Mail", labels: [
+ "com.apple.email.maild",
+ ]),
+ Feature(id: "photos", name: "Photos library & analysis", labels: [
+ "com.apple.assetsd",
+ "com.apple.photoanalysisd",
+ ]),
+ Feature(id: "health", name: "HealthKit", labels: [
+ "com.apple.healthd",
+ ]),
+ Feature(id: "homekit", name: "HomeKit", labels: [
+ "com.apple.homed",
+ ]),
+ Feature(id: "imessage", name: "iMessage & FaceTime", labels: [
+ "com.apple.identityservicesd",
+ ]),
+ Feature(id: "widgets", name: "Widgets & Live Activities", labels: [
+ "com.apple.chronod",
+ "com.apple.liveactivitiesd",
+ "com.apple.navd",
+ ]),
+ Feature(id: "wallet", name: "Wallet & passes", labels: [
+ "com.apple.passd",
+ ]),
+ Feature(id: "maps", name: "Maps background services", labels: [
+ "com.apple.Maps.mapssyncd",
+ ]),
+ Feature(id: "weather", name: "Weather", labels: [
+ "com.apple.weatherd",
+ ]),
+ Feature(id: "news", name: "News", labels: [
+ "com.apple.newsd",
+ ]),
+ Feature(id: "game-center", name: "Game Center", labels: [
+ "com.apple.gamed",
+ ]),
+ Feature(id: "find-my", name: "Find My", labels: [
+ "com.apple.findmy.findmylocated",
+ ]),
+ Feature(id: "mdm", name: "Declarative device management", labels: [
+ "com.apple.remotemanagementd",
+ "com.apple.RemoteManagementAgent",
+ ]),
+ Feature(id: "app-clips", name: "App Clips", labels: [
+ "com.apple.ClipServices.clipserviced",
+ ]),
+ Feature(id: "screen-time", name: "Screen Time", labels: [
+ "com.apple.ScreenTimeAgent",
+ ]),
+]
diff --git a/swift/Sources/SimSlimKit/Profile.swift b/swift/Sources/SimSlimKit/Profile.swift
new file mode 100644
index 0000000..8571f72
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Profile.swift
@@ -0,0 +1,54 @@
+import Foundation
+
+/// Selects which managed daemons a slim boot should disable.
+public struct Profile: Equatable, Sendable {
+ public var exceptCategories: Set // category IDs to leave fully enabled
+ public var keep: Set // individual labels to leave enabled
+
+ public init(exceptCategories: Set = [], keep: Set = []) {
+ self.exceptCategories = exceptCategories
+ self.keep = keep
+ }
+
+ /// The labels this profile wants disabled. Categories may share labels, so a
+ /// label stays enabled when any excepted category lists it.
+ public func desired() -> Set {
+ var set = Catalog.slimmableSet
+ for category in Catalog.categories where exceptCategories.contains(category.id) {
+ set.subtract(category.labels)
+ }
+ set.subtract(keep)
+ return set
+ }
+
+ /// Applies platform-specific service requirements. `desired()` remains the
+ /// platform-independent catalog for profile editors.
+ public func desired(for device: Device) -> Set {
+ desiredForDevice(device, desired())
+ }
+}
+
+func desiredForDevice(_ device: Device, _ desired: Set) -> Set {
+ desired.filter { label in
+ // watchOS re-enables homed after startup, even when launchd initially
+ // honours the override. Keep it enabled rather than report a full slim
+ // that drifts as soon as the Watch finishes starting up.
+ if device.platformName == "watchOS" && label == "com.apple.homed" { return false }
+ // visionOS serves the simulated surroundings as mobile assets. Without
+ // mobileassetd the device boots into a black space.
+ if device.platformName == "visionOS" && label == "com.apple.mobileassetd" { return false }
+ return true
+ }
+}
+
+/// The launchctl transitions that move `current` to `desired`, scoped to
+/// `managed`. Labels outside `managed` are never touched: an unmanaged desired
+/// label is ignored, and an unmanaged label that is already disabled stays
+/// disabled. Empty results mean the device is already correct.
+public func delta(
+ current: Set, desired: Set, managed: Set
+) -> (toDisable: [String], toEnable: [String]) {
+ let toDisable = desired.filter { managed.contains($0) && !current.contains($0) }
+ let toEnable = current.filter { managed.contains($0) && !desired.contains($0) }
+ return (toDisable.sorted(), toEnable.sorted())
+}
diff --git a/swift/Sources/SimSlimKit/ProfileFile.swift b/swift/Sources/SimSlimKit/ProfileFile.swift
new file mode 100644
index 0000000..30384e0
--- /dev/null
+++ b/swift/Sources/SimSlimKit/ProfileFile.swift
@@ -0,0 +1,227 @@
+import Foundation
+
+/// The on-disk profile applied with `simslim on --profile `. `except` and
+/// `keep` mirror the `--except` and `--keep` flags.
+public struct SlimProfile: Equatable, Sendable {
+ public var name: String
+ public var description: String
+ public var except: [String]
+ public var keep: [String]
+
+ public init(
+ name: String = "", description: String = "", except: [String] = [], keep: [String] = []
+ ) {
+ self.name = name
+ self.description = description
+ self.except = except
+ self.keep = keep
+ }
+
+ /// Turns a parsed SlimProfile into the validated Profile it selects.
+ func resolve(path: String) throws -> Profile {
+ var profile = Profile()
+ for raw in except {
+ let id = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if id.isEmpty { continue }
+ guard Catalog.category(id: id) != nil else {
+ throw SimSlimError(
+ "profile \(path): unknown category \"\(id)\" (see `simslim profiles`)")
+ }
+ profile.exceptCategories.insert(id)
+ }
+ // Accept keep entries for required services too: profiles written as
+ // workarounds before a service became always-enabled must remain valid.
+ for raw in keep {
+ let label = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if label.isEmpty { continue }
+ guard Catalog.managedSet.contains(label) else {
+ throw SimSlimError(
+ "profile \(path): \"\(label)\" is not a managed daemon (see `simslim profiles`)")
+ }
+ profile.keep.insert(label)
+ }
+ return profile
+ }
+}
+
+/// Reads a profile file and resolves it to a validated Profile.
+///
+/// Like the Go version it rejects unknown fields and matches field names
+/// case-insensitively. Unlike it, a malformed document with trailing text after
+/// the first JSON value is rejected rather than ignored.
+public func loadSlimProfile(path: String) throws -> Profile {
+ let data: Data
+ do {
+ data = try Data(contentsOf: URL(fileURLWithPath: path))
+ } catch {
+ throw SimSlimError("read profile \(path): \(readFailureReason(error))")
+ }
+ return try parseSlimProfile(data, path: path).resolve(path: path)
+}
+
+func parseSlimProfile(_ data: Data, path: String) throws -> SlimProfile {
+ let trimmed = String(decoding: data, as: UTF8.self)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ if trimmed.isEmpty {
+ throw SimSlimError("profile \(path) is empty; write {} for the default profile")
+ }
+
+ let parsed: Any
+ do {
+ parsed = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
+ } catch {
+ throw SimSlimError("parse profile \(path): \(error.localizedDescription)")
+ }
+
+ // JSON null decodes to the zero value, as in Go.
+ if parsed is NSNull { return SlimProfile() }
+ guard let object = parsed as? [String: Any] else {
+ throw SimSlimError("parse profile \(path): the top level must be a JSON object")
+ }
+
+ var profile = SlimProfile()
+ for (key, value) in object {
+ switch key.lowercased() {
+ case "name": profile.name = try stringValue(value, field: "name", path: path)
+ case "description":
+ profile.description = try stringValue(value, field: "description", path: path)
+ case "except": profile.except = try stringList(value, field: "except", path: path)
+ case "keep": profile.keep = try stringList(value, field: "keep", path: path)
+ default: throw SimSlimError("parse profile \(path): unknown field \"\(key)\"")
+ }
+ }
+ return profile
+}
+
+private func stringValue(_ value: Any, field: String, path: String) throws -> String {
+ if value is NSNull { return "" }
+ guard let string = value as? String else {
+ throw SimSlimError("parse profile \(path): field \"\(field)\" must be a string")
+ }
+ return string
+}
+
+private func stringList(_ value: Any, field: String, path: String) throws -> [String] {
+ if value is NSNull { return [] }
+ guard let array = value as? [Any] else {
+ throw SimSlimError("parse profile \(path): field \"\(field)\" must be an array of strings")
+ }
+ return try array.map { element in
+ if element is NSNull { return "" }
+ guard let string = element as? String else {
+ throw SimSlimError("parse profile \(path): field \"\(field)\" must be an array of strings")
+ }
+ return string
+ }
+}
+
+private func readFailureReason(_ error: Error) -> String {
+ let ns = error as NSError
+ if let posix = ns.userInfo[NSUnderlyingErrorKey] as? NSError, posix.domain == NSPOSIXErrorDomain {
+ return String(cString: strerror(Int32(posix.code))).lowercased()
+ }
+ return ns.localizedDescription
+}
+
+/// Parses the comma-separated list syntax shared by the `--except`, `--keep`,
+/// `--requires` and `--categories` flags, dropping blank entries.
+public func splitList(_ text: String) -> [String] {
+ text.split(separator: ",", omittingEmptySubsequences: false)
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+}
+
+/// Selects the slim profile for an `on` invocation. A `--profile` file is the
+/// single source of truth, so it cannot be combined with `--except`/`--keep`.
+public func buildProfile(profilePath: String, except: String, keep: String) throws -> Profile {
+ if !profilePath.isEmpty {
+ if !except.isEmpty || !keep.isEmpty {
+ throw SimSlimError("--profile cannot be combined with --except or --keep")
+ }
+ return try loadSlimProfile(path: profilePath)
+ }
+ var profile = Profile()
+ for id in splitList(except) {
+ guard Catalog.category(id: id) != nil else {
+ throw SimSlimError("unknown category \"\(id)\" (see `simslim profiles`)")
+ }
+ profile.exceptCategories.insert(id)
+ }
+ for label in splitList(keep) {
+ profile.keep.insert(label)
+ }
+ return profile
+}
+
+/// Renders a profile as indented JSON with a trailing newline, in the same
+/// field order and escaping as the Go encoder (so files round-trip between the
+/// two tools without churn): name, description, except, keep; empty fields are
+/// omitted; `<`, `>`, `&`, U+2028 and U+2029 are escaped.
+public func marshalProfile(_ profile: SlimProfile) -> Data {
+ var fields: [String] = []
+ if !profile.name.isEmpty { fields.append(" \"name\": \(goJSONString(profile.name))") }
+ if !profile.description.isEmpty {
+ fields.append(" \"description\": \(goJSONString(profile.description))")
+ }
+ if !profile.except.isEmpty { fields.append(jsonList("except", profile.except)) }
+ if !profile.keep.isEmpty { fields.append(jsonList("keep", profile.keep)) }
+
+ let body = fields.isEmpty ? "{}" : "{\n" + fields.joined(separator: ",\n") + "\n}"
+ return Data((body + "\n").utf8)
+}
+
+private func jsonList(_ key: String, _ items: [String]) -> String {
+ let rendered = items.map { " \(goJSONString($0))" }.joined(separator: ",\n")
+ return " \"\(key)\": [\n\(rendered)\n ]"
+}
+
+private func goJSONString(_ value: String) -> String {
+ var out = "\""
+ for scalar in value.unicodeScalars {
+ switch scalar {
+ case "\"": out += "\\\""
+ case "\\": out += "\\\\"
+ case "\n": out += "\\n"
+ case "\r": out += "\\r"
+ case "\t": out += "\\t"
+ case "\u{08}": out += "\\b"
+ case "\u{0C}": out += "\\f"
+ case "<": out += "\\u003c"
+ case ">": out += "\\u003e"
+ case "&": out += "\\u0026"
+ case "\u{2028}": out += "\\u2028"
+ case "\u{2029}": out += "\\u2029"
+ default:
+ if scalar.value < 0x20 {
+ out += String(format: "\\u%04x", scalar.value)
+ } else {
+ out.unicodeScalars.append(scalar)
+ }
+ }
+ }
+ return out + "\""
+}
+
+/// Derives a JSON filename from a profile name, for when the command targets a
+/// directory. Runs of characters that are not filename-safe collapse to a
+/// hyphen; an empty name falls back to `profile.json`.
+public func profileFileName(_ name: String) -> String {
+ var slug = ""
+ var previousDash = false
+ for scalar in name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased().unicodeScalars {
+ switch scalar {
+ case "a"..."z", "0"..."9", "_", ".":
+ slug.unicodeScalars.append(scalar)
+ previousDash = false
+ default:
+ if !previousDash {
+ slug += "-"
+ previousDash = true
+ }
+ }
+ }
+ slug = slug.trimmingCharacters(in: CharacterSet(charactersIn: "-."))
+ if slug.isEmpty { return "profile.json" }
+ if slug.hasSuffix(".json") { return slug }
+ return slug + ".json"
+}
diff --git a/swift/Sources/SimSlimKit/Subprocess.swift b/swift/Sources/SimSlimKit/Subprocess.swift
new file mode 100644
index 0000000..dc04869
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Subprocess.swift
@@ -0,0 +1,66 @@
+import Foundation
+
+/// Every program simslim may start. This is a closed list of absolute paths:
+/// nothing is looked up through PATH, and `Process` is used only in this file
+/// (`scripts/verify-deps.sh` enforces both).
+public enum Executable: String, CaseIterable, Sendable {
+ case xcrun = "/usr/bin/xcrun"
+ case plutil = "/usr/bin/plutil"
+ case du = "/usr/bin/du"
+ case pgrep = "/usr/bin/pgrep"
+ case ps = "/bin/ps"
+ case top = "/usr/bin/top"
+ case lsof = "/usr/sbin/lsof"
+}
+
+public struct CommandResult: Equatable, Sendable {
+ public var status: Int32
+ public var stdout: Data
+ public var stderr: Data
+
+ public init(status: Int32, stdout: Data = Data(), stderr: Data = Data()) {
+ self.status = status
+ self.stdout = stdout
+ self.stderr = stderr
+ }
+
+ public var stdoutText: String { String(decoding: stdout, as: UTF8.self) }
+ public var stderrText: String { String(decoding: stderr, as: UTF8.self) }
+}
+
+/// The seam tests use to replace real processes with a fake.
+public protocol CommandRunning: Sendable {
+ func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult
+}
+
+public struct SystemCommandRunner: CommandRunning {
+ public init() {}
+
+ public func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: executable.rawValue)
+ process.arguments = arguments
+ process.standardInput = FileHandle.nullDevice
+
+ let out = Pipe()
+ let err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+
+ try process.run()
+
+ // Drain both pipes while the child runs; waiting first can deadlock when
+ // the child fills a pipe buffer.
+ var errData = Data()
+ let errDone = DispatchSemaphore(value: 0)
+ DispatchQueue.global().async {
+ errData = err.fileHandleForReading.readDataToEndOfFile()
+ errDone.signal()
+ }
+ let outData = out.fileHandleForReading.readDataToEndOfFile()
+ errDone.wait()
+ process.waitUntilExit()
+
+ return CommandResult(status: process.terminationStatus, stdout: outData, stderr: errData)
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Version.swift b/swift/Sources/SimSlimKit/Version.swift
new file mode 100644
index 0000000..756cea6
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Version.swift
@@ -0,0 +1,2 @@
+/// Overridden at build time by the release script; "dev" for local builds.
+public let simslimVersion = "dev"
diff --git a/swift/Sources/simslim/main.swift b/swift/Sources/simslim/main.swift
new file mode 100644
index 0000000..cd9fdb6
--- /dev/null
+++ b/swift/Sources/simslim/main.swift
@@ -0,0 +1,13 @@
+import Foundation
+import SimSlimKit
+
+// M0 scaffold: only --version works. Commands arrive with the later milestones.
+let arguments = Array(CommandLine.arguments.dropFirst())
+
+if arguments == ["--version"] || arguments == ["version"] {
+ print("simslim \(simslimVersion)")
+ exit(0)
+}
+
+FileHandle.standardError.write(Data("simslim: the Swift port is not feature-complete yet\n".utf8))
+exit(2)
diff --git a/swift/Tests/SimSlimKitTests/FeaturesTests.swift b/swift/Tests/SimSlimKitTests/FeaturesTests.swift
new file mode 100644
index 0000000..210ab1f
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/FeaturesTests.swift
@@ -0,0 +1,122 @@
+import XCTest
+
+@testable import SimSlimKit
+
+/// Ports of features_test.go.
+final class FeaturesTests: XCTestCase {
+ func testFeatureLabelsAreManaged() {
+ for feature in Catalog.features {
+ XCTAssertFalse(feature.labels.isEmpty, "feature \(feature.id) has no labels")
+ for label in feature.labels {
+ XCTAssertTrue(
+ Catalog.managedSet.contains(label),
+ "feature \(feature.id) names unmanaged daemon \(label)")
+ }
+ }
+ }
+
+ func testFeatureIDsAreUniqueAndNamed() {
+ var seen = Set()
+ for feature in Catalog.features {
+ XCTAssertFalse(feature.id.isEmpty)
+ XCTAssertFalse(feature.name.isEmpty, "feature \(feature.id) has no name")
+ XCTAssertTrue(seen.insert(feature.id).inserted, "duplicate feature ID \(feature.id)")
+ }
+ XCTAssertFalse(seen.isEmpty)
+ }
+
+ func testResolveFeatures() throws {
+ let got = try Catalog.resolveFeatures(["push", "storekit"])
+ XCTAssertEqual(got.map(\.id), ["push", "storekit"])
+ XCTAssertThrowsError(try Catalog.resolveFeatures(["push", "nope"])) { error in
+ XCTAssertEqual(
+ (error as? SimSlimError)?.message,
+ "unknown feature \"nope\" (see `simslim doctor --list`)")
+ }
+ }
+
+ func testGameCenterDiagnosesLegacyDisabledGamed() throws {
+ let features = try Catalog.resolveFeatures(["game-center"])
+ XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok)
+ let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.gamed"])
+ XCTAssertFalse(report.ok)
+ XCTAssertEqual(report.features.first?.disabled, ["com.apple.gamed"])
+ }
+
+ func testWidgetsDiagnoseDisabledNavd() throws {
+ let features = try Catalog.resolveFeatures(["widgets"])
+ XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok)
+ let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.navd"])
+ XCTAssertFalse(report.ok)
+ XCTAssertEqual(report.features.first?.disabled, ["com.apple.navd"])
+ }
+
+ func testFilesRecentsDiagnoseDisabledSearchd() throws {
+ let features = try Catalog.resolveFeatures(["files-recents"])
+ XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: ["com.apple.searchtoold"]).ok)
+ let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.searchd"])
+ XCTAssertFalse(report.ok)
+ XCTAssertEqual(report.features.first?.disabled, ["com.apple.searchd"])
+ }
+
+ func testSlimProfileReportsMDMAndAppClipsUntilExcepted() throws {
+ let features = try Catalog.resolveFeatures(["mdm", "app-clips"])
+ XCTAssertFalse(
+ Catalog.diagnoseFeatures(features, disabled: Profile().desired()).ok,
+ "a full slim profile must break MDM and App Clips")
+ let kept = Profile(exceptCategories: ["mdm", "other"])
+ XCTAssertTrue(
+ Catalog.diagnoseFeatures(features, disabled: kept.desired()).ok,
+ "--except mdm,other must keep MDM and App Clips")
+ }
+
+ func testDiagnoseFeatures() throws {
+ let features = try Catalog.resolveFeatures(["push", "storekit", "universal-links"])
+
+ XCTAssertTrue(Catalog.diagnoseFeatures(features, disabled: []).ok, "healthy on a stock device")
+
+ let report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.storekitd"])
+ XCTAssertFalse(report.ok)
+ let byID = Dictionary(uniqueKeysWithValues: report.features.map { ($0.id, $0) })
+ XCTAssertEqual(byID["storekit"]?.ok, false)
+ XCTAssertEqual(byID["storekit"]?.disabled, ["com.apple.storekitd"])
+ XCTAssertEqual(byID["push"]?.ok, true)
+ XCTAssertEqual(byID["universal-links"]?.ok, true)
+
+ let spotlight = try Catalog.resolveFeatures(["spotlight"])
+ XCTAssertFalse(
+ Catalog.diagnoseFeatures(spotlight, disabled: ["com.apple.searchtoold"]).ok,
+ "any disabled backing daemon breaks a multi-daemon feature")
+ }
+
+ // MARK: - JSON contract
+
+ func testDoctorOutputOmitsEmptyFields() throws {
+ let features = try Catalog.resolveFeatures(["push"])
+ let healthy = Catalog.diagnoseFeatures(features, disabled: [])
+ let json = try jsonObject(healthy)
+ XCTAssertEqual(Set(json.keys), ["ok", "features"], "empty udid is omitted")
+ let status = try XCTUnwrap((json["features"] as? [[String: Any]])?.first)
+ XCTAssertEqual(Set(status.keys), ["id", "name", "ok"], "empty disabled list is omitted")
+
+ var broken = Catalog.diagnoseFeatures(features, disabled: ["com.apple.apsd"])
+ broken.udid = "UDID-1"
+ let brokenJSON = try jsonObject(broken)
+ XCTAssertEqual(Set(brokenJSON.keys), ["udid", "ok", "features"])
+ let brokenStatus = try XCTUnwrap((brokenJSON["features"] as? [[String: Any]])?.first)
+ XCTAssertEqual(Set(brokenStatus.keys), ["id", "name", "ok", "disabled"])
+ }
+
+ func testDoctorOutputRoundTrips() throws {
+ let features = try Catalog.resolveFeatures(["push", "storekit"])
+ var report = Catalog.diagnoseFeatures(features, disabled: ["com.apple.storekitd"])
+ report.udid = "UDID-2"
+ let data = try JSONEncoder().encode(report)
+ XCTAssertEqual(try JSONDecoder().decode(DoctorOutput.self, from: data), report)
+ }
+
+ private func jsonObject(_ value: T) throws -> [String: Any] {
+ let data = try JSONEncoder().encode(value)
+ return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
new file mode 100644
index 0000000..dcdf7ac
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
@@ -0,0 +1,20 @@
+// Generated by swift/Tools/gen_catalog.py from profiles_test.go. Do not edit by hand.
+
+/// Daemons that wedge a simulator when disabled; none may ever be managed.
+let forbiddenLabels: [String] = [
+ "com.apple.nanoregistryd",
+ "com.apple.nanoregistrylaunchd",
+ "com.apple.nanoprefsyncd.2",
+ "com.apple.nanotimekitcompaniond",
+ "com.apple.nanobackupd",
+ "com.apple.sleepd",
+ "com.apple.appprotectiond",
+ "com.apple.ManagedSettingsAgent",
+ "com.apple.managedconfiguration.profiled",
+ "com.apple.mobiletimerd",
+ "com.apple.routined",
+ "com.apple.biomed",
+ "com.apple.biomesyncd",
+ "com.apple.dmd",
+ "com.apple.donotdisturbd",
+]
diff --git a/swift/Tests/SimSlimKitTests/ProfileFileTests.swift b/swift/Tests/SimSlimKitTests/ProfileFileTests.swift
new file mode 100644
index 0000000..0fcf5ed
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/ProfileFileTests.swift
@@ -0,0 +1,197 @@
+import XCTest
+
+@testable import SimSlimKit
+
+/// Ports of profile_file_test.go.
+final class ProfileFileTests: XCTestCase {
+ /// Writes `contents` to a fresh temporary file and returns its path.
+ private func writeProfile(_ contents: String) throws -> String {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("simslim-tests-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ addTeardownBlock { try? FileManager.default.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("profile.json")
+ try Data(contents.utf8).write(to: url)
+ return url.path
+ }
+
+ private func missingPath() -> String {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("simslim-absent-\(UUID().uuidString).json").path
+ }
+
+ func testLoadSlimProfile() throws {
+ let path = try writeProfile(
+ """
+ {
+ "name": "ci",
+ "description": "UI test runs",
+ "except": ["search", "store"],
+ "keep": ["com.apple.apsd"]
+ }
+ """)
+ let profile = try loadSlimProfile(path: path)
+ XCTAssertEqual(profile.exceptCategories, ["search", "store"])
+ XCTAssertEqual(profile.keep, ["com.apple.apsd"])
+ }
+
+ func testLoadSlimProfileMinimal() throws {
+ let profile = try loadSlimProfile(path: try writeProfile("{}"))
+ XCTAssertTrue(profile.exceptCategories.isEmpty)
+ XCTAssertTrue(profile.keep.isEmpty)
+ }
+
+ func testNullDocumentIsTheEmptyProfile() throws {
+ // Go decodes JSON null into the zero value.
+ XCTAssertEqual(try loadSlimProfile(path: try writeProfile("null")), Profile())
+ }
+
+ func testLoadSlimProfileKeepsRequiredEnabledLabels() throws {
+ let path = try writeProfile(#"{"keep": ["com.apple.gamed", "com.apple.sharingd"]}"#)
+ let profile = try loadSlimProfile(path: path)
+ for label in ["com.apple.gamed", "com.apple.sharingd"] {
+ XCTAssertTrue(profile.keep.contains(label))
+ XCTAssertFalse(
+ profile.desired().contains(label), "must keep required service \(label) enabled")
+ }
+ }
+
+ func testLoadSlimProfileTrimsAndSkipsBlankEntries() throws {
+ let path = try writeProfile(
+ #"{"except": [" search ", "", " "], "keep": [" com.apple.apsd "]}"#)
+ let profile = try loadSlimProfile(path: path)
+ XCTAssertEqual(profile.exceptCategories, ["search"])
+ XCTAssertEqual(profile.keep, ["com.apple.apsd"])
+ }
+
+ func testLoadSlimProfileRejects() throws {
+ let cases: [(name: String, contents: String, messagePart: String)] = [
+ ("unknown category", #"{"except": ["nope"]}"#, "unknown category \"nope\""),
+ (
+ "unknown keep label", #"{"keep": ["com.apple.does-not-exist"]}"#,
+ "\"com.apple.does-not-exist\" is not a managed daemon"
+ ),
+ ("unknown field", #"{"disable": ["search"]}"#, "unknown field \"disable\""),
+ ("malformed json", #"{"except": ["#, "parse profile"),
+ ("wrong type for except", #"{"except": "search"}"#, "must be an array of strings"),
+ ("wrong type for name", #"{"name": 5}"#, "must be a string"),
+ ("array at top level", #"[]"#, "top level must be a JSON object"),
+ ("empty file", "", "is empty; write {} for the default profile"),
+ ("whitespace only", " \n ", "is empty; write {} for the default profile"),
+ ]
+ for tc in cases {
+ let path = try writeProfile(tc.contents)
+ XCTAssertThrowsError(try loadSlimProfile(path: path), tc.name) { error in
+ let message = (error as? SimSlimError)?.message ?? "\(error)"
+ XCTAssertTrue(message.contains(tc.messagePart), "\(tc.name): got \"\(message)\"")
+ }
+ }
+ }
+
+ func testUnknownFieldMatchingIsCaseInsensitiveLikeGo() throws {
+ let profile = try loadSlimProfile(path: try writeProfile(#"{"Except": ["search"]}"#))
+ XCTAssertEqual(profile.exceptCategories, ["search"])
+ }
+
+ func testLoadSlimProfileMissingFile() {
+ XCTAssertThrowsError(try loadSlimProfile(path: missingPath())) { error in
+ let message = (error as? SimSlimError)?.message ?? ""
+ XCTAssertTrue(message.hasPrefix("read profile "), message)
+ XCTAssertTrue(message.contains("no such file"), message)
+ }
+ }
+
+ func testBuildProfile() throws {
+ let fromFlags = try buildProfile(profilePath: "", except: "search", keep: "com.apple.apsd")
+ XCTAssertTrue(fromFlags.exceptCategories.contains("search"))
+ XCTAssertTrue(fromFlags.keep.contains("com.apple.apsd"))
+
+ XCTAssertThrowsError(try buildProfile(profilePath: "", except: "nope", keep: ""))
+
+ let path = try writeProfile(#"{"except": ["search"]}"#)
+ XCTAssertEqual(
+ try buildProfile(profilePath: path, except: "", keep: "").exceptCategories, ["search"])
+
+ XCTAssertThrowsError(try buildProfile(profilePath: "some.json", except: "search", keep: "")) {
+ XCTAssertEqual(
+ ($0 as? SimSlimError)?.message, "--profile cannot be combined with --except or --keep")
+ }
+ XCTAssertThrowsError(
+ try buildProfile(profilePath: "some.json", except: "", keep: "com.apple.apsd"))
+ }
+
+ func testBuildProfileKeepFlagIsNotValidatedLikeGo() throws {
+ // Go's --keep flag accepts any label (only profile files are validated);
+ // delta() later ignores unmanaged labels, so this is safe. Ported as-is.
+ let profile = try buildProfile(profilePath: "", except: "", keep: "com.apple.unknown")
+ XCTAssertEqual(profile.keep, ["com.apple.unknown"])
+ }
+
+ func testSplitList() {
+ XCTAssertEqual(splitList("a, b ,,c"), ["a", "b", "c"])
+ XCTAssertEqual(splitList(""), [])
+ XCTAssertEqual(splitList(" , "), [])
+ }
+
+ func testProfileFileName() {
+ let cases: [(String, String)] = [
+ ("ci", "ci.json"),
+ ("UI Test Runs", "ui-test-runs.json"),
+ ("", "profile.json"),
+ (" ", "profile.json"),
+ ("prod.json", "prod.json"),
+ ("a/b:c", "a-b-c.json"),
+ ("--weird--", "weird.json"),
+ ]
+ for (name, want) in cases {
+ XCTAssertEqual(profileFileName(name), want, "profileFileName(\"\(name)\")")
+ }
+ }
+
+ // MARK: - marshalProfile: byte-for-byte what Go's json.MarshalIndent prints
+
+ func testMarshalProfileFull() {
+ let data = marshalProfile(
+ SlimProfile(
+ name: "ci", description: "UI test runs", except: ["search", "store"],
+ keep: ["com.apple.apsd"]))
+ XCTAssertEqual(
+ String(decoding: data, as: UTF8.self),
+ """
+ {
+ "name": "ci",
+ "description": "UI test runs",
+ "except": [
+ "search",
+ "store"
+ ],
+ "keep": [
+ "com.apple.apsd"
+ ]
+ }
+
+ """)
+ }
+
+ func testMarshalProfileEmptyAndPartial() {
+ XCTAssertEqual(String(decoding: marshalProfile(SlimProfile()), as: UTF8.self), "{}\n")
+ XCTAssertEqual(
+ String(decoding: marshalProfile(SlimProfile(keep: ["com.apple.apsd"])), as: UTF8.self),
+ "{\n \"keep\": [\n \"com.apple.apsd\"\n ]\n}\n")
+ }
+
+ func testMarshalProfileEscapesLikeGo() {
+ let data = marshalProfile(SlimProfile(name: "a&\"q\"\\\n\u{2028}\u{01}"))
+ XCTAssertEqual(
+ String(decoding: data, as: UTF8.self),
+ "{\n \"name\": \"a\\u003cb\\u003e\\u0026\\\"q\\\"\\\\\\n\\u2028\\u0001\"\n}\n")
+ }
+
+ func testMarshalThenLoadRoundTrips() throws {
+ let original = SlimProfile(
+ name: "x & y", description: "d", except: ["search", "store"], keep: ["com.apple.apsd"])
+ let path = try writeProfile(String(decoding: marshalProfile(original), as: UTF8.self))
+ let parsed = try parseSlimProfile(try Data(contentsOf: URL(fileURLWithPath: path)), path: path)
+ XCTAssertEqual(parsed, original)
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/ProfilesTests.swift b/swift/Tests/SimSlimKitTests/ProfilesTests.swift
new file mode 100644
index 0000000..6588a01
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/ProfilesTests.swift
@@ -0,0 +1,300 @@
+import XCTest
+
+@testable import SimSlimKit
+
+/// Ports of profiles_test.go. These encode the safety invariants of the tool:
+/// what may ever be disabled, and that nothing outside the allowlist is touched.
+final class ProfilesTests: XCTestCase {
+ private let full = Profile()
+
+ func testManagedExcludesForbidden() {
+ for label in forbiddenLabels {
+ XCTAssertFalse(
+ Catalog.managedSet.contains(label),
+ "forbidden daemon \(label) is in a category; it must never be managed")
+ }
+ }
+
+ func testForbiddenListIsNotEmpty() {
+ // Guards against the generator silently producing an empty list, which
+ // would make testManagedExcludesForbidden vacuous.
+ XCTAssertGreaterThanOrEqual(forbiddenLabels.count, 10)
+ XCTAssertTrue(forbiddenLabels.contains("com.apple.nanoregistryd"))
+ }
+
+ func testFullProfileDoesNotClaimUnmanagedProcesses() {
+ let desired = full.desired()
+ for label in [
+ "com.apple.routined", "com.apple.sharingd", "com.apple.locationd",
+ "com.apple.eventkitsyncd", "com.apple.Spotlight", "com.apple.MercuryPoster",
+ "com.apple.texttospeech.SiriAUSP",
+ ] {
+ XCTAssertFalse(desired.contains(label), "full profile claims live process \(label)")
+ }
+ }
+
+ func testNoDuplicateLabelsWithinCategory() {
+ for category in Catalog.categories {
+ XCTAssertEqual(
+ category.labels.count, Set(category.labels).count,
+ "category \(category.id) lists a label twice")
+ }
+ }
+
+ func testCategoryIDsAreUnique() {
+ let ids = Catalog.categories.map(\.id)
+ XCTAssertEqual(ids.count, Set(ids).count)
+ XCTAssertFalse(ids.isEmpty)
+ }
+
+ func testDesiredKeepsSharedLabelsOfExceptedCategories() {
+ var owners: [String: [String]] = [:]
+ for category in Catalog.categories {
+ for label in category.labels { owners[label, default: []].append(category.id) }
+ }
+ var sharedSeen = false
+ for (label, ids) in owners where ids.count >= 2 {
+ sharedSeen = true
+ for id in ids {
+ let profile = Profile(exceptCategories: [id])
+ XCTAssertFalse(
+ profile.desired().contains(label),
+ "--except \(id) should keep shared label \(label) enabled")
+ }
+ }
+ XCTAssertTrue(sharedSeen, "expected at least one shared label (the AMS payment-sheet daemons)")
+ }
+
+ func testEveryServiceHasShortDescription() {
+ var known = Set()
+ for category in Catalog.categories {
+ XCTAssertEqual(
+ category.serviceDescriptions.count, category.labels.count,
+ "category \(category.id) label and description counts differ")
+ for label in category.labels {
+ known.insert(label)
+ let description = category.serviceDescriptions[label] ?? ""
+ XCTAssertFalse(
+ description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ "service \(label) has no user-facing description")
+ XCTAssertFalse(
+ description.contains("\n") || description.contains("\r"),
+ "service \(label) description must stay on one logical line")
+ XCTAssertLessThanOrEqual(
+ description.utf8.count, 90, "service \(label) description is too long")
+ }
+ }
+ for label in serviceDescriptionByLabel.keys {
+ XCTAssertTrue(known.contains(label), "description exists for unmanaged service \(label)")
+ }
+ }
+
+ func testRequiredEnabledLabelsAreNeverSlimmed() {
+ let desired = full.desired()
+ var sawRequired = false
+ for category in Catalog.categories {
+ for service in category.alwaysEnabled {
+ sawRequired = true
+ XCTAssertFalse(
+ Catalog.slimmableSet.contains(service.label) || desired.contains(service.label),
+ "required daemon \(service.label) is included in a slim profile")
+ XCTAssertTrue(
+ Catalog.managedSet.contains(service.label),
+ "required daemon \(service.label) is missing from the repair allowlist")
+ XCTAssertFalse(service.reason.isEmpty, "\(service.label) has no user-facing reason")
+ }
+ }
+ XCTAssertTrue(sawRequired)
+ }
+
+ func testDeltaRepairsRequiredEnabledLabels() {
+ let current: Set = ["com.apple.sharingd"]
+ let result = delta(current: current, desired: full.desired(), managed: Catalog.managedSet)
+ XCTAssertFalse(result.toDisable.isEmpty, "full profile should still disable slimmable labels")
+ XCTAssertEqual(result.toEnable, ["com.apple.sharingd"])
+ }
+
+ func testGamedStaysEnabledForXCTest() throws {
+ let label = "com.apple.gamed"
+ let desired = full.desired()
+ XCTAssertFalse(Catalog.slimmableSet.contains(label) || desired.contains(label))
+ let apps = try XCTUnwrap(Catalog.category(id: "apps"))
+ XCTAssertTrue(
+ apps.alwaysEnabled.contains {
+ $0.label == label && !$0.reason.trimmingCharacters(in: .whitespaces).isEmpty
+ }, "apps must explain why gamed stays enabled")
+ let repair = delta(current: [label], desired: desired, managed: Catalog.managedSet)
+ XCTAssertEqual(repair.toEnable, [label])
+ for other in ["com.apple.gamesaved", "com.apple.GameController.gamecontrollerd"] {
+ XCTAssertTrue(
+ desired.contains(other), "unrelated game service \(other) should stay slimmable")
+ }
+ }
+
+ func testAssistantdStaysEnabledForSpotlight() throws {
+ let label = "com.apple.assistantd"
+ let desired = full.desired()
+ XCTAssertFalse(Catalog.slimmableSet.contains(label) || desired.contains(label))
+ let siri = try XCTUnwrap(Catalog.category(id: "siri"))
+ XCTAssertTrue(
+ siri.alwaysEnabled.contains {
+ $0.label == label && !$0.reason.trimmingCharacters(in: .whitespaces).isEmpty
+ }, "siri must explain why assistantd stays enabled")
+ let repair = delta(current: [label], desired: desired, managed: Catalog.managedSet)
+ XCTAssertEqual(repair.toEnable, [label])
+ for other in [
+ "com.apple.assistant_service", "com.apple.corespeechd", "com.apple.siriknowledged",
+ ] {
+ XCTAssertTrue(desired.contains(other), "other Siri service \(other) should stay slimmable")
+ }
+ }
+
+ func testWidgetsKeepNavdForMapsWidget() {
+ let label = "com.apple.navd"
+ XCTAssertFalse(
+ Profile(exceptCategories: ["widgets"]).desired().contains(label),
+ "--except widgets must keep navd enabled: the Maps widget spins without it")
+ XCTAssertTrue(
+ full.desired().contains(label), "navd should stay slimmable when widgets are disabled")
+ }
+
+ func testCategoriesHaveUserImpactMetadata() {
+ for category in Catalog.categories {
+ XCTAssertFalse(category.downside.isEmpty, "category \(category.id) has no downside")
+ XCTAssertGreaterThan(category.approxMemoryMB, 0, "category \(category.id) memory estimate")
+ }
+ }
+
+ func testCategoryByID() {
+ for category in Catalog.categories {
+ XCTAssertEqual(Catalog.category(id: category.id)?.id, category.id)
+ }
+ XCTAssertNil(Catalog.category(id: "nope"))
+ }
+
+ func testDesiredHonorsKeep() {
+ XCTAssertTrue(full.desired().contains("com.apple.apsd"))
+ XCTAssertFalse(Profile(keep: ["com.apple.apsd"]).desired().contains("com.apple.apsd"))
+ }
+
+ // MARK: - Platform rules (Profile.desired(for:))
+
+ func testWatchOSKeepsHomedEnabled() {
+ let watch = Device(udid: "W", platform: "watchOS")
+ XCTAssertTrue(full.desired().contains("com.apple.homed"))
+ XCTAssertFalse(full.desired(for: watch).contains("com.apple.homed"))
+ XCTAssertTrue(full.desired(for: watch).contains("com.apple.mobileassetd"))
+ }
+
+ func testVisionOSKeepsMobileassetdEnabled() {
+ let vision = Device(udid: "V", platform: "visionOS")
+ XCTAssertTrue(full.desired().contains("com.apple.mobileassetd"))
+ XCTAssertFalse(full.desired(for: vision).contains("com.apple.mobileassetd"))
+ XCTAssertTrue(full.desired(for: vision).contains("com.apple.homed"))
+ }
+
+ func testIOSAndEmptyPlatformGetTheFullCatalog() {
+ for platform in ["", "iOS", "tvOS"] {
+ let device = Device(udid: "D", platform: platform)
+ XCTAssertEqual(full.desired(for: device), full.desired(), "platform \"\(platform)\"")
+ }
+ }
+
+ // MARK: - delta
+
+ func testDelta() {
+ let managed: Set = ["a", "b", "c"]
+ struct Case {
+ let name: String
+ let current: Set
+ let desired: Set
+ let disable: [String]
+ let enable: [String]
+ }
+ let cases = [
+ Case(
+ name: "enable all from stock", current: [], desired: ["a", "b", "c"],
+ disable: ["a", "b", "c"], enable: []),
+ Case(
+ name: "restore all to stock", current: ["a", "b", "c"], desired: [], disable: [],
+ enable: ["a", "b", "c"]),
+ Case(
+ name: "already in desired state", current: ["a", "b"], desired: ["a", "b"], disable: [],
+ enable: []),
+ Case(
+ name: "profile edit adds and removes", current: ["a", "b"], desired: ["b", "c"],
+ disable: ["c"], enable: ["a"]),
+ Case(
+ name: "unmanaged desired label is ignored", current: [], desired: ["x"], disable: [],
+ enable: []),
+ Case(
+ name: "unmanaged disabled label is left alone", current: ["x"], desired: [], disable: [],
+ enable: []),
+ ]
+ for tc in cases {
+ let got = delta(current: tc.current, desired: tc.desired, managed: managed)
+ XCTAssertEqual(got.toDisable, tc.disable, tc.name)
+ XCTAssertEqual(got.toEnable, tc.enable, tc.name)
+ }
+ }
+
+ func testDeltaNeverTouchesUnmanagedLabels() {
+ // The central safety property, checked against the real allowlist: whatever
+ // the device has disabled and whatever the profile asks for, delta only
+ // ever names managed labels.
+ let current: Set = Set(forbiddenLabels).union(["com.apple.not-ours", "com.apple.apsd"])
+ let desired = Set(forbiddenLabels).union(full.desired()).union(["com.apple.also-not-ours"])
+ let result = delta(current: current, desired: desired, managed: Catalog.managedSet)
+ for label in result.toDisable + result.toEnable {
+ XCTAssertTrue(Catalog.managedSet.contains(label), "delta named unmanaged label \(label)")
+ }
+ for label in forbiddenLabels {
+ XCTAssertFalse(result.toDisable.contains(label) || result.toEnable.contains(label))
+ }
+ }
+
+ func testDeltaIsSorted() {
+ let result = delta(current: [], desired: ["c", "a", "b"], managed: ["a", "b", "c"])
+ XCTAssertEqual(result.toDisable, ["a", "b", "c"])
+ }
+
+ // MARK: - JSON contract with the SwiftUI app
+
+ func testCategoryJSONKeys() throws {
+ let siri = try XCTUnwrap(Catalog.category(id: "siri"))
+ let search = try XCTUnwrap(Catalog.category(id: "search"))
+
+ let siriJSON = try jsonObject(siri)
+ XCTAssertEqual(
+ Set(siriJSON.keys),
+ [
+ "id", "name", "description", "downside", "approxMemoryMB", "labels",
+ "serviceDescriptions", "alwaysEnabled",
+ ])
+ // `omitempty`: a category with no always-enabled services omits the key.
+ XCTAssertFalse(try jsonObject(search).keys.contains("alwaysEnabled"))
+
+ let alwaysEnabled = try XCTUnwrap(siriJSON["alwaysEnabled"] as? [[String: Any]])
+ XCTAssertEqual(Set(try XCTUnwrap(alwaysEnabled.first).keys), ["label", "reason"])
+ }
+
+ func testCategoryRoundTrips() throws {
+ for category in Catalog.categories {
+ let data = try JSONEncoder().encode(category)
+ XCTAssertEqual(try JSONDecoder().decode(Category.self, from: data), category)
+ }
+ }
+
+ func testDeviceJSONKeysExcludeInternalFields() throws {
+ let device = Device(
+ udid: "U", name: "N", state: "Booted", platform: "iOS", osVersion: "27.2", set: "default",
+ dataPath: "/secret/path", runtimeID: "com.apple.CoreSimulator.SimRuntime.iOS-27-2")
+ XCTAssertEqual(
+ Set(try jsonObject(device).keys), ["udid", "name", "state", "platform", "osVersion", "set"])
+ }
+
+ private func jsonObject(_ value: T) throws -> [String: Any] {
+ let data = try JSONEncoder().encode(value)
+ return try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/SubprocessTests.swift b/swift/Tests/SimSlimKitTests/SubprocessTests.swift
new file mode 100644
index 0000000..011b082
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/SubprocessTests.swift
@@ -0,0 +1,31 @@
+import XCTest
+
+@testable import SimSlimKit
+
+final class SubprocessTests: XCTestCase {
+ func testEveryExecutablePathIsAbsolute() {
+ for executable in Executable.allCases {
+ XCTAssertTrue(executable.rawValue.hasPrefix("/"), "\(executable) must be an absolute path")
+ }
+ }
+
+ func testEveryExecutableExistsOnThisMac() {
+ for executable in Executable.allCases {
+ XCTAssertTrue(
+ FileManager.default.isExecutableFile(atPath: executable.rawValue),
+ "\(executable.rawValue) is missing or not executable")
+ }
+ }
+
+ func testSystemRunnerCapturesOutputAndStatus() throws {
+ // plutil -help prints usage to stdout and exits 0.
+ let ok = try SystemCommandRunner().run(.plutil, ["-help"])
+ XCTAssertEqual(ok.status, 0)
+ XCTAssertFalse(ok.stdoutText.isEmpty)
+
+ // A missing file is a non-zero exit with a message, not a thrown error.
+ let missing = try SystemCommandRunner().run(.plutil, ["-lint", "/nonexistent/simslim-test"])
+ XCTAssertNotEqual(missing.status, 0)
+ XCTAssertFalse((missing.stdoutText + missing.stderrText).isEmpty)
+ }
+}
diff --git a/swift/Tools/gen_catalog.py b/swift/Tools/gen_catalog.py
new file mode 100644
index 0000000..380d990
--- /dev/null
+++ b/swift/Tools/gen_catalog.py
@@ -0,0 +1,264 @@
+#!/usr/bin/env python3
+"""Generates the Swift catalog data from the Go source of truth.
+
+ python3 swift/Tools/gen_catalog.py # rewrite the generated files
+ python3 swift/Tools/gen_catalog.py --check # exit 1 if they are out of date
+
+Reads profiles.go (Categories), service_descriptions.go, features.go (Features)
+and profiles_test.go (forbiddenLabels). Standard library only. This is a
+developer tool for the transition period: the normal build never runs it, and
+it goes away together with the Go tree at cutover.
+"""
+import re
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+OUT_CATALOG = ROOT / "swift/Sources/SimSlimKit/Generated/CatalogData.swift"
+OUT_FORBIDDEN = ROOT / "swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift"
+
+TOKEN = re.compile(
+ r"""
+ (?P\s+)
+ | (?P//[^\n]*)
+ | (?P/\*.*?\*/)
+ | (?P"(?:[^"\\\n]|\\.)*")
+ | (?P`[^`]*`)
+ | (?P\d+)
+ | (?P[A-Za-z_][A-Za-z0-9_.]*)
+ | (?P[{}\[\]():,=])
+ """,
+ re.VERBOSE | re.DOTALL,
+)
+
+
+class Ident(str):
+ pass
+
+
+def tokenize(text):
+ """Tokenizes a literal. Stops quietly at the first character that cannot be
+ part of one: the parser has finished the literal long before that point."""
+ pos, out = 0, []
+ while pos < len(text):
+ m = TOKEN.match(text, pos)
+ if not m:
+ break
+ pos = m.end()
+ kind = m.lastgroup
+ if kind in ("ws", "comment", "block"):
+ continue
+ val = m.group()
+ if kind == "string":
+ val = decode_go_string(val)
+ elif kind == "raw":
+ kind, val = "string", val[1:-1]
+ elif kind == "int":
+ val = int(val)
+ elif kind == "ident":
+ val = Ident(val)
+ out.append((kind, val))
+ return out
+
+
+def decode_go_string(lit):
+ body, out, i = lit[1:-1], [], 0
+ simple = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"', "'": "'"}
+ while i < len(body):
+ c = body[i]
+ if c != "\\":
+ out.append(c)
+ i += 1
+ continue
+ n = body[i + 1]
+ if n in simple:
+ out.append(simple[n])
+ i += 2
+ elif n == "u":
+ out.append(chr(int(body[i + 2 : i + 6], 16)))
+ i += 6
+ else:
+ raise SystemExit(f"gen_catalog: unsupported escape \\{n} in {lit!r}")
+ return "".join(out)
+
+
+class Parser:
+ """A parser for the subset of Go composite literals these files use."""
+
+ def __init__(self, tokens):
+ self.t, self.i = tokens, 0
+
+ def peek(self, k=0):
+ return self.t[self.i + k] if self.i + k < len(self.t) else (None, None)
+
+ def take(self):
+ tok = self.t[self.i]
+ self.i += 1
+ return tok
+
+ def value(self):
+ kind, val = self.peek()
+ if kind in ("string", "int"):
+ self.take()
+ return val
+ if kind == "punct" and val == "{":
+ return self.braces()
+ if kind == "punct" and val == "[" or (kind == "ident" and val == "map"):
+ # A type prefix such as []string, []Category or map[string]string.
+ while self.peek() != ("punct", "{"):
+ self.take()
+ return self.braces()
+ if kind == "ident":
+ self.take()
+ if self.peek() == ("punct", "{"):
+ return self.braces()
+ return val
+ raise SystemExit(f"gen_catalog: unexpected token {kind} {val!r}")
+
+ def braces(self):
+ assert self.take() == ("punct", "{")
+ entries = []
+ while self.peek() != ("punct", "}"):
+ v = self.value()
+ if self.peek() == ("punct", ":"):
+ self.take()
+ entries.append((v, self.value()))
+ else:
+ entries.append((None, v))
+ if self.peek() == ("punct", ","):
+ self.take()
+ self.take()
+ if entries and all(k is not None for k, _ in entries):
+ keys = [k for k, _ in entries]
+ dupes = {k for k in keys if keys.count(k) > 1}
+ if dupes:
+ raise SystemExit(f"gen_catalog: duplicate keys in a literal: {sorted(dupes)}")
+ return dict(entries)
+ if any(k is not None for k, _ in entries):
+ raise SystemExit("gen_catalog: mixed keyed and positional entries")
+ return [v for _, v in entries]
+
+
+def parse_var(path, name):
+ text = path.read_text()
+ m = re.search(r"^var\s+" + re.escape(name) + r"\s*=\s*", text, re.M)
+ if not m:
+ raise SystemExit(f"gen_catalog: `var {name} =` not found in {path.name}")
+ return Parser(tokenize(text[m.end():])).value()
+
+
+def swift_string(s):
+ out = ['"']
+ for ch in s:
+ if ch == "\\":
+ out.append("\\\\")
+ elif ch == '"':
+ out.append('\\"')
+ elif ch == "\n":
+ out.append("\\n")
+ elif ch == "\t":
+ out.append("\\t")
+ elif ch == "\r":
+ out.append("\\r")
+ elif ord(ch) < 0x20 or ord(ch) == 0x7F:
+ out.append("\\u{%X}" % ord(ch))
+ else:
+ out.append(ch)
+ out.append('"')
+ return "".join(out)
+
+
+def label_list(labels, indent):
+ pad = " " * indent
+ return "[\n" + "".join(f"{pad} {swift_string(l)},\n" for l in labels) + f"{pad}]"
+
+
+def render_catalog():
+ categories = parse_var(ROOT / "profiles.go", "Categories")
+ descriptions = parse_var(ROOT / "service_descriptions.go", "serviceDescriptionByLabel")
+ features = parse_var(ROOT / "features.go", "Features")
+
+ header = (
+ "// Generated by swift/Tools/gen_catalog.py from profiles.go, service_descriptions.go\n"
+ "// and features.go. Do not edit by hand; rerun the tool.\n\n"
+ )
+ out = [header, "let categorySeeds: [CategorySeed] = [\n"]
+ for c in categories:
+ for key in ("ID", "Name", "Description", "Downside", "ApproxMemoryMB", "Labels"):
+ if key not in c:
+ raise SystemExit(f"gen_catalog: category {c.get('ID')} lacks {key}")
+ out.append(" CategorySeed(\n")
+ out.append(f" id: {swift_string(c['ID'])},\n")
+ out.append(f" name: {swift_string(c['Name'])},\n")
+ out.append(f" description: {swift_string(c['Description'])},\n")
+ out.append(f" downside: {swift_string(c['Downside'])},\n")
+ out.append(f" approxMemoryMB: {int(c['ApproxMemoryMB'])},\n")
+ out.append(f" labels: {label_list(c['Labels'], 4)},\n")
+ always = c.get("AlwaysEnabled", [])
+ if always:
+ out.append(" alwaysEnabled: [\n")
+ for a in always:
+ out.append(
+ f" AlwaysEnabledService(label: {swift_string(a['Label'])}, "
+ f"reason: {swift_string(a['Reason'])}),\n"
+ )
+ out.append(" ]\n")
+ else:
+ out.append(" alwaysEnabled: []\n")
+ out.append(" ),\n")
+ out.append("]\n\n")
+
+ out.append("let serviceDescriptionByLabel: [String: String] = [\n")
+ for label, desc in descriptions.items():
+ out.append(f" {swift_string(label)}: {swift_string(desc)},\n")
+ out.append("]\n\n")
+
+ out.append("let featureList: [Feature] = [\n")
+ for f in features:
+ out.append(
+ f" Feature(id: {swift_string(f['ID'])}, name: {swift_string(f['Name'])}, "
+ f"labels: {label_list(f['Labels'], 2)}),\n"
+ )
+ out.append("]\n")
+
+ counts = (
+ f"{len(categories)} categories, "
+ f"{sum(len(c['Labels']) for c in categories)} category labels, "
+ f"{len(descriptions)} descriptions, {len(features)} features"
+ )
+ return "".join(out), counts
+
+
+def render_forbidden():
+ labels = parse_var(ROOT / "profiles_test.go", "forbiddenLabels")
+ body = "".join(f" {swift_string(l)},\n" for l in labels)
+ return (
+ "// Generated by swift/Tools/gen_catalog.py from profiles_test.go. Do not edit by hand.\n\n"
+ "/// Daemons that wedge a simulator when disabled; none may ever be managed.\n"
+ f"let forbiddenLabels: [String] = [\n{body}]\n"
+ )
+
+
+def main():
+ check = "--check" in sys.argv[1:]
+ catalog, counts = render_catalog()
+ targets = [(OUT_CATALOG, catalog), (OUT_FORBIDDEN, render_forbidden())]
+ stale = []
+ for path, content in targets:
+ current = path.read_text() if path.exists() else None
+ if current != content:
+ stale.append(path)
+ if not check:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ if check:
+ if stale:
+ print("gen_catalog: out of date: " + ", ".join(str(p.relative_to(ROOT)) for p in stale))
+ sys.exit(1)
+ print(f"gen_catalog: up to date ({counts})")
+ else:
+ print(f"gen_catalog: wrote {len(targets)} files ({counts})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/swift/expected-libs.txt b/swift/expected-libs.txt
new file mode 100644
index 0000000..d66aa34
--- /dev/null
+++ b/swift/expected-libs.txt
@@ -0,0 +1,11 @@
+/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
+/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation
+/usr/lib/libobjc.A.dylib
+/usr/lib/libSystem.B.dylib
+/usr/lib/swift/libswiftCore.dylib
+/usr/lib/swift/libswiftCoreFoundation.dylib
+/usr/lib/swift/libswiftDarwin.dylib
+/usr/lib/swift/libswiftDispatch.dylib
+/usr/lib/swift/libswiftIOKit.dylib
+/usr/lib/swift/libswiftObjectiveC.dylib
+/usr/lib/swift/libswiftXPC.dylib
From e5f59ffc4369c5874396be5ab705ecf3d098d27c Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:44:12 -0700
Subject: [PATCH 02/32] feat(swift): read-only commands (list, profiles,
status, verify, doctor, measure)
Adds the simctl layer, status/verify/measure, and a SimSlimCLI target with an
injected runner so every command is tested against a fake host. Output matches
the GUI's Models.swift (contract test). Verified live on a throwaway simulator.
---
docs/swift-port-plan.md | 2 +-
scripts/verify-deps.sh | 18 +-
swift/Package.swift | 15 +-
swift/Sources/SimSlimCLI/Arguments.swift | 77 +++
swift/Sources/SimSlimCLI/CLI.swift | 188 +++++++
swift/Sources/SimSlimCLI/Commands.swift | 234 ++++++++
swift/Sources/SimSlimCLI/Duration.swift | 54 ++
swift/Sources/SimSlimCLI/Format.swift | 36 ++
swift/Sources/SimSlimCLI/Usage.swift | 73 +++
swift/Sources/SimSlimKit/Measure.swift | 191 +++++++
swift/Sources/SimSlimKit/Output.swift | 81 +++
swift/Sources/SimSlimKit/Simctl.swift | 224 ++++++++
swift/Sources/SimSlimKit/Status.swift | 100 ++++
swift/Sources/SimSlimKit/Subprocess.swift | 161 +++++-
swift/Sources/SimSlimKit/Verify.swift | 63 +++
swift/Sources/simslim/main.swift | 16 +-
.../SimSlimCLITests/ArgumentsTests.swift | 128 +++++
.../Tests/SimSlimCLITests/CommandTests.swift | 531 ++++++++++++++++++
.../SimSlimCLITests/GUIContract/Models.swift | 1 +
.../SimSlimCLITests/GUIContractTests.swift | 73 +++
swift/Tests/SimSlimCLITests/Support.swift | 66 +++
swift/Tests/SimSlimKitTests/SimctlTests.swift | 291 ++++++++++
.../StatusVerifyMeasureTests.swift | 261 +++++++++
.../SubprocessRunnerTests.swift | 76 +++
swift/Tests/TestSupport/FakeHost.swift | 158 ++++++
25 files changed, 3085 insertions(+), 33 deletions(-)
create mode 100644 swift/Sources/SimSlimCLI/Arguments.swift
create mode 100644 swift/Sources/SimSlimCLI/CLI.swift
create mode 100644 swift/Sources/SimSlimCLI/Commands.swift
create mode 100644 swift/Sources/SimSlimCLI/Duration.swift
create mode 100644 swift/Sources/SimSlimCLI/Format.swift
create mode 100644 swift/Sources/SimSlimCLI/Usage.swift
create mode 100644 swift/Sources/SimSlimKit/Measure.swift
create mode 100644 swift/Sources/SimSlimKit/Output.swift
create mode 100644 swift/Sources/SimSlimKit/Simctl.swift
create mode 100644 swift/Sources/SimSlimKit/Status.swift
create mode 100644 swift/Sources/SimSlimKit/Verify.swift
create mode 100644 swift/Tests/SimSlimCLITests/ArgumentsTests.swift
create mode 100644 swift/Tests/SimSlimCLITests/CommandTests.swift
create mode 120000 swift/Tests/SimSlimCLITests/GUIContract/Models.swift
create mode 100644 swift/Tests/SimSlimCLITests/GUIContractTests.swift
create mode 100644 swift/Tests/SimSlimCLITests/Support.swift
create mode 100644 swift/Tests/SimSlimKitTests/SimctlTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift
create mode 100644 swift/Tests/TestSupport/FakeHost.swift
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
index 7bd3bca..af7cc07 100644
--- a/docs/swift-port-plan.md
+++ b/docs/swift-port-plan.md
@@ -160,7 +160,7 @@ These are not in the first release. The SwiftUI app depends on several of them,
- **M0** Scaffold: package, subprocess layer, dependency gate, `make verify-deps`.
- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first.
-- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`.
+- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Not yet run against a live `simctl spawn launchctl` read, which `list`, `status`, `verify` and `doctor` all use.
- **M3** Slimming: `on`, `off`, `on --no-reboot`, offline fast path, `boot`, `shutdown`, `enable`/`disable`, `--save`.
- **M4** `watch`.
- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/scripts/verify-deps.sh b/scripts/verify-deps.sh
index af443bf..9916a80 100755
--- a/scripts/verify-deps.sh
+++ b/scripts/verify-deps.sh
@@ -48,8 +48,8 @@ ok() { print -- " ok: $*" }
section() { print -- "\n[$1]" }
# Modules each tree may import. Everything here ships with Xcode.
-ALLOWED_SOURCES=(Foundation Darwin Dispatch SimSlimKit)
-ALLOWED_TESTS=(Foundation Darwin Dispatch SimSlimKit XCTest Testing)
+ALLOWED_SOURCES=(Foundation Darwin Dispatch SimSlimKit SimSlimCLI)
+ALLOWED_TESTS=(Foundation Darwin Dispatch SimSlimKit SimSlimCLI TestSupport XCTest Testing)
ALLOWED_GUI=(Foundation AppKit SwiftUI)
# Prints ": " for each import in the given directory.
@@ -234,11 +234,23 @@ if (( CHECK_BINARY )); then
# Behavior check: the binary still works with all network access denied.
if command -v sandbox-exec >/dev/null 2>&1; then
- if out="$(sandbox-exec -p '(version 1)(allow default)(deny network*)' "$BIN" --version 2>&1)"; then
+ # Only commands that never touch a simulator are exercised here.
+ sandboxed() { sandbox-exec -p '(version 1)(allow default)(deny network*)' "$BIN" "$@" 2>&1; }
+ if out="$(sandboxed --version)"; then
ok "runs with network denied: $out"
else
fail "binary failed under sandbox-exec with network denied: $out"
fi
+ if out="$(sandboxed profiles --json)" && [[ "$out" == *'"id" : "widgets"'* ]]; then
+ ok "profiles --json works with network denied"
+ else
+ fail "profiles --json failed under sandbox-exec with network denied"
+ fi
+ if out="$(sandboxed doctor --list)" && [[ "$out" == *"com.apple.apsd"* ]]; then
+ ok "doctor --list works with network denied"
+ else
+ fail "doctor --list failed under sandbox-exec with network denied"
+ fi
else
print -- " skip: sandbox-exec not available"
fi
diff --git a/swift/Package.swift b/swift/Package.swift
index a037473..b73736f 100644
--- a/swift/Package.swift
+++ b/swift/Package.swift
@@ -2,7 +2,7 @@
import PackageDescription
// No third-party packages, ever. `scripts/verify-deps.sh` fails the check if
-// `dependencies` is anything other than an empty list.
+// the package declares one.
let package = Package(
name: "simslim",
platforms: [.macOS(.v14)],
@@ -11,9 +11,18 @@ let package = Package(
],
dependencies: [],
targets: [
+ // All logic. Never writes to stdout.
.target(name: "SimSlimKit"),
- .executableTarget(name: "simslim", dependencies: ["SimSlimKit"]),
- .testTarget(name: "SimSlimKitTests", dependencies: ["SimSlimKit"]),
+ // Argument parsing and printing, with injected output and command runner so
+ // every command is testable without a terminal or a simulator.
+ .target(name: "SimSlimCLI", dependencies: ["SimSlimKit"]),
+ // main.swift only.
+ .executableTarget(name: "simslim", dependencies: ["SimSlimCLI", "SimSlimKit"]),
+ // Test-only helpers (a fake simulator host). Not a dependency of any product.
+ .target(name: "TestSupport", dependencies: ["SimSlimKit"], path: "Tests/TestSupport"),
+ .testTarget(name: "SimSlimKitTests", dependencies: ["SimSlimKit", "TestSupport"]),
+ .testTarget(
+ name: "SimSlimCLITests", dependencies: ["SimSlimCLI", "SimSlimKit", "TestSupport"]),
],
swiftLanguageModes: [.v5]
)
diff --git a/swift/Sources/SimSlimCLI/Arguments.swift b/swift/Sources/SimSlimCLI/Arguments.swift
new file mode 100644
index 0000000..7517b80
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Arguments.swift
@@ -0,0 +1,77 @@
+import Foundation
+import SimSlimKit
+
+struct FlagSpec {
+ let name: String
+ let isBool: Bool
+ var onlyOnce = false
+
+ static func bool(_ name: String, onlyOnce: Bool = false) -> FlagSpec {
+ FlagSpec(name: name, isBool: true, onlyOnce: onlyOnce)
+ }
+ static func string(_ name: String) -> FlagSpec { FlagSpec(name: name, isBool: false) }
+}
+
+struct ParsedArguments {
+ var positionals: [String] = []
+ var bools: [String: Bool] = [:]
+ var strings: [String: String] = [:]
+
+ func bool(_ name: String) -> Bool { bools[name] ?? false }
+ func string(_ name: String) -> String { strings[name] ?? "" }
+ func has(_ name: String) -> Bool { bools[name] != nil || strings[name] != nil }
+}
+
+/// Parses flags and positionals in any order (`on --except search` and
+/// `on --except search ` are the same), as the Go CLI does. Accepts `-flag`
+/// and `--flag`, `--flag=value` and `--flag value`; `--` ends flag parsing. A bool
+/// flag never consumes the next token.
+func parseArguments(_ tokens: [String], specs: [FlagSpec]) throws -> ParsedArguments {
+ var parsed = ParsedArguments()
+ var i = 0
+ while i < tokens.count {
+ let token = tokens[i]
+ i += 1
+ if token == "--" {
+ parsed.positionals.append(contentsOf: tokens[i...])
+ break
+ }
+ guard token.hasPrefix("-"), token.count > 1 else {
+ parsed.positionals.append(token)
+ continue
+ }
+
+ let body = token.drop(while: { $0 == "-" })
+ let name: String
+ var inline: String?
+ if let eq = body.firstIndex(of: "=") {
+ name = String(body[.. Void
+
+ public var version: String
+ public var environment: [String: String]
+ public var runner: CommandRunning
+ public var stdout: Sink
+ public var stderr: Sink
+
+ public init(
+ version: String = simslimVersion,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ runner: CommandRunning = SystemCommandRunner(),
+ stdout: @escaping Sink,
+ stderr: @escaping Sink
+ ) {
+ self.version = version
+ self.environment = environment
+ self.runner = runner
+ self.stdout = stdout
+ self.stderr = stderr
+ }
+
+ /// Everything a command needs, after the global options are applied.
+ struct Context {
+ var simctl: Simctl
+ var bootTimeout: TimeInterval
+ var parsed: ParsedArguments
+ var stdout: Sink
+ var stderr: Sink
+ }
+
+ /// Commands that exist in the Go CLI but are not in the Swift port yet.
+ static let notYetPorted: Set = [
+ "profile", "on", "off", "enable", "disable", "watch", "top", "size", "disk-categories",
+ "disk-plan", "disk-clean", "clone", "repair-clone", "rename", "boot", "shutdown", "erase",
+ "delete",
+ ]
+
+ static let globalSpecs: [FlagSpec] = [
+ .string("set"), .string("boot-timeout"), .string("spawn-timeout"),
+ ]
+
+ static let commandSpecs: [String: [FlagSpec]] = [
+ "list": [.bool("json", onlyOnce: true), .bool("booted")],
+ "profiles": [.bool("json", onlyOnce: true)],
+ "status": [.bool("json", onlyOnce: true), .bool("dropped")],
+ "verify": [
+ .bool("json", onlyOnce: true), .string("profile"), .string("except"), .string("keep"),
+ ],
+ "doctor": [.bool("json", onlyOnce: true), .string("requires"), .bool("list")],
+ "measure": [.bool("json", onlyOnce: true)],
+ ]
+
+ /// Runs the command line (without the program name) and returns the exit status.
+ public func run(_ arguments: [String]) -> Int32 {
+ guard let first = arguments.first else {
+ stdout(usageText)
+ return 2
+ }
+ switch first {
+ case "-v", "--version", "version":
+ stdout("simslim \(version)\n")
+ return 0
+ case "-h", "--help", "help":
+ stdout(usageText)
+ return 0
+ default:
+ break
+ }
+
+ do {
+ return try dispatch(arguments)
+ } catch let error as SimSlimError {
+ stderr("simslim: \(error.message)\n")
+ return 1
+ } catch {
+ stderr("simslim: \(error.localizedDescription)\n")
+ return 1
+ }
+ }
+
+ private func dispatch(_ arguments: [String]) throws -> Int32 {
+ // Global options may precede the command name.
+ var index = 0
+ var leading: [String] = []
+ while index < arguments.count, arguments[index].hasPrefix("-") {
+ leading.append(arguments[index])
+ let name = arguments[index].drop(while: { $0 == "-" })
+ index += 1
+ if !name.contains("="), CLI.globalSpecs.first(where: { $0.name == name }) != nil,
+ index < arguments.count
+ {
+ leading.append(arguments[index])
+ index += 1
+ }
+ }
+ guard index < arguments.count else {
+ // Only global options were given.
+ _ = try parseArguments(leading, specs: CLI.globalSpecs)
+ stdout(usageText)
+ return 2
+ }
+
+ let command = arguments[index]
+ let rest = leading + Array(arguments[(index + 1)...])
+
+ if CLI.notYetPorted.contains(command) {
+ throw SimSlimError(
+ "\"\(command)\" is not available in the Swift port yet; use the Go CLI for it")
+ }
+ guard let specs = CLI.commandSpecs[command] else {
+ stderr("unknown command \"\(command)\"\n\n")
+ stdout(usageText)
+ return 2
+ }
+
+ let parsed: ParsedArguments
+ do {
+ parsed = try parseArguments(rest, specs: specs + CLI.globalSpecs)
+ } catch let error as SimSlimError where error.message == "flag needs an argument: --set" {
+ throw SimSlimError("--set requires a device set name (such as `testing`) or a path")
+ }
+
+ var simctl = Simctl(runner: runner)
+ let bootTimeout = try applyGlobalOptions(parsed, to: &simctl)
+ let context = Context(
+ simctl: simctl, bootTimeout: bootTimeout, parsed: parsed, stdout: stdout, stderr: stderr)
+
+ switch command {
+ case "list": return try cmdList(context)
+ case "profiles": return try cmdProfiles(context)
+ case "status": return try cmdStatus(context)
+ case "verify": return try cmdVerify(context)
+ case "doctor": return try cmdDoctor(context)
+ case "measure": return try cmdMeasure(context)
+ default: preconditionFailure("command \(command) has specs but no handler")
+ }
+ }
+
+ /// Applies --set, --boot-timeout and --spawn-timeout (each also settable from
+ /// the environment, for the two timeouts) and returns the boot timeout.
+ private func applyGlobalOptions(_ parsed: ParsedArguments, to simctl: inout Simctl) throws
+ -> TimeInterval
+ {
+ if parsed.has("set") {
+ let sets = splitList(parsed.string("set"))
+ if sets.isEmpty {
+ throw SimSlimError("--set requires a device set name (such as `testing`) or a path")
+ }
+ for set in sets { simctl.registerDeviceSet(set) }
+ }
+
+ func duration(flag: String, env: String, fallback: TimeInterval) throws -> TimeInterval {
+ let raw = parsed.has(flag) ? parsed.string(flag) : (environment[env] ?? "")
+ if raw.isEmpty { return fallback }
+ let value: TimeInterval
+ do {
+ value = try parseGoDuration(raw)
+ } catch {
+ throw SimSlimError(
+ "invalid value \"\(raw)\" for flag -\(flag): \((error as? SimSlimError)?.message ?? "parse error")"
+ )
+ }
+ if value <= 0 {
+ let example = flag == "boot-timeout" ? "15m" : "2m"
+ throw SimSlimError("--\(flag) must be a positive duration (such as `\(example)`)")
+ }
+ return value
+ }
+
+ simctl.spawnTimeout = try duration(
+ flag: "spawn-timeout", env: "SIMSLIM_SPAWN_TIMEOUT", fallback: simctl.spawnTimeout)
+ return try duration(flag: "boot-timeout", env: "SIMSLIM_BOOT_TIMEOUT", fallback: 600)
+ }
+}
+
+func oneUDID(_ positionals: [String]) throws -> String {
+ guard positionals.count == 1 else {
+ throw SimSlimError("expected exactly one simulator UDID (see `simslim list`)")
+ }
+ return positionals[0]
+}
diff --git a/swift/Sources/SimSlimCLI/Commands.swift b/swift/Sources/SimSlimCLI/Commands.swift
new file mode 100644
index 0000000..1dc9be6
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Commands.swift
@@ -0,0 +1,234 @@
+import Foundation
+import SimSlimKit
+
+// The read-only commands. Each returns the exit status; an error is reported by
+// the caller as `simslim: ` with status 1.
+
+extension CLI {
+ func cmdList(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ guard context.parsed.positionals.isEmpty else {
+ throw SimSlimError("list takes no arguments")
+ }
+ let simctl = context.simctl
+ var devices = try simctl.listDevices()
+ if context.parsed.bool("booted") { devices = devices.filter { $0.state == "Booted" } }
+ devices.sort { a, b in
+ if a.platformName != b.platformName { return a.platformName < b.platformName }
+ if a.osVersion != b.osVersion { return a.osVersion > b.osVersion }
+ if a.name != b.name { return a.name < b.name }
+ return a.udid < b.udid
+ }
+
+ var memory: [String: MemoryMeasurement] = [:]
+ var memoryErrors: [String: String] = [:]
+ if json {
+ let booted = devices.filter { $0.state == "Booted" }.map(\.udid)
+ (memory, memoryErrors) = simctl.measureMany(udids: booted)
+ }
+
+ var summaries: [DeviceSummary] = []
+ for device in devices {
+ let managed = Profile().desired(for: device).count
+ var tag = "shutdown"
+ var summary = DeviceSummary(device: device, managedTotal: managed)
+ if device.state == "Booted" {
+ tag = "booted"
+ summary.memory = memory[device.udid]
+ summary.memoryError = memoryErrors[device.udid] ?? ""
+ do {
+ let status = try simctl.readStatus(for: device).status
+ tag = "booted · \(status.managedDisabled)/\(managed) slim"
+ summary.managedDisabled = status.managedDisabled
+ } catch {
+ summary.statusError = error.localizedDescription
+ }
+ }
+ summaries.append(summary)
+ if !json {
+ var line =
+ "\(device.udid) \(padRight(truncate(device.name, 22), 22)) "
+ + "\(padRight(device.runtimeName, 14)) \(tag)"
+ if !device.set.isEmpty && device.set != "default" { line += " (\(device.set))" }
+ context.stdout(line + "\n")
+ }
+ }
+ if json { context.stdout(try jsonText(summaries)) }
+ return 0
+ }
+
+ func cmdProfiles(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let args = context.parsed.positionals
+ guard args.count <= 1 else {
+ throw SimSlimError("profiles takes at most one category ID (see `simslim profiles`)")
+ }
+ let out = context.stdout
+
+ if let id = args.first {
+ guard let category = Catalog.category(id: id) else {
+ throw SimSlimError("unknown category \"\(id)\" (see `simslim profiles`)")
+ }
+ if json {
+ out(try jsonText(category))
+ return 0
+ }
+ out("\(padRight(category.id, 14)) \(category.name)\n")
+ out(" \(category.description)\n")
+ out(
+ " \(category.labels.count) daemons · ~\(category.approxMemoryMB) MB idle footprint when enabled\n"
+ )
+ out(" When disabled: \(category.downside)\n")
+ out("\nDaemons:\n")
+ for label in category.labels {
+ let description = category.serviceDescriptions[label] ?? ""
+ out(description.isEmpty ? " \(label)\n" : " \(padRight(label, 44)) \(description)\n")
+ }
+ for service in category.alwaysEnabled {
+ out(" \(padRight(service.label, 44)) Always on — \(service.reason)\n")
+ }
+ return 0
+ }
+
+ if json {
+ out(try jsonText(Catalog.categories))
+ return 0
+ }
+ for category in Catalog.categories {
+ out("\(padRight(category.id, 14)) \(category.name)\n")
+ out(
+ " \(category.labels.count) daemons · ~\(category.approxMemoryMB) MB idle footprint when enabled\n"
+ )
+ out(" When disabled: \(category.downside)\n")
+ for service in category.alwaysEnabled {
+ out(" Always on: \(service.label) — \(service.reason)\n")
+ }
+ }
+ out(
+ "\n\(Catalog.slimmableSet.count) daemons across \(Catalog.categories.count) categories. "
+ + "Core workflow and deadlock-prone daemons are never disabled.\n")
+ out(
+ "Memory estimates are iOS 26.5 clean-boot measurements; they vary by runtime and workload and are not additive.\n"
+ )
+ return 0
+ }
+
+ func cmdStatus(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let showDropped = context.parsed.bool("dropped")
+ let udid = try oneUDID(context.parsed.positionals)
+ let (status, disabled) = try context.simctl.readStatus(udid: udid)
+ let dropped = showDropped ? Catalog.droppedCategories(disabled: disabled) : []
+
+ if json {
+ context.stdout(
+ try jsonText(StatusOutput(status: status, verdict: status.verdict, dropped: dropped)))
+ return 0
+ }
+ let out = context.stdout
+ out(
+ "\(udid): \(status.managedDisabled)/\(status.managedTotal) managed launchd labels disabled (\(status.verdict))\n"
+ )
+ if status.managedDisabled > 0 && !status.persistent {
+ out(
+ " This runtime cannot persist launchd overrides: the state reverts to stock at the next reboot.\n"
+ )
+ }
+ if showDropped {
+ if dropped.isEmpty { out(" Nothing dropped; every managed launchd label is enabled.\n") }
+ for category in dropped {
+ out(" \(padRight(category.id, 14)) \(category.name) — \(category.downside)\n")
+ for label in category.labels { out(" \(label)\n") }
+ }
+ }
+ return 0
+ }
+
+ func cmdVerify(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let udid = try oneUDID(context.parsed.positionals)
+ let profile = try buildProfile(
+ profilePath: context.parsed.string("profile"), except: context.parsed.string("except"),
+ keep: context.parsed.string("keep"))
+ let result = try context.simctl.verifyProfile(udid: udid, profile: profile)
+ let out = context.stdout
+
+ if json {
+ out(try jsonText(result))
+ } else if result.ok {
+ out("\(udid) matches the profile: all expected disable overrides are applied.\n")
+ } else {
+ out(
+ "\(udid) does not match the profile (\(result.missing.count) missing, \(result.extra.count) extra):\n"
+ )
+ for label in result.missing {
+ out(" missing \(label) (should be disabled, is enabled)\n")
+ }
+ for label in result.extra { out(" extra \(label) (disabled beyond the profile)\n") }
+ out("Re-run `simslim on` with the same profile to repair.\n")
+ }
+ return result.ok ? 0 : 1
+ }
+
+ func cmdDoctor(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let out = context.stdout
+
+ if context.parsed.bool("list") {
+ guard context.parsed.positionals.isEmpty else {
+ throw SimSlimError("doctor --list takes no arguments")
+ }
+ if json {
+ out(try jsonText(Catalog.features))
+ return 0
+ }
+ for feature in Catalog.features {
+ out(
+ "\(padRight(feature.id, 16)) \(padRight(feature.name, 38)) \(feature.labels.joined(separator: ", "))\n"
+ )
+ }
+ return 0
+ }
+
+ let udid = try oneUDID(context.parsed.positionals)
+ let features = try Catalog.resolveFeatures(splitList(context.parsed.string("requires")))
+ guard !features.isEmpty else {
+ throw SimSlimError(
+ "doctor needs at least one feature via --requires (see `simslim doctor --list`)")
+ }
+
+ let (_, disabled) = try context.simctl.readStatus(udid: udid)
+ var report = Catalog.diagnoseFeatures(features, disabled: disabled)
+ report.udid = udid
+
+ if json {
+ out(try jsonText(report))
+ } else {
+ let broken = report.features.filter { !$0.ok }.count
+ out(
+ "\(udid): \(report.features.count - broken)/\(report.features.count) required features OK\n"
+ )
+ for feature in report.features {
+ if feature.ok {
+ out(" ok \(feature.id)\n")
+ } else {
+ out(" BROKEN \(feature.id) — \(feature.disabled.joined(separator: ", ")) disabled\n")
+ }
+ }
+ }
+ return report.ok ? 0 : 1
+ }
+
+ func cmdMeasure(_ context: Context) throws -> Int32 {
+ let udid = try oneUDID(context.parsed.positionals)
+ let measurement = try context.simctl.measure(udid: udid)
+ if context.parsed.bool("json") {
+ context.stdout(try jsonText(measurement))
+ } else {
+ context.stdout(
+ "\(udid): \(measurement.processes) processes, \(humanBytes(measurement.bytes)) memory footprint (phys_footprint)\n"
+ )
+ }
+ return 0
+ }
+}
diff --git a/swift/Sources/SimSlimCLI/Duration.swift b/swift/Sources/SimSlimCLI/Duration.swift
new file mode 100644
index 0000000..6ed4016
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Duration.swift
@@ -0,0 +1,54 @@
+import Foundation
+import SimSlimKit
+
+/// Parses durations the way Go's time.ParseDuration does ("90s", "10m", "1h30m",
+/// "1.5h", "500ms"), so `--boot-timeout 15m` and SIMSLIM_BOOT_TIMEOUT behave the
+/// same in both tools. Returns seconds.
+func parseGoDuration(_ text: String) throws -> TimeInterval {
+ let invalid = SimSlimErrorMessage.invalidDuration(text)
+ var rest = Substring(text)
+ var sign = 1.0
+ if let first = rest.first, first == "-" || first == "+" {
+ if first == "-" { sign = -1 }
+ rest = rest.dropFirst()
+ }
+ if rest == "0" { return 0 }
+ if rest.isEmpty { throw invalid }
+
+ let units: [(String, Double)] = [
+ ("ns", 1e-9), ("us", 1e-6), ("µs", 1e-6), ("μs", 1e-6), ("ms", 1e-3),
+ ("s", 1), ("m", 60), ("h", 3600),
+ ]
+ var total = 0.0
+ while !rest.isEmpty {
+ var number = ""
+ while let c = rest.first, c.isASCII, c.isNumber || c == "." {
+ number.append(c)
+ rest = rest.dropFirst()
+ }
+ guard !number.isEmpty, let value = Double(number) else { throw invalid }
+ var unit = ""
+ while let c = rest.first, !(c.isASCII && (c.isNumber || c == ".")) {
+ unit.append(c)
+ rest = rest.dropFirst()
+ }
+ if unit.isEmpty { throw SimSlimErrorMessage.missingUnit(text) }
+ guard let scale = units.first(where: { $0.0 == unit })?.1 else {
+ throw SimSlimErrorMessage.unknownUnit(unit, text)
+ }
+ total += value * scale
+ }
+ return sign * total
+}
+
+enum SimSlimErrorMessage {
+ static func invalidDuration(_ s: String) -> SimSlimError {
+ SimSlimError("time: invalid duration \"\(s)\"")
+ }
+ static func missingUnit(_ s: String) -> SimSlimError {
+ SimSlimError("time: missing unit in duration \"\(s)\"")
+ }
+ static func unknownUnit(_ unit: String, _ s: String) -> SimSlimError {
+ SimSlimError("time: unknown unit \"\(unit)\" in duration \"\(s)\"")
+ }
+}
diff --git a/swift/Sources/SimSlimCLI/Format.swift b/swift/Sources/SimSlimCLI/Format.swift
new file mode 100644
index 0000000..4e49ec7
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Format.swift
@@ -0,0 +1,36 @@
+import Foundation
+import SimSlimKit
+
+/// Pads on the right to `width`, counting Unicode scalars like Go's `%-Ns`.
+func padRight(_ text: String, _ width: Int) -> String {
+ let count = text.unicodeScalars.count
+ return count >= width ? text : text + String(repeating: " ", count: width - count)
+}
+
+/// Shortens to at most `limit` scalars, ending with an ellipsis when cut.
+func truncate(_ text: String, _ limit: Int) -> String {
+ let scalars = Array(text.unicodeScalars)
+ if scalars.count <= limit { return text }
+ if limit <= 1 { return "…" }
+ var out = String.UnicodeScalarView()
+ out.append(contentsOf: scalars[..<(limit - 1)])
+ return String(out) + "…"
+}
+
+func humanBytes(_ bytes: Int64) -> String {
+ switch bytes {
+ case (1 << 30)...: return String(format: "%.2f GB", Double(bytes) / Double(1 << 30))
+ case (1 << 20)...: return String(format: "%.0f MB", Double(bytes) / Double(1 << 20))
+ case (1 << 10)...: return String(format: "%.0f KB", Double(bytes) / Double(1 << 10))
+ default: return "\(bytes) B"
+ }
+}
+
+/// Renders machine-readable output: indented, keys sorted so the output is
+/// deterministic, with a trailing newline. (Go emits struct-field order; JSON
+/// consumers do not depend on key order.)
+func jsonText(_ value: T) throws -> String {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
+ return String(decoding: try encoder.encode(value), as: UTF8.self) + "\n"
+}
diff --git a/swift/Sources/SimSlimCLI/Usage.swift b/swift/Sources/SimSlimCLI/Usage.swift
new file mode 100644
index 0000000..e93643b
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Usage.swift
@@ -0,0 +1,73 @@
+/// `simslim --help`. Commands marked † exist in the Go CLI but are not in the
+/// Swift port yet.
+let usageText = """
+ simslim runs more iOS, tvOS, watchOS, and visionOS simulators on the same Mac by disabling the
+ background daemons a simulator does not need.
+
+ This is the Swift port. Commands marked † are not available yet.
+
+ USAGE
+ simslim [args]
+
+ GLOBAL OPTIONS
+ --set Also scan these device sets (comma-separated). The default
+ and Xcode `testing` (parallel-testing) sets are always
+ scanned; use this to add a set at a custom path.
+ --boot-timeout dur Max time to boot and reconfigure a simulator (default 10m;
+ e.g. `15m`). Raise it for slow CI runners. Also settable
+ via the SIMSLIM_BOOT_TIMEOUT environment variable.
+ --spawn-timeout dur Max time for a single launchctl transition inside the
+ simulator (default 2m). Raise it for hosts where a busy
+ first boot makes individual spawns very slow. Also
+ settable via the SIMSLIM_SPAWN_TIMEOUT environment
+ variable.
+
+ COMMANDS
+ list List available simulators and their slim status
+ --booted Only list booted simulators
+ profiles [id] Show the daemon categories a slim boot disables;
+ pass a category ID to list that category's daemons
+ profile [path] † Interactively build a --profile JSON file
+ on † Slim a simulator (persist disables + reboot slim)
+ off † Restore a simulator to stock (re-enable + reboot)
+ enable † Re-enable categories or daemons on a booted simulator now
+ disable † Stop categories or daemons on a booted simulator now
+ watch † Slim every simulator until Ctrl-C
+ status Report how slim a booted simulator is
+ --dropped Also list the disabled daemons grouped by category
+ verify Check that a booted simulator's disable overrides still
+ match a profile exactly; exits non-zero and lists the
+ drift otherwise. Catches a silently stock recreated or
+ erased device; re-run `on` to repair
+ --profile path Verify against a committed JSON profile; mutually
+ exclusive with --except/--keep
+ --except ids The profile's enabled categories (comma-separated)
+ --keep labels The profile's kept daemons (comma-separated)
+ doctor Check required features against a booted simulator;
+ exits non-zero if slimming has broken any of them
+ --requires ids Comma-separated feature IDs to verify
+ --list List every checkable feature and its daemons
+ measure Report a booted simulator's memory footprint
+ top [udid] † Live fleet monitor
+ size † Report a simulator's allocated disk footprint
+ disk-categories † Show cleanup and protected system-asset categories
+ disk-plan † Measure reclaimable and stored data without deleting
+ disk-clean † Permanently delete selected per-device data
+ clone † Clone apps, data, settings, and the service profile
+ repair-clone †
+ rename † Rename a simulator
+ boot † Boot a simulator and wait for its services
+ shutdown † Shut down a booted simulator
+ erase † Erase a simulator's apps, data, and settings
+ delete † Permanently delete a simulator
+ --json Print machine-readable JSON (also supported by list,
+ profiles, status, verify, doctor)
+ version Print the version
+
+ A `--profile` file is JSON you commit alongside your project and apply per run
+ (for example a ci.json and a dev.json). Its "except" and "keep" arrays match the
+ flags of the same name:
+
+ { "name": "ci", "except": ["search", "store"], "keep": ["com.apple.apsd"] }
+
+ """
diff --git a/swift/Sources/SimSlimKit/Measure.swift b/swift/Sources/SimSlimKit/Measure.swift
new file mode 100644
index 0000000..e27fa09
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Measure.swift
@@ -0,0 +1,191 @@
+import Foundation
+
+/// A device's real memory cost.
+public struct MemoryMeasurement: Codable, Equatable, Sendable {
+ public var processes: Int
+ /// Summed phys_footprint (compressed + dirty): the number that caps how many
+ /// simulators fit.
+ public var bytes: Int64
+ /// Summed %cpu across the tree (ps's decaying average; can exceed 100).
+ public var cpu: Double
+
+ public init(processes: Int, bytes: Int64, cpu: Double) {
+ self.processes = processes
+ self.bytes = bytes
+ self.cpu = cpu
+ }
+}
+
+/// One `ps` sweep of every process: parent links, cpu, and name.
+struct ProcessSnapshot: Equatable {
+ var children: [Int: [Int]] = [:]
+ var cpu: [Int: Double] = [:]
+ var comm: [Int: String] = [:]
+}
+
+extension Simctl {
+ /// Sums the phys_footprint of every process in the device's launchd tree.
+ /// phys_footprint (the value Activity Monitor's "Memory" column reports)
+ /// counts compressed and swapped pages, so it stays accurate under memory
+ /// pressure where resident size would read misleadingly low.
+ public func measure(udid: String) throws -> MemoryMeasurement {
+ let root = try simLaunchdPID(udid: udid)
+ let snapshot = try processSnapshot()
+ let footprint = try footprintByPID()
+ return Simctl.measureTree(root: root, snapshot: snapshot, footprint: footprint)
+ }
+
+ /// Takes one process and footprint snapshot for every requested simulator, so
+ /// the RAM column stays current without running the relatively expensive `top`
+ /// once per booted device. Returns measurements and per-UDID error messages.
+ public func measureMany(udids: [String]) -> (
+ measurements: [String: MemoryMeasurement], errors: [String: String]
+ ) {
+ var measurements: [String: MemoryMeasurement] = [:]
+ var errors: [String: String] = [:]
+ var roots: [String: Int] = [:]
+ for udid in udids {
+ do {
+ roots[udid] = try simLaunchdPID(udid: udid)
+ } catch {
+ errors[udid] = error.localizedDescription
+ }
+ }
+ if roots.isEmpty { return (measurements, errors) }
+
+ do {
+ let snapshot = try processSnapshot()
+ let footprint = try footprintByPID()
+ for (udid, root) in roots {
+ measurements[udid] = Simctl.measureTree(
+ root: root, snapshot: snapshot, footprint: footprint)
+ }
+ } catch {
+ for udid in roots.keys { errors[udid] = error.localizedDescription }
+ }
+ return (measurements, errors)
+ }
+
+ func simLaunchdPID(udid: String) throws -> Int {
+ let notBooted = SimSlimError("simulator \(udid) does not appear to be booted")
+ let result: CommandResult
+ do {
+ result = try runner.run(.pgrep, ["-f", udid + "/data/var/run/launchd_bootstrap"])
+ } catch {
+ throw notBooted
+ }
+ guard result.succeeded,
+ let first = result.stdoutText.split(whereSeparator: \.isWhitespace).first
+ else { throw notBooted }
+ guard let pid = Int(first) else {
+ throw SimSlimError("unexpected pgrep output: \(first)")
+ }
+ return pid
+ }
+
+ func processSnapshot() throws -> ProcessSnapshot {
+ // comm is the full executable path (untruncated, unlike ucomm); the basename
+ // is what the drill-down shows (backboardd, SpringBoard, ...).
+ let result = try runner.run(.ps, ["-axo", "pid,ppid,%cpu,comm"])
+ guard result.succeeded else {
+ throw SimSlimError("ps: exit status \(result.status): \(result.combinedText)")
+ }
+ return Simctl.parsePS(result.stdoutText)
+ }
+
+ func footprintByPID() throws -> [Int: Int64] {
+ let result = try runner.run(.top, ["-l", "1", "-stats", "pid,mem"])
+ guard result.succeeded else {
+ throw SimSlimError("top: exit status \(result.status): \(result.combinedText)")
+ }
+ return Simctl.parseTopMemory(result.stdoutText)
+ }
+
+ static func measureTree(
+ root: Int, snapshot: ProcessSnapshot, footprint: [Int: Int64]
+ ) -> MemoryMeasurement {
+ var measurement = MemoryMeasurement(processes: 0, bytes: 0, cpu: 0)
+ for pid in treePIDs(root: root, children: snapshot.children) {
+ measurement.processes += 1
+ measurement.bytes += footprint[pid] ?? 0
+ measurement.cpu += snapshot.cpu[pid] ?? 0
+ }
+ return measurement
+ }
+
+ /// Every pid reachable from `root` through the child map.
+ static func treePIDs(root: Int, children: [Int: [Int]]) -> Set {
+ var seen = Set()
+ var stack = [root]
+ while let pid = stack.popLast() {
+ if !seen.insert(pid).inserted { continue }
+ stack.append(contentsOf: children[pid] ?? [])
+ }
+ return seen
+ }
+
+ static func parsePS(_ output: String) -> ProcessSnapshot {
+ var snapshot = ProcessSnapshot()
+ for line in output.split(separator: "\n") {
+ let fields = line.split(whereSeparator: \.isWhitespace)
+ if fields.count < 4 { continue }
+ guard let pid = Int(fields[0]), let ppid = Int(fields[1]) else { continue }
+ snapshot.children[ppid, default: []].append(pid)
+ if let cpu = Double(fields[2]) { snapshot.cpu[pid] = cpu }
+ // Joining defends against spaces in the executable path.
+ snapshot.comm[pid] = commName(fields[3...].joined(separator: " "))
+ }
+ return snapshot
+ }
+
+ /// Reduces a full executable path to its basename.
+ static func commName(_ path: String) -> String {
+ guard let slash = path.lastIndex(of: "/") else { return path }
+ return String(path[path.index(after: slash)...])
+ }
+
+ /// Parses `top -l 1 -stats pid,mem` lines: a pid, then a size such as `45M`
+ /// or `1234K+`. Anything else (headers, the summary block) is skipped.
+ static func parseTopMemory(_ output: String) -> [Int: Int64] {
+ var memory: [Int: Int64] = [:]
+ for line in output.split(separator: "\n") {
+ let fields = line.split(whereSeparator: \.isWhitespace)
+ guard fields.count >= 2, fields[0].allSatisfy(\.isASCIIDigit), let pid = Int(fields[0]) else {
+ continue
+ }
+ // The size must start with a digit or '.', like the Go regex's [0-9.]+.
+ guard let first = fields[1].first, first.isASCIIDigit || first == "." else { continue }
+ memory[pid] = parseBytes(String(fields[1]))
+ }
+ return memory
+ }
+
+ /// Parses sizes such as `45M`, `1.5G`, `900K+` or `12B`; the suffix is
+ /// optional. Unparseable input is 0.
+ static func parseBytes(_ text: String) -> Int64 {
+ var s = text.trimmingCharacters(in: .whitespaces)
+ if s.hasSuffix("+") { s.removeLast() }
+ if s.hasSuffix("-") { s.removeLast() }
+ if s.isEmpty { return 0 }
+ var multiplier: Double = 1
+ switch s.last {
+ case "K":
+ multiplier = 1_024
+ s.removeLast()
+ case "M":
+ multiplier = 1_048_576
+ s.removeLast()
+ case "G":
+ multiplier = 1_073_741_824
+ s.removeLast()
+ case "B": s.removeLast()
+ default: break
+ }
+ guard let value = Double(s) else { return 0 }
+ return Int64(value * multiplier)
+ }
+}
+
+extension Character {
+ fileprivate var isASCIIDigit: Bool { self >= "0" && self <= "9" }
+}
diff --git a/swift/Sources/SimSlimKit/Output.swift b/swift/Sources/SimSlimKit/Output.swift
new file mode 100644
index 0000000..617d0c6
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Output.swift
@@ -0,0 +1,81 @@
+import Foundation
+
+/// The stable, machine-readable shapes the macOS app and other integrations
+/// decode. Changing a field breaks `gui/*.swift`; keep them in sync.
+
+/// A device plus its slim status and memory. The device fields are flattened
+/// into the same JSON object, as in the Go output.
+public struct DeviceSummary: Codable, Equatable, Sendable {
+ public var device: Device
+ public var managedDisabled: Int? // omitted for shutdown simulators
+ public var managedTotal: Int
+ public var statusError: String
+ public var memory: MemoryMeasurement?
+ public var memoryError: String
+
+ public init(
+ device: Device, managedDisabled: Int? = nil, managedTotal: Int, statusError: String = "",
+ memory: MemoryMeasurement? = nil, memoryError: String = ""
+ ) {
+ self.device = device
+ self.managedDisabled = managedDisabled
+ self.managedTotal = managedTotal
+ self.statusError = statusError
+ self.memory = memory
+ self.memoryError = memoryError
+ }
+
+ private enum ExtraKeys: String, CodingKey {
+ case managedDisabled, managedTotal, statusError, memory, memoryError
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ try device.encode(to: encoder) // flatten the device's keys into this object
+ var c = encoder.container(keyedBy: ExtraKeys.self)
+ try c.encodeIfPresent(managedDisabled, forKey: .managedDisabled)
+ try c.encode(managedTotal, forKey: .managedTotal)
+ if !statusError.isEmpty { try c.encode(statusError, forKey: .statusError) } // Go omitempty
+ try c.encodeIfPresent(memory, forKey: .memory)
+ if !memoryError.isEmpty { try c.encode(memoryError, forKey: .memoryError) }
+ }
+
+ public init(from decoder: Decoder) throws {
+ device = try Device(from: decoder)
+ let c = try decoder.container(keyedBy: ExtraKeys.self)
+ managedDisabled = try c.decodeIfPresent(Int.self, forKey: .managedDisabled)
+ managedTotal = try c.decode(Int.self, forKey: .managedTotal)
+ statusError = try c.decodeIfPresent(String.self, forKey: .statusError) ?? ""
+ memory = try c.decodeIfPresent(MemoryMeasurement.self, forKey: .memory)
+ memoryError = try c.decodeIfPresent(String.self, forKey: .memoryError) ?? ""
+ }
+}
+
+/// `simslim status --json`: the status fields flattened, plus the verdict and,
+/// only with `--dropped`, the disabled daemons grouped by category.
+public struct StatusOutput: Codable, Equatable, Sendable {
+ public var status: Status
+ public var verdict: String
+ public var dropped: [DroppedCategory]
+
+ public init(status: Status, verdict: String, dropped: [DroppedCategory] = []) {
+ self.status = status
+ self.verdict = verdict
+ self.dropped = dropped
+ }
+
+ private enum ExtraKeys: String, CodingKey { case verdict, dropped }
+
+ public func encode(to encoder: Encoder) throws {
+ try status.encode(to: encoder)
+ var c = encoder.container(keyedBy: ExtraKeys.self)
+ try c.encode(verdict, forKey: .verdict)
+ if !dropped.isEmpty { try c.encode(dropped, forKey: .dropped) } // Go omitempty
+ }
+
+ public init(from decoder: Decoder) throws {
+ status = try Status(from: decoder)
+ let c = try decoder.container(keyedBy: ExtraKeys.self)
+ verdict = try c.decode(String.self, forKey: .verdict)
+ dropped = try c.decodeIfPresent([DroppedCategory].self, forKey: .dropped) ?? []
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Simctl.swift b/swift/Sources/SimSlimKit/Simctl.swift
new file mode 100644
index 0000000..9cda419
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Simctl.swift
@@ -0,0 +1,224 @@
+import Foundation
+
+/// A CoreSimulator device set: the default one, Xcode's `testing` set, or a
+/// custom path named with `--set`.
+public struct DeviceSet: Equatable, Sendable {
+ /// "" for the default set; otherwise passed to `simctl --set`.
+ public let token: String
+ public let name: String
+}
+
+/// The only place that shells out to `xcrun simctl`.
+public struct Simctl: Sendable {
+ public var runner: CommandRunning
+ /// Sets named with `--set`, beyond the always-scanned default and `testing`.
+ public private(set) var extraSets: [String] = []
+ /// Bounds one `simctl spawn launchctl` call. A first boot can saturate the
+ /// simulator, so a single spawn can stall for minutes; a per-spawn bound turns
+ /// that into a retryable failure instead of an unbounded wait.
+ public var spawnTimeout: TimeInterval = 120
+ /// Pauses between attempts to read a simulator's launchd state. Right after a
+ /// boot, and while a reboot tears the old session down, launchd_sim refuses
+ /// spawns for a few seconds (error 124, "Domain is tearing down").
+ public var retryDelays: [TimeInterval] = [1, 2, 4, 8]
+ public var sleep: @Sendable (TimeInterval) -> Void = { Thread.sleep(forTimeInterval: $0) }
+
+ public init(runner: CommandRunning = SystemCommandRunner()) {
+ self.runner = runner
+ }
+
+ // MARK: - Device sets
+
+ public var knownSets: [DeviceSet] {
+ [DeviceSet(token: "", name: "default"), DeviceSet(token: "testing", name: "testing")]
+ + extraSets.map { DeviceSet(token: $0, name: $0) }
+ }
+
+ /// Adds a `--set` value to the scanned sets, ignoring one that duplicates a
+ /// known token.
+ public mutating func registerDeviceSet(_ value: String) {
+ if knownSets.contains(where: { $0.token == value }) { return }
+ extraSets.append(value)
+ }
+
+ func token(forSet name: String) -> String {
+ knownSets.first { $0.name == name }?.token ?? ""
+ }
+
+ /// `--set` must precede the subcommand.
+ func simctlArgs(set name: String, _ sub: [String]) -> [String] {
+ Simctl.simctlArgs(token: token(forSet: name), sub)
+ }
+
+ static func simctlArgs(token: String, _ sub: [String]) -> [String] {
+ token.isEmpty ? ["simctl"] + sub : ["simctl", "--set", token] + sub
+ }
+
+ // MARK: - Listing
+
+ private struct ListOutput: Decodable {
+ struct Entry: Decodable {
+ var udid: String?
+ var name: String?
+ var state: String?
+ var isAvailable: Bool?
+ var dataPath: String?
+ }
+ var devices: [String: [Entry]]
+ }
+
+ func listDevices(in set: DeviceSet) throws -> [Device] {
+ let args = Simctl.simctlArgs(token: set.token, ["list", "devices", "-j"])
+ let result: CommandResult
+ do {
+ result = try runner.run(.xcrun, args)
+ } catch {
+ throw SimSlimError("simctl list: \(error.localizedDescription)")
+ }
+ guard result.succeeded else {
+ throw Simctl.listError(status: result.status, stderr: result.stderrText)
+ }
+ let parsed: ListOutput
+ do {
+ parsed = try JSONDecoder().decode(ListOutput.self, from: result.stdout)
+ } catch {
+ throw SimSlimError("parse simctl list: \(error.localizedDescription)")
+ }
+
+ var devices: [Device] = []
+ for runtime in parsed.devices.keys.sorted() {
+ guard let (platform, version) = Simctl.parseRuntime(runtime) else { continue }
+ for entry in parsed.devices[runtime] ?? [] {
+ // Like the Go tool, an entry without isAvailable is treated as unavailable.
+ guard entry.isAvailable == true, let udid = entry.udid else { continue }
+ devices.append(
+ Device(
+ udid: udid, name: entry.name ?? "", state: entry.state ?? "", platform: platform,
+ osVersion: version, set: set.name, dataPath: entry.dataPath ?? "", runtimeID: runtime))
+ }
+ }
+ return devices
+ }
+
+ /// Surfaces xcrun's stderr, and when xcrun cannot find simctl at all (xcode-select
+ /// pointing at the Command Line Tools) says how to select a full Xcode.
+ static func listError(status: Int32, stderr: String) -> SimSlimError {
+ let base = "simctl list: exit status \(status)"
+ let text = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ if text.isEmpty { return SimSlimError(base) }
+ if text.contains("unable to find utility \"simctl\"") {
+ return SimSlimError(
+ "\(base): \(text) (simctl ships with full Xcode, not the Command Line Tools; "
+ + "select one with `sudo xcode-select -s /Applications/Xcode.app`)")
+ }
+ return SimSlimError("\(base): \(text)")
+ }
+
+ /// Lists every available simulator. The default set is mandatory; a secondary
+ /// set that cannot be listed (for example, one that does not exist) is skipped.
+ public func listDevices() throws -> [Device] {
+ var devices: [Device] = []
+ for set in knownSets {
+ do {
+ devices += try listDevices(in: set)
+ } catch {
+ if set.token.isEmpty { throw error }
+ }
+ }
+ return devices
+ }
+
+ /// Accepts only the simulator platforms supported by slimming.
+ static func parseRuntime(_ runtime: String) -> (platform: String, version: String)? {
+ let prefix = "com.apple.CoreSimulator.SimRuntime."
+ guard runtime.hasPrefix(prefix) else { return nil }
+ let name = runtime.dropFirst(prefix.count)
+ guard let dash = name.firstIndex(of: "-") else { return nil }
+ let platform = String(name[.. Device {
+ for candidate in knownSets {
+ if !set.isEmpty && candidate.name != set { continue }
+ let found: [Device]
+ do {
+ found = try listDevices(in: candidate)
+ } catch {
+ if candidate.token.isEmpty { throw error }
+ continue
+ }
+ if let device = found.first(where: { $0.udid == udid }) { return device }
+ }
+ throw SimSlimError("no simulator with udid \(udid)")
+ }
+
+ // MARK: - launchd inside a simulator
+
+ /// The labels currently disabled in the device's system domain. A label absent
+ /// from the output is enabled.
+ public func readDisabled(set: String, udid: String) throws -> Set {
+ let output = try readLaunchd(set: set, udid: udid, ["print-disabled", "system"])
+ return Simctl.parseDisabled(output)
+ }
+
+ /// Runs a read-only launchctl command inside the simulator, each attempt bounded
+ /// by `spawnTimeout`. launchd_sim's transient error 124 and an attempt that ran
+ /// out of time are retried after each of `retryDelays`; any other failure is
+ /// returned at once.
+ func readLaunchd(set: String, udid: String, _ args: [String]) throws -> String {
+ let arguments = simctlArgs(set: set, ["spawn", udid, "launchctl"] + args)
+ var attempt = 0
+ while true {
+ let result: CommandResult
+ do {
+ result = try runner.run(.xcrun, arguments, timeout: spawnTimeout)
+ } catch {
+ throw SimSlimError("launchctl \(args[0]): \(error.localizedDescription)")
+ }
+ if result.succeeded { return result.stdoutText }
+
+ let reason =
+ result.timedOut
+ ? "timed out after \(Int(spawnTimeout))s" : "exit status \(result.status)"
+ let message = "launchctl \(args[0]): \(reason): \(result.combinedText)"
+ let settling = Simctl.launchdSettling(result) || result.timedOut
+ if !settling || attempt >= retryDelays.count { throw SimSlimError(message) }
+ sleep(retryDelays[attempt])
+ attempt += 1
+ }
+ }
+
+ /// Whether a spawn failed with launchd_sim's error 124, which it answers while
+ /// a boot session starts or tears down.
+ static func launchdSettling(_ result: CommandResult) -> Bool {
+ if result.status == 124 { return true }
+ let text = result.stdoutText + result.stderrText
+ return text.contains("code=124") || text.contains("Domain is tearing down")
+ }
+
+ /// Reads `launchctl print-disabled` lines. Recent launchd prints
+ /// `"com.apple.x" => disabled`; older builds print `=> true` / `=> false`.
+ static func parseDisabled(_ output: String) -> Set {
+ var set = Set()
+ for line in output.split(separator: "\n", omittingEmptySubsequences: false) {
+ guard let open = line.firstIndex(of: "\"") else { continue }
+ let rest = line[line.index(after: open)...]
+ guard let close = rest.firstIndex(of: "\"") else { continue }
+ let label = String(rest[..") else { continue }
+ let value = rest[arrow.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines)
+ if value.hasPrefix("disabled") || value.hasPrefix("true") { set.insert(label) }
+ }
+ return set
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Status.swift b/swift/Sources/SimSlimKit/Status.swift
new file mode 100644
index 0000000..d642fd3
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Status.swift
@@ -0,0 +1,100 @@
+import Foundation
+
+/// How slim a device currently is. The JSON keys are a contract with the app.
+public struct Status: Codable, Equatable, Sendable {
+ public var managedDisabled: Int // managed labels currently disabled
+ public var managedTotal: Int // size of the managed universe
+ public var booted: Bool
+ public var persistent: Bool // the runtime keeps disabled state across reboot
+
+ public init(managedDisabled: Int, managedTotal: Int, booted: Bool, persistent: Bool) {
+ self.managedDisabled = managedDisabled
+ self.managedTotal = managedTotal
+ self.booted = booted
+ self.persistent = persistent
+ }
+
+ /// The static fields of a device's status, before its launchd state is read.
+ public static func initial(for device: Device) -> Status {
+ Status(
+ managedDisabled: 0,
+ managedTotal: Profile().desired(for: device).count,
+ booted: device.state == "Booted",
+ persistent: device.supportsPersistentOverrides)
+ }
+
+ /// "stock", "partially slim" or "slim".
+ public var verdict: String {
+ if managedDisabled == managedTotal { return "slim" }
+ return managedDisabled > 0 ? "partially slim" : "stock"
+ }
+}
+
+extension Device {
+ var minimumPersistentVersion: String {
+ switch platformName {
+ case "watchOS": return "11.5"
+ case "visionOS": return "2.5"
+ default: return "18.5"
+ }
+ }
+
+ /// Applies the launchd persistence version gate to the device's platform.
+ /// tvOS 18.5, watchOS 11.5 and visionOS 2.5 are the release generation
+ /// corresponding to iOS 18.5. This gate is not proof of persistence: slimming
+ /// always reads overrides back after boot and fails if the runtime lost them.
+ public var supportsPersistentOverrides: Bool {
+ var minimumMajor = 18
+ switch platformName {
+ case "iOS", "tvOS": break
+ case "watchOS": minimumMajor = 11
+ case "visionOS": minimumMajor = 2
+ default: return false
+ }
+ let parts = osVersion.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false)
+ guard parts.count >= 2, let major = Int(parts[0]), let minor = Int(parts[1]), minor >= 0 else {
+ return false
+ }
+ return major > minimumMajor || (major == minimumMajor && minor >= 5)
+ }
+}
+
+/// The managed launchd labels a category has disabled on a simulator, alongside
+/// the feature that stops working as a result.
+public struct DroppedCategory: Codable, Equatable, Sendable {
+ public let id: String
+ public let name: String
+ public let downside: String
+ public let labels: [String]
+}
+
+extension Catalog {
+ /// Groups the disabled managed daemons by category, in category order,
+ /// omitting categories with nothing disabled.
+ public static func droppedCategories(disabled: Set) -> [DroppedCategory] {
+ categories.compactMap { category in
+ let labels = category.labels.filter { disabled.contains($0) }.sorted()
+ if labels.isEmpty { return nil }
+ return DroppedCategory(
+ id: category.id, name: category.name, downside: category.downside, labels: labels)
+ }
+ }
+}
+
+extension Simctl {
+ /// Reads a booted device's status and its disabled labels.
+ public func readStatus(for device: Device) throws -> (status: Status, disabled: Set) {
+ var status = Status.initial(for: device)
+ guard status.booted else {
+ throw SimSlimError("simulator must be booted to read its state (it is \(device.state))")
+ }
+ let managed = Profile().desired(for: device)
+ let disabled = try readDisabled(set: device.set, udid: device.udid)
+ status.managedDisabled = disabled.filter { managed.contains($0) }.count
+ return (status, disabled)
+ }
+
+ public func readStatus(udid: String) throws -> (status: Status, disabled: Set) {
+ try readStatus(for: try findDevice(udid: udid))
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Subprocess.swift b/swift/Sources/SimSlimKit/Subprocess.swift
index dc04869..44e7623 100644
--- a/swift/Sources/SimSlimKit/Subprocess.swift
+++ b/swift/Sources/SimSlimKit/Subprocess.swift
@@ -14,31 +14,70 @@ public enum Executable: String, CaseIterable, Sendable {
}
public struct CommandResult: Equatable, Sendable {
+ /// The exit status, or the negated signal number if the process was killed.
public var status: Int32
public var stdout: Data
public var stderr: Data
+ /// True when the runner killed the process for exceeding its timeout.
+ public var timedOut: Bool
- public init(status: Int32, stdout: Data = Data(), stderr: Data = Data()) {
+ public init(
+ status: Int32, stdout: Data = Data(), stderr: Data = Data(), timedOut: Bool = false
+ ) {
self.status = status
self.stdout = stdout
self.stderr = stderr
+ self.timedOut = timedOut
}
+ public var succeeded: Bool { status == 0 && !timedOut }
public var stdoutText: String { String(decoding: stdout, as: UTF8.self) }
public var stderrText: String { String(decoding: stderr, as: UTF8.self) }
+
+ /// stdout followed by stderr, trimmed: what Go's CombinedOutput would show.
+ public var combinedText: String {
+ (stdoutText + stderrText).trimmingCharacters(in: .whitespacesAndNewlines)
+ }
}
/// The seam tests use to replace real processes with a fake.
public protocol CommandRunning: Sendable {
- func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult
+ /// Runs `executable` and returns its result. A non-zero exit is a result, not
+ /// an error; only a failure to start the process throws. With a `timeout`
+ /// the process is killed when it expires and `timedOut` is set.
+ func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws
+ -> CommandResult
+}
+
+extension CommandRunning {
+ public func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult {
+ try run(executable, arguments, timeout: nil)
+ }
}
public struct SystemCommandRunner: CommandRunning {
- public init() {}
+ /// How long to keep reading a finished process's output pipes. When a timed-out
+ /// `xcrun` is killed, the `simctl` child it started can still hold the pipe;
+ /// without this bound the read would never return.
+ var waitDelay: TimeInterval
+ /// Maps an Executable to the path to start. Always the real path outside tests.
+ var resolve: @Sendable (Executable) -> String
- public func run(_ executable: Executable, _ arguments: [String]) throws -> CommandResult {
+ public init() {
+ self.init(waitDelay: 5, resolve: { $0.rawValue })
+ }
+
+ init(waitDelay: TimeInterval, resolve: @escaping @Sendable (Executable) -> String) {
+ self.waitDelay = waitDelay
+ self.resolve = resolve
+ }
+
+ public func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws
+ -> CommandResult
+ {
+ let path = resolve(executable)
let process = Process()
- process.executableURL = URL(fileURLWithPath: executable.rawValue)
+ process.executableURL = URL(fileURLWithPath: path)
process.arguments = arguments
process.standardInput = FileHandle.nullDevice
@@ -47,20 +86,108 @@ public struct SystemCommandRunner: CommandRunning {
process.standardOutput = out
process.standardError = err
- try process.run()
+ let outCollector = Collector(out)
+ let errCollector = Collector(err)
+ let exited = DispatchSemaphore(value: 0)
+ process.terminationHandler = { _ in exited.signal() }
+
+ do {
+ try process.run()
+ } catch {
+ outCollector.abandon()
+ errCollector.abandon()
+ throw SimSlimError("cannot run \(path): \(error.localizedDescription)")
+ }
+ // The child holds its own copies; ours must close or EOF never arrives.
+ try? out.fileHandleForWriting.close()
+ try? err.fileHandleForWriting.close()
+
+ let timeoutState = TimeoutState()
+ var killer: DispatchWorkItem?
+ if let timeout {
+ let pid = process.processIdentifier
+ let item = DispatchWorkItem {
+ if timeoutState.markTimedOut(ifRunning: process) { kill(pid, SIGKILL) }
+ }
+ killer = item
+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: item)
+ }
+
+ exited.wait()
+ killer?.cancel()
- // Drain both pipes while the child runs; waiting first can deadlock when
- // the child fills a pipe buffer.
- var errData = Data()
- let errDone = DispatchSemaphore(value: 0)
- DispatchQueue.global().async {
- errData = err.fileHandleForReading.readDataToEndOfFile()
- errDone.signal()
+ // After exit the pipes normally reach EOF at once. If a grandchild still
+ // holds one open, give it `waitDelay` and then stop waiting.
+ let deadline = DispatchTime.now() + waitDelay
+ let outDone = outCollector.waitForEOF(until: deadline)
+ let errDone = errCollector.waitForEOF(until: deadline)
+ if !outDone { outCollector.abandon() }
+ if !errDone { errCollector.abandon() }
+
+ var status = process.terminationStatus
+ if process.terminationReason == .uncaughtSignal { status = -status }
+ return CommandResult(
+ status: status, stdout: outCollector.data, stderr: errCollector.data,
+ timedOut: timeoutState.timedOut)
+ }
+}
+
+/// Reads a pipe through its readability handler so a pipe that never closes can
+/// be abandoned instead of blocking a thread forever.
+private final class Collector: @unchecked Sendable {
+ private let lock = NSLock()
+ private var buffer = Data()
+ private let eof = DispatchSemaphore(value: 0)
+ private let handle: FileHandle
+
+ init(_ pipe: Pipe) {
+ handle = pipe.fileHandleForReading
+ handle.readabilityHandler = { [weak self] h in
+ guard let self else { return }
+ let chunk = h.availableData
+ if chunk.isEmpty {
+ h.readabilityHandler = nil
+ self.eof.signal()
+ } else {
+ self.lock.lock()
+ self.buffer.append(chunk)
+ self.lock.unlock()
+ }
}
- let outData = out.fileHandleForReading.readDataToEndOfFile()
- errDone.wait()
- process.waitUntilExit()
+ }
+
+ var data: Data {
+ lock.lock()
+ defer { lock.unlock() }
+ return buffer
+ }
+
+ func waitForEOF(until deadline: DispatchTime) -> Bool {
+ eof.wait(timeout: deadline) == .success
+ }
+
+ func abandon() {
+ handle.readabilityHandler = nil
+ }
+}
+
+private final class TimeoutState: @unchecked Sendable {
+ private let lock = NSLock()
+ private var flag = false
+
+ var timedOut: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return flag
+ }
- return CommandResult(status: process.terminationStatus, stdout: outData, stderr: errData)
+ /// Records the timeout only if the process is still running, so a process
+ /// that exits just before the timer fires is not reported as timed out.
+ func markTimedOut(ifRunning process: Process) -> Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ guard process.isRunning else { return false }
+ flag = true
+ return true
}
}
diff --git a/swift/Sources/SimSlimKit/Verify.swift b/swift/Sources/SimSlimKit/Verify.swift
new file mode 100644
index 0000000..446cd77
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Verify.swift
@@ -0,0 +1,63 @@
+import Foundation
+
+/// How a booted simulator's launchd disable overrides compare to a profile's
+/// desired set. Only managed labels are considered.
+public struct VerifyResult: Codable, Equatable, Sendable {
+ public var udid: String
+ public var ok: Bool
+ public var missing: [String] // the profile wants these disabled; they are enabled
+ public var extra: [String] // managed labels disabled beyond the profile
+
+ public init(udid: String = "", ok: Bool, missing: [String], extra: [String]) {
+ self.udid = udid
+ self.ok = ok
+ self.missing = missing
+ self.extra = extra
+ }
+
+ private enum CodingKeys: String, CodingKey { case udid, ok, missing, extra }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(udid, forKey: .udid)
+ try c.encode(ok, forKey: .ok)
+ if !missing.isEmpty { try c.encode(missing, forKey: .missing) } // Go omitempty
+ if !extra.isEmpty { try c.encode(extra, forKey: .extra) }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ udid = try c.decode(String.self, forKey: .udid)
+ ok = try c.decode(Bool.self, forKey: .ok)
+ missing = try c.decodeIfPresent([String].self, forKey: .missing) ?? []
+ extra = try c.decodeIfPresent([String].self, forKey: .extra) ?? []
+ }
+}
+
+/// Diffs the currently disabled labels against the desired set, restricted to
+/// the managed universe: unmanaged labels are never simslim's business and
+/// never count as drift.
+public func compareDisabled(
+ disabled: Set, desired: Set, managed: Set
+) -> VerifyResult {
+ let missing = desired.filter { !disabled.contains($0) }.sorted()
+ let extra = disabled.filter { managed.contains($0) && !desired.contains($0) }.sorted()
+ return VerifyResult(ok: missing.isEmpty && extra.isEmpty, missing: missing, extra: extra)
+}
+
+extension Simctl {
+ /// Checks, without mutating anything, that a booted simulator's disable
+ /// overrides match the profile exactly. The overrides are per-simulator state
+ /// that is easy to lose silently when a device is erased or recreated.
+ public func verifyProfile(udid: String, profile: Profile) throws -> VerifyResult {
+ let device = try findDevice(udid: udid)
+ guard device.state == "Booted" else {
+ throw SimSlimError("simulator must be booted to read its state (it is \(device.state))")
+ }
+ let disabled = try readDisabled(set: device.set, udid: device.udid)
+ var result = compareDisabled(
+ disabled: disabled, desired: profile.desired(for: device), managed: Catalog.managedSet)
+ result.udid = udid
+ return result
+ }
+}
diff --git a/swift/Sources/simslim/main.swift b/swift/Sources/simslim/main.swift
index cd9fdb6..37b9679 100644
--- a/swift/Sources/simslim/main.swift
+++ b/swift/Sources/simslim/main.swift
@@ -1,13 +1,11 @@
import Foundation
-import SimSlimKit
+import SimSlimCLI
-// M0 scaffold: only --version works. Commands arrive with the later milestones.
-let arguments = Array(CommandLine.arguments.dropFirst())
-
-if arguments == ["--version"] || arguments == ["version"] {
- print("simslim \(simslimVersion)")
- exit(0)
+// Output goes through unbuffered writes so progress and results interleave
+// correctly when stdout and stderr are the same pipe.
+func write(_ handle: FileHandle) -> CLI.Sink {
+ { text in handle.write(Data(text.utf8)) }
}
-FileHandle.standardError.write(Data("simslim: the Swift port is not feature-complete yet\n".utf8))
-exit(2)
+let cli = CLI(stdout: write(.standardOutput), stderr: write(.standardError))
+exit(cli.run(Array(CommandLine.arguments.dropFirst())))
diff --git a/swift/Tests/SimSlimCLITests/ArgumentsTests.swift b/swift/Tests/SimSlimCLITests/ArgumentsTests.swift
new file mode 100644
index 0000000..90c1053
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/ArgumentsTests.swift
@@ -0,0 +1,128 @@
+import SimSlimKit
+import XCTest
+
+@testable import SimSlimCLI
+
+final class ArgumentsTests: XCTestCase {
+ private let specs: [FlagSpec] = [
+ .bool("json", onlyOnce: true), .bool("booted"), .string("except"), .string("set"),
+ ]
+
+ func testFlagsMayComeBeforeOrAfterPositionals() throws {
+ let a = try parseArguments(["udid", "--except", "search", "--json"], specs: specs)
+ let b = try parseArguments(["--json", "--except", "search", "udid"], specs: specs)
+ for parsed in [a, b] {
+ XCTAssertEqual(parsed.positionals, ["udid"])
+ XCTAssertEqual(parsed.string("except"), "search")
+ XCTAssertTrue(parsed.bool("json"))
+ }
+ }
+
+ func testFlagForms() throws {
+ let parsed = try parseArguments(["-json", "--except=a,b", "--set", "/x y"], specs: specs)
+ XCTAssertTrue(parsed.bool("json"))
+ XCTAssertEqual(parsed.string("except"), "a,b")
+ XCTAssertEqual(parsed.string("set"), "/x y")
+ }
+
+ func testEmptyInlineValueIsKeptNotDropped() throws {
+ let parsed = try parseArguments(["--except="], specs: specs)
+ XCTAssertTrue(parsed.has("except"))
+ XCTAssertEqual(parsed.string("except"), "")
+ }
+
+ func testBoolFlagNeverConsumesTheNextToken() throws {
+ let parsed = try parseArguments(["--booted", "udid"], specs: specs)
+ XCTAssertEqual(parsed.positionals, ["udid"])
+ XCTAssertTrue(parsed.bool("booted"))
+ }
+
+ func testBoolFlagValues() throws {
+ XCTAssertFalse(try parseArguments(["--booted=false"], specs: specs).bool("booted"))
+ XCTAssertTrue(try parseArguments(["--booted=true"], specs: specs).bool("booted"))
+ XCTAssertThrowsError(try parseArguments(["--booted=maybe"], specs: specs))
+ }
+
+ func testDoubleDashEndsFlagParsing() throws {
+ let parsed = try parseArguments(["--json", "--", "--except", "-x"], specs: specs)
+ XCTAssertEqual(parsed.positionals, ["--except", "-x"])
+ XCTAssertTrue(parsed.bool("json"))
+ XCTAssertFalse(parsed.has("except"))
+ }
+
+ func testLoneDashIsAPositional() throws {
+ XCTAssertEqual(try parseArguments(["-"], specs: specs).positionals, ["-"])
+ }
+
+ func testStringFlagConsumesTheNextTokenEvenIfItLooksLikeAFlag() throws {
+ XCTAssertEqual(
+ try parseArguments(["--except", "--json"], specs: specs).string("except"), "--json")
+ }
+
+ func testErrors() {
+ func message(_ tokens: [String]) -> String? {
+ do {
+ _ = try parseArguments(tokens, specs: specs)
+ return nil
+ } catch { return (error as? SimSlimError)?.message }
+ }
+ XCTAssertEqual(message(["--nope"]), "flag provided but not defined: -nope")
+ XCTAssertEqual(message(["--except"]), "flag needs an argument: --except")
+ XCTAssertEqual(message(["--json", "--json"]), "flag --json can only be used once")
+ XCTAssertNil(message(["--booted", "--booted"]), "only json is once-only")
+ }
+
+ func testLastStringValueWins() throws {
+ XCTAssertEqual(
+ try parseArguments(["--except", "a", "--except", "b"], specs: specs).string("except"), "b")
+ }
+}
+
+final class DurationTests: XCTestCase {
+ func testValidDurations() throws {
+ let cases: [(String, TimeInterval)] = [
+ ("10m", 600), ("90s", 90), ("1h", 3600), ("1h30m", 5400), ("1.5h", 5400), ("500ms", 0.5),
+ ("2m30s", 150), ("0", 0), ("+5s", 5), ("-5s", -5), ("1us", 1e-6), ("1µs", 1e-6),
+ ("1ns", 1e-9),
+ ]
+ for (text, seconds) in cases {
+ XCTAssertEqual(try parseGoDuration(text), seconds, accuracy: 1e-9, text)
+ }
+ }
+
+ func testInvalidDurations() {
+ for text in ["", "abc", "10", "10x", "m10", "1h 30m", ".", "--5s", "5s5"] {
+ XCTAssertThrowsError(try parseGoDuration(text), "\"\(text)\"")
+ }
+ XCTAssertThrowsError(try parseGoDuration("10")) { error in
+ XCTAssertEqual((error as? SimSlimError)?.message, "time: missing unit in duration \"10\"")
+ }
+ XCTAssertThrowsError(try parseGoDuration("10x")) { error in
+ XCTAssertEqual(
+ (error as? SimSlimError)?.message, "time: unknown unit \"x\" in duration \"10x\"")
+ }
+ }
+}
+
+final class FormatTests: XCTestCase {
+ func testPadRightCountsScalarsLikeGo() {
+ XCTAssertEqual(padRight("ab", 5), "ab ")
+ XCTAssertEqual(padRight("abcdef", 3), "abcdef", "never truncates")
+ XCTAssertEqual(padRight("é", 3), "é ")
+ }
+
+ func testTruncate() {
+ XCTAssertEqual(truncate("short", 22), "short")
+ XCTAssertEqual(truncate("abcdefghij", 5), "abcd…")
+ XCTAssertEqual(truncate("abcdefghij", 1), "…")
+ XCTAssertEqual(truncate("abcde", 5), "abcde")
+ }
+
+ func testHumanBytes() {
+ XCTAssertEqual(humanBytes(0), "0 B")
+ XCTAssertEqual(humanBytes(1023), "1023 B")
+ XCTAssertEqual(humanBytes(1024), "1 KB")
+ XCTAssertEqual(humanBytes(5 * 1_048_576), "5 MB")
+ XCTAssertEqual(humanBytes(1_610_612_736), "1.50 GB")
+ }
+}
diff --git a/swift/Tests/SimSlimCLITests/CommandTests.swift b/swift/Tests/SimSlimCLITests/CommandTests.swift
new file mode 100644
index 0000000..b1b887e
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/CommandTests.swift
@@ -0,0 +1,531 @@
+import SimSlimKit
+import TestSupport
+import XCTest
+
+@testable import SimSlimCLI
+
+final class DispatchTests: XCTestCase {
+ func testVersion() {
+ for arguments in [["version"], ["--version"], ["-v"]] {
+ let result = runCLI(arguments)
+ XCTAssertEqual(result.stdout, "simslim test-version\n")
+ XCTAssertEqual(result.status, 0)
+ }
+ }
+
+ func testHelpAndNoArguments() {
+ for arguments in [["help"], ["--help"], ["-h"]] {
+ let result = runCLI(arguments)
+ XCTAssertEqual(result.status, 0)
+ XCTAssertTrue(result.stdout.hasPrefix("simslim runs more iOS"))
+ }
+ let none = runCLI([])
+ XCTAssertEqual(none.status, 2)
+ XCTAssertTrue(none.stdout.hasPrefix("simslim runs more iOS"))
+ }
+
+ func testUnknownCommandPrintsUsageAndExitsTwo() {
+ let result = runCLI(["bogus"])
+ XCTAssertEqual(result.status, 2)
+ XCTAssertEqual(result.stderr, "unknown command \"bogus\"\n\n")
+ XCTAssertTrue(result.stdout.contains("COMMANDS"))
+ }
+
+ func testNotYetPortedCommandsSaySoAndTouchNothing() {
+ let host = standardHost()
+ for command in CLI.notYetPorted.sorted() {
+ let result = runCLI([command, bootedUDID], host: host)
+ XCTAssertEqual(result.status, 1, command)
+ XCTAssertEqual(
+ result.stderr,
+ "simslim: \"\(command)\" is not available in the Swift port yet; use the Go CLI for it\n")
+ XCTAssertEqual(result.stdout, "", command)
+ }
+ XCTAssertTrue(host.calls.isEmpty, "a command that is not ported must not run anything")
+ }
+
+ func testEveryUsageCommandIsEitherPortedOrMarked() {
+ // The help text and the dispatcher must agree about what exists.
+ let marked = usageText.split(separator: "\n").filter { $0.contains("†") }.count
+ // `repair-clone` is marked on a line of its own, so allow one fewer.
+ XCTAssertGreaterThanOrEqual(marked, CLI.notYetPorted.count - 1)
+ for command in CLI.commandSpecs.keys {
+ XCTAssertTrue(usageText.contains(" \(command)"), "\(command) is missing from the usage text")
+ }
+ }
+
+ func testGlobalOptionsMayPrecedeOrFollowTheCommand() {
+ let host = FakeHost(devices: [.init(udid: "A", name: "d")])
+ host.sets["/custom"] = [.init(udid: "C", name: "custom one")]
+ for arguments in [
+ ["--set", "/custom", "list"], ["list", "--set", "/custom"], ["list", "--set=/custom"],
+ ] {
+ let result = runCLI(arguments, host: host)
+ XCTAssertEqual(result.status, 0, "\(arguments)")
+ XCTAssertTrue(result.stdout.contains("custom one"), "\(arguments)")
+ XCTAssertTrue(result.stdout.contains("(/custom)"), "the set is shown for non-default sets")
+ }
+ }
+
+ func testSetNeedsAValue() {
+ for arguments in [["list", "--set"], ["list", "--set", ""], ["list", "--set", " , "]] {
+ let result = runCLI(arguments)
+ XCTAssertEqual(
+ result.stderr, "simslim: --set requires a device set name (such as `testing`) or a path\n",
+ "\(arguments)")
+ XCTAssertEqual(result.status, 1)
+ }
+ }
+
+ func testTimeoutOptions() {
+ let host = standardHost()
+ _ = runCLI(["status", bootedUDID, "--spawn-timeout", "5m"], host: host)
+ XCTAssertEqual(host.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 300)
+
+ let envHost = standardHost()
+ _ = runCLI(
+ ["status", bootedUDID], host: envHost, environment: ["SIMSLIM_SPAWN_TIMEOUT": "90s"])
+ XCTAssertEqual(envHost.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 90)
+
+ let defaultHost = standardHost()
+ _ = runCLI(["status", bootedUDID], host: defaultHost)
+ XCTAssertEqual(defaultHost.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 120)
+
+ let flagWins = standardHost()
+ _ = runCLI(
+ ["status", bootedUDID, "--spawn-timeout", "10s"], host: flagWins,
+ environment: ["SIMSLIM_SPAWN_TIMEOUT": "90s"])
+ XCTAssertEqual(flagWins.calls.last { $0.arguments.contains("print-disabled") }?.timeout, 10)
+ }
+
+ func testInvalidTimeouts() {
+ var result = runCLI(["profiles", "--boot-timeout", "0"])
+ XCTAssertEqual(
+ result.stderr, "simslim: --boot-timeout must be a positive duration (such as `15m`)\n")
+ result = runCLI(["profiles", "--spawn-timeout", "-1m"])
+ XCTAssertEqual(
+ result.stderr, "simslim: --spawn-timeout must be a positive duration (such as `2m`)\n")
+ result = runCLI(["profiles", "--boot-timeout", "soon"])
+ XCTAssertEqual(
+ result.stderr,
+ "simslim: invalid value \"soon\" for flag -boot-timeout: time: invalid duration \"soon\"\n")
+ result = runCLI(["profiles"], environment: ["SIMSLIM_BOOT_TIMEOUT": "nope"])
+ XCTAssertEqual(result.status, 1, "a bad environment value is an error too")
+ }
+
+ func testUnknownFlagAndArgumentCountErrors() {
+ XCTAssertEqual(
+ runCLI(["list", "--nope"]).stderr, "simslim: flag provided but not defined: -nope\n")
+ XCTAssertEqual(runCLI(["list", "x"]).stderr, "simslim: list takes no arguments\n")
+ XCTAssertEqual(
+ runCLI(["status"]).stderr,
+ "simslim: expected exactly one simulator UDID (see `simslim list`)\n")
+ XCTAssertEqual(
+ runCLI(["status", "a", "b"]).stderr,
+ "simslim: expected exactly one simulator UDID (see `simslim list`)\n")
+ XCTAssertEqual(
+ runCLI(["profiles", "a", "b"]).stderr,
+ "simslim: profiles takes at most one category ID (see `simslim profiles`)\n")
+ }
+}
+
+final class ListCommandTests: XCTestCase {
+ func testHumanOutputIsSortedAndShowsSlimStatus() {
+ let result = runCLI(["list"], host: standardHost())
+ XCTAssertEqual(result.status, 0)
+ let lines = result.stdout.split(separator: "\n").map(String.init)
+ XCTAssertEqual(lines.count, 3)
+ // iOS first, newest version first: 27.2 (iPad Air, iPhone 17 by name) then 18.4.
+ XCTAssertEqual(
+ lines[0], "\(shutdownUDID) \(padRight("iPad Air", 22)) \(padRight("iOS 27.2", 14)) shutdown")
+ XCTAssertEqual(
+ lines[1],
+ "\(bootedUDID) \(padRight("iPhone 17", 22)) \(padRight("iOS 27.2", 14)) booted · 100/173 slim"
+ )
+ XCTAssertEqual(
+ lines[2],
+ "\(oldUDID) \(padRight("iPhone 16", 22)) \(padRight("iOS 18.4", 14)) booted · 0/173 slim")
+ }
+
+ func testBootedFilter() {
+ let result = runCLI(["list", "--booted"], host: standardHost())
+ XCTAssertEqual(result.stdout.split(separator: "\n").count, 2)
+ XCTAssertFalse(result.stdout.contains(shutdownUDID))
+ }
+
+ func testShutdownDevicesAreNeverSpawnedInto() {
+ let host = standardHost()
+ _ = runCLI(["list"], host: host)
+ let spawned = host.calls.filter { $0.arguments.contains("spawn") }.compactMap {
+ $0.arguments[safe: 2]
+ }
+ XCTAssertFalse(spawned.contains(shutdownUDID))
+ XCTAssertEqual(Set(spawned), [bootedUDID, oldUDID])
+ }
+
+ func testLongNamesAreTruncatedInHumanOutput() {
+ let host = FakeHost(devices: [.init(udid: "A", name: String(repeating: "x", count: 40))])
+ let result = runCLI(["list"], host: host)
+ XCTAssertTrue(result.stdout.contains(String(repeating: "x", count: 21) + "…"))
+ XCTAssertFalse(result.stdout.contains(String(repeating: "x", count: 22)))
+ }
+
+ func testAStatusFailureDoesNotFailTheListing() throws {
+ let host = standardHost()
+ host.queueSpawnResults(
+ udid: bootedUDID,
+ Array(repeating: CommandResult(status: 2, stderr: Data("denied".utf8)), count: 1))
+ let human = runCLI(["list"], host: host)
+ XCTAssertEqual(human.status, 0)
+ XCTAssertTrue(
+ human.stdout.contains("\(padRight("iOS 27.2", 14)) booted\n"),
+ "tag falls back to plain booted")
+
+ let jsonHost = standardHost()
+ jsonHost.queueSpawnResults(
+ udid: bootedUDID, [CommandResult(status: 2, stderr: Data("denied".utf8))])
+ let json = runCLI(["list", "--json"], host: jsonHost)
+ let rows = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(json.stdout.utf8)) as? [[String: Any]])
+ let row = try XCTUnwrap(rows.first { $0["udid"] as? String == bootedUDID })
+ XCTAssertTrue((row["statusError"] as? String ?? "").contains("denied"))
+ XCTAssertNil(row["managedDisabled"])
+ }
+
+ func testJSONShape() throws {
+ let result = runCLI(["list", "--json"], host: standardHost())
+ XCTAssertEqual(result.status, 0)
+ XCTAssertTrue(result.stdout.hasSuffix("\n"))
+ let rows = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [[String: Any]])
+ XCTAssertEqual(rows.count, 3)
+
+ let booted = try XCTUnwrap(rows.first { $0["udid"] as? String == bootedUDID })
+ XCTAssertEqual(booted["managedDisabled"] as? Int, 100)
+ XCTAssertEqual(booted["managedTotal"] as? Int, 173)
+ XCTAssertEqual(booted["platform"] as? String, "iOS")
+ XCTAssertEqual(booted["osVersion"] as? String, "27.2")
+ XCTAssertEqual(booted["set"] as? String, "default")
+ let memory = try XCTUnwrap(booted["memory"] as? [String: Any])
+ XCTAssertEqual(memory["processes"] as? Int, 2)
+ XCTAssertEqual(memory["bytes"] as? Int, 30 * 1_048_576)
+ XCTAssertNil(booted["dataPath"], "internal fields never leak")
+ XCTAssertNil(booted["runtimeID"])
+
+ let shutdown = try XCTUnwrap(rows.first { $0["udid"] as? String == shutdownUDID })
+ XCTAssertNil(shutdown["managedDisabled"], "unknown while shut down")
+ XCTAssertNil(shutdown["memory"])
+ XCTAssertEqual(shutdown["managedTotal"] as? Int, 173)
+ }
+
+ func testJSONOfAnEmptyListIsAnEmptyArray() {
+ XCTAssertEqual(runCLI(["list", "--json"], host: FakeHost()).stdout, "[\n\n]\n")
+ }
+
+ func testJSONMeasuresAllBootedDevicesWithOneSnapshot() {
+ let host = standardHost()
+ _ = runCLI(["list", "--json"], host: host)
+ XCTAssertEqual(host.calls.filter { $0.executable == .ps }.count, 1)
+ XCTAssertEqual(host.calls.filter { $0.executable == .top }.count, 1)
+ }
+
+ func testHumanListDoesNotMeasureMemory() {
+ let host = standardHost()
+ _ = runCLI(["list"], host: host)
+ XCTAssertFalse(host.calls.contains { $0.executable == .ps || $0.executable == .top })
+ }
+
+ func testListFailureIsReported() {
+ let host = FakeHost()
+ host.listFailure = "CoreSimulator is down"
+ let result = runCLI(["list"], host: host)
+ XCTAssertEqual(result.status, 1)
+ XCTAssertEqual(result.stderr, "simslim: simctl list: exit status 1: CoreSimulator is down\n")
+ }
+}
+
+final class ProfilesCommandTests: XCTestCase {
+ func testOverview() {
+ let result = runCLI(["profiles"])
+ XCTAssertEqual(result.status, 0)
+ XCTAssertTrue(result.stdout.hasPrefix("widgets Widgets & Wallpaper\n"))
+ XCTAssertTrue(
+ result.stdout.contains(" 4 daemons · ~675 MB idle footprint when enabled\n"))
+ XCTAssertTrue(
+ result.stdout.contains(
+ " Always on: com.apple.assistantd — Hosts the dictation service; without it the system Spotlight app leaks memory.\n"
+ ))
+ XCTAssertTrue(
+ result.stdout.contains(
+ "\n173 daemons across 16 categories. Core workflow and deadlock-prone daemons are never disabled.\n"
+ ))
+ }
+
+ func testOneCategory() {
+ let result = runCLI(["profiles", "search"])
+ XCTAssertEqual(result.status, 0)
+ XCTAssertTrue(result.stdout.contains("search Spotlight & Search\n"))
+ XCTAssertTrue(
+ result.stdout.contains(" 5 daemons · ~50 MB idle footprint when enabled\n"))
+ XCTAssertTrue(result.stdout.contains("\nDaemons:\n"))
+ XCTAssertTrue(result.stdout.contains(" \(padRight("com.apple.searchd", 44)) "))
+ }
+
+ func testAlwaysEnabledLinesAppearInACategoryListing() {
+ XCTAssertTrue(
+ runCLI(["profiles", "siri"]).stdout.contains(
+ " \(padRight("com.apple.assistantd", 44)) Always on — Hosts the dictation service"))
+ }
+
+ func testUnknownCategory() {
+ let result = runCLI(["profiles", "nope"])
+ XCTAssertEqual(result.status, 1)
+ XCTAssertEqual(result.stderr, "simslim: unknown category \"nope\" (see `simslim profiles`)\n")
+ }
+
+ func testJSON() throws {
+ let all = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(runCLI(["profiles", "--json"]).stdout.utf8))
+ as? [[String: Any]])
+ XCTAssertEqual(all.count, 16)
+ XCTAssertEqual(all.compactMap { $0["id"] as? String }.first, "widgets")
+
+ let one = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(runCLI(["profiles", "siri", "--json"]).stdout.utf8))
+ as? [String: Any])
+ XCTAssertEqual(one["id"] as? String, "siri")
+ XCTAssertNotNil(one["alwaysEnabled"])
+ }
+}
+
+final class StatusCommandTests: XCTestCase {
+ func testHumanStatus() {
+ let result = runCLI(["status", bootedUDID], host: standardHost())
+ XCTAssertEqual(result.status, 0)
+ XCTAssertEqual(
+ result.stdout, "\(bootedUDID): 100/173 managed launchd labels disabled (partially slim)\n")
+ }
+
+ func testStockStatus() {
+ let result = runCLI(["status", oldUDID], host: standardHost())
+ XCTAssertEqual(result.stdout, "\(oldUDID): 0/173 managed launchd labels disabled (stock)\n")
+ }
+
+ func testSlimStatusOnANonPersistentRuntimeWarns() {
+ let host = standardHost()
+ host.disabled[oldUDID] = Profile().desired() // iOS 18.4 cannot persist overrides
+ let result = runCLI(["status", oldUDID], host: host)
+ XCTAssertTrue(result.stdout.contains("(slim)\n"))
+ XCTAssertTrue(
+ result.stdout.contains(
+ " This runtime cannot persist launchd overrides: the state reverts to stock at the next reboot.\n"
+ ))
+ }
+
+ func testStatusOfAShutdownSimulatorFails() {
+ let result = runCLI(["status", shutdownUDID], host: standardHost())
+ XCTAssertEqual(result.status, 1)
+ XCTAssertEqual(
+ result.stderr, "simslim: simulator must be booted to read its state (it is Shutdown)\n")
+ }
+
+ func testUnknownUDID() {
+ let result = runCLI(["status", "nope"], host: standardHost())
+ XCTAssertEqual(result.stderr, "simslim: no simulator with udid nope\n")
+ }
+
+ func testDropped() {
+ let host = standardHost()
+ host.disabled[bootedUDID] = ["com.apple.searchd", "com.apple.PosterBoard"]
+ let result = runCLI(["status", bootedUDID, "--dropped"], host: host)
+ XCTAssertTrue(
+ result.stdout.contains(" widgets Widgets & Wallpaper — Home and Lock Screen widgets"))
+ XCTAssertTrue(result.stdout.contains(" com.apple.PosterBoard\n"))
+ XCTAssertTrue(result.stdout.contains(" search Spotlight & Search — "))
+
+ host.disabled[bootedUDID] = []
+ XCTAssertTrue(
+ runCLI(["status", bootedUDID, "--dropped"], host: host).stdout.contains(
+ " Nothing dropped; every managed launchd label is enabled.\n"))
+ }
+
+ func testJSON() throws {
+ let result = runCLI(["status", bootedUDID, "--json"], host: standardHost())
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any])
+ XCTAssertEqual(
+ Set(object.keys), ["managedDisabled", "managedTotal", "booted", "persistent", "verdict"])
+ XCTAssertEqual(object["verdict"] as? String, "partially slim")
+ XCTAssertEqual(object["managedDisabled"] as? Int, 100)
+
+ let dropped = runCLI(["status", bootedUDID, "--json", "--dropped"], host: standardHost())
+ let withDropped = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(dropped.stdout.utf8)) as? [String: Any])
+ XCTAssertNotNil(withDropped["dropped"])
+ }
+}
+
+final class VerifyCommandTests: XCTestCase {
+ private func host(disabled: Set) -> FakeHost {
+ let host = standardHost()
+ host.disabled[bootedUDID] = disabled
+ return host
+ }
+
+ func testMatchExitsZero() {
+ let result = runCLI(["verify", bootedUDID], host: host(disabled: Profile().desired()))
+ XCTAssertEqual(result.status, 0)
+ XCTAssertEqual(
+ result.stdout,
+ "\(bootedUDID) matches the profile: all expected disable overrides are applied.\n")
+ }
+
+ func testDriftExitsOneAndListsIt() {
+ var disabled = Profile().desired()
+ disabled.remove("com.apple.apsd")
+ disabled.insert("com.apple.sharingd") // managed, disabled beyond the profile
+ disabled.insert("com.apple.unmanaged") // never drift
+ let result = runCLI(["verify", bootedUDID], host: host(disabled: disabled))
+ XCTAssertEqual(result.status, 1)
+ XCTAssertEqual(result.stderr, "")
+ XCTAssertTrue(
+ result.stdout.hasPrefix("\(bootedUDID) does not match the profile (1 missing, 1 extra):\n"))
+ XCTAssertTrue(
+ result.stdout.contains(" missing com.apple.apsd (should be disabled, is enabled)\n"))
+ XCTAssertTrue(
+ result.stdout.contains(" extra com.apple.sharingd (disabled beyond the profile)\n"))
+ XCTAssertFalse(result.stdout.contains("unmanaged"))
+ XCTAssertTrue(result.stdout.hasSuffix("Re-run `simslim on` with the same profile to repair.\n"))
+ }
+
+ func testExceptAndKeepFlagsDefineTheProfile() {
+ let profile = Profile(exceptCategories: ["search"], keep: ["com.apple.apsd"])
+ let ok = runCLI(
+ ["verify", bootedUDID, "--except", "search", "--keep", "com.apple.apsd"],
+ host: host(disabled: profile.desired()))
+ XCTAssertEqual(ok.status, 0)
+
+ // The same device no longer matches the default (full) profile.
+ XCTAssertEqual(
+ runCLI(["verify", bootedUDID], host: host(disabled: profile.desired())).status, 1)
+ }
+
+ func testProfileFileCannotBeCombinedWithFlags() {
+ let result = runCLI(
+ ["verify", bootedUDID, "--profile", "x.json", "--except", "search"], host: standardHost())
+ XCTAssertEqual(result.stderr, "simslim: --profile cannot be combined with --except or --keep\n")
+ XCTAssertEqual(result.status, 1)
+ }
+
+ func testUnknownCategoryIsRejectedBeforeAnythingRuns() {
+ let host = standardHost()
+ let result = runCLI(["verify", bootedUDID, "--except", "nope"], host: host)
+ XCTAssertEqual(result.status, 1)
+ XCTAssertTrue(result.stderr.contains("unknown category \"nope\""))
+ XCTAssertTrue(host.calls.isEmpty || !host.calls.contains { $0.arguments.contains("spawn") })
+ }
+
+ func testJSON() throws {
+ var disabled = Profile().desired()
+ disabled.remove("com.apple.apsd")
+ let result = runCLI(["verify", bootedUDID, "--json"], host: host(disabled: disabled))
+ XCTAssertEqual(result.status, 1, "JSON output still signals drift through the exit status")
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any])
+ XCTAssertEqual(object["ok"] as? Bool, false)
+ XCTAssertEqual(object["missing"] as? [String], ["com.apple.apsd"])
+ XCTAssertNil(object["extra"])
+ }
+}
+
+final class DoctorCommandTests: XCTestCase {
+ func testList() {
+ let result = runCLI(["doctor", "--list"])
+ XCTAssertEqual(result.status, 0)
+ XCTAssertTrue(
+ result.stdout.hasPrefix(
+ "\(padRight("push", 16)) \(padRight("Push notifications", 38)) com.apple.apsd\n"))
+ XCTAssertEqual(result.stdout.split(separator: "\n").count, Catalog.features.count)
+ XCTAssertEqual(
+ runCLI(["doctor", "--list", "x"]).stderr, "simslim: doctor --list takes no arguments\n")
+ }
+
+ func testRequiresIsMandatory() {
+ let result = runCLI(["doctor", bootedUDID], host: standardHost())
+ XCTAssertEqual(
+ result.stderr,
+ "simslim: doctor needs at least one feature via --requires (see `simslim doctor --list`)\n")
+ XCTAssertEqual(result.status, 1)
+ }
+
+ func testUnknownFeatureFailsLoudly() {
+ let result = runCLI(["doctor", bootedUDID, "--requires", "push,nope"], host: standardHost())
+ XCTAssertEqual(
+ result.stderr, "simslim: unknown feature \"nope\" (see `simslim doctor --list`)\n")
+ }
+
+ func testHealthyAndBroken() {
+ let healthy = standardHost()
+ healthy.disabled[bootedUDID] = []
+ let ok = runCLI(["doctor", bootedUDID, "--requires", "push,storekit"], host: healthy)
+ XCTAssertEqual(ok.status, 0)
+ XCTAssertEqual(
+ ok.stdout, "\(bootedUDID): 2/2 required features OK\n ok push\n ok storekit\n")
+
+ let broken = standardHost()
+ broken.disabled[bootedUDID] = ["com.apple.storekitd", "com.apple.passd"]
+ let bad = runCLI(["doctor", bootedUDID, "--requires", "push,storekit"], host: broken)
+ XCTAssertEqual(bad.status, 1)
+ XCTAssertTrue(bad.stdout.hasPrefix("\(bootedUDID): 1/2 required features OK\n ok push\n"))
+ XCTAssertTrue(
+ bad.stdout.contains(" BROKEN storekit — com.apple.storekitd, com.apple.passd disabled\n"))
+ }
+
+ func testAFullSlimProfileBreaksPushWhichIsWhyDoctorExists() {
+ let host = standardHost()
+ host.disabled[bootedUDID] = Profile().desired()
+ XCTAssertEqual(runCLI(["doctor", bootedUDID, "--requires", "push"], host: host).status, 1)
+ host.disabled[bootedUDID] = Profile(exceptCategories: ["store"]).desired()
+ XCTAssertEqual(runCLI(["doctor", bootedUDID, "--requires", "push"], host: host).status, 0)
+ }
+
+ func testJSON() throws {
+ let host = standardHost()
+ host.disabled[bootedUDID] = ["com.apple.apsd"]
+ let result = runCLI(["doctor", bootedUDID, "--requires", "push", "--json"], host: host)
+ XCTAssertEqual(result.status, 1)
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any])
+ XCTAssertEqual(object["udid"] as? String, bootedUDID)
+ XCTAssertEqual(object["ok"] as? Bool, false)
+ }
+}
+
+final class MeasureCommandTests: XCTestCase {
+ func testHuman() {
+ let result = runCLI(["measure", bootedUDID], host: standardHost())
+ XCTAssertEqual(result.status, 0)
+ XCTAssertEqual(
+ result.stdout, "\(bootedUDID): 2 processes, 30 MB memory footprint (phys_footprint)\n")
+ }
+
+ func testJSON() throws {
+ let result = runCLI(["measure", bootedUDID, "--json"], host: standardHost())
+ let object = try XCTUnwrap(
+ JSONSerialization.jsonObject(with: Data(result.stdout.utf8)) as? [String: Any])
+ XCTAssertEqual(object["processes"] as? Int, 2)
+ XCTAssertEqual(object["bytes"] as? Int, 30 * 1_048_576)
+ XCTAssertEqual(object["cpu"] as? Double, 3.0)
+ }
+
+ func testNotBooted() {
+ let result = runCLI(["measure", shutdownUDID], host: standardHost())
+ XCTAssertEqual(result.status, 1)
+ XCTAssertEqual(
+ result.stderr, "simslim: simulator \(shutdownUDID) does not appear to be booted\n")
+ }
+}
+
+extension Array {
+ fileprivate subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }
+}
diff --git a/swift/Tests/SimSlimCLITests/GUIContract/Models.swift b/swift/Tests/SimSlimCLITests/GUIContract/Models.swift
new file mode 120000
index 0000000..1d09b67
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/GUIContract/Models.swift
@@ -0,0 +1 @@
+../../../../gui/Models.swift
\ No newline at end of file
diff --git a/swift/Tests/SimSlimCLITests/GUIContractTests.swift b/swift/Tests/SimSlimCLITests/GUIContractTests.swift
new file mode 100644
index 0000000..55ccecf
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/GUIContractTests.swift
@@ -0,0 +1,73 @@
+import SimSlimKit
+import TestSupport
+import XCTest
+
+@testable import SimSlimCLI
+
+/// `Models.swift` is the macOS app's own file (symlinked from gui/). Decoding the
+/// Swift CLI's JSON with those exact types is the contract check: if an output
+/// field is renamed, dropped or retyped, this fails instead of the app at runtime.
+final class GUIContractTests: XCTestCase {
+ private func decode(
+ _ type: T.Type, _ arguments: [String], host: FakeHostFactory = .standard
+ ) throws -> T {
+ let result = runCLI(arguments, host: host.make())
+ XCTAssertEqual(result.status, 0, result.stderr)
+ return try JSONDecoder().decode(type, from: Data(result.stdout.utf8))
+ }
+
+ func testListDecodesAsTheAppsSimulatorDevice() throws {
+ let devices = try decode([SimulatorDevice].self, ["list", "--json"])
+ XCTAssertEqual(devices.count, 3)
+
+ let booted = try XCTUnwrap(devices.first { $0.udid == bootedUDID })
+ XCTAssertTrue(booted.isBooted)
+ XCTAssertEqual(booted.name, "iPhone 17")
+ XCTAssertEqual(booted.runtimeName, "iOS 27.2")
+ XCTAssertEqual(booted.managedDisabled, 100)
+ XCTAssertEqual(booted.managedTotal, 173)
+ XCTAssertEqual(booted.memory?.processes, 2)
+ XCTAssertEqual(booted.memory?.bytes, 30 * 1_048_576)
+ XCTAssertNil(booted.statusError)
+
+ let shutdown = try XCTUnwrap(devices.first { $0.udid == shutdownUDID })
+ XCTAssertFalse(shutdown.isBooted)
+ XCTAssertNil(shutdown.managedDisabled)
+ XCTAssertNil(shutdown.memory)
+ }
+
+ func testProfilesDecodeAsTheAppsSlimCategory() throws {
+ let categories = try decode([SlimCategory].self, ["profiles", "--json"])
+ XCTAssertEqual(categories.count, 16)
+ for category in categories {
+ XCTAssertFalse(category.labels.isEmpty, category.id)
+ XCTAssertGreaterThan(category.approxMemoryMB, 0, category.id)
+ for label in category.labels {
+ XCTAssertNotEqual(
+ category.serviceDescription(for: label), "Apple background service.",
+ "\(category.id): \(label) has no description, so the app would show its placeholder")
+ }
+ }
+ let siri = try XCTUnwrap(categories.first { $0.id == "siri" })
+ XCTAssertEqual(siri.alwaysEnabledServices.map(\.label), ["com.apple.assistantd"])
+ XCTAssertEqual(categories.first { $0.id == "search" }?.alwaysEnabledServices.count, 0)
+ }
+
+ func testOneCategoryDecodes() throws {
+ let category = try decode(SlimCategory.self, ["profiles", "apps", "--json"])
+ XCTAssertEqual(category.id, "apps")
+ XCTAssertEqual(category.alwaysEnabledServices.first?.label, "com.apple.gamed")
+ }
+
+ func testMeasureDecodesAsTheAppsMeasurement() throws {
+ let measurement = try decode(SimulatorMeasurement.self, ["measure", bootedUDID, "--json"])
+ XCTAssertEqual(measurement.processes, 2)
+ XCTAssertEqual(measurement.bytes, 30 * 1_048_576)
+ }
+}
+
+/// Builds a fresh standard host per call (FakeHost is stateful).
+struct FakeHostFactory {
+ var make: () -> FakeHost
+ static let standard = FakeHostFactory(make: standardHost)
+}
diff --git a/swift/Tests/SimSlimCLITests/Support.swift b/swift/Tests/SimSlimCLITests/Support.swift
new file mode 100644
index 0000000..2200df9
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/Support.swift
@@ -0,0 +1,66 @@
+import Foundation
+import SimSlimKit
+import TestSupport
+
+@testable import SimSlimCLI
+
+struct CLIResult {
+ var status: Int32
+ var stdout: String
+ var stderr: String
+}
+
+private final class Buffer: @unchecked Sendable {
+ private let lock = NSLock()
+ private var text = ""
+ func append(_ s: String) {
+ lock.lock()
+ text += s
+ lock.unlock()
+ }
+ var value: String {
+ lock.lock()
+ defer { lock.unlock() }
+ return text
+ }
+}
+
+/// Runs the CLI against a fake host, capturing both streams.
+func runCLI(
+ _ arguments: [String], host: FakeHost = FakeHost(), environment: [String: String] = [:]
+) -> CLIResult {
+ let out = Buffer()
+ let err = Buffer()
+ let cli = CLI(
+ version: "test-version", environment: environment, runner: host,
+ stdout: { out.append($0) }, stderr: { err.append($0) })
+ let status = cli.run(arguments)
+ return CLIResult(status: status, stdout: out.value, stderr: err.value)
+}
+
+let bootedUDID = "11111111-1111-1111-1111-111111111111"
+let shutdownUDID = "22222222-2222-2222-2222-222222222222"
+let oldUDID = "33333333-3333-3333-3333-333333333333"
+
+/// A host with a booted iOS 27.2 iPhone, a shut-down iPad, and a booted iOS 18.4
+/// iPhone, all partly slimmed.
+func standardHost() -> FakeHost {
+ let host = FakeHost(devices: [
+ .init(udid: shutdownUDID, name: "iPad Air", state: "Shutdown"),
+ .init(udid: bootedUDID, name: "iPhone 17", state: "Booted"),
+ .init(
+ udid: oldUDID, name: "iPhone 16",
+ runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-4", state: "Booted"),
+ ])
+ host.disabled[bootedUDID] = Set(Profile().desired().sorted().prefix(100))
+ host.disabled[oldUDID] = []
+ host.launchdPIDs = [bootedUDID: 200, oldUDID: 300]
+ host.psOutput = """
+ PID PPID %CPU COMM
+ 200 1 1.0 /x/launchd_sim
+ 201 200 2.0 /x/SpringBoard
+ 300 1 4.0 /x/launchd_sim
+ """
+ host.topOutput = "PID MEM\n200 10M\n201 20M\n300 1G\n"
+ return host
+}
diff --git a/swift/Tests/SimSlimKitTests/SimctlTests.swift b/swift/Tests/SimSlimKitTests/SimctlTests.swift
new file mode 100644
index 0000000..ac6166d
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/SimctlTests.swift
@@ -0,0 +1,291 @@
+import TestSupport
+import XCTest
+
+@testable import SimSlimKit
+
+final class SimctlTests: XCTestCase {
+ private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2"
+ private let tvos = "com.apple.CoreSimulator.SimRuntime.tvOS-27-2"
+ private let xros = "com.apple.CoreSimulator.SimRuntime.xrOS-27-2"
+
+ // MARK: - parseRuntime
+
+ func testParseRuntime() {
+ let cases: [(String, String?, String?)] = [
+ ("com.apple.CoreSimulator.SimRuntime.iOS-27-2", "iOS", "27.2"),
+ ("com.apple.CoreSimulator.SimRuntime.iOS-18-5", "iOS", "18.5"),
+ ("com.apple.CoreSimulator.SimRuntime.tvOS-26-5", "tvOS", "26.5"),
+ ("com.apple.CoreSimulator.SimRuntime.watchOS-11-5", "watchOS", "11.5"),
+ ("com.apple.CoreSimulator.SimRuntime.xrOS-2-5", "visionOS", "2.5"),
+ ("com.apple.CoreSimulator.SimRuntime.iOS-17-0-1", "iOS", "17.0.1"),
+ ("com.apple.CoreSimulator.SimRuntime.macOS-15-0", nil, nil),
+ ("com.apple.CoreSimulator.SimRuntime.iOS", nil, nil),
+ ("com.apple.CoreSimulator.SimRuntime.iOS-", nil, nil),
+ ("something.else.iOS-27-2", nil, nil),
+ ("", nil, nil),
+ ]
+ for (runtime, platform, version) in cases {
+ let parsed = Simctl.parseRuntime(runtime)
+ XCTAssertEqual(parsed?.platform, platform, runtime)
+ XCTAssertEqual(parsed?.version, version, runtime)
+ }
+ }
+
+ // MARK: - parseDisabled
+
+ func testParseDisabled() {
+ let output = """
+ disabled services = {
+ \t"com.apple.a" => disabled
+ \t"com.apple.b" => enabled
+ \t"com.apple.c" => true
+ \t"com.apple.d" => false
+ \t"com.apple.e"=>disabled
+ \tno quotes => disabled
+ \t"unterminated => disabled
+ \t"com.apple.f" disabled
+ }
+ """
+ XCTAssertEqual(Simctl.parseDisabled(output), ["com.apple.a", "com.apple.c", "com.apple.e"])
+ XCTAssertEqual(Simctl.parseDisabled(""), [])
+ }
+
+ // MARK: - listing
+
+ func testListDevicesFiltersAndMapsFields() throws {
+ let host = FakeHost(devices: [
+ .init(udid: "A", name: "iPhone", state: "Booted"),
+ .init(udid: "B", name: "iPad"),
+ .init(udid: "C", name: "Gone", isAvailable: false),
+ .init(udid: "D", name: "TV", runtime: tvos),
+ .init(udid: "E", name: "Vision", runtime: xros),
+ .init(udid: "F", name: "Mac", runtime: "com.apple.CoreSimulator.SimRuntime.macOS-15-0"),
+ ])
+ let devices = try Simctl(runner: host).listDevices()
+ XCTAssertEqual(
+ Set(devices.map(\.udid)), ["A", "B", "D", "E"], "unavailable and unsupported dropped")
+
+ let iphone = try XCTUnwrap(devices.first { $0.udid == "A" })
+ XCTAssertEqual(iphone.name, "iPhone")
+ XCTAssertEqual(iphone.state, "Booted")
+ XCTAssertEqual(iphone.platform, "iOS")
+ XCTAssertEqual(iphone.osVersion, "27.2")
+ XCTAssertEqual(iphone.set, "default")
+ XCTAssertEqual(iphone.runtimeID, ios)
+ XCTAssertEqual(iphone.dataPath, "/fake/A/data")
+ XCTAssertEqual(devices.first { $0.udid == "E" }?.platform, "visionOS")
+ }
+
+ func testListDevicesTreatsMissingIsAvailableAsUnavailable() throws {
+ // Like the Go tool: an entry without isAvailable is not listed.
+ final class Raw: CommandRunning, @unchecked Sendable {
+ func run(_ e: Executable, _ a: [String], timeout: TimeInterval?) throws -> CommandResult {
+ let json =
+ #"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-2":[{"udid":"X","name":"n","state":"Shutdown"}]}}"#
+ return CommandResult(status: 0, stdout: Data(json.utf8))
+ }
+ }
+ XCTAssertTrue(try Simctl(runner: Raw()).listDevices().isEmpty)
+ }
+
+ func testDefaultSetFailureIsFatalWithStderrAndHint() {
+ let host = FakeHost()
+ host.listFailure =
+ "xcrun: error: unable to find utility \"simctl\", not a developer tool or in PATH"
+ XCTAssertThrowsError(try Simctl(runner: host).listDevices()) { error in
+ let message = (error as? SimSlimError)?.message ?? ""
+ XCTAssertTrue(message.hasPrefix("simctl list: exit status 1: xcrun: error"), message)
+ XCTAssertTrue(
+ message.contains("select one with `sudo xcode-select -s /Applications/Xcode.app`"), message)
+ }
+ host.listFailure = "boom"
+ XCTAssertThrowsError(try Simctl(runner: host).listDevices()) { error in
+ XCTAssertEqual((error as? SimSlimError)?.message, "simctl list: exit status 1: boom")
+ }
+ }
+
+ func testSecondarySetThatCannotBeListedIsSkipped() throws {
+ let host = FakeHost(devices: [.init(udid: "A", name: "default one")])
+ var simctl = Simctl(runner: host)
+ simctl.registerDeviceSet("/no/such/set")
+ let devices = try simctl.listDevices()
+ XCTAssertEqual(devices.map(\.udid), ["A"])
+ }
+
+ func testExtraAndTestingSetsAreScanned() throws {
+ let host = FakeHost(devices: [.init(udid: "A", name: "d")])
+ host.sets["testing"] = [.init(udid: "T", name: "clone")]
+ host.sets["/custom"] = [.init(udid: "C", name: "custom")]
+ var simctl = Simctl(runner: host)
+ simctl.registerDeviceSet("/custom")
+ let devices = try simctl.listDevices()
+ XCTAssertEqual(Set(devices.map(\.udid)), ["A", "T", "C"])
+ XCTAssertEqual(devices.first { $0.udid == "T" }?.set, "testing")
+ XCTAssertEqual(devices.first { $0.udid == "C" }?.set, "/custom")
+ }
+
+ func testRegisterDeviceSetIgnoresDuplicatesAndKnownTokens() {
+ var simctl = Simctl(runner: FakeHost())
+ simctl.registerDeviceSet("testing")
+ simctl.registerDeviceSet("/x")
+ simctl.registerDeviceSet("/x")
+ XCTAssertEqual(simctl.extraSets, ["/x"])
+ XCTAssertEqual(simctl.knownSets.map(\.token), ["", "testing", "/x"])
+ }
+
+ func testSimctlArgsPutSetBeforeTheSubcommand() {
+ var simctl = Simctl(runner: FakeHost())
+ simctl.registerDeviceSet("/x")
+ XCTAssertEqual(simctl.simctlArgs(set: "default", ["list"]), ["simctl", "list"])
+ XCTAssertEqual(
+ simctl.simctlArgs(set: "testing", ["list"]), ["simctl", "--set", "testing", "list"])
+ XCTAssertEqual(simctl.simctlArgs(set: "/x", ["list"]), ["simctl", "--set", "/x", "list"])
+ XCTAssertEqual(simctl.simctlArgs(set: "unknown", ["list"]), ["simctl", "list"])
+ }
+
+ func testFindDevice() throws {
+ let host = FakeHost(devices: [.init(udid: "A", name: "d")])
+ host.sets["testing"] = [.init(udid: "T", name: "clone")]
+ let simctl = Simctl(runner: host)
+ XCTAssertEqual(try simctl.findDevice(udid: "A").set, "default")
+ XCTAssertEqual(try simctl.findDevice(udid: "T").set, "testing")
+ XCTAssertThrowsError(try simctl.findDevice(udid: "nope")) { error in
+ XCTAssertEqual((error as? SimSlimError)?.message, "no simulator with udid nope")
+ }
+ // A named set looks only there.
+ XCTAssertThrowsError(try simctl.findDevice(udid: "A", set: "testing"))
+ XCTAssertEqual(try simctl.findDevice(udid: "T", set: "testing").udid, "T")
+ }
+
+ func testFindDeviceNeverMatchesAnAlias() {
+ // `simctl` accepts aliases like "all" and "booted"; a lookup by UDID must not.
+ let host = FakeHost(devices: [.init(udid: "A", name: "d", state: "Booted")])
+ for alias in ["all", "booted", "available", ""] {
+ XCTAssertThrowsError(try Simctl(runner: host).findDevice(udid: alias), alias)
+ }
+ }
+
+ // MARK: - reading launchd, with retries
+
+ private func settling() -> CommandResult {
+ CommandResult(status: 124, stderr: Data("launchctl: Domain is tearing down".utf8))
+ }
+
+ private func slept(_ simctl: inout Simctl) -> SleepLog {
+ let log = SleepLog()
+ simctl.sleep = { log.record($0) }
+ return log
+ }
+
+ func testReadDisabledPassesTheSpawnTimeoutAndArguments() throws {
+ let host = FakeHost()
+ host.disabled["U"] = ["com.apple.apsd"]
+ var simctl = Simctl(runner: host)
+ simctl.spawnTimeout = 77
+ XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"])
+ let call = try XCTUnwrap(host.calls.last)
+ XCTAssertEqual(
+ call.arguments, ["simctl", "spawn", "U", "launchctl", "print-disabled", "system"])
+ XCTAssertEqual(call.timeout, 77)
+ }
+
+ func testReadLaunchdRetriesErrorOneTwentyFourWithBackoff() throws {
+ let host = FakeHost()
+ host.disabled["U"] = ["com.apple.apsd"]
+ host.queueSpawnResults(udid: "U", [settling(), settling()])
+ var simctl = Simctl(runner: host)
+ let log = slept(&simctl)
+ XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"])
+ XCTAssertEqual(log.values, [1, 2], "waits the first two retry delays")
+ XCTAssertEqual(host.calls.count, 3)
+ }
+
+ func testReadLaunchdRecognizesSettlingByTextToo() throws {
+ let host = FakeHost()
+ host.disabled["U"] = []
+ host.queueSpawnResults(
+ udid: "U", [CommandResult(status: 1, stderr: Data("xpc error code=124".utf8))])
+ var simctl = Simctl(runner: host)
+ _ = slept(&simctl)
+ XCTAssertNoThrow(try simctl.readDisabled(set: "default", udid: "U"))
+ XCTAssertEqual(host.calls.count, 2)
+ }
+
+ func testReadLaunchdGivesUpAfterTheLastDelay() {
+ let host = FakeHost()
+ host.disabled["U"] = []
+ host.queueSpawnResults(udid: "U", Array(repeating: settling(), count: 10))
+ var simctl = Simctl(runner: host)
+ let log = slept(&simctl)
+ XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U")) { error in
+ let message = (error as? SimSlimError)?.message ?? ""
+ XCTAssertTrue(message.hasPrefix("launchctl print-disabled: exit status 124:"), message)
+ XCTAssertTrue(message.contains("Domain is tearing down"), message)
+ }
+ XCTAssertEqual(log.values, [1, 2, 4, 8])
+ XCTAssertEqual(host.calls.count, 5, "the first attempt plus one per delay")
+ }
+
+ func testReadLaunchdDoesNotRetryOtherFailures() {
+ let host = FakeHost()
+ host.disabled["U"] = []
+ host.queueSpawnResults(
+ udid: "U", [CommandResult(status: 2, stderr: Data("permission denied".utf8))])
+ var simctl = Simctl(runner: host)
+ let log = slept(&simctl)
+ XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U"))
+ XCTAssertEqual(log.values, [])
+ XCTAssertEqual(host.calls.count, 1)
+ }
+
+ func testReadLaunchdRetriesATimedOutAttempt() throws {
+ let host = FakeHost()
+ host.disabled["U"] = ["com.apple.apsd"]
+ host.queueSpawnResults(udid: "U", [CommandResult(status: -9, timedOut: true)])
+ var simctl = Simctl(runner: host)
+ let log = slept(&simctl)
+ XCTAssertEqual(try simctl.readDisabled(set: "default", udid: "U"), ["com.apple.apsd"])
+ XCTAssertEqual(log.values, [1])
+ }
+
+ func testTimedOutErrorMessageSaysSo() {
+ let host = FakeHost()
+ host.queueSpawnResults(
+ udid: "U", Array(repeating: CommandResult(status: -9, timedOut: true), count: 5))
+ var simctl = Simctl(runner: host)
+ simctl.spawnTimeout = 90
+ _ = slept(&simctl)
+ XCTAssertThrowsError(try simctl.readDisabled(set: "default", udid: "U")) { error in
+ XCTAssertTrue(
+ ((error as? SimSlimError)?.message ?? "").hasPrefix(
+ "launchctl print-disabled: timed out after 90s"))
+ }
+ }
+
+ func testReadLaunchdOnANonDefaultSetTargetsIt() throws {
+ let host = FakeHost()
+ host.disabled["U"] = []
+ var simctl = Simctl(runner: host)
+ simctl.registerDeviceSet("testing")
+ _ = try simctl.readDisabled(set: "testing", udid: "U")
+ XCTAssertEqual(
+ host.calls.last?.arguments,
+ ["simctl", "--set", "testing", "spawn", "U", "launchctl", "print-disabled", "system"])
+ }
+}
+
+/// Records the pauses a retry loop asked for, without actually sleeping.
+final class SleepLog: @unchecked Sendable {
+ private let lock = NSLock()
+ private var _values: [TimeInterval] = []
+ func record(_ value: TimeInterval) {
+ lock.lock()
+ _values.append(value)
+ lock.unlock()
+ }
+ var values: [TimeInterval] {
+ lock.lock()
+ defer { lock.unlock() }
+ return _values
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
new file mode 100644
index 0000000..10ff7b7
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
@@ -0,0 +1,261 @@
+import TestSupport
+import XCTest
+
+@testable import SimSlimKit
+
+final class StatusTests: XCTestCase {
+ func testSupportsPersistentOverrides() {
+ let cases: [(String, String, Bool)] = [
+ ("iOS", "18.5", true), ("iOS", "18.4", false), ("iOS", "18.3", false),
+ ("iOS", "19.0", true), ("iOS", "27.2", true), ("iOS", "17.9", false),
+ ("iOS", "18", false), ("iOS", "", false), ("iOS", "x.y", false), ("iOS", "18.5.1", true),
+ ("", "18.5", true), // empty platform defaults to iOS
+ ("tvOS", "18.5", true), ("tvOS", "18.4", false),
+ ("watchOS", "11.5", true), ("watchOS", "11.4", false), ("watchOS", "12.0", true),
+ ("watchOS", "18.5", true),
+ ("visionOS", "2.5", true), ("visionOS", "2.4", false), ("visionOS", "3.0", true),
+ ("macOS", "99.9", false),
+ ]
+ for (platform, version, expected) in cases {
+ let device = Device(udid: "U", platform: platform, osVersion: version)
+ XCTAssertEqual(
+ device.supportsPersistentOverrides, expected, "\(platform) \(version)")
+ }
+ }
+
+ func testMinimumPersistentVersionMatchesTheGate() {
+ XCTAssertEqual(Device(udid: "U", platform: "watchOS").minimumPersistentVersion, "11.5")
+ XCTAssertEqual(Device(udid: "U", platform: "visionOS").minimumPersistentVersion, "2.5")
+ XCTAssertEqual(Device(udid: "U", platform: "iOS").minimumPersistentVersion, "18.5")
+ XCTAssertEqual(Device(udid: "U", platform: "tvOS").minimumPersistentVersion, "18.5")
+ }
+
+ func testVerdict() {
+ func verdict(_ disabled: Int, _ total: Int) -> String {
+ Status(managedDisabled: disabled, managedTotal: total, booted: true, persistent: true).verdict
+ }
+ XCTAssertEqual(verdict(0, 173), "stock")
+ XCTAssertEqual(verdict(1, 173), "partially slim")
+ XCTAssertEqual(verdict(172, 173), "partially slim")
+ XCTAssertEqual(verdict(173, 173), "slim")
+ }
+
+ func testInitialStatusUsesThePlatformSpecificTotal() {
+ let ios = Status.initial(
+ for: Device(udid: "U", state: "Booted", platform: "iOS", osVersion: "27.2"))
+ let watch = Status.initial(for: Device(udid: "U", platform: "watchOS", osVersion: "11.5"))
+ XCTAssertEqual(ios.managedTotal, 173)
+ XCTAssertEqual(watch.managedTotal, 172, "homed stays enabled on watchOS")
+ XCTAssertTrue(ios.booted)
+ XCTAssertFalse(watch.booted)
+ XCTAssertTrue(ios.persistent)
+ }
+
+ func testReadStatusCountsOnlyManagedLabels() throws {
+ let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Booted")])
+ host.disabled["U"] = [
+ "com.apple.apsd", // managed
+ "com.apple.searchd", // managed
+ "com.apple.sharingd", // managed (always-enabled): a legacy disable counts as managed
+ "com.apple.nanoregistryd", // forbidden and unmanaged
+ "com.apple.not-ours",
+ ]
+ let (status, disabled) = try Simctl(runner: host).readStatus(udid: "U")
+ XCTAssertEqual(status.managedDisabled, 2, "only labels in the full slim set count")
+ XCTAssertEqual(disabled.count, 5, "the raw disabled set is returned unfiltered")
+ }
+
+ func testReadStatusRequiresABootedDevice() {
+ let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Shutdown")])
+ XCTAssertThrowsError(try Simctl(runner: host).readStatus(udid: "U")) { error in
+ XCTAssertEqual(
+ (error as? SimSlimError)?.message,
+ "simulator must be booted to read its state (it is Shutdown)")
+ }
+ XCTAssertFalse(
+ host.calls.contains { $0.arguments.contains("spawn") }, "no spawn into a shutdown device")
+ }
+
+ func testDroppedCategoriesAreGroupedInCategoryOrder() {
+ let dropped = Catalog.droppedCategories(disabled: [
+ "com.apple.searchd", "com.apple.PosterBoard", "com.apple.chronod", "com.apple.not-ours",
+ ])
+ XCTAssertEqual(dropped.map(\.id), ["widgets", "search"], "category order, not label order")
+ XCTAssertEqual(dropped[0].labels, ["com.apple.PosterBoard", "com.apple.chronod"])
+ XCTAssertEqual(Catalog.droppedCategories(disabled: []), [])
+ XCTAssertEqual(Catalog.droppedCategories(disabled: ["com.apple.not-ours"]), [])
+ }
+}
+
+final class VerifyTests: XCTestCase {
+ func testCompareDisabled() {
+ let managed: Set = ["a", "b", "c", "d"]
+ let result = compareDisabled(
+ disabled: ["a", "d", "zzz"], desired: ["a", "b"], managed: managed)
+ XCTAssertFalse(result.ok)
+ XCTAssertEqual(result.missing, ["b"])
+ XCTAssertEqual(result.extra, ["d"], "unmanaged 'zzz' never counts as drift")
+
+ let match = compareDisabled(
+ disabled: ["a", "b", "zzz"], desired: ["a", "b"], managed: managed)
+ XCTAssertTrue(match.ok)
+ XCTAssertTrue(match.missing.isEmpty && match.extra.isEmpty)
+ }
+
+ func testVerifyAgainstTheFullProfile() throws {
+ let host = FakeHost(devices: [.init(udid: "U", name: "n", state: "Booted")])
+ host.disabled["U"] = Profile().desired()
+ let simctl = Simctl(runner: host)
+ let ok = try simctl.verifyProfile(udid: "U", profile: Profile())
+ XCTAssertTrue(ok.ok)
+ XCTAssertEqual(ok.udid, "U")
+
+ host.disabled["U"] = Profile().desired().subtracting(["com.apple.apsd"])
+ let drift = try simctl.verifyProfile(udid: "U", profile: Profile())
+ XCTAssertFalse(drift.ok)
+ XCTAssertEqual(drift.missing, ["com.apple.apsd"])
+ }
+
+ func testVerifyUsesThePlatformSpecificDesiredSet() throws {
+ // On watchOS homed must stay enabled, so a device that is slim except for homed matches.
+ let watch = "com.apple.CoreSimulator.SimRuntime.watchOS-11-5"
+ let host = FakeHost(devices: [.init(udid: "W", name: "w", runtime: watch, state: "Booted")])
+ host.disabled["W"] = Profile().desired().subtracting(["com.apple.homed"])
+ XCTAssertTrue(try Simctl(runner: host).verifyProfile(udid: "W", profile: Profile()).ok)
+ }
+
+ func testVerifyRequiresBooted() {
+ let host = FakeHost(devices: [.init(udid: "U", name: "n")])
+ XCTAssertThrowsError(try Simctl(runner: host).verifyProfile(udid: "U", profile: Profile()))
+ }
+
+ func testVerifyResultOmitsEmptyLists() throws {
+ let data = try JSONEncoder().encode(VerifyResult(udid: "U", ok: true, missing: [], extra: []))
+ let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ XCTAssertEqual(Set(object.keys), ["udid", "ok"])
+ }
+}
+
+final class MeasureTests: XCTestCase {
+ func testParseBytes() {
+ let cases: [(String, Int64)] = [
+ ("45M", 45 * 1_048_576), ("45M+", 45 * 1_048_576), ("45M-", 45 * 1_048_576),
+ ("1.5G", 1_610_612_736), ("900K", 900 * 1024), ("12B", 12), ("12", 12), ("0", 0),
+ ("", 0), ("+", 0), ("abc", 0), ("1.5.2M", 0),
+ ]
+ for (text, expected) in cases {
+ XCTAssertEqual(Simctl.parseBytes(text), expected, "parseBytes(\"\(text)\")")
+ }
+ }
+
+ func testParseTopMemory() {
+ let output = """
+ Processes: 400 total, 3 running
+ Load Avg: 1.0, 1.0, 1.0
+ PID MEM
+ 101 45M
+ 102 1.5G+
+ 103 900K-
+ 104 12B
+ abc 5M
+ 105 notasize
+ 7
+ """
+ XCTAssertEqual(
+ Simctl.parseTopMemory(output),
+ [101: 45 * 1_048_576, 102: 1_610_612_736, 103: 900 * 1024, 104: 12])
+ }
+
+ func testParsePSKeepsParentLinksCPUAndBasename() {
+ let output = """
+ PID PPID %CPU COMM
+ 1 0 0.0 /sbin/launchd
+ 200 1 1.5 /Library/Developer/CoreSimulator/Volumes/iOS 27.2/launchd_sim
+ 201 200 12.5 /Applications/Xcode.app/Contents/Developer/SpringBoard
+ 202 200 0.0 backboardd
+ garbage line
+ """
+ let snapshot = Simctl.parsePS(output)
+ XCTAssertEqual(snapshot.children[200], [201, 202])
+ XCTAssertEqual(snapshot.cpu[201], 12.5)
+ XCTAssertEqual(snapshot.comm[200], "launchd_sim", "spaces in the path are tolerated")
+ XCTAssertEqual(snapshot.comm[201], "SpringBoard")
+ XCTAssertEqual(snapshot.comm[202], "backboardd")
+ XCTAssertNil(snapshot.comm[0])
+ }
+
+ func testTreePIDsCoversTheWholeTreeOnlyAndSurvivesCycles() {
+ let children = [1: [2, 3], 2: [4], 3: [], 9: [10], 4: [2]] // 4 -> 2 is a cycle
+ XCTAssertEqual(Simctl.treePIDs(root: 1, children: children), [1, 2, 3, 4])
+ XCTAssertEqual(Simctl.treePIDs(root: 9, children: children), [9, 10])
+ XCTAssertEqual(Simctl.treePIDs(root: 77, children: children), [77])
+ }
+
+ private func host() -> FakeHost {
+ let host = FakeHost()
+ host.launchdPIDs = ["AAAA": 200, "BBBB": 300]
+ host.psOutput = """
+ PID PPID %CPU COMM
+ 200 1 1.0 /x/launchd_sim
+ 201 200 2.0 /x/SpringBoard
+ 300 1 4.0 /x/launchd_sim
+ 301 300 0.5 /x/backboardd
+ 999 1 50.0 /x/unrelated
+ """
+ host.topOutput = """
+ PID MEM
+ 200 10M
+ 201 20M
+ 300 1G
+ 301 5M
+ 999 100M
+ """
+ return host
+ }
+
+ func testMeasureSumsOnlyThatSimulatorsTree() throws {
+ let measurement = try Simctl(runner: host()).measure(udid: "AAAA")
+ XCTAssertEqual(measurement.processes, 2)
+ XCTAssertEqual(measurement.bytes, 30 * 1_048_576)
+ XCTAssertEqual(measurement.cpu, 3.0, accuracy: 0.0001)
+ }
+
+ func testMeasureManyTakesOneSnapshotAndReportsPerDeviceErrors() {
+ let fake = host()
+ let (measurements, errors) = Simctl(runner: fake).measureMany(udids: ["AAAA", "BBBB", "CCCC"])
+ XCTAssertEqual(measurements["AAAA"]?.bytes, 30 * 1_048_576)
+ XCTAssertEqual(measurements["BBBB"]?.bytes, 1_073_741_824 + 5 * 1_048_576)
+ XCTAssertNil(measurements["CCCC"])
+ XCTAssertEqual(errors["CCCC"], "simulator CCCC does not appear to be booted")
+ XCTAssertEqual(fake.calls.filter { $0.executable == .ps }.count, 1, "one ps for every device")
+ XCTAssertEqual(fake.calls.filter { $0.executable == .top }.count, 1, "one top for every device")
+ }
+
+ func testMeasureManyWithNothingBootedSpawnsNoPsOrTop() {
+ let fake = FakeHost()
+ let (measurements, errors) = Simctl(runner: fake).measureMany(udids: ["X"])
+ XCTAssertTrue(measurements.isEmpty)
+ XCTAssertEqual(errors.count, 1)
+ XCTAssertFalse(fake.calls.contains { $0.executable == .ps || $0.executable == .top })
+ }
+
+ func testMeasureOfANotBootedSimulatorFails() {
+ XCTAssertThrowsError(try Simctl(runner: FakeHost()).measure(udid: "X")) { error in
+ XCTAssertEqual(
+ (error as? SimSlimError)?.message, "simulator X does not appear to be booted")
+ }
+ }
+
+ func testPgrepMatchesTheBootstrapPath() throws {
+ let fake = host()
+ _ = try Simctl(runner: fake).measure(udid: "AAAA")
+ let pgrep = try XCTUnwrap(fake.calls.first { $0.executable == .pgrep })
+ XCTAssertEqual(pgrep.arguments, ["-f", "AAAA/data/var/run/launchd_bootstrap"])
+ }
+
+ func testMemoryMeasurementJSONKeys() throws {
+ let data = try JSONEncoder().encode(MemoryMeasurement(processes: 2, bytes: 3, cpu: 1.5))
+ let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ XCTAssertEqual(Set(object.keys), ["processes", "bytes", "cpu"])
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift b/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift
new file mode 100644
index 0000000..79e7376
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/SubprocessRunnerTests.swift
@@ -0,0 +1,76 @@
+import XCTest
+
+@testable import SimSlimKit
+
+/// Behavior of the real process runner, using harmless system tools mapped over
+/// the closed Executable list (only possible from tests, via `resolve`).
+final class SubprocessRunnerTests: XCTestCase {
+ private func runner(
+ _ path: String, waitDelay: TimeInterval = 5
+ ) -> SystemCommandRunner {
+ SystemCommandRunner(waitDelay: waitDelay, resolve: { _ in path })
+ }
+
+ func testCapturesStdoutStderrAndStatusSeparately() throws {
+ let result = try runner("/bin/sh").run(
+ .xcrun, ["-c", "echo out; echo err 1>&2; exit 3"])
+ XCTAssertEqual(result.status, 3)
+ XCTAssertEqual(result.stdoutText, "out\n")
+ XCTAssertEqual(result.stderrText, "err\n")
+ XCTAssertEqual(result.combinedText, "out\nerr")
+ XCTAssertFalse(result.timedOut)
+ XCTAssertFalse(result.succeeded)
+ }
+
+ func testLargeOutputDoesNotDeadlock() throws {
+ // Far more than a pipe buffer on both streams.
+ let script =
+ "head -c 3000000 /dev/zero | tr '\\0' a; head -c 3000000 /dev/zero | tr '\\0' b 1>&2"
+ let result = try runner("/bin/sh").run(.xcrun, ["-c", script], timeout: 30)
+ XCTAssertEqual(result.stdout.count, 3_000_000)
+ XCTAssertEqual(result.stderr.count, 3_000_000)
+ XCTAssertTrue(result.succeeded)
+ }
+
+ func testTimeoutKillsTheProcess() throws {
+ let start = Date()
+ let result = try runner("/bin/sleep").run(.xcrun, ["30"], timeout: 0.3)
+ XCTAssertTrue(result.timedOut)
+ XCTAssertFalse(result.succeeded)
+ XCTAssertLessThan(Date().timeIntervalSince(start), 5, "the runner waited for the sleep")
+ XCTAssertLessThan(result.status, 0, "a killed process reports the negated signal")
+ }
+
+ func testFastProcessIsNotReportedAsTimedOut() throws {
+ let result = try runner("/bin/sh").run(.xcrun, ["-c", "exit 0"], timeout: 30)
+ XCTAssertTrue(result.succeeded)
+ XCTAssertFalse(result.timedOut)
+ }
+
+ func testPipeHeldOpenByGrandchildIsAbandonedAfterWaitDelay() throws {
+ // The shell exits at once but its background child keeps stdout open for 5s,
+ // like the simctl child a killed xcrun leaves behind. Without the wait delay
+ // this call would block for those 5s.
+ let start = Date()
+ let result = try runner("/bin/sh", waitDelay: 0.4).run(
+ .xcrun, ["-c", "sleep 5 & echo out"], timeout: 30)
+ XCTAssertEqual(result.stdoutText, "out\n")
+ XCTAssertTrue(result.succeeded)
+ XCTAssertLessThan(Date().timeIntervalSince(start), 3)
+ }
+
+ func testMissingExecutableThrowsAReadableError() {
+ XCTAssertThrowsError(try runner("/nonexistent/simslim-tool").run(.xcrun, [])) { error in
+ XCTAssertTrue(
+ (error as? SimSlimError)?.message.hasPrefix("cannot run /nonexistent/simslim-tool") == true,
+ "\(error)")
+ }
+ }
+
+ func testStdinIsClosed() throws {
+ // A child that reads stdin must see EOF immediately, not hang on our terminal.
+ let result = try runner("/bin/cat").run(.xcrun, [], timeout: 10)
+ XCTAssertTrue(result.succeeded)
+ XCTAssertTrue(result.stdout.isEmpty)
+ }
+}
diff --git a/swift/Tests/TestSupport/FakeHost.swift b/swift/Tests/TestSupport/FakeHost.swift
new file mode 100644
index 0000000..eb41a50
--- /dev/null
+++ b/swift/Tests/TestSupport/FakeHost.swift
@@ -0,0 +1,158 @@
+import Foundation
+import SimSlimKit
+
+/// A simulated host for tests: it answers the `xcrun simctl`, `pgrep`, `ps` and
+/// `top` calls simslim makes, from data the test provides, and records every
+/// call. No real process is ever started.
+public final class FakeHost: CommandRunning, @unchecked Sendable {
+ public struct FakeDevice {
+ public var udid: String
+ public var name: String
+ public var runtime: String
+ public var state: String
+ public var isAvailable: Bool
+
+ public init(
+ udid: String, name: String, runtime: String = "com.apple.CoreSimulator.SimRuntime.iOS-27-2",
+ state: String = "Shutdown", isAvailable: Bool = true
+ ) {
+ self.udid = udid
+ self.name = name
+ self.runtime = runtime
+ self.state = state
+ self.isAvailable = isAvailable
+ }
+ }
+
+ public struct Call: Equatable {
+ public var executable: Executable
+ public var arguments: [String]
+ public var timeout: TimeInterval?
+ }
+
+ private let lock = NSLock()
+ private var _calls: [Call] = []
+ private var spawnQueues: [String: [CommandResult]] = [:]
+
+ /// Devices in the default set.
+ public var devices: [FakeDevice]
+ /// Devices per extra set token (for example "testing"); a set absent here
+ /// fails to list, like a set that does not exist.
+ public var sets: [String: [FakeDevice]] = [:]
+ /// `launchctl print-disabled` state per UDID, as `label => disabled` lines.
+ public var disabled: [String: Set] = [:]
+ /// pid of each booted simulator's launchd, as pgrep reports it.
+ public var launchdPIDs: [String: Int] = [:]
+ public var psOutput = ""
+ public var topOutput = ""
+ /// When set, `simctl list` for the default set fails with this stderr.
+ public var listFailure: String?
+
+ public init(devices: [FakeDevice] = []) {
+ self.devices = devices
+ }
+
+ public var calls: [Call] {
+ lock.lock()
+ defer { lock.unlock() }
+ return _calls
+ }
+
+ /// Queues results returned, in order, by the next `print-disabled` spawns for a
+ /// UDID before the normal answer resumes: used to simulate launchd error 124.
+ public func queueSpawnResults(udid: String, _ results: [CommandResult]) {
+ lock.lock()
+ spawnQueues[udid, default: []].append(contentsOf: results)
+ lock.unlock()
+ }
+
+ public func run(_ executable: Executable, _ arguments: [String], timeout: TimeInterval?) throws
+ -> CommandResult
+ {
+ lock.lock()
+ _calls.append(Call(executable: executable, arguments: arguments, timeout: timeout))
+ lock.unlock()
+
+ switch executable {
+ case .xcrun: return xcrun(arguments)
+ case .pgrep: return pgrep(arguments)
+ case .ps: return CommandResult(status: 0, stdout: Data(psOutput.utf8))
+ case .top: return CommandResult(status: 0, stdout: Data(topOutput.utf8))
+ default:
+ return CommandResult(status: 127, stderr: Data("FakeHost: unexpected \(executable)".utf8))
+ }
+ }
+
+ // MARK: - Answers
+
+ private func xcrun(_ args: [String]) -> CommandResult {
+ guard args.first == "simctl" else { return failure("unexpected xcrun \(args)") }
+ var rest = Array(args.dropFirst())
+ var token = ""
+ if rest.first == "--set", rest.count >= 2 {
+ token = rest[1]
+ rest = Array(rest.dropFirst(2))
+ }
+
+ if rest == ["list", "devices", "-j"] { return list(token: token) }
+ if rest.count == 5, rest[0] == "spawn", rest[2] == "launchctl", rest[3] == "print-disabled",
+ rest[4] == "system"
+ {
+ return printDisabled(udid: rest[1])
+ }
+ return failure("FakeHost: unhandled simctl \(rest)")
+ }
+
+ private func list(token: String) -> CommandResult {
+ let source: [FakeDevice]
+ if token.isEmpty {
+ if let listFailure { return CommandResult(status: 1, stderr: Data(listFailure.utf8)) }
+ source = devices
+ } else if let set = sets[token] {
+ source = set
+ } else {
+ return CommandResult(status: 1, stderr: Data("Invalid device set: \(token)".utf8))
+ }
+
+ var byRuntime: [String: [[String: Any]]] = [:]
+ for device in source {
+ byRuntime[device.runtime, default: []].append([
+ "udid": device.udid, "name": device.name, "state": device.state,
+ "isAvailable": device.isAvailable, "dataPath": "/fake/\(device.udid)/data",
+ ])
+ }
+ let data = try! JSONSerialization.data(withJSONObject: ["devices": byRuntime])
+ return CommandResult(status: 0, stdout: data)
+ }
+
+ private func printDisabled(udid: String) -> CommandResult {
+ lock.lock()
+ if var queue = spawnQueues[udid], !queue.isEmpty {
+ let next = queue.removeFirst()
+ spawnQueues[udid] = queue
+ lock.unlock()
+ return next
+ }
+ lock.unlock()
+
+ guard let labels = disabled[udid] else {
+ return CommandResult(status: 1, stderr: Data("Unable to find device \(udid)".utf8))
+ }
+ var text = "disabled services = {\n"
+ for label in labels.sorted() { text += "\t\"\(label)\" => disabled\n" }
+ text += "\t\"com.apple.some.enabled.service\" => enabled\n}\n"
+ return CommandResult(status: 0, stdout: Data(text.utf8))
+ }
+
+ private func pgrep(_ args: [String]) -> CommandResult {
+ guard args.count == 2, args[0] == "-f" else { return failure("unexpected pgrep \(args)") }
+ for (udid, pid) in launchdPIDs where args[1].hasPrefix(udid) {
+ return CommandResult(status: 0, stdout: Data("\(pid)\n".utf8))
+ }
+ return CommandResult(status: 1)
+ }
+
+ private func failure(_ message: String) -> CommandResult {
+ CommandResult(status: 99, stderr: Data(message.utf8))
+ }
+}
From 733b4b4364e20ca7b7ff34ce13b79cf74302ea2f Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:44:12 -0700
Subject: [PATCH 03/32] fix(swift): parseBytes no longer traps on out-of-range
sizes
Int64(Double) crashes on overflow and NaN. Sizes such as 1e30 now parse
to 0, like any other unparseable size.
---
swift/Sources/SimSlimKit/Measure.swift | 3 ++-
swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift | 2 +-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/swift/Sources/SimSlimKit/Measure.swift b/swift/Sources/SimSlimKit/Measure.swift
index e27fa09..dbaa2a2 100644
--- a/swift/Sources/SimSlimKit/Measure.swift
+++ b/swift/Sources/SimSlimKit/Measure.swift
@@ -182,7 +182,8 @@ extension Simctl {
default: break
}
guard let value = Double(s) else { return 0 }
- return Int64(value * multiplier)
+ // Int64(_:) traps on overflow and NaN; an unparseable size is 0.
+ return Int64(exactly: (value * multiplier).rounded(.towardZero)) ?? 0
}
}
diff --git a/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
index 10ff7b7..1875151 100644
--- a/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
+++ b/swift/Tests/SimSlimKitTests/StatusVerifyMeasureTests.swift
@@ -141,7 +141,7 @@ final class MeasureTests: XCTestCase {
let cases: [(String, Int64)] = [
("45M", 45 * 1_048_576), ("45M+", 45 * 1_048_576), ("45M-", 45 * 1_048_576),
("1.5G", 1_610_612_736), ("900K", 900 * 1024), ("12B", 12), ("12", 12), ("0", 0),
- ("", 0), ("+", 0), ("abc", 0), ("1.5.2M", 0),
+ ("", 0), ("+", 0), ("abc", 0), ("1.5.2M", 0), ("1e30", 0), ("1e30G", 0), ("1e400", 0),
]
for (text, expected) in cases {
XCTAssertEqual(Simctl.parseBytes(text), expected, "parseBytes(\"\(text)\")")
From 4daf6ebe7d4d90a84641c6fa43e96a4e81778b9c Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:44:12 -0700
Subject: [PATCH 04/32] feat(swift): slimming (on, off, on --no-reboot, boot,
shutdown) and a hardened dependency gate
Offline disabled.plist route with launchctl fallback, batched unload, 8-worker
pool, operation deadline. Gate now catches private/@_spi imports, non-Swift
sources, a same-named Subprocess.swift and swallowed grep errors. Verified on a
throwaway simulator: 246 -> 83 processes, ~10.5 -> ~2.7 GB.
---
docs/swift-port-plan.md | 5 +-
scripts/verify-deps.sh | 39 +-
swift/Sources/SimSlimCLI/CLI.swift | 21 +-
swift/Sources/SimSlimCLI/Mutations.swift | 203 ++++++
swift/Sources/SimSlimCLI/Usage.swift | 8 +-
swift/Sources/SimSlimKit/DisabledStore.swift | 119 ++++
swift/Sources/SimSlimKit/LaunchdBatch.swift | 94 +++
swift/Sources/SimSlimKit/Lifecycle.swift | 86 +++
swift/Sources/SimSlimKit/Measure.swift | 4 +-
swift/Sources/SimSlimKit/Output.swift | 33 +
swift/Sources/SimSlimKit/Simctl.swift | 39 +-
swift/Sources/SimSlimKit/Slim.swift | 386 ++++++++++++
.../MutationCommandTests.swift | 260 ++++++++
swift/Tests/SimSlimCLITests/Support.swift | 5 +-
swift/Tests/SimSlimKitTests/SlimTests.swift | 591 ++++++++++++++++++
swift/Tests/TestSupport/FakeHost.swift | 153 +++++
16 files changed, 2019 insertions(+), 27 deletions(-)
create mode 100644 swift/Sources/SimSlimCLI/Mutations.swift
create mode 100644 swift/Sources/SimSlimKit/DisabledStore.swift
create mode 100644 swift/Sources/SimSlimKit/LaunchdBatch.swift
create mode 100644 swift/Sources/SimSlimKit/Lifecycle.swift
create mode 100644 swift/Sources/SimSlimKit/Slim.swift
create mode 100644 swift/Tests/SimSlimCLITests/MutationCommandTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/SlimTests.swift
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
index af7cc07..2f95511 100644
--- a/docs/swift-port-plan.md
+++ b/docs/swift-port-plan.md
@@ -160,7 +160,8 @@ These are not in the first release. The SwiftUI app depends on several of them,
- **M0** Scaffold: package, subprocess layer, dependency gate, `make verify-deps`.
- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first.
-- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Not yet run against a live `simctl spawn launchctl` read, which `list`, `status`, `verify` and `doctor` all use.
-- **M3** Slimming: `on`, `off`, `on --no-reboot`, offline fast path, `boot`, `shutdown`, `enable`/`disable`, `--save`.
+- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Also run against a live throwaway simulator in an isolated device set (Xcode 27.2, iOS 27.2).
+- **M3a** Slimming: `on`, `off`, `on --no-reboot`, `boot`, `shutdown`, offline fast path, batch unload, 8-worker pool. **Done** (222 tests; 12 mutations in the slimming core, all caught; live run on a throwaway simulator: 246 to 83 processes, about 10.5 GB to 2.7 GB, slim persists across shutdown and boot, `off` restores stock). Awaiting the independent review of this core.
+- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): not started.
- **M4** `watch`.
- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/scripts/verify-deps.sh b/scripts/verify-deps.sh
index 9916a80..383aeda 100755
--- a/scripts/verify-deps.sh
+++ b/scripts/verify-deps.sh
@@ -58,7 +58,7 @@ list_imports() {
[[ -d "$dir" ]] || return 0
find "$dir" -name '*.swift' -not -path '*/.build/*' | sort | while read -r file; do
awk -v f="${file#$ROOT_DIR/}" '
- /^[[:space:]]*(@[A-Za-z_]+[[:space:]]+)*((public|internal|package)[[:space:]]+)?import[[:space:]]/ {
+ /^[[:space:]]*(@[A-Za-z_]+(\([^)]*\))?[[:space:]]+)*((public|internal|package|private|fileprivate)[[:space:]]+)?import[[:space:]]/ {
n = split($0, w, /[[:space:]]+/)
for (i = 1; i <= n; i++) if (w[i] == "import") { j = i + 1; break }
if (w[j] ~ /^(struct|class|enum|protocol|typealias|func|var|let)$/) j++
@@ -100,7 +100,7 @@ PKG="$SWIFT_DIR/Package.swift"
if [[ ! -f "$PKG" ]]; then
fail "missing $PKG"
else
- pkg_hits="$(hits -nE '\.package\(|\.binaryTarget|\.plugin|\.systemLibrary' "$PKG")"
+ pkg_hits="$(hits -nE '\.package\(|\.binaryTarget|\.plugin|\.systemLibrary|unsafeFlags|cSettings|cxxSettings|linkerSettings|path:[[:space:]]*"(\.\.|/)' "$PKG")"
if [[ -n "$pkg_hits" ]]; then
print -u2 -- "$pkg_hits"
fail "Package.swift declares a package, binary target, plugin, or system library"
@@ -108,6 +108,17 @@ else
ok "Package.swift declares no packages, binary targets, or plugins"
fi
fi
+# Only Swift may be compiled: a C/ObjC/C++ target would escape every Swift-only check.
+foreign="$(find "$SWIFT_DIR" -path "$SWIFT_DIR/.build" -prune -o -type f \
+ \( -name '*.c' -o -name '*.h' -o -name '*.m' -o -name '*.mm' -o -name '*.cpp' -o -name '*.cc' \
+ -o -name '*.hpp' -o -name '*.s' -o -name '*.S' -o -name '*.modulemap' -o -name '*.a' \
+ -o -name '*.dylib' -o -name '*.framework' -o -name '*.xcframework' \) -print)"
+if [[ -n "$foreign" ]]; then
+ print -u2 -- "$foreign"
+ fail "non-Swift source or binary under swift/ (above)"
+else
+ ok "swift/ contains only Swift sources"
+fi
artifacts_ok=1
for artifact in "$SWIFT_DIR/Package.resolved" "$SWIFT_DIR/Packages" "$SWIFT_DIR/vendor" \
"$ROOT_DIR/Package.swift" "$ROOT_DIR/Package.resolved" \
@@ -129,7 +140,11 @@ check_imports "gui" "$GUI_DIR" "${ALLOWED_GUI[@]}"
# ---------------------------------------------------------------- 3 network
section "3. No network APIs in source"
NET_PATTERN='URLSession|URLRequest|NSURLConnection|NWConnection|NWListener|NWPathMonitor|CFNetwork|CFSocket|CFStream|InputStream|OutputStream|WKWebView|getaddrinfo|socket\(|connect\(|URL\(string:|http://|https://|ftp://'
-net_hits="$(hits -rnE "$NET_PATTERN" "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift')"
+# The one allowed URL is the plist DOCTYPE's public identifier: a fixed string
+# written into a file, never opened. Anything else with a scheme still fails.
+APPLE_DTD='http://www.apple.com/DTDs/PropertyList-1.0.dtd'
+net_hits="$(hits -rnE "$NET_PATTERN" "$SWIFT_DIR/Sources" "$GUI_DIR" --include='*.swift' \
+ | grep -vF "$APPLE_DTD" || true)"
if [[ -n "$net_hits" ]]; then
print -u2 -- "$net_hits"
fail "network-capable API or URL found in source (above)"
@@ -151,23 +166,26 @@ fi
# ---------------------------------------------------------------- 4 subprocess
section "4. Subprocesses go through Subprocess.swift only"
SUBPROC="$SWIFT_DIR/Sources/SimSlimKit/Subprocess.swift"
-spawn_hits="$(hits -rnE '\bProcess\(|NSTask|posix_spawn|\bpopen\(|\bsystem\(|\bexecv|\bfork\(|/bin/(ba|z)?sh' \
- "$SWIFT_DIR/Sources" --include='*.swift' --exclude=Subprocess.swift)"
+# Only the one real Subprocess.swift is exempt, never a same-named file elsewhere.
+outside_subproc() { grep -vF "$SUBPROC:" || true; }
+spawn_hits="$(hits -rnE '\bProcess[[:space:]]*(\(|\.run)|NSTask|NSUserUnixTask|posix_spawn|\bpopen\(|\bsystem\(|\bexecv|\bfork\(|/bin/(ba|z)?sh' \
+ "$SWIFT_DIR/Sources" --include='*.swift' | outside_subproc)"
if [[ -n "$spawn_hits" ]]; then
print -u2 -- "$spawn_hits"
fail "process spawning outside Subprocess.swift (above)"
else
ok "Process/posix_spawn/popen/system only in Subprocess.swift"
fi
-path_hits="$(hits -rnE '"/(usr/(s)?bin|bin|sbin|opt|Applications)/' "$SWIFT_DIR/Sources" --include='*.swift' \
- --exclude=Subprocess.swift)"
+path_hits="$(hits -rnE '"/(usr/(s)?bin|bin|sbin|opt|Applications|Library|System)/' "$SWIFT_DIR/Sources" --include='*.swift' \
+ | outside_subproc)"
if [[ -n "$path_hits" ]]; then
print -u2 -- "$path_hits"
fail "hard-coded executable path outside Subprocess.swift (above)"
else
ok "no executable paths outside the Executable enum"
fi
-if [[ -n "$(hits -nE 'getenv|environment\[|\.environment|/usr/bin/env|"PATH"' "$SUBPROC")" ]]; then
+env_hits="$(hits -nE 'getenv|environment\[|\.environment|/usr/bin/env|"PATH"' "$SUBPROC")"
+if [[ -n "$env_hits" ]]; then
fail "Subprocess.swift reads the environment or PATH"
else
ok "Subprocess.swift reads no environment and does no PATH lookup"
@@ -216,7 +234,7 @@ if (( CHECK_BINARY )); then
fi
# Undefined symbols that would indicate networking.
- NET_SYMBOLS='NSURLSession|NSURLConnection|CFNetwork|nw_connection|nw_listener|_getaddrinfo|_socket$|_connect$'
+ NET_SYMBOLS='NSURLSession|NSURLConnection|CFNetwork|nw_connection|nw_listener|_getaddrinfo|_gethostbyname|_getifaddrs|_sendto|_socket$|_connect$|_bind$'
net_syms="$(nm -u "$BIN" | hits -E "$NET_SYMBOLS")"
if [[ -n "$net_syms" ]]; then
print -u2 -- "$net_syms"
@@ -226,7 +244,8 @@ if (( CHECK_BINARY )); then
fi
# Test-only hooks must never ship. By convention they are named SIMSLIM_TEST_*.
- if [[ -n "$(strings -a "$BIN" | hits 'SIMSLIM_TEST_')" ]]; then
+ test_hooks="$(strings -a "$BIN" | hits 'SIMSLIM_TEST_')"
+ if [[ -n "$test_hooks" ]]; then
fail "release binary contains a SIMSLIM_TEST_ hook"
else
ok "no SIMSLIM_TEST_ hooks in the release binary"
diff --git a/swift/Sources/SimSlimCLI/CLI.swift b/swift/Sources/SimSlimCLI/CLI.swift
index 8b32193..ff1c36b 100644
--- a/swift/Sources/SimSlimCLI/CLI.swift
+++ b/swift/Sources/SimSlimCLI/CLI.swift
@@ -9,6 +9,8 @@ public struct CLI {
public var version: String
public var environment: [String: String]
public var runner: CommandRunning
+ /// Where simulators' launchd disable overrides live on the host; tests redirect it.
+ public var storeRoot: String
public var stdout: Sink
public var stderr: Sink
@@ -16,12 +18,14 @@ public struct CLI {
version: String = simslimVersion,
environment: [String: String] = ProcessInfo.processInfo.environment,
runner: CommandRunning = SystemCommandRunner(),
+ storeRoot: String = "/private/var/tmp",
stdout: @escaping Sink,
stderr: @escaping Sink
) {
self.version = version
self.environment = environment
self.runner = runner
+ self.storeRoot = storeRoot
self.stdout = stdout
self.stderr = stderr
}
@@ -37,9 +41,8 @@ public struct CLI {
/// Commands that exist in the Go CLI but are not in the Swift port yet.
static let notYetPorted: Set = [
- "profile", "on", "off", "enable", "disable", "watch", "top", "size", "disk-categories",
- "disk-plan", "disk-clean", "clone", "repair-clone", "rename", "boot", "shutdown", "erase",
- "delete",
+ "profile", "enable", "disable", "watch", "top", "size", "disk-categories",
+ "disk-plan", "disk-clean", "clone", "repair-clone", "rename", "erase", "delete",
]
static let globalSpecs: [FlagSpec] = [
@@ -55,6 +58,13 @@ public struct CLI {
],
"doctor": [.bool("json", onlyOnce: true), .string("requires"), .bool("list")],
"measure": [.bool("json", onlyOnce: true)],
+ "boot": [.bool("json", onlyOnce: true)],
+ "shutdown": [.bool("json", onlyOnce: true)],
+ "on": [
+ .string("profile"), .string("except"), .string("keep"), .bool("no-reboot"),
+ .bool("preserve-boot-state"),
+ ],
+ "off": [.bool("preserve-boot-state")],
]
/// Runs the command line (without the program name) and returns the exit status.
@@ -128,6 +138,7 @@ public struct CLI {
}
var simctl = Simctl(runner: runner)
+ simctl.storeRoot = storeRoot
let bootTimeout = try applyGlobalOptions(parsed, to: &simctl)
let context = Context(
simctl: simctl, bootTimeout: bootTimeout, parsed: parsed, stdout: stdout, stderr: stderr)
@@ -139,6 +150,10 @@ public struct CLI {
case "verify": return try cmdVerify(context)
case "doctor": return try cmdDoctor(context)
case "measure": return try cmdMeasure(context)
+ case "boot": return try cmdBoot(context)
+ case "shutdown": return try cmdShutdown(context)
+ case "on": return try cmdOn(context)
+ case "off": return try cmdOff(context)
default: preconditionFailure("command \(command) has specs but no handler")
}
}
diff --git a/swift/Sources/SimSlimCLI/Mutations.swift b/swift/Sources/SimSlimCLI/Mutations.swift
new file mode 100644
index 0000000..3e377b6
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/Mutations.swift
@@ -0,0 +1,203 @@
+import Foundation
+import SimSlimKit
+
+// The commands that change simulator state. Each resolves the exact device
+// first, so a simctl alias such as `all` can never fan out a boot or a slim.
+
+extension CLI {
+ /// A copy of the simctl handle that gives up `seconds` from now.
+ private func bounded(_ simctl: Simctl, by seconds: TimeInterval) -> Simctl {
+ var copy = simctl
+ copy.deadline = copy.now().addingTimeInterval(seconds)
+ return copy
+ }
+
+ private func progress(_ context: Context) -> Reporter {
+ let stderr = context.stderr
+ return { stderr($0 + "\n") }
+ }
+
+ func cmdBoot(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let udid = try oneUDID(context.parsed.positionals)
+ let device = try context.simctl.findDevice(udid: udid)
+ let result = SimulatorMutationOutput(action: "boot", udid: udid)
+ if device.state == "Booted" {
+ if json {
+ context.stdout(try jsonText(result))
+ } else {
+ context.stdout("Simulator \(udid) is already booted.\n")
+ }
+ return 0
+ }
+ // Booting and waiting for services can take about a minute. Stderr is quiet
+ // under --json so a consumer reading a combined stream gets clean JSON.
+ if !json { context.stderr("Booting \(udid)...\n") }
+ try bounded(context.simctl, by: context.bootTimeout).bootAndWait(
+ set: device.set, udid: udid)
+ context.stdout(json ? try jsonText(result) : "Booted \(udid).\n")
+ return 0
+ }
+
+ func cmdShutdown(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let udid = try oneUDID(context.parsed.positionals)
+ let device = try context.simctl.findDevice(udid: udid)
+ let result = SimulatorMutationOutput(action: "shutdown", udid: udid)
+ if device.state != "Booted" {
+ if json {
+ context.stdout(try jsonText(result))
+ } else {
+ context.stdout("Simulator \(udid) is already shut down.\n")
+ }
+ return 0
+ }
+ try bounded(context.simctl, by: Simctl.shutdownTimeout).shutdownAndWait(
+ set: device.set, udid: udid)
+ context.stdout(json ? try jsonText(result) : "Shut down \(udid).\n")
+ return 0
+ }
+
+ /// Returns a simulator that started shut down to that state.
+ private func returnToShutdown(_ context: Context, set: String, udid: String) throws {
+ do {
+ try context.simctl.shutdownAndWait(set: set, udid: udid)
+ } catch {
+ throw SimSlimError("restore original shutdown state: \(error.localizedDescription)")
+ }
+ }
+
+ /// Runs `operation`, then restores a shut-down state when asked. The restore
+ /// happens even when the operation failed, and both failures are reported.
+ private func withBootStateRestored(
+ _ context: Context, restore: Bool, set: String, udid: String,
+ operation: () throws -> Bool
+ ) throws -> Bool {
+ var changed = false
+ var operationError: Error?
+ do { changed = try operation() } catch { operationError = error }
+ if restore {
+ do {
+ try returnToShutdown(context, set: set, udid: udid)
+ } catch {
+ if let operationError {
+ throw SimSlimError(
+ "\(operationError.localizedDescription); additionally could not restore original shutdown state: \(error.localizedDescription)"
+ )
+ }
+ throw error
+ }
+ }
+ if let operationError { throw operationError }
+ return changed
+ }
+
+ func cmdOn(_ context: Context) throws -> Int32 {
+ let parsed = context.parsed
+ let preserve = parsed.bool("preserve-boot-state")
+ let noReboot = parsed.bool("no-reboot")
+ if noReboot && preserve {
+ throw SimSlimError(
+ "--no-reboot cannot be combined with --preserve-boot-state: shutting the simulator down discards a no-reboot slim"
+ )
+ }
+ let udid = try oneUDID(parsed.positionals)
+ let profile = try buildProfile(
+ profilePath: parsed.string("profile"), except: parsed.string("except"),
+ keep: parsed.string("keep"))
+ // Resolve once: this pins the device's set (routing every simctl call below),
+ // fails fast on an unknown UDID, and says whether to restore a shut-down state.
+ let device = try context.simctl.findDevice(udid: udid)
+ let reporter = progress(context)
+ let simctl = bounded(context.simctl, by: context.bootTimeout)
+ let count = profile.desired(for: device).count
+
+ if noReboot {
+ context.stderr(
+ "Slimming \(udid) for this boot session: stopping \(count) background services without a reboot.\n"
+ )
+ let changed = try simctl.enableSlimNoReboot(
+ set: device.set, udid: udid, profile: profile, reporter: reporter)
+ context.stdout(
+ changed
+ ? "Done. Simulator slimmed for this boot session without a reboot.\n"
+ : "Already slim. Confirmed every profiled daemon is stopped for this boot session.\n")
+ if device.supportsPersistentOverrides {
+ context.stdout(
+ "The disable overrides are also stored, so the next boot should come up slim; `simslim verify` after a reboot confirms it.\n"
+ )
+ } else {
+ context.stdout(
+ "\(device.runtimeName) cannot persist overrides: the simulator returns to stock at its next boot, so re-run this command after every boot.\n"
+ )
+ }
+ return 0
+ }
+
+ let startedShutdown = device.state == "Shutdown"
+ let originallyShutdown = preserve && startedShutdown
+ if startedShutdown {
+ context.stderr(
+ "Slimming \(udid): disabling \(count) background services while it is off, then booting it slim.\n"
+ )
+ } else {
+ context.stderr(
+ "Slimming \(udid): disabling \(count) background services. The simulator will reboot to apply the changes.\n"
+ )
+ }
+ let changed = try withBootStateRestored(
+ context, restore: originallyShutdown, set: device.set, udid: udid
+ ) {
+ try simctl.enableSlim(set: device.set, udid: udid, profile: profile, reporter: reporter)
+ }
+ if changed {
+ if originallyShutdown {
+ context.stdout("Done. Simulator reconfigured slim and returned to shutdown.\n")
+ } else if startedShutdown {
+ context.stdout("Done. Simulator reconfigured slim and booted.\n")
+ } else {
+ context.stdout("Done. Simulator reconfigured and rebooted slim.\n")
+ }
+ } else if originallyShutdown {
+ context.stdout("Already slim. Original shutdown state restored.\n")
+ } else {
+ context.stdout("Already slim. Nothing to change.\n")
+ }
+ return 0
+ }
+
+ func cmdOff(_ context: Context) throws -> Int32 {
+ let preserve = context.parsed.bool("preserve-boot-state")
+ let udid = try oneUDID(context.parsed.positionals)
+ let device = try context.simctl.findDevice(udid: udid)
+ let startedShutdown = device.state == "Shutdown"
+ let originallyShutdown = preserve && startedShutdown
+ if startedShutdown {
+ context.stderr("Restoring \(udid) to stock while it is off, then booting it.\n")
+ } else {
+ context.stderr(
+ "Restoring \(udid) to stock. The simulator will reboot to apply the changes.\n")
+ }
+ let reporter = progress(context)
+ let simctl = bounded(context.simctl, by: context.bootTimeout)
+ let changed = try withBootStateRestored(
+ context, restore: originallyShutdown, set: device.set, udid: udid
+ ) {
+ try simctl.disableSlim(set: device.set, udid: udid, reporter: reporter)
+ }
+ if changed {
+ if originallyShutdown {
+ context.stdout("Done. All daemons re-enabled and simulator returned to shutdown.\n")
+ } else if startedShutdown {
+ context.stdout("Done. All daemons re-enabled and simulator booted.\n")
+ } else {
+ context.stdout("Done. All daemons re-enabled and simulator rebooted.\n")
+ }
+ } else if originallyShutdown {
+ context.stdout("Already stock. Original shutdown state restored.\n")
+ } else {
+ context.stdout("Already stock. Nothing to change.\n")
+ }
+ return 0
+ }
+}
diff --git a/swift/Sources/SimSlimCLI/Usage.swift b/swift/Sources/SimSlimCLI/Usage.swift
index e93643b..f86bb0c 100644
--- a/swift/Sources/SimSlimCLI/Usage.swift
+++ b/swift/Sources/SimSlimCLI/Usage.swift
@@ -28,8 +28,8 @@ let usageText = """
profiles [id] Show the daemon categories a slim boot disables;
pass a category ID to list that category's daemons
profile [path] † Interactively build a --profile JSON file
- on † Slim a simulator (persist disables + reboot slim)
- off † Restore a simulator to stock (re-enable + reboot)
+ on Slim a simulator (persist disables + reboot slim)
+ off Restore a simulator to stock (re-enable + reboot)
enable † Re-enable categories or daemons on a booted simulator now
disable † Stop categories or daemons on a booted simulator now
watch † Slim every simulator until Ctrl-C
@@ -56,8 +56,8 @@ let usageText = """
clone † Clone apps, data, settings, and the service profile
repair-clone †
rename † Rename a simulator
- boot † Boot a simulator and wait for its services
- shutdown † Shut down a booted simulator
+ boot Boot a simulator and wait for its services
+ shutdown Shut down a booted simulator
erase † Erase a simulator's apps, data, and settings
delete † Permanently delete a simulator
--json Print machine-readable JSON (also supported by list,
diff --git a/swift/Sources/SimSlimKit/DisabledStore.swift b/swift/Sources/SimSlimKit/DisabledStore.swift
new file mode 100644
index 0000000..abc509b
--- /dev/null
+++ b/swift/Sources/SimSlimKit/DisabledStore.swift
@@ -0,0 +1,119 @@
+import Foundation
+
+// launchd_sim is a host process, so a simulator's launchd disable overrides are
+// not in the device's data directory: they live beside its launchd.log, keyed
+// only by UDID. launchd_sim reads the file when it starts and rewrites it on every
+// `launchctl disable`/`enable`. It is an undocumented CoreSimulator detail, so
+// everything here is best effort and callers fall back to launchctl.
+
+struct DisabledStore: Sendable {
+ var root: String
+
+ func directory(udid: String) -> String {
+ (root as NSString).appendingPathComponent("com.apple.CoreSimulator.SimDevice.\(udid)")
+ }
+
+ func path(udid: String) -> String {
+ (directory(udid: udid) as NSString).appendingPathComponent("disabled.plist")
+ }
+
+ /// The labels the store marks disabled; a label absent from the result is
+ /// enabled. A device that never booted has no store, which is the same as
+ /// nothing disabled.
+ func readDisabled(udid: String) throws -> Set {
+ Set(try readEntries(udid: udid).filter { $0.value }.keys)
+ }
+
+ /// Every entry verbatim, including the explicit-enable (false) entries the
+ /// runtime writes for itself, which a merge must preserve.
+ func readEntries(udid: String) throws -> [String: Bool] {
+ let file = path(udid: udid)
+ guard FileManager.default.fileExists(atPath: file) else { return [:] }
+ let data: Data
+ do {
+ data = try Data(contentsOf: URL(fileURLWithPath: file))
+ } catch {
+ throw SimSlimError("read launchd disable store: \(error.localizedDescription)")
+ }
+ return try DisabledStore.parse(data)
+ }
+
+ /// Merges the transitions into the store, leaving every other entry as it
+ /// was. The write is atomic so launchd_sim never reads a half-written store.
+ func write(udid: String, toDisable: [String], toEnable: [String]) throws {
+ var entries = try readEntries(udid: udid)
+ for label in toDisable { entries[label] = true }
+ for label in toEnable { entries[label] = false }
+
+ let dir = directory(udid: udid)
+ do {
+ try FileManager.default.createDirectory(
+ atPath: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ } catch {
+ throw SimSlimError("create launchd disable store: \(error.localizedDescription)")
+ }
+ let temp = (dir as NSString).appendingPathComponent("disabled.plist.\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(atPath: temp) }
+ do {
+ try DisabledStore.encode(entries).write(to: URL(fileURLWithPath: temp))
+ try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: temp)
+ } catch {
+ throw SimSlimError("write launchd disable store: \(error.localizedDescription)")
+ }
+ // rename(2) replaces the destination atomically; FileManager.replaceItem and
+ // moveItem would refuse or copy.
+ guard rename(temp, path(udid: udid)) == 0 else {
+ throw SimSlimError("write launchd disable store: \(String(cString: strerror(errno)))")
+ }
+ }
+
+ /// The same XML plist shape launchd_sim writes, sorted so a rewrite that
+ /// changes nothing produces an identical file.
+ static func encode(_ entries: [String: Bool]) -> Data {
+ var text = "\n"
+ text +=
+ "\n"
+ text += "\n\n"
+ for label in entries.keys.sorted() {
+ text += "\t\(escape(label))\n\t<\(entries[label]! ? "true" : "false")/>\n"
+ }
+ text += "\n\n"
+ return Data(text.utf8)
+ }
+
+ private static func escape(_ text: String) -> String {
+ var out = ""
+ for ch in text.unicodeScalars {
+ switch ch {
+ case "&": out += "&"
+ case "<": out += "<"
+ case ">": out += ">"
+ case "\"": out += """
+ case "'": out += "'"
+ default: out.unicodeScalars.append(ch)
+ }
+ }
+ return out
+ }
+
+ /// Reads the flat `label|` dict. Values of any other
+ /// type are ignored rather than rejected, so an unexpected one cannot make the
+ /// store unreadable.
+ static func parse(_ data: Data) throws -> [String: Bool] {
+ let object: Any
+ do {
+ object = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ } catch {
+ throw SimSlimError("parse launchd disable store: \(error.localizedDescription)")
+ }
+ guard let dict = object as? [String: Any] else { return [:] }
+ var entries: [String: Bool] = [:]
+ for (label, value) in dict where !label.isEmpty {
+ // Only real booleans: an integer 1 is not a disable override.
+ if let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() {
+ entries[label] = number.boolValue
+ }
+ }
+ return entries
+ }
+}
diff --git a/swift/Sources/SimSlimKit/LaunchdBatch.swift b/swift/Sources/SimSlimKit/LaunchdBatch.swift
new file mode 100644
index 0000000..b07fe11
--- /dev/null
+++ b/swift/Sources/SimSlimKit/LaunchdBatch.swift
@@ -0,0 +1,94 @@
+import Foundation
+
+/// The RuntimeRoot directories holding the job plists launchd_sim bootstraps
+/// into the simulator's system domain.
+let launchdJobDirs = ["System/Library/LaunchDaemons", "System/Library/LaunchAgents"]
+
+/// Bounds how many plist paths go into one `launchctl unload`, so the argument
+/// list stays far below ARG_MAX however long the profile grows.
+let unloadChunk = 64
+
+/// Reads `launchctl list` rows: "PIDStatusLabel", with "-" as the PID
+/// of a loaded job that is not running.
+func parseLaunchctlList(_ output: String) -> Set {
+ var loaded = Set()
+ for line in output.split(whereSeparator: \.isNewline) {
+ let fields = line.split(whereSeparator: { $0 == " " || $0 == "\t" || $0 == "\r" })
+ if fields.count != 3 || fields[2] == "Label" { continue }
+ loaded.insert(String(fields[2]))
+ }
+ return loaded
+}
+
+/// Keeps the labels the batch did not finish: no disable override yet, or still
+/// loaded. A few jobs stay listed even with their override in place, so they
+/// always take the per-label bootout.
+func stillToStop(_ labels: [String], disabled: Set, loaded: Set) -> [String] {
+ labels.filter { !disabled.contains($0) || loaded.contains($0) }
+}
+
+extension Simctl {
+ /// Reads a job plist's Label with the host's plutil, which handles both XML
+ /// and binary plists.
+ func readPlistLabel(path: String) throws -> String {
+ let result = try exec(.plutil, ["-extract", "Label", "raw", "-o", "-", path])
+ guard result.succeeded else {
+ throw SimSlimError("plutil: exit status \(result.status): \(result.combinedText)")
+ }
+ return result.stdoutText.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ /// Maps each label to the job plist that defines exactly that label. A plist
+ /// is used only when its own Label key matches, so a renamed or shared file
+ /// can never unload a daemon outside the allowlist.
+ func launchdJobPlists(root: String, labels: [String], plistLabel: (String) throws -> String)
+ -> [String: String]
+ {
+ var paths: [String: String] = [:]
+ for label in labels {
+ if deadlineExpired { break }
+ for dir in launchdJobDirs {
+ let path = ((root as NSString).appendingPathComponent(dir) as NSString)
+ .appendingPathComponent(label + ".plist")
+ guard FileManager.default.fileExists(atPath: path) else { continue }
+ if let got = try? plistLabel(path), got == label {
+ paths[label] = path
+ break
+ }
+ }
+ }
+ return paths
+ }
+
+ /// Every label currently loaded in the simulator's launchd.
+ func loadedLabels(set: String, udid: String) throws -> Set {
+ parseLaunchctlList(try readLaunchd(set: set, udid: udid, ["list"]))
+ }
+
+ /// One `launchctl -w` spawn per chunk of plists. The exit status is not
+ /// trusted: launchctl reports any single failure for the whole call, so the
+ /// caller reads the state back. A chunk that runs out of time ends the batch,
+ /// so a slow host keeps the rest of its budget for the per-label path.
+ func batchJobs(set: String, udid: String, verb: String, paths: [String]) {
+ var start = 0
+ while start < paths.count {
+ let end = min(start + unloadChunk, paths.count)
+ let args = simctlArgs(
+ set: set, ["spawn", udid, "launchctl", verb, "-w"] + Array(paths[start.. [String] {
+ let disabled = try readDisabled(set: set, udid: udid)
+ let loaded = try loadedLabels(set: set, udid: udid)
+ return stillToStop(labels, disabled: disabled, loaded: loaded)
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Lifecycle.swift b/swift/Sources/SimSlimKit/Lifecycle.swift
new file mode 100644
index 0000000..564c085
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Lifecycle.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+/// Progress lines for operations that take minutes. The caller decides where
+/// they go (the CLI sends them to stderr); a nil reporter is a no-op.
+public typealias Reporter = @Sendable (String) -> Void
+
+func report(_ reporter: Reporter?, _ message: String) { reporter?(message) }
+
+extension Simctl {
+ public static let shutdownTimeout: TimeInterval = 30
+
+ /// Boots the device, tolerating one that is already booted, and blocks on
+ /// `bootstatus -b` until its services are ready.
+ public func bootAndWait(set: String, udid: String) throws {
+ let boot = try exec(.xcrun, simctlArgs(set: set, ["boot", udid]))
+ if !boot.succeeded {
+ let message = boot.combinedText
+ if !message.contains("already booted") && !message.contains("current state: Booted") {
+ throw SimSlimError("simctl boot: exit status \(boot.status): \(message)")
+ }
+ }
+ let status = try exec(.xcrun, simctlArgs(set: set, ["bootstatus", udid, "-b"]))
+ guard status.succeeded else {
+ throw SimSlimError("simctl bootstatus: exit status \(status.status): \(status.combinedText)")
+ }
+ }
+
+ /// Shuts the device down, tolerating one that is already shut down.
+ public func shutdown(set: String, udid: String) throws {
+ let result = try exec(.xcrun, simctlArgs(set: set, ["shutdown", udid]))
+ if result.succeeded { return }
+ if result.combinedText.contains("current state: Shutdown") { return }
+ throw SimSlimError("simctl shutdown: exit status \(result.status): \(result.combinedText)")
+ }
+
+ /// Polls until the device reports Shutdown.
+ public func waitShutdown(
+ set: String, udid: String, timeout: TimeInterval = Simctl.shutdownTimeout
+ ) throws {
+ let limit = now().addingTimeInterval(timeout)
+ while now() < limit {
+ if try findDevice(udid: udid, set: set).state == "Shutdown" { return }
+ sleep(0.5)
+ }
+ throw SimSlimError("timed out waiting for \(udid) to shut down")
+ }
+
+ /// Shuts the device down and waits for it, under the shutdown timeout.
+ public func shutdownAndWait(set: String, udid: String) throws {
+ var bounded = self
+ bounded.deadline = now().addingTimeInterval(Simctl.shutdownTimeout)
+ try bounded.shutdown(set: set, udid: udid)
+ try bounded.waitShutdown(set: set, udid: udid)
+ }
+
+ /// The host path of a CoreSimulator runtime's RuntimeRoot. Simulator processes
+ /// see the host file system, so launchctl inside the simulator can read job
+ /// plists by these paths. Runtimes are global, never per device set.
+ func runtimeRoot(runtimeID: String) throws -> String {
+ let result = try exec(.xcrun, ["simctl", "list", "runtimes", "-j"])
+ guard result.succeeded else {
+ throw Simctl.listError(status: result.status, stderr: result.stderrText)
+ }
+ return try Simctl.parseRuntimeRoot(result.stdout, runtimeID: runtimeID)
+ }
+
+ static func parseRuntimeRoot(_ data: Data, runtimeID: String) throws -> String {
+ struct Runtimes: Decodable {
+ struct Entry: Decodable {
+ var identifier: String?
+ var runtimeRoot: String?
+ }
+ var runtimes: [Entry]
+ }
+ let parsed: Runtimes
+ do {
+ parsed = try JSONDecoder().decode(Runtimes.self, from: data)
+ } catch {
+ throw SimSlimError("parse simctl list runtimes: \(error.localizedDescription)")
+ }
+ for entry in parsed.runtimes where entry.identifier == runtimeID {
+ if let root = entry.runtimeRoot, !root.isEmpty { return root }
+ }
+ throw SimSlimError("runtime \(runtimeID) has no runtimeRoot")
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Measure.swift b/swift/Sources/SimSlimKit/Measure.swift
index dbaa2a2..1932c39 100644
--- a/swift/Sources/SimSlimKit/Measure.swift
+++ b/swift/Sources/SimSlimKit/Measure.swift
@@ -126,7 +126,7 @@ extension Simctl {
static func parsePS(_ output: String) -> ProcessSnapshot {
var snapshot = ProcessSnapshot()
- for line in output.split(separator: "\n") {
+ for line in output.split(whereSeparator: \.isNewline) {
let fields = line.split(whereSeparator: \.isWhitespace)
if fields.count < 4 { continue }
guard let pid = Int(fields[0]), let ppid = Int(fields[1]) else { continue }
@@ -148,7 +148,7 @@ extension Simctl {
/// or `1234K+`. Anything else (headers, the summary block) is skipped.
static func parseTopMemory(_ output: String) -> [Int: Int64] {
var memory: [Int: Int64] = [:]
- for line in output.split(separator: "\n") {
+ for line in output.split(whereSeparator: \.isNewline) {
let fields = line.split(whereSeparator: \.isWhitespace)
guard fields.count >= 2, fields[0].allSatisfy(\.isASCIIDigit), let pid = Int(fields[0]) else {
continue
diff --git a/swift/Sources/SimSlimKit/Output.swift b/swift/Sources/SimSlimKit/Output.swift
index 617d0c6..0e9c676 100644
--- a/swift/Sources/SimSlimKit/Output.swift
+++ b/swift/Sources/SimSlimKit/Output.swift
@@ -79,3 +79,36 @@ public struct StatusOutput: Codable, Equatable, Sendable {
dropped = try c.decodeIfPresent([DroppedCategory].self, forKey: .dropped) ?? []
}
}
+
+/// The result of a simulator lifecycle command (`boot`, `shutdown`, ...).
+public struct SimulatorMutationOutput: Codable, Equatable, Sendable {
+ public var action: String
+ public var udid: String
+ public var name: String
+ public var sourceUdid: String
+
+ public init(action: String, udid: String, name: String = "", sourceUdid: String = "") {
+ self.action = action
+ self.udid = udid
+ self.name = name
+ self.sourceUdid = sourceUdid
+ }
+
+ private enum CodingKeys: String, CodingKey { case action, udid, name, sourceUdid }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(action, forKey: .action)
+ try c.encode(udid, forKey: .udid)
+ if !name.isEmpty { try c.encode(name, forKey: .name) } // Go omitempty
+ if !sourceUdid.isEmpty { try c.encode(sourceUdid, forKey: .sourceUdid) }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ action = try c.decode(String.self, forKey: .action)
+ udid = try c.decode(String.self, forKey: .udid)
+ name = try c.decodeIfPresent(String.self, forKey: .name) ?? ""
+ sourceUdid = try c.decodeIfPresent(String.self, forKey: .sourceUdid) ?? ""
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Simctl.swift b/swift/Sources/SimSlimKit/Simctl.swift
index 9cda419..8b9f449 100644
--- a/swift/Sources/SimSlimKit/Simctl.swift
+++ b/swift/Sources/SimSlimKit/Simctl.swift
@@ -22,11 +22,40 @@ public struct Simctl: Sendable {
/// spawns for a few seconds (error 124, "Domain is tearing down").
public var retryDelays: [TimeInterval] = [1, 2, 4, 8]
public var sleep: @Sendable (TimeInterval) -> Void = { Thread.sleep(forTimeInterval: $0) }
+ /// Where launchd_sim keeps each device's disable overrides (a test redirects it).
+ public var storeRoot = "/private/var/tmp"
+ /// An overall bound for the operation in progress, standing in for Go's context
+ /// deadline: every command is capped to what is left of it, and nothing starts
+ /// once it has passed.
+ public var deadline: Date?
+ /// The clock the deadline is read from (a test replaces it).
+ public var now: @Sendable () -> Date = { Date() }
public init(runner: CommandRunning = SystemCommandRunner()) {
self.runner = runner
}
+ // MARK: - Running commands
+
+ var deadlineExpired: Bool { deadline.map { now() >= $0 } ?? false }
+
+ /// Runs a command under the operation deadline. The per-call `timeout` is
+ /// capped to what is left of the deadline; a command killed by the deadline
+ /// (rather than by its own `timeout`) is an error.
+ func exec(_ executable: Executable, _ arguments: [String], timeout: TimeInterval? = nil) throws
+ -> CommandResult
+ {
+ var limit = timeout
+ if let deadline {
+ let left = deadline.timeIntervalSince(now())
+ if left <= 0 { throw SimSlimError("context deadline exceeded") }
+ limit = min(limit ?? left, left)
+ }
+ let result = try runner.run(executable, arguments, timeout: limit)
+ if result.timedOut, deadlineExpired { throw SimSlimError("context deadline exceeded") }
+ return result
+ }
+
// MARK: - Device sets
public var knownSets: [DeviceSet] {
@@ -71,7 +100,7 @@ public struct Simctl: Sendable {
let args = Simctl.simctlArgs(token: set.token, ["list", "devices", "-j"])
let result: CommandResult
do {
- result = try runner.run(.xcrun, args)
+ result = try exec(.xcrun, args)
} catch {
throw SimSlimError("simctl list: \(error.localizedDescription)")
}
@@ -181,7 +210,7 @@ public struct Simctl: Sendable {
while true {
let result: CommandResult
do {
- result = try runner.run(.xcrun, arguments, timeout: spawnTimeout)
+ result = try exec(.xcrun, arguments, timeout: spawnTimeout)
} catch {
throw SimSlimError("launchctl \(args[0]): \(error.localizedDescription)")
}
@@ -192,7 +221,9 @@ public struct Simctl: Sendable {
? "timed out after \(Int(spawnTimeout))s" : "exit status \(result.status)"
let message = "launchctl \(args[0]): \(reason): \(result.combinedText)"
let settling = Simctl.launchdSettling(result) || result.timedOut
- if !settling || attempt >= retryDelays.count { throw SimSlimError(message) }
+ if !settling || attempt >= retryDelays.count || deadlineExpired {
+ throw SimSlimError(message)
+ }
sleep(retryDelays[attempt])
attempt += 1
}
@@ -210,7 +241,7 @@ public struct Simctl: Sendable {
/// `"com.apple.x" => disabled`; older builds print `=> true` / `=> false`.
static func parseDisabled(_ output: String) -> Set {
var set = Set()
- for line in output.split(separator: "\n", omittingEmptySubsequences: false) {
+ for line in output.split(omittingEmptySubsequences: false, whereSeparator: { $0.isNewline }) {
guard let open = line.firstIndex(of: "\"") else { continue }
let rest = line[line.index(after: open)...]
guard let close = rest.firstIndex(of: "\"") else { continue }
diff --git a/swift/Sources/SimSlimKit/Slim.swift b/swift/Sources/SimSlimKit/Slim.swift
new file mode 100644
index 0000000..1881b85
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Slim.swift
@@ -0,0 +1,386 @@
+import Foundation
+
+/// The offline route wrote the store but the booted device did not come up in the
+/// desired state. The store is an undocumented CoreSimulator detail, so a runtime
+/// is always free to ignore it: callers treat this as "take the supported path
+/// instead", never as a failure.
+struct OfflineIneffective: Error {
+ var reason: String
+}
+
+/// How many `simctl spawn launchctl` transitions run at once. Overrides are
+/// independent launchd writes, so they parallelize, and a small pool hides most
+/// of the per-spawn latency without hammering a simulator still settling after
+/// its first boot.
+let spawnWorkers = 8
+
+/// How many times `applyDelta` walks the remaining labels. Disables are
+/// persistent, so each pass only retries what earlier passes failed.
+let applyPasses = 3
+
+/// launchctl's exit status when the service to boot out is not loaded ("No such
+/// process"), which is already the state a live disable wants.
+let bootoutGone: Int32 = 3
+
+/// What a disable does to the running service.
+enum DisableAction: Equatable {
+ /// `launchctl disable` only: takes effect at the next boot.
+ case overrideOnly
+ /// `disable` then `bootout`: the daemon stops now and cannot respawn.
+ case liveStop
+}
+
+/// The managed labels that differ between `after` and `desired`.
+func countLost(after: Set, desired: Set, managed: Set) -> Int {
+ let moves = delta(current: after, desired: desired, managed: managed)
+ return moves.toDisable.count + moves.toEnable.count
+}
+
+private final class PassResults: @unchecked Sendable {
+ struct Transition: Sendable {
+ var action: String // "disable", "enable" or "bootout" (live stop)
+ var label: String
+ }
+
+ private let lock = NSLock()
+ private(set) var failed: [Transition] = []
+ private(set) var failures: [String] = []
+ private(set) var done: Int
+ let total: Int
+ private let reporter: Reporter?
+
+ init(done: Int, total: Int, reporter: Reporter?) {
+ self.done = done
+ self.total = total
+ self.reporter = reporter
+ }
+
+ func record(_ transition: Transition, error: String?) {
+ lock.lock()
+ defer { lock.unlock() }
+ if let error {
+ failed.append(transition)
+ failures.append(error)
+ return
+ }
+ done += 1
+ if done == total || done % 20 == 0 { report(reporter, " \(done)/\(total) services updated") }
+ }
+}
+
+extension Simctl {
+ // MARK: - Per-label transitions
+
+ /// `disable`/`enable`/`bootout` of one label, inside the simulator.
+ private func launchctl(set: String, udid: String, verb: String, label: String) throws
+ -> CommandResult
+ {
+ try exec(
+ .xcrun, simctlArgs(set: set, ["spawn", udid, "launchctl", verb, "system/\(label)"]),
+ timeout: spawnTimeout)
+ }
+
+ private func failureText(_ verb: String, _ label: String, _ result: CommandResult) -> String {
+ let reason =
+ result.timedOut ? "timed out after \(Int(spawnTimeout))s" : "exit status \(result.status)"
+ return "\(verb) \(label): \(reason): \(result.combinedText)"
+ }
+
+ /// Runs one transition; returns nil on success or the failure text.
+ private func runTransition(set: String, udid: String, action: String, label: String) -> String? {
+ let verb = action == "bootout" ? "disable" : action
+ do {
+ let result = try launchctl(set: set, udid: udid, verb: verb, label: label)
+ if !result.succeeded { return failureText(verb, label, result) }
+ if action != "bootout" { return nil }
+ let out = try launchctl(set: set, udid: udid, verb: "bootout", label: label)
+ if !out.succeeded && !(out.status == bootoutGone && !out.timedOut) {
+ return failureText("bootout", label, out)
+ }
+ return nil
+ } catch {
+ return "\(verb) \(label): \(error.localizedDescription)"
+ }
+ }
+
+ /// Disables then enables the given labels. Each transition is its own
+ /// `simctl spawn launchctl`, run through a pool of `spawnWorkers`. A non-zero
+ /// exit is a real failure; failures are collected and retried on later passes
+ /// rather than aborting the whole profile.
+ func applyDelta(
+ set: String, udid: String, toDisable: [String], toEnable: [String],
+ disableAction: DisableAction, reporter: Reporter?
+ ) throws {
+ typealias Transition = PassResults.Transition
+ var pending: [Transition] = []
+ for label in toDisable {
+ pending.append(
+ Transition(action: disableAction == .liveStop ? "bootout" : "disable", label: label))
+ }
+ for label in toEnable { pending.append(Transition(action: "enable", label: label)) }
+ let total = pending.count
+ var done = 0
+ var failures: [String] = []
+
+ var pass = 1
+ while pass <= applyPasses && !pending.isEmpty {
+ if pass > 1 {
+ report(
+ reporter, " retrying \(pending.count) failed services (pass \(pass)/\(applyPasses))...")
+ // Give a launchd that refused the spawns a moment before asking again.
+ if !retryDelays.isEmpty, !deadlineExpired {
+ sleep(retryDelays[min(pass - 2, retryDelays.count - 1)])
+ }
+ }
+ let results = PassResults(done: done, total: total, reporter: reporter)
+ let slots = DispatchSemaphore(value: spawnWorkers)
+ let group = DispatchGroup()
+ for transition in pending {
+ if deadlineExpired { break }
+ slots.wait()
+ group.enter()
+ DispatchQueue.global().async {
+ defer {
+ slots.signal()
+ group.leave()
+ }
+ let error = self.runTransition(
+ set: set, udid: udid, action: transition.action, label: transition.label)
+ results.record(transition, error: error)
+ }
+ }
+ group.wait()
+ done = results.done
+ failures = results.failures
+ if deadlineExpired {
+ throw SimSlimError(
+ "\(total - done)/\(total) launchctl transitions incomplete: context deadline exceeded")
+ }
+ pending = results.failed
+ pass += 1
+ }
+ if !pending.isEmpty {
+ throw SimSlimError(
+ "\(pending.count)/\(total) launchctl transitions failed after \(applyPasses) passes: "
+ + failures.joined(separator: "; "))
+ }
+ }
+
+ // MARK: - ensure
+
+ private func minimumPersistentMessage(_ device: Device) -> String {
+ "\(device.runtimeName) runtime cannot persist launchd disable overrides across reboot; "
+ + "simslim requires \(device.platformName) \(device.minimumPersistentVersion) or newer, "
+ + "or `simslim on --no-reboot` to slim the current boot session only"
+ }
+
+ /// Brings the device to exactly the desired disabled state and boots it. A
+ /// non-empty profile is rejected before anything is booted or changed on
+ /// runtimes without persistent overrides. On a runtime that persists them the
+ /// device takes the far cheaper offline route, whatever state it starts in.
+ /// Returns whether anything changed.
+ @discardableResult
+ public func ensure(
+ set: String, udid: String, desired requested: Set, reporter: Reporter? = nil
+ ) throws -> Bool {
+ var device = try findDevice(udid: udid, set: set)
+ let desired = desiredForDevice(device, requested)
+ let persistent = device.supportsPersistentOverrides
+ if !desired.isEmpty && !persistent { throw SimSlimError(minimumPersistentMessage(device)) }
+ let managed = Catalog.managedSet
+
+ // A shut-down device can be reconfigured by writing the overrides
+ // launchd_sim reads when it starts, which skips both the per-label
+ // spawns and the reboot that would apply them.
+ let booted = device.state == "Booted"
+ if booted && persistent {
+ // `simctl list` says Booted from the moment the boot starts, so wait for
+ // launchd to be up before asking it anything.
+ try bootAndWait(set: set, udid: udid)
+ // An override only takes effect at the next boot, so a booted device
+ // already owes a shutdown and a boot. Spending them up front makes it a
+ // shut-down device and lets the store replace every launchctl spawn.
+ let live = try readDisabled(set: set, udid: udid)
+ let moves = delta(current: live, desired: desired, managed: managed)
+ if moves.toDisable.isEmpty && moves.toEnable.isEmpty { return false }
+ report(reporter, "Shutting the simulator down to reconfigure it offline...")
+ do {
+ try shutdown(set: set, udid: udid)
+ } catch {
+ throw SimSlimError("shutdown before reconfigure: \(error.localizedDescription)")
+ }
+ try waitShutdown(set: set, udid: udid)
+ device.state = "Shutdown"
+ }
+ if device.state == "Shutdown" && persistent {
+ do {
+ let changed = try ensureOffline(
+ set: set, udid: udid, desired: desired, reporter: reporter)
+ // A device that started booted only gets here with a real delta.
+ return changed || booted
+ } catch is OfflineIneffective {
+ report(
+ reporter,
+ "Could not apply the changes while the simulator was off; reconfiguring it while booted instead..."
+ )
+ }
+ }
+
+ report(reporter, "Booting the simulator (a first boot can take up to a minute)...")
+ try bootAndWait(set: set, udid: udid)
+ let current = try readDisabled(set: set, udid: udid)
+ let moves = delta(current: current, desired: desired, managed: managed)
+ if moves.toDisable.isEmpty && moves.toEnable.isEmpty { return false }
+ if !moves.toDisable.isEmpty {
+ report(reporter, "Disabling \(moves.toDisable.count) background services...")
+ }
+ if !moves.toEnable.isEmpty {
+ report(reporter, "Re-enabling \(moves.toEnable.count) background services...")
+ }
+ try applyDelta(
+ set: set, udid: udid, toDisable: moves.toDisable, toEnable: moves.toEnable,
+ disableAction: .overrideOnly, reporter: reporter)
+ report(reporter, "Rebooting the simulator to apply the changes...")
+ do {
+ try shutdown(set: set, udid: udid)
+ } catch {
+ throw SimSlimError("shutdown before reboot: \(error.localizedDescription)")
+ }
+ try waitShutdown(set: set, udid: udid)
+ try bootAndWait(set: set, udid: udid)
+ let after = try readDisabled(set: set, udid: udid)
+ let lost = countLost(after: after, desired: desired, managed: managed)
+ if lost > 0 {
+ throw SimSlimError(
+ "the disable overrides did not survive the reboot (\(lost) of \(moves.toDisable.count + moves.toEnable.count) changes lost)"
+ )
+ }
+ return true
+ }
+
+ /// Reaches the desired state on a shut-down device by writing its launchd
+ /// overrides directly, then boots it once, already slim. The state is read back
+ /// from the booted device rather than trusted.
+ func ensureOffline(set: String, udid: String, desired: Set, reporter: Reporter?) throws
+ -> Bool
+ {
+ let store = DisabledStore(root: storeRoot)
+ let managed = Catalog.managedSet
+ let current: Set
+ do {
+ current = try store.readDisabled(udid: udid)
+ } catch {
+ throw OfflineIneffective(reason: error.localizedDescription)
+ }
+ let moves = delta(current: current, desired: desired, managed: managed)
+ let changed = !moves.toDisable.isEmpty || !moves.toEnable.isEmpty
+ if changed {
+ report(
+ reporter,
+ "Reconfiguring \(moves.toDisable.count + moves.toEnable.count) background services while the simulator is off..."
+ )
+ do {
+ try store.write(udid: udid, toDisable: moves.toDisable, toEnable: moves.toEnable)
+ } catch {
+ throw OfflineIneffective(reason: error.localizedDescription)
+ }
+ }
+ report(reporter, "Booting the simulator (a first boot can take up to a minute)...")
+ try bootAndWait(set: set, udid: udid)
+ let after = try readDisabled(set: set, udid: udid)
+ let lost = countLost(after: after, desired: desired, managed: managed)
+ if lost > 0 {
+ throw OfflineIneffective(
+ reason:
+ "\(lost) of \(moves.toDisable.count + moves.toEnable.count) offline overrides were not honoured at boot"
+ )
+ }
+ return changed
+ }
+
+ /// Disables the profile's daemons and boots the device slim.
+ @discardableResult
+ public func enableSlim(
+ set: String, udid: String, profile: Profile, reporter: Reporter? = nil
+ ) throws -> Bool {
+ try ensure(set: set, udid: udid, desired: profile.desired(), reporter: reporter)
+ }
+
+ /// Re-enables every managed daemon, returning the device to stock.
+ @discardableResult
+ public func disableSlim(set: String, udid: String, reporter: Reporter? = nil) throws -> Bool {
+ try ensure(set: set, udid: udid, desired: [], reporter: reporter)
+ }
+
+ // MARK: - No-reboot
+
+ /// Slims the running boot session without a reboot: each daemon the profile
+ /// disables is booted out of launchd, and the override keeps launchd from
+ /// respawning it. Works on every runtime, but without persistent overrides the
+ /// simulator comes back stock at its next boot. Only moves toward more-disabled:
+ /// managed labels disabled beyond the profile are left alone.
+ @discardableResult
+ public func enableSlimNoReboot(
+ set: String, udid: String, profile: Profile, reporter: Reporter? = nil
+ ) throws -> Bool {
+ let device = try findDevice(udid: udid, set: set)
+ let desired = profile.desired(for: device)
+ report(reporter, "Booting the simulator (a first boot can take up to a minute)...")
+ try bootAndWait(set: set, udid: udid)
+ let current = try readDisabled(set: set, udid: udid)
+ let managed = Catalog.managedSet
+ let moves = delta(current: current, desired: desired, managed: managed)
+ if !moves.toEnable.isEmpty {
+ report(
+ reporter,
+ "Leaving \(moves.toEnable.count) services disabled beyond this profile; only `simslim off` re-enables them."
+ )
+ }
+ // Check every profiled label, not just those without an override: an
+ // override says nothing about whether the job is still loaded. Labels that
+ // are both disabled and unloaded are skipped, so the command is idempotent.
+ let changed = !moves.toDisable.isEmpty
+ let labels = desired.filter { managed.contains($0) }.sorted()
+ report(reporter, "Stopping \(labels.count) background services for this boot session...")
+ let remaining = unloadInBatch(
+ set: set, udid: udid, runtimeID: device.runtimeID, labels: labels, reporter: reporter)
+ try applyDelta(
+ set: set, udid: udid, toDisable: remaining, toEnable: [], disableAction: .liveStop,
+ reporter: reporter)
+ let after = try readDisabled(set: set, udid: udid)
+ let missing = delta(current: after, desired: desired, managed: managed).toDisable
+ if !missing.isEmpty {
+ throw SimSlimError("\(missing.count) of \(labels.count) disable overrides did not take")
+ }
+ return changed
+ }
+
+ /// Disables and unloads the labels whose job plist it can find with one
+ /// `launchctl unload -w` per chunk, then reads the state back and returns what
+ /// still needs the per-label disable and bootout. Anything that goes wrong here
+ /// only means more labels take the per-label path.
+ func unloadInBatch(
+ set: String, udid: String, runtimeID: String, labels: [String], reporter: Reporter?
+ ) -> [String] {
+ if runtimeID.isEmpty { return labels }
+ guard let root = try? runtimeRoot(runtimeID: runtimeID) else { return labels }
+ // Only what is still enabled or loaded needs stopping, so an already-slim
+ // device spawns no unload and does not report work it did not do.
+ guard let pending = try? stopState(set: set, udid: udid, labels: labels) else {
+ return labels
+ }
+ if pending.isEmpty {
+ report(reporter, " all \(labels.count) services were already stopped")
+ return []
+ }
+ let plists = launchdJobPlists(
+ root: root, labels: pending, plistLabel: { try self.readPlistLabel(path: $0) })
+ if plists.isEmpty { return pending }
+ let paths = pending.compactMap { plists[$0] }
+ unloadJobs(set: set, udid: udid, paths: paths)
+ guard let rest = try? stopState(set: set, udid: udid, labels: pending) else { return pending }
+ report(
+ reporter, " \(pending.count - rest.count)/\(pending.count) services stopped in one batch")
+ return rest
+ }
+}
diff --git a/swift/Tests/SimSlimCLITests/MutationCommandTests.swift b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift
new file mode 100644
index 0000000..0e4193c
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift
@@ -0,0 +1,260 @@
+import SimSlimKit
+import TestSupport
+import XCTest
+
+@testable import SimSlimCLI
+
+final class MutationCommandTests: XCTestCase {
+ private let udid = "AAAAAAAA-0000-0000-0000-000000000001"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-cli-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ private func host(state: String, runtime: String = "com.apple.CoreSimulator.SimRuntime.iOS-27-2")
+ -> FakeHost
+ {
+ let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", runtime: runtime, state: state)]
+ )
+ host.storeRoot = root
+ if state == "Booted" { host.disabled[udid] = [] }
+ return host
+ }
+
+ private func run(_ args: [String], _ host: FakeHost) -> CLIResult {
+ runCLI(args, host: host, storeRoot: root)
+ }
+
+ private func subcommands(_ host: FakeHost) -> [String] {
+ host.calls.compactMap { $0.executable == .xcrun ? $0.arguments.dropFirst().first : nil }
+ }
+
+ // MARK: - boot / shutdown
+
+ func testBootAnAlreadyBootedSimulatorDoesNothing() {
+ let host = host(state: "Booted")
+ let r = run(["boot", udid], host)
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stdout, "Simulator \(udid) is already booted.\n")
+ XCTAssertFalse(subcommands(host).contains("boot"))
+ }
+
+ func testBootJSONIsCleanAndQuiet() throws {
+ let host = host(state: "Shutdown")
+ let r = run(["boot", udid, "--json"], host)
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stderr, "", "no progress chatter under --json")
+ let result = try JSONDecoder().decode(
+ SimulatorMutationOutput.self, from: Data(r.stdout.utf8))
+ XCTAssertEqual(result, SimulatorMutationOutput(action: "boot", udid: udid))
+ XCTAssertEqual(host.devices[0].state, "Booted")
+ }
+
+ func testBootAnUnknownUDIDOrAliasNeverReachesSimctlBoot() {
+ for target in ["all", "booted", "00000000-0000-0000-0000-000000000000"] {
+ let host = host(state: "Shutdown")
+ let r = run(["boot", target], host)
+ XCTAssertEqual(r.status, 1, target)
+ XCTAssertEqual(r.stderr, "simslim: no simulator with udid \(target)\n")
+ XCTAssertFalse(subcommands(host).contains("boot"), target)
+ XCTAssertFalse(subcommands(host).contains("shutdown"), target)
+ }
+ }
+
+ func testBootFailureIsReported() {
+ let host = host(state: "Shutdown")
+ host.bootFailure = "Unable to boot: no runtime"
+ let r = run(["boot", udid], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("simctl boot: exit status 1: Unable to boot: no runtime"))
+ }
+
+ func testShutdownWaitsUntilShutdown() {
+ let host = host(state: "Booted")
+ let r = run(["shutdown", udid], host)
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stdout, "Shut down \(udid).\n")
+ XCTAssertEqual(host.devices[0].state, "Shutdown")
+ }
+
+ func testShutdownOfAShutdownSimulatorDoesNothing() {
+ let host = host(state: "Shutdown")
+ let r = run(["shutdown", udid, "--json"], host)
+ XCTAssertEqual(r.status, 0)
+ XCTAssertTrue(r.stdout.contains("\"action\" : \"shutdown\""))
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ }
+
+ func testShutdownAliasNeverReachesSimctl() {
+ let host = host(state: "Booted")
+ XCTAssertEqual(run(["shutdown", "all"], host).status, 1)
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ }
+
+ // MARK: - on
+
+ func testOnRejectsNoRebootWithPreserveBootStateBeforeAnyWork() {
+ let host = host(state: "Shutdown")
+ let r = run(["on", udid, "--no-reboot", "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("--no-reboot cannot be combined with --preserve-boot-state"))
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ func testOnValidatesTheProfileBeforeTouchingTheSimulator() {
+ let host = host(state: "Shutdown")
+ let r = run(["on", udid, "--except", "no-such-category"], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("unknown category \"no-such-category\""))
+ XCTAssertTrue(host.calls.isEmpty)
+ XCTAssertEqual(run(["on", udid, "--profile", "x.json", "--keep", "a"], host).status, 1)
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ func testOnSlimsAShutdownSimulatorAndBootsIt() {
+ let host = host(state: "Shutdown")
+ let r = run(["on", udid], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Done. Simulator reconfigured slim and booted.\n")
+ XCTAssertTrue(r.stderr.hasPrefix("Slimming \(udid): disabling "))
+ XCTAssertEqual(host.devices[0].state, "Booted")
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired())
+ }
+
+ func testOnPreserveBootStateReturnsToShutdown() {
+ let host = host(state: "Shutdown")
+ let r = run(["on", udid, "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Done. Simulator reconfigured slim and returned to shutdown.\n")
+ XCTAssertEqual(host.devices[0].state, "Shutdown")
+ // The next boot comes up slim from the stored overrides.
+ XCTAssertEqual(run(["boot", udid], host).status, 0)
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired())
+ }
+
+ func testOnPreserveBootStateStillShutsDownWhenTheOperationFails() {
+ let host = host(state: "Shutdown")
+ host.bootFailure = "Unable to boot"
+ let r = run(["on", udid, "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("Unable to boot"), r.stderr)
+ XCTAssertEqual(host.devices[0].state, "Shutdown")
+ }
+
+ func testOnReportsBothFailuresWhenTheShutdownRestoreFailsToo() {
+ let host = host(state: "Shutdown")
+ host.honoursStore = true
+ // The operation boots the device, then shutdown is refused.
+ host.shutdownFailure = "Unable to shut down"
+ let r = run(["on", udid, "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("restore original shutdown state"), r.stderr)
+ }
+
+ func testOnAlreadySlimChangesNothing() {
+ let host = host(state: "Booted")
+ host.disabled[udid] = Profile().desired()
+ let r = run(["on", udid], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Already slim. Nothing to change.\n")
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ }
+
+ func testOnRefusesAnOldRuntimeAndSuggestsNoReboot() {
+ let host = host(
+ state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0")
+ let r = run(["on", udid], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(r.stderr.contains("iOS 17.0 runtime cannot persist"), r.stderr)
+ XCTAssertTrue(r.stderr.contains("--no-reboot"))
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ XCTAssertFalse(subcommands(host).contains("spawn"))
+ }
+
+ func testOnNoRebootOnAnOldRuntimeSaysTheSlimIsLostAtReboot() {
+ let host = host(
+ state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0")
+ host.loaded[udid] = []
+ let r = run(["on", udid, "--no-reboot"], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertTrue(
+ r.stdout.contains("Done. Simulator slimmed for this boot session without a reboot."))
+ XCTAssertTrue(r.stdout.contains("iOS 17.0 cannot persist overrides"), r.stdout)
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ }
+
+ func testOnExceptKeepsThatCategoryEnabled() {
+ let host = host(state: "Shutdown")
+ let r = run(["on", udid, "--except", "siri"], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ let siri = Set(Catalog.category(id: "siri")!.labels)
+ let slim = host.disabled[udid]!.intersection(Catalog.managedSet)
+ XCTAssertTrue(slim.isDisjoint(with: siri.subtracting(Catalog.category(id: "store")!.labels)))
+ XCTAssertEqual(slim, Profile(exceptCategories: ["siri"]).desired())
+ }
+
+ // MARK: - off
+
+ func testOffRestoresStockAndReboots() {
+ let host = host(state: "Booted")
+ host.disabled[udid] = Profile().desired()
+ let r = run(["off", udid], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Done. All daemons re-enabled and simulator rebooted.\n")
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), [])
+ XCTAssertEqual(host.devices[0].state, "Booted")
+ }
+
+ func testOffAlreadyStock() {
+ let host = host(state: "Booted")
+ let r = run(["off", udid], host)
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stdout, "Already stock. Nothing to change.\n")
+ XCTAssertFalse(subcommands(host).contains("shutdown"))
+ }
+
+ func testOffWorksOnARuntimeWithoutPersistence() {
+ // Restoring stock is always allowed, even where slimming is refused.
+ let host = host(
+ state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-17-0")
+ host.persistsOverrides = false
+ host.disabled[udid] = ["com.apple.unmanaged"]
+ let r = run(["off", udid], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Already stock. Nothing to change.\n")
+ }
+
+ func testOffPreserveBootStateOfAShutdownSimulator() {
+ let host = host(state: "Shutdown")
+ try? writeStoreLikeLaunchd(host, root: root, udid: udid, labels: Array(Profile().desired()))
+ let r = run(["off", udid, "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stdout, "Done. All daemons re-enabled and simulator returned to shutdown.\n")
+ XCTAssertEqual(host.devices[0].state, "Shutdown")
+ }
+
+ func testNoCommandAcceptsTwoUDIDs() {
+ for command in ["boot", "shutdown", "on", "off"] {
+ let r = run([command, udid, "other"], host(state: "Booted"))
+ XCTAssertEqual(r.status, 1, command)
+ XCTAssertTrue(r.stderr.contains("expected exactly one simulator UDID"), command)
+ }
+ }
+}
+
+/// Writes a store the way launchd_sim would, independently of the code under test.
+private func writeStoreLikeLaunchd(_ host: FakeHost, root: String, udid: String, labels: [String])
+ throws
+{
+ let dir = root + "/com.apple.CoreSimulator.SimDevice.\(udid)"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let dict = Dictionary(uniqueKeysWithValues: labels.map { ($0, true) })
+ let data = try PropertyListSerialization.data(fromPropertyList: dict, format: .xml, options: 0)
+ try data.write(to: URL(fileURLWithPath: dir + "/disabled.plist"))
+}
diff --git a/swift/Tests/SimSlimCLITests/Support.swift b/swift/Tests/SimSlimCLITests/Support.swift
index 2200df9..b44abb9 100644
--- a/swift/Tests/SimSlimCLITests/Support.swift
+++ b/swift/Tests/SimSlimCLITests/Support.swift
@@ -27,12 +27,13 @@ private final class Buffer: @unchecked Sendable {
/// Runs the CLI against a fake host, capturing both streams.
func runCLI(
- _ arguments: [String], host: FakeHost = FakeHost(), environment: [String: String] = [:]
+ _ arguments: [String], host: FakeHost = FakeHost(), environment: [String: String] = [:],
+ storeRoot: String = "/nonexistent/simslim-tests"
) -> CLIResult {
let out = Buffer()
let err = Buffer()
let cli = CLI(
- version: "test-version", environment: environment, runner: host,
+ version: "test-version", environment: environment, runner: host, storeRoot: storeRoot,
stdout: { out.append($0) }, stderr: { err.append($0) })
let status = cli.run(arguments)
return CLIResult(status: status, stdout: out.value, stderr: err.value)
diff --git a/swift/Tests/SimSlimKitTests/SlimTests.swift b/swift/Tests/SimSlimKitTests/SlimTests.swift
new file mode 100644
index 0000000..deb938a
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/SlimTests.swift
@@ -0,0 +1,591 @@
+import TestSupport
+import XCTest
+
+@testable import SimSlimKit
+
+private final class Counter: @unchecked Sendable {
+ private let lock = NSLock()
+ private var current = 0
+ private(set) var peak = 0
+ func enter() {
+ lock.lock()
+ current += 1
+ peak = max(peak, current)
+ lock.unlock()
+ }
+ func leave() {
+ lock.lock()
+ current -= 1
+ lock.unlock()
+ }
+}
+
+private final class Tally: @unchecked Sendable {
+ private let lock = NSLock()
+ private var counts: [String: Int] = [:]
+ func bump(_ key: String) -> Int {
+ lock.lock()
+ defer { lock.unlock() }
+ counts[key, default: 0] += 1
+ return counts[key]!
+ }
+}
+
+private final class Log: @unchecked Sendable {
+ private let lock = NSLock()
+ private var lines: [String] = []
+ func add(_ line: String) {
+ lock.lock()
+ lines.append(line)
+ lock.unlock()
+ }
+ var all: [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return lines
+ }
+}
+
+final class SlimTests: XCTestCase {
+ private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2"
+ private let old = "com.apple.CoreSimulator.SimRuntime.iOS-17-0"
+ private let udid = "AAAAAAAA-0000-0000-0000-000000000001"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-slim-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ private var profileLabels: Set { Profile().desired() }
+
+ private func host(
+ state: String = "Shutdown", runtime: String? = nil, disabled: Set? = nil
+ ) -> FakeHost {
+ let host = FakeHost(devices: [
+ .init(udid: udid, name: "iPhone", runtime: runtime ?? ios, state: state)
+ ])
+ host.storeRoot = root + "/store"
+ if state == "Booted" { host.disabled[udid] = disabled ?? [] }
+ return host
+ }
+
+ private func simctl(_ host: FakeHost) -> Simctl {
+ var simctl = Simctl(runner: host)
+ simctl.retryDelays = [0, 0, 0, 0]
+ simctl.sleep = { _ in }
+ simctl.storeRoot = root + "/store"
+ return simctl
+ }
+
+ private func storeFile() -> String {
+ root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)/disabled.plist"
+ }
+
+ private func verbs(_ host: FakeHost) -> [String] {
+ host.calls.compactMap { call -> String? in
+ guard call.executable == .xcrun else { return nil }
+ var args = call.arguments
+ if args.count > 2, args[1] == "--set" { args.removeSubrange(1...2) }
+ if args.count > 2, args[1] == "spawn" { return "spawn:" + args[4...].joined(separator: " ") }
+ return args.dropFirst().first
+ }
+ }
+
+ private func transitions(_ host: FakeHost) -> [String] {
+ verbs(host).filter {
+ $0.hasPrefix("spawn:disable ") || $0.hasPrefix("spawn:enable ")
+ || $0.hasPrefix("spawn:bootout ") || $0.hasPrefix("spawn:unload ")
+ }
+ }
+
+ // MARK: - CRLF output
+
+ func testParsersSplitCRLFLines() {
+ XCTAssertEqual(
+ Simctl.parseDisabled("\"a\" => disabled\r\n\"b\" => disabled\r\n\"c\" => enabled\r\n"),
+ ["a", "b"])
+ XCTAssertEqual(parseLaunchctlList("PID\tStatus\tLabel\r\n-\t0\tx\r\n-\t0\ty\r\n"), ["x", "y"])
+ }
+
+ // MARK: - DisabledStore
+
+ func testStoreRoundTripAndMerge() throws {
+ let store = DisabledStore(root: root + "/store")
+ XCTAssertEqual(
+ try store.readDisabled(udid: udid), [], "a device that never booted has no store")
+
+ try store.write(udid: udid, toDisable: ["b.service", "a.service"], toEnable: [])
+ XCTAssertEqual(try store.readDisabled(udid: udid), ["a.service", "b.service"])
+
+ // Enabling records an explicit false and keeps everything else.
+ try store.write(udid: udid, toDisable: ["c.service"], toEnable: ["a.service"])
+ XCTAssertEqual(
+ try store.readEntries(udid: udid),
+ ["a.service": false, "b.service": true, "c.service": true])
+ XCTAssertEqual(try store.readDisabled(udid: udid), ["b.service", "c.service"])
+ }
+
+ func testStoreKeepsTheRuntimesOwnEntries() throws {
+ let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let runtimeWritten = """
+
+
+ com.apple.runtime.enabled
+ com.apple.unmanaged.disabled
+
+ """
+ try runtimeWritten.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8)
+
+ let store = DisabledStore(root: root + "/store")
+ try store.write(udid: udid, toDisable: ["com.apple.mine"], toEnable: [])
+ XCTAssertEqual(
+ try store.readEntries(udid: udid),
+ [
+ "com.apple.runtime.enabled": false, "com.apple.unmanaged.disabled": true,
+ "com.apple.mine": true,
+ ])
+ }
+
+ func testStoreIgnoresNonBooleanValuesAndRejectsGarbage() throws {
+ let text = """
+
+
+ a
+ count1
+ nametrue
+
+ """
+ XCTAssertEqual(try DisabledStore.parse(Data(text.utf8)), ["a": true])
+ XCTAssertThrowsError(try DisabledStore.parse(Data("not a plist".utf8)))
+ }
+
+ func testStoreEncodesSortedAndEscaped() throws {
+ let data = DisabledStore.encode(["z&<>": true, "a": false])
+ let text = String(decoding: data, as: UTF8.self)
+ XCTAssertLessThan(
+ text.range(of: "a")!.lowerBound, text.range(of: "z")!.lowerBound)
+ XCTAssertTrue(text.contains("z&<>"))
+ XCTAssertEqual(try DisabledStore.parse(data), ["z&<>": true, "a": false])
+ XCTAssertEqual(DisabledStore.encode(["z&<>": true, "a": false]), data, "stable output")
+ }
+
+ func testStoreWriteIsAtomicAndLeavesNoTemporaryFiles() throws {
+ let store = DisabledStore(root: root + "/store")
+ try store.write(udid: udid, toDisable: ["a"], toEnable: [])
+ try store.write(udid: udid, toDisable: ["b"], toEnable: [])
+ let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
+ XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: dir), ["disabled.plist"])
+ let attrs = try FileManager.default.attributesOfItem(atPath: dir + "/disabled.plist")
+ XCTAssertEqual(attrs[.posixPermissions] as? Int, 0o644)
+ }
+
+ func testStoreWriteFailureIsAnError() throws {
+ // A file where the device directory should be.
+ try FileManager.default.createDirectory(
+ atPath: root + "/store", withIntermediateDirectories: true)
+ FileManager.default.createFile(
+ atPath: root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)", contents: Data())
+ let store = DisabledStore(root: root + "/store")
+ XCTAssertThrowsError(try store.write(udid: udid, toDisable: ["a"], toEnable: []))
+ }
+
+ // MARK: - ensure: refusals
+
+ func testRefusesNonEmptyProfileOnRuntimeWithoutPersistence() throws {
+ let host = host(state: "Booted", runtime: old)
+ XCTAssertThrowsError(
+ try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ ) { error in
+ let text = "\(error)"
+ XCTAssertTrue(text.contains("iOS 17.0 runtime cannot persist"), text)
+ XCTAssertTrue(text.contains("iOS 18.5 or newer"), text)
+ }
+ // Nothing but the device lookup ran: no boot, shutdown or launchctl.
+ XCTAssertEqual(verbs(host), ["list"])
+ }
+
+ // MARK: - ensure: offline route
+
+ func testShutdownDeviceIsSlimmedByTheStoreWithOneBootAndNoSpawns() throws {
+ let host = host()
+ let lines = Log()
+ let changed = try simctl(host).ensure(
+ set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) })
+ XCTAssertTrue(changed)
+ XCTAssertEqual(host.devices[0].state, "Booted")
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ XCTAssertTrue(transitions(host).isEmpty, "no per-label launchctl spawns: \(transitions(host))")
+ XCTAssertEqual(verbs(host).filter { $0 == "boot" }.count, 1)
+ XCTAssertFalse(verbs(host).contains("shutdown"))
+ XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring \(profileLabels.count)") })
+ XCTAssertEqual(try DisabledStore(root: root + "/store").readDisabled(udid: udid), profileLabels)
+ }
+
+ func testBootedDeviceWithADeltaShutsDownThenBootsOnce() throws {
+ let host = host(state: "Booted")
+ let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ XCTAssertTrue(changed)
+ let v = verbs(host)
+ let shutdownIndex = try XCTUnwrap(v.firstIndex(of: "shutdown"))
+ let lastBoot = try XCTUnwrap(v.lastIndex(of: "boot"))
+ XCTAssertLessThan(shutdownIndex, lastBoot)
+ XCTAssertTrue(transitions(host).isEmpty)
+ XCTAssertEqual(host.devices[0].state, "Booted")
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ }
+
+ func testBootedDeviceAlreadyMatchingIsLeftAlone() throws {
+ let host = host(state: "Booted", disabled: profileLabels)
+ let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ XCTAssertFalse(changed)
+ XCTAssertFalse(verbs(host).contains("shutdown"), "an already-slim device is not rebooted")
+ XCTAssertTrue(transitions(host).isEmpty)
+ }
+
+ func testStockProfileRestoresEveryManagedLabelAndOnlyThose() throws {
+ var all = Catalog.managedSet
+ all.insert("com.apple.unmanaged.service")
+ let host = host(state: "Booted", disabled: all)
+ // The runtime's own record for the unmanaged label lives in the store.
+ try DisabledStore(root: root + "/store").write(
+ udid: udid, toDisable: Array(all), toEnable: [])
+ let changed = try simctl(host).ensure(set: "default", udid: udid, desired: [])
+ XCTAssertTrue(changed)
+ XCTAssertEqual(host.disabled[udid], ["com.apple.unmanaged.service"])
+ }
+
+ func testManagedLabelsAreTheOnlyOnesEverWritten() throws {
+ let host = host()
+ try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ let written = try DisabledStore(root: root + "/store").readEntries(udid: udid)
+ XCTAssertTrue(Set(written.keys).isSubset(of: Catalog.managedSet))
+ }
+
+ func testWatchOSKeepsHomedEnabledAndVisionOSKeepsMobileassetd() throws {
+ let watch = FakeHost(devices: [
+ .init(udid: udid, name: "Watch", runtime: "com.apple.CoreSimulator.SimRuntime.watchOS-11-5")
+ ])
+ watch.storeRoot = root + "/store"
+ try simctl(watch).ensure(set: "default", udid: udid, desired: profileLabels)
+ XCTAssertFalse(watch.disabled[udid]!.contains("com.apple.homed"))
+
+ let vision = FakeHost(devices: [
+ .init(udid: udid, name: "Vision", runtime: "com.apple.CoreSimulator.SimRuntime.xrOS-2-5")
+ ])
+ vision.storeRoot = root + "/store2"
+ var visionCtl = simctl(vision)
+ visionCtl.storeRoot = root + "/store2"
+ try visionCtl.ensure(set: "default", udid: udid, desired: profileLabels)
+ XCTAssertFalse(vision.disabled[udid]!.contains("com.apple.mobileassetd"))
+ }
+
+ // MARK: - ensure: fallback to launchctl
+
+ func testIgnoredStoreFallsBackToLaunchctlAndStillEndsSlim() throws {
+ let host = host()
+ host.honoursStore = false
+ let lines = Log()
+ let changed = try simctl(host).ensure(
+ set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) })
+ XCTAssertTrue(changed)
+ XCTAssertTrue(
+ lines.all.contains { $0.hasPrefix("Could not apply the changes while the simulator was off") }
+ )
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ XCTAssertEqual(
+ transitions(host).filter { $0.hasPrefix("spawn:disable ") }.count, profileLabels.count)
+ XCTAssertTrue(verbs(host).contains("shutdown"), "the fallback reboots to persist")
+ }
+
+ func testOverridesLostAtRebootIsAnError() throws {
+ let host = host()
+ host.honoursStore = false
+ host.persistsOverrides = false // the runtime lies about persistence
+ XCTAssertThrowsError(
+ try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ ) { error in
+ XCTAssertTrue("\(error)".contains("did not survive the reboot"), "\(error)")
+ }
+ }
+
+ func testUnreadableStoreFallsBack() throws {
+ let host = host()
+ let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ try "garbage".write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8)
+ host.honoursStore = false
+ let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
+ XCTAssertTrue(changed)
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ }
+
+ // MARK: - applyDelta
+
+ func testApplyDeltaRetriesAFailedLabelOnALaterPass() throws {
+ let host = host(state: "Booted")
+ let tally = Tally()
+ host.failTransition = { verb, label in
+ guard label == "com.apple.flaky" else { return nil }
+ return tally.bump("\(verb) \(label)") == 1
+ ? CommandResult(status: 124, stderr: Data("Domain is tearing down".utf8)) : nil
+ }
+ let lines = Log()
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: ["com.apple.flaky", "com.apple.fine"], toEnable: [],
+ disableAction: .overrideOnly, reporter: { lines.add($0) })
+ XCTAssertEqual(host.disabled[udid], ["com.apple.flaky", "com.apple.fine"])
+ XCTAssertTrue(lines.all.contains { $0.contains("retrying 1 failed services (pass 2/3)") })
+ }
+
+ func testApplyDeltaGivesUpAfterThreePasses() throws {
+ let host = host(state: "Booted")
+ host.failTransition = { _, label in
+ label == "com.apple.bad" ? CommandResult(status: 1, stderr: Data("nope".utf8)) : nil
+ }
+ XCTAssertThrowsError(
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: ["com.apple.bad", "com.apple.ok"], toEnable: [],
+ disableAction: .overrideOnly, reporter: nil)
+ ) { error in
+ let text = "\(error)"
+ XCTAssertTrue(text.contains("1/2 launchctl transitions failed after 3 passes"), text)
+ XCTAssertTrue(text.contains("disable com.apple.bad: exit status 1: nope"), text)
+ }
+ XCTAssertEqual(host.disabled[udid], ["com.apple.ok"])
+ }
+
+ func testApplyDeltaEnablesAndDisables() throws {
+ let host = host(state: "Booted", disabled: ["com.apple.on"])
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: ["com.apple.off"], toEnable: ["com.apple.on"],
+ disableAction: .overrideOnly, reporter: nil)
+ XCTAssertEqual(host.disabled[udid], ["com.apple.off"])
+ }
+
+ func testLiveStopBootsOutAndToleratesAnUnloadedService() throws {
+ let host = host(state: "Booted")
+ host.loaded[udid] = ["com.apple.running"] // com.apple.gone is not loaded: bootout exits 3
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: ["com.apple.running", "com.apple.gone"], toEnable: [],
+ disableAction: .liveStop, reporter: nil)
+ XCTAssertEqual(host.disabled[udid], ["com.apple.running", "com.apple.gone"])
+ XCTAssertEqual(host.loaded[udid], [])
+ let outs = transitions(host).filter { $0.hasPrefix("spawn:bootout ") }
+ XCTAssertEqual(outs.count, 2)
+ }
+
+ func testApplyDeltaUsesAtMostEightWorkers() throws {
+ let host = host(state: "Booted")
+ let counter = Counter()
+ host.onCall = { _, args in
+ guard args.contains("launchctl") else { return }
+ counter.enter()
+ Thread.sleep(forTimeInterval: 0.01)
+ counter.leave()
+ }
+ let labels = (0..<60).map { "com.apple.l\($0)" }
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: labels, toEnable: [],
+ disableAction: .overrideOnly, reporter: nil)
+ XCTAssertEqual(host.disabled[udid], Set(labels))
+ XCTAssertLessThanOrEqual(counter.peak, 8)
+ XCTAssertGreaterThan(counter.peak, 1, "the pool really runs transitions concurrently")
+ }
+
+ func testApplyDeltaReportsProgress() throws {
+ let host = host(state: "Booted")
+ let lines = Log()
+ let labels = (0..<45).map { "com.apple.l\($0)" }
+ try simctl(host).applyDelta(
+ set: "default", udid: udid, toDisable: labels, toEnable: [],
+ disableAction: .overrideOnly, reporter: { lines.add($0) })
+ XCTAssertEqual(
+ lines.all,
+ [" 20/45 services updated", " 40/45 services updated", " 45/45 services updated"])
+ }
+
+ // MARK: - deadline
+
+ func testAnExpiredDeadlineRunsNothing() throws {
+ let host = host()
+ var ctl = simctl(host)
+ ctl.deadline = Date(timeIntervalSinceNow: -1)
+ XCTAssertThrowsError(try ctl.ensure(set: "default", udid: udid, desired: profileLabels)) {
+ XCTAssertTrue("\($0)".contains("context deadline exceeded"), "\($0)")
+ }
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ func testDeadlineCapsEachCommandsTimeout() throws {
+ let host = host(state: "Booted")
+ var ctl = simctl(host)
+ ctl.deadline = Date(timeIntervalSinceNow: 50)
+ ctl.spawnTimeout = 120
+ _ = try ctl.readDisabled(set: "default", udid: udid)
+ let timeout = try XCTUnwrap(host.calls.last?.timeout)
+ XCTAssertLessThanOrEqual(timeout, 50)
+ XCTAssertGreaterThan(timeout, 40)
+ }
+
+ func testACommandKilledByTheDeadlineIsAnErrorNotAFailureToRetry() throws {
+ struct Slow: CommandRunning {
+ let clock: Clock
+ func run(_ e: Executable, _ a: [String], timeout: TimeInterval?) throws -> CommandResult {
+ clock.advance(100) // the deadline passes while the command runs
+ return CommandResult(status: -9, timedOut: true)
+ }
+ }
+ let clock = Clock()
+ var ctl = Simctl(runner: Slow(clock: clock))
+ ctl.now = { clock.now }
+ ctl.deadline = clock.now.addingTimeInterval(10)
+ XCTAssertThrowsError(try ctl.shutdown(set: "default", udid: udid)) {
+ XCTAssertEqual("\($0)", "context deadline exceeded")
+ }
+ }
+
+ func testWaitShutdownTimesOut() throws {
+ let host = host(state: "Booted")
+ host.stuckBooted = true
+ var ctl = simctl(host)
+ let clock = Clock()
+ ctl.now = { clock.now }
+ ctl.sleep = { clock.advance($0) }
+ XCTAssertThrowsError(try ctl.waitShutdown(set: "default", udid: udid, timeout: 30)) {
+ XCTAssertEqual("\($0)", "timed out waiting for \(udid) to shut down")
+ }
+ }
+
+ // MARK: - enableSlimNoReboot
+
+ /// Creates job plists for `labels` under a fake RuntimeRoot, and registers them
+ /// with the fake host. `mismatched` plists carry a different Label inside.
+ private func installPlists(
+ _ host: FakeHost, labels: [String], mismatched: Set = [], missing: Set = []
+ ) throws {
+ let dir = root + "/runtime/System/Library/LaunchDaemons"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ host.runtimeRoots[ios] = root + "/runtime"
+ for label in labels where !missing.contains(label) {
+ let path = "\(dir)/\(label).plist"
+ FileManager.default.createFile(atPath: path, contents: Data())
+ host.plistLabels[path] = mismatched.contains(label) ? "com.apple.other" : label
+ }
+ }
+
+ func testNoRebootStopsLabelsInBatchesOfSixtyFour() throws {
+ let host = host(state: "Booted")
+ let labels = profileLabels.sorted()
+ XCTAssertGreaterThan(labels.count, 128)
+ host.loaded[udid] = Set(labels)
+ try installPlists(host, labels: labels)
+
+ let lines = Log()
+ let changed = try simctl(host).enableSlimNoReboot(
+ set: "default", udid: udid, profile: Profile(), reporter: { lines.add($0) })
+ XCTAssertTrue(changed)
+ let unloads = verbs(host).filter { $0.hasPrefix("spawn:unload -w") }
+ XCTAssertEqual(unloads.count, (labels.count + 63) / 64)
+ XCTAssertTrue(
+ verbs(host).filter { $0.hasPrefix("spawn:disable ") || $0.hasPrefix("spawn:bootout ") }
+ .isEmpty,
+ "everything was stopped in the batch")
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ XCTAssertEqual(host.loaded[udid]?.intersection(profileLabels), [])
+ XCTAssertTrue(
+ lines.all.contains(" \(labels.count)/\(labels.count) services stopped in one batch"))
+ }
+
+ func testNoRebootNeverUnloadsAPlistWhoseLabelDiffers() throws {
+ let host = host(state: "Booted")
+ let labels = profileLabels.sorted()
+ host.loaded[udid] = Set(labels)
+ let impostor = labels[0]
+ let absent = labels[1]
+ try installPlists(host, labels: labels, mismatched: [impostor], missing: [absent])
+
+ try simctl(host).enableSlimNoReboot(set: "default", udid: udid, profile: Profile())
+ let batchArgs = host.calls.filter { $0.arguments.contains("unload") }.flatMap(\.arguments)
+ XCTAssertFalse(batchArgs.contains { $0.hasSuffix("/\(impostor).plist") })
+ XCTAssertFalse(batchArgs.contains { $0.hasSuffix("/\(absent).plist") })
+ // They still end up stopped, through the per-label path.
+ XCTAssertTrue(host.disabled[udid]!.isSuperset(of: [impostor, absent]))
+ XCTAssertFalse(host.loaded[udid]!.contains(impostor))
+ let perLabel = verbs(host).filter { $0.hasPrefix("spawn:bootout ") }
+ XCTAssertEqual(
+ Set(perLabel), ["spawn:bootout system/\(impostor)", "spawn:bootout system/\(absent)"])
+ }
+
+ func testNoRebootIsIdempotent() throws {
+ let host = host(state: "Booted", disabled: profileLabels)
+ host.loaded[udid] = []
+ try installPlists(host, labels: profileLabels.sorted())
+ let lines = Log()
+ let changed = try simctl(host).enableSlimNoReboot(
+ set: "default", udid: udid, profile: Profile(), reporter: { lines.add($0) })
+ XCTAssertFalse(changed)
+ XCTAssertTrue(transitions(host).isEmpty)
+ XCTAssertTrue(lines.all.contains(" all \(profileLabels.count) services were already stopped"))
+ }
+
+ func testNoRebootStopsADisabledButStillLoadedJob() throws {
+ // An earlier run disabled the job but failed to boot it out.
+ let label = profileLabels.sorted()[0]
+ let host = host(state: "Booted", disabled: profileLabels)
+ host.loaded[udid] = [label]
+ try installPlists(host, labels: [])
+ let changed = try simctl(host).enableSlimNoReboot(
+ set: "default", udid: udid, profile: Profile())
+ XCTAssertFalse(changed, "nothing was newly disabled")
+ XCTAssertEqual(host.loaded[udid], [])
+ XCTAssertEqual(
+ transitions(host), ["spawn:disable system/\(label)", "spawn:bootout system/\(label)"])
+ }
+
+ func testNoRebootLeavesExtraDisabledLabelsAlone() throws {
+ var disabled = profileLabels
+ let extra = Catalog.categories[0].labels[0]
+ var profile = Profile()
+ profile.keep = [extra]
+ disabled = profile.desired().union([extra]) // slim, plus one the profile keeps enabled
+ let host = host(state: "Booted", disabled: disabled)
+ host.loaded[udid] = []
+ let lines = Log()
+ try simctl(host).enableSlimNoReboot(
+ set: "default", udid: udid, profile: profile, reporter: { lines.add($0) })
+ XCTAssertTrue(host.disabled[udid]!.contains(extra), "only `off` re-enables")
+ XCTAssertTrue(lines.all.contains { $0.hasPrefix("Leaving 1 services disabled beyond") })
+ }
+
+ func testNoRebootReportsOverridesThatDidNotTake() throws {
+ let host = host(state: "Booted")
+ let victim = profileLabels.sorted()[0]
+ host.loaded[udid] = []
+ host.failTransition = { _, label in
+ label == victim ? CommandResult(status: 1, stderr: Data("no".utf8)) : nil
+ }
+ XCTAssertThrowsError(
+ try simctl(host).enableSlimNoReboot(set: "default", udid: udid, profile: Profile()))
+ }
+}
+
+private final class Clock: @unchecked Sendable {
+ private let lock = NSLock()
+ private var t = Date(timeIntervalSince1970: 1_000_000)
+ var now: Date {
+ lock.lock()
+ defer { lock.unlock() }
+ return t
+ }
+ func advance(_ seconds: TimeInterval) {
+ lock.lock()
+ t = t.addingTimeInterval(seconds)
+ lock.unlock()
+ }
+}
diff --git a/swift/Tests/TestSupport/FakeHost.swift b/swift/Tests/TestSupport/FakeHost.swift
index eb41a50..e81d4a9 100644
--- a/swift/Tests/TestSupport/FakeHost.swift
+++ b/swift/Tests/TestSupport/FakeHost.swift
@@ -48,6 +48,32 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
/// When set, `simctl list` for the default set fails with this stderr.
public var listFailure: String?
+ // MARK: Mutable simulator behaviour
+
+ /// Directory standing in for /private/var/tmp: a boot reads
+ /// `com.apple.CoreSimulator.SimDevice./disabled.plist` from it.
+ public var storeRoot: String?
+ /// Whether a boot honours that file (a runtime may ignore it).
+ public var honoursStore = true
+ /// Whether disable overrides survive a shutdown (iOS before 18.5 forgets them).
+ public var persistsOverrides = true
+ /// Labels loaded in each booted simulator's launchd.
+ public var loaded: [String: Set] = [:]
+ /// Job plist path to the Label inside it, as plutil reports it.
+ public var plistLabels: [String: String] = [:]
+ /// runtime identifier to RuntimeRoot, for `simctl list runtimes -j`.
+ public var runtimeRoots: [String: String] = [:]
+ /// Decides a failure for a transition: (verb, label) -> result, or nil to succeed.
+ public var failTransition: (@Sendable (String, String) -> CommandResult?)?
+ /// Fails `simctl boot` / `shutdown` / `bootstatus` with this stderr when set.
+ public var bootFailure: String?
+ public var shutdownFailure: String?
+ /// Makes the device ignore shutdown, to exercise the shutdown timeout.
+ public var stuckBooted = false
+ /// Called at the start of every command, with the arguments; lets a test
+ /// observe ordering or inject behaviour.
+ public var onCall: (@Sendable (Executable, [String]) -> Void)?
+
public init(devices: [FakeDevice] = []) {
self.devices = devices
}
@@ -72,8 +98,10 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
lock.lock()
_calls.append(Call(executable: executable, arguments: arguments, timeout: timeout))
lock.unlock()
+ onCall?(executable, arguments)
switch executable {
+ case .plutil: return plutil(arguments)
case .xcrun: return xcrun(arguments)
case .pgrep: return pgrep(arguments)
case .ps: return CommandResult(status: 0, stdout: Data(psOutput.utf8))
@@ -100,9 +128,134 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
{
return printDisabled(udid: rest[1])
}
+ if let result = mutating(rest) { return result }
return failure("FakeHost: unhandled simctl \(rest)")
}
+ // MARK: - State changes
+
+ private func setState(_ udid: String, _ state: String) -> Bool {
+ if let i = devices.firstIndex(where: { $0.udid == udid }) {
+ devices[i].state = state
+ return true
+ }
+ for (token, list) in sets {
+ if let i = list.firstIndex(where: { $0.udid == udid }) {
+ sets[token]![i].state = state
+ return true
+ }
+ }
+ return false
+ }
+
+ private func stateOf(_ udid: String) -> String? {
+ (devices + sets.values.flatMap { $0 }).first { $0.udid == udid }?.state
+ }
+
+ private func storeDisabled(_ udid: String) -> Set {
+ guard let storeRoot else { return [] }
+ let path = "\(storeRoot)/com.apple.CoreSimulator.SimDevice.\(udid)/disabled.plist"
+ guard let data = FileManager.default.contents(atPath: path),
+ let object = try? PropertyListSerialization.propertyList(
+ from: data, options: [], format: nil),
+ let dict = object as? [String: Bool]
+ else { return [] }
+ return Set(dict.filter { $0.value }.keys)
+ }
+
+ private func mutating(_ rest: [String]) -> CommandResult? {
+ lock.lock()
+ defer { lock.unlock() }
+ guard let verb = rest.first else { return nil }
+ switch verb {
+ case "boot" where rest.count == 2:
+ let udid = rest[1]
+ if let bootFailure { return CommandResult(status: 1, stderr: Data(bootFailure.utf8)) }
+ guard let state = stateOf(udid) else { return failure("Invalid device: \(udid)") }
+ if state == "Booted" {
+ return CommandResult(
+ status: 149, stderr: Data("Unable to boot device in current state: Booted".utf8))
+ }
+ _ = setState(udid, "Booted")
+ var live = persistsOverrides ? (disabled[udid] ?? []) : []
+ if honoursStore { live.formUnion(storeDisabled(udid)) }
+ disabled[udid] = live
+ loaded[udid] = loaded[udid] ?? Self.defaultLoaded
+ loaded[udid]!.subtract(live)
+ return CommandResult(status: 0)
+ case "bootstatus" where rest.count == 3:
+ return stateOf(rest[1]) == "Booted"
+ ? CommandResult(status: 0) : CommandResult(status: 1, stderr: Data("not booted".utf8))
+ case "shutdown" where rest.count == 2:
+ let udid = rest[1]
+ if let shutdownFailure { return CommandResult(status: 1, stderr: Data(shutdownFailure.utf8)) }
+ guard let state = stateOf(udid) else { return failure("Invalid device: \(udid)") }
+ if state != "Booted" {
+ return CommandResult(
+ status: 149, stderr: Data("Unable to shutdown device in current state: Shutdown".utf8))
+ }
+ if !stuckBooted { _ = setState(udid, "Shutdown") }
+ return CommandResult(status: 0)
+ case "list" where rest == ["list", "runtimes", "-j"]:
+ let runtimes = runtimeRoots.map { ["identifier": $0.key, "runtimeRoot": $0.value] }
+ let data = try! JSONSerialization.data(withJSONObject: ["runtimes": runtimes])
+ return CommandResult(status: 0, stdout: data)
+ case "spawn" where rest.count >= 4 && rest[2] == "launchctl":
+ return launchctl(udid: rest[1], Array(rest.dropFirst(3)))
+ default:
+ return nil
+ }
+ }
+
+ /// Labels loaded in a freshly booted simulator.
+ public static var defaultLoaded: Set { [] }
+
+ private func launchctl(udid: String, _ args: [String]) -> CommandResult? {
+ guard stateOf(udid) == "Booted" else {
+ return CommandResult(status: 1, stderr: Data("Unable to spawn: not booted".utf8))
+ }
+ switch args[0] {
+ case "list":
+ var text = "PID\tStatus\tLabel\n"
+ for label in (loaded[udid] ?? []).sorted() { text += "-\t0\t\(label)\n" }
+ return CommandResult(status: 0, stdout: Data(text.utf8))
+ case "disable", "enable", "bootout":
+ guard args.count == 2, args[1].hasPrefix("system/") else { return nil }
+ let label = String(args[1].dropFirst("system/".count))
+ if let fail = failTransition?(args[0], label) { return fail }
+ switch args[0] {
+ case "disable": disabled[udid, default: []].insert(label)
+ case "enable": disabled[udid, default: []].remove(label)
+ default:
+ if loaded[udid]?.remove(label) == nil {
+ return CommandResult(status: 3, stderr: Data("No such process".utf8))
+ }
+ }
+ return CommandResult(status: 0)
+ case "unload" where args.count >= 3 && args[1] == "-w":
+ for path in args.dropFirst(2) {
+ guard let label = plistLabels[path] else { continue }
+ if let fail = failTransition?("unload", label) {
+ _ = fail
+ continue
+ }
+ disabled[udid, default: []].insert(label)
+ loaded[udid]?.remove(label)
+ }
+ return CommandResult(status: 0)
+ default:
+ return nil
+ }
+ }
+
+ private func plutil(_ args: [String]) -> CommandResult {
+ // plutil -extract Label raw -o -
+ guard args.count == 6, let label = plistLabels[args[5]] else {
+ return CommandResult(status: 1, stderr: Data("plutil: no such file".utf8))
+ }
+ return CommandResult(status: 0, stdout: Data((label + "\n").utf8))
+ }
+
private func list(token: String) -> CommandResult {
let source: [FakeDevice]
if token.isEmpty {
From 5b08730fb44a19cd355d382dd4d65638140254c8 Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:44:12 -0700
Subject: [PATCH 05/32] fix(swift): keep non-boolean entries when writing
disabled.plist; lint generated code
DisabledStore.write rebuilt the file from the boolean entries only, so any
other value the runtime had stored was silently deleted. It now reads those
entries back and writes them through unchanged. Covered by a new test.
The generated catalog and forbidden-label files carry swift-format-ignore-file,
which clears 155 lint errors that were only in generated code. Add a
`make swift-lint` target.
---
Makefile | 5 +++-
swift/Sources/SimSlimKit/DisabledStore.swift | 27 ++++++++++++++++++-
.../SimSlimKit/Generated/CatalogData.swift | 1 +
.../Generated/ForbiddenLabels.swift | 1 +
swift/Tests/SimSlimKitTests/SlimTests.swift | 24 +++++++++++++++++
swift/Tools/gen_catalog.py | 2 ++
6 files changed, 58 insertions(+), 2 deletions(-)
diff --git a/Makefile b/Makefile
index 9f6be14..418bb5b 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: app cli check format test swift-test swift-gen swift-gen-check verify-deps
+.PHONY: app cli check format test swift-lint swift-test swift-gen swift-gen-check verify-deps
VERSION ?= $(shell git describe --tags --always --dirty)
@@ -21,6 +21,9 @@ format:
gofmt -w *.go
xcrun swift-format format --in-place --recursive gui
+swift-lint:
+ xcrun swift-format lint --strict --recursive swift/Sources swift/Tests
+
swift-test:
cd swift && swift test
diff --git a/swift/Sources/SimSlimKit/DisabledStore.swift b/swift/Sources/SimSlimKit/DisabledStore.swift
index abc509b..80cf3b7 100644
--- a/swift/Sources/SimSlimKit/DisabledStore.swift
+++ b/swift/Sources/SimSlimKit/DisabledStore.swift
@@ -38,10 +38,24 @@ struct DisabledStore: Sendable {
return try DisabledStore.parse(data)
}
+ /// Entries whose value is not a boolean, kept verbatim across a write.
+ private func readForeign(udid: String) -> [String: Any] {
+ let file = path(udid: udid)
+ guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)),
+ let dict = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ as? [String: Any]
+ else { return [:] }
+ return dict.filter { entry in
+ guard let number = entry.value as? NSNumber else { return true }
+ return CFGetTypeID(number) != CFBooleanGetTypeID()
+ }
+ }
+
/// Merges the transitions into the store, leaving every other entry as it
/// was. The write is atomic so launchd_sim never reads a half-written store.
func write(udid: String, toDisable: [String], toEnable: [String]) throws {
var entries = try readEntries(udid: udid)
+ let foreign = readForeign(udid: udid)
for label in toDisable { entries[label] = true }
for label in toEnable { entries[label] = false }
@@ -55,7 +69,18 @@ struct DisabledStore: Sendable {
let temp = (dir as NSString).appendingPathComponent("disabled.plist.\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(atPath: temp) }
do {
- try DisabledStore.encode(entries).write(to: URL(fileURLWithPath: temp))
+ let data: Data
+ if foreign.isEmpty {
+ data = DisabledStore.encode(entries)
+ } else {
+ // Entries of another type are not ours to drop; let the plist writer
+ // serialize the mixed dictionary.
+ var merged: [String: Any] = foreign
+ for (label, value) in entries { merged[label] = value }
+ data = try PropertyListSerialization.data(
+ fromPropertyList: merged, format: .xml, options: 0)
+ }
+ try data.write(to: URL(fileURLWithPath: temp))
try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: temp)
} catch {
throw SimSlimError("write launchd disable store: \(error.localizedDescription)")
diff --git a/swift/Sources/SimSlimKit/Generated/CatalogData.swift b/swift/Sources/SimSlimKit/Generated/CatalogData.swift
index c6049e5..81e4c46 100644
--- a/swift/Sources/SimSlimKit/Generated/CatalogData.swift
+++ b/swift/Sources/SimSlimKit/Generated/CatalogData.swift
@@ -1,3 +1,4 @@
+// swift-format-ignore-file
// Generated by swift/Tools/gen_catalog.py from profiles.go, service_descriptions.go
// and features.go. Do not edit by hand; rerun the tool.
diff --git a/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
index dcdf7ac..aa74bb6 100644
--- a/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
+++ b/swift/Tests/SimSlimKitTests/Generated/ForbiddenLabels.swift
@@ -1,3 +1,4 @@
+// swift-format-ignore-file
// Generated by swift/Tools/gen_catalog.py from profiles_test.go. Do not edit by hand.
/// Daemons that wedge a simulator when disabled; none may ever be managed.
diff --git a/swift/Tests/SimSlimKitTests/SlimTests.swift b/swift/Tests/SimSlimKitTests/SlimTests.swift
index deb938a..a7a7b02 100644
--- a/swift/Tests/SimSlimKitTests/SlimTests.swift
+++ b/swift/Tests/SimSlimKitTests/SlimTests.swift
@@ -152,6 +152,30 @@ final class SlimTests: XCTestCase {
])
}
+ func testStoreWriteDoesNotDropNonBooleanEntries() throws {
+ let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let text = """
+
+
+ com.apple.other7
+ com.apple.runtime.enabled
+
+ """
+ try text.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8)
+
+ let store = DisabledStore(root: root + "/store")
+ try store.write(udid: udid, toDisable: ["com.apple.mine"], toEnable: [])
+
+ let data = try Data(contentsOf: URL(fileURLWithPath: dir + "/disabled.plist"))
+ let dict = try XCTUnwrap(
+ PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ as? [String: Any])
+ XCTAssertEqual(dict["com.apple.other"] as? Int, 7, "an entry simslim does not own must survive")
+ XCTAssertEqual(dict["com.apple.mine"] as? Bool, true)
+ XCTAssertEqual(dict["com.apple.runtime.enabled"] as? Bool, false)
+ }
+
func testStoreIgnoresNonBooleanValuesAndRejectsGarbage() throws {
let text = """
diff --git a/swift/Tools/gen_catalog.py b/swift/Tools/gen_catalog.py
index 380d990..b2e3bfc 100644
--- a/swift/Tools/gen_catalog.py
+++ b/swift/Tools/gen_catalog.py
@@ -179,6 +179,7 @@ def render_catalog():
features = parse_var(ROOT / "features.go", "Features")
header = (
+ "// swift-format-ignore-file\n"
"// Generated by swift/Tools/gen_catalog.py from profiles.go, service_descriptions.go\n"
"// and features.go. Do not edit by hand; rerun the tool.\n\n"
)
@@ -233,6 +234,7 @@ def render_forbidden():
labels = parse_var(ROOT / "profiles_test.go", "forbiddenLabels")
body = "".join(f" {swift_string(l)},\n" for l in labels)
return (
+ "// swift-format-ignore-file\n"
"// Generated by swift/Tools/gen_catalog.py from profiles_test.go. Do not edit by hand.\n\n"
"/// Daemons that wedge a simulator when disabled; none may ever be managed.\n"
f"let forbiddenLabels: [String] = [\n{body}]\n"
From 5575bc6c97863b83733296543641db18a14e901e Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 02:56:29 -0700
Subject: [PATCH 06/32] fix(swift): harden disabled.plist parsing, cap retry
sleeps, tighten M3a tests
Independent review found no safety bug; it found tests that passed vacuously.
The fake host now scopes devices to their --set and treats the store as
authoritative at boot. A zero-byte store is an empty store; non-dictionary or
old-style plists fall back to launchctl instead of being overwritten.
---
swift/Sources/SimSlimKit/DisabledStore.swift | 13 +++-
swift/Sources/SimSlimKit/Simctl.swift | 9 ++-
swift/Sources/SimSlimKit/Slim.swift | 2 +-
.../MutationCommandTests.swift | 49 +++++++++++--
swift/Tests/SimSlimKitTests/SlimTests.swift | 64 ++++++++++++++---
swift/Tests/TestSupport/FakeHost.swift | 69 +++++++++++--------
6 files changed, 158 insertions(+), 48 deletions(-)
diff --git a/swift/Sources/SimSlimKit/DisabledStore.swift b/swift/Sources/SimSlimKit/DisabledStore.swift
index 80cf3b7..25d9763 100644
--- a/swift/Sources/SimSlimKit/DisabledStore.swift
+++ b/swift/Sources/SimSlimKit/DisabledStore.swift
@@ -125,13 +125,22 @@ struct DisabledStore: Sendable {
/// type are ignored rather than rejected, so an unexpected one cannot make the
/// store unreadable.
static func parse(_ data: Data) throws -> [String: Bool] {
+ // A zero-byte file (a launchd_sim that died mid-write) is an empty store.
+ if data.isEmpty { return [:] }
let object: Any
+ var format = PropertyListSerialization.PropertyListFormat.xml
do {
- object = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ object = try PropertyListSerialization.propertyList(
+ from: data, options: [], format: &format)
} catch {
throw SimSlimError("parse launchd disable store: \(error.localizedDescription)")
}
- guard let dict = object as? [String: Any] else { return [:] }
+ // Foundation also accepts old-style text such as `garbage` as a string plist;
+ // only an XML or binary dictionary is a store.
+ guard format != .openStep, let dict = object as? [String: Any] else {
+ throw SimSlimError(
+ "parse launchd disable store: not an XML or binary property list dictionary")
+ }
var entries: [String: Bool] = [:]
for (label, value) in dict where !label.isEmpty {
// Only real booleans: an integer 1 is not a disable override.
diff --git a/swift/Sources/SimSlimKit/Simctl.swift b/swift/Sources/SimSlimKit/Simctl.swift
index 8b9f449..78cd70f 100644
--- a/swift/Sources/SimSlimKit/Simctl.swift
+++ b/swift/Sources/SimSlimKit/Simctl.swift
@@ -37,6 +37,13 @@ public struct Simctl: Sendable {
// MARK: - Running commands
+ /// Sleeps, but never past the deadline, so an expired operation wakes at once.
+ func pause(_ seconds: TimeInterval) {
+ var length = seconds
+ if let deadline { length = min(length, max(0, deadline.timeIntervalSince(now()))) }
+ sleep(length)
+ }
+
var deadlineExpired: Bool { deadline.map { now() >= $0 } ?? false }
/// Runs a command under the operation deadline. The per-call `timeout` is
@@ -224,7 +231,7 @@ public struct Simctl: Sendable {
if !settling || attempt >= retryDelays.count || deadlineExpired {
throw SimSlimError(message)
}
- sleep(retryDelays[attempt])
+ pause(retryDelays[attempt])
attempt += 1
}
}
diff --git a/swift/Sources/SimSlimKit/Slim.swift b/swift/Sources/SimSlimKit/Slim.swift
index 1881b85..f00de9c 100644
--- a/swift/Sources/SimSlimKit/Slim.swift
+++ b/swift/Sources/SimSlimKit/Slim.swift
@@ -129,7 +129,7 @@ extension Simctl {
reporter, " retrying \(pending.count) failed services (pass \(pass)/\(applyPasses))...")
// Give a launchd that refused the spawns a moment before asking again.
if !retryDelays.isEmpty, !deadlineExpired {
- sleep(retryDelays[min(pass - 2, retryDelays.count - 1)])
+ pause(retryDelays[min(pass - 2, retryDelays.count - 1)])
}
}
let results = PassResults(done: done, total: total, reporter: reporter)
diff --git a/swift/Tests/SimSlimCLITests/MutationCommandTests.swift b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift
index 0e4193c..636932b 100644
--- a/swift/Tests/SimSlimCLITests/MutationCommandTests.swift
+++ b/swift/Tests/SimSlimCLITests/MutationCommandTests.swift
@@ -140,21 +140,56 @@ final class MutationCommandTests: XCTestCase {
func testOnPreserveBootStateStillShutsDownWhenTheOperationFails() {
let host = host(state: "Shutdown")
- host.bootFailure = "Unable to boot"
+ // The boot starts and the device stays Booted, but never becomes ready.
+ host.bootstatusFailure = "Unable to wait for boot"
let r = run(["on", udid, "--preserve-boot-state"], host)
XCTAssertEqual(r.status, 1)
- XCTAssertTrue(r.stderr.contains("Unable to boot"), r.stderr)
- XCTAssertEqual(host.devices[0].state, "Shutdown")
+ XCTAssertTrue(r.stderr.contains("Unable to wait for boot"), r.stderr)
+ XCTAssertEqual(host.devices[0].state, "Shutdown", "the restore ran despite the failure")
+ XCTAssertTrue(subcommands(host).contains("shutdown"))
}
func testOnReportsBothFailuresWhenTheShutdownRestoreFailsToo() {
let host = host(state: "Shutdown")
- host.honoursStore = true
- // The operation boots the device, then shutdown is refused.
- host.shutdownFailure = "Unable to shut down"
+ host.bootstatusFailure = "boot never ready"
+ host.shutdownFailure = "shutdown refused"
let r = run(["on", udid, "--preserve-boot-state"], host)
XCTAssertEqual(r.status, 1)
- XCTAssertTrue(r.stderr.contains("restore original shutdown state"), r.stderr)
+ XCTAssertTrue(
+ r.stderr.hasSuffix(
+ "simslim: simctl bootstatus: exit status 1: boot never ready; additionally could not "
+ + "restore original shutdown state: restore original shutdown state: "
+ + "simctl shutdown: exit status 1: shutdown refused\n"), r.stderr)
+ }
+
+ func testOnlyTheRestoreFailingIsReportedOnItsOwn() {
+ let host = host(state: "Shutdown")
+ host.shutdownFailure = "shutdown refused"
+ let r = run(["on", udid, "--preserve-boot-state"], host)
+ XCTAssertEqual(r.status, 1)
+ XCTAssertTrue(
+ r.stderr.hasSuffix(
+ "simslim: restore original shutdown state: simctl shutdown: exit status 1: shutdown refused\n"
+ ), r.stderr)
+ }
+
+ func testEveryMutationStaysInTheDeviceSetItLivesIn() {
+ // The fake only shows a device through its own --set, like simctl, so a
+ // command that lost the set would fail with "Invalid device".
+ for token in ["testing", "/custom/set"] {
+ let extra: [String] = token == "testing" ? [] : ["--set", token]
+ for state in ["Shutdown", "Booted"] {
+ let host = FakeHost(devices: [])
+ host.sets[token] = [.init(udid: udid, name: "iPhone", state: state)]
+ host.storeRoot = root
+ if state == "Booted" { host.disabled[udid] = [] }
+ for command in [["on"], ["on", "--no-reboot"], ["off"], ["boot"], ["shutdown"]] {
+ let r = runCLI(
+ extra + [command[0], udid] + command.dropFirst(), host: host, storeRoot: root)
+ XCTAssertEqual(r.status, 0, "\(token) \(state) \(command): \(r.stderr)")
+ }
+ }
+ }
}
func testOnAlreadySlimChangesNothing() {
diff --git a/swift/Tests/SimSlimKitTests/SlimTests.swift b/swift/Tests/SimSlimKitTests/SlimTests.swift
index a7a7b02..2dccf87 100644
--- a/swift/Tests/SimSlimKitTests/SlimTests.swift
+++ b/swift/Tests/SimSlimKitTests/SlimTests.swift
@@ -272,15 +272,21 @@ final class SlimTests: XCTestCase {
XCTAssertTrue(transitions(host).isEmpty)
}
- func testStockProfileRestoresEveryManagedLabelAndOnlyThose() throws {
+ func testStockProfileRestoresEveryManagedLabelOfflineAndOnlyThose() throws {
var all = Catalog.managedSet
all.insert("com.apple.unmanaged.service")
let host = host(state: "Booted", disabled: all)
- // The runtime's own record for the unmanaged label lives in the store.
+ // The store records what launchd_sim keeps for the device.
try DisabledStore(root: root + "/store").write(
udid: udid, toDisable: Array(all), toEnable: [])
- let changed = try simctl(host).ensure(set: "default", udid: udid, desired: [])
+ let lines = Log()
+ let changed = try simctl(host).ensure(
+ set: "default", udid: udid, desired: [], reporter: { lines.add($0) })
XCTAssertTrue(changed)
+ // The offline route did it: the store's explicit enables won at boot.
+ XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring \(Catalog.managedSet.count)") })
+ XCTAssertFalse(lines.all.contains { $0.hasPrefix("Could not apply") })
+ XCTAssertTrue(transitions(host).isEmpty)
XCTAssertEqual(host.disabled[udid], ["com.apple.unmanaged.service"])
}
@@ -338,15 +344,39 @@ final class SlimTests: XCTestCase {
}
}
- func testUnreadableStoreFallsBack() throws {
- let host = host()
+ func testUnreadableStoreFallsBackWithoutTouchingIt() throws {
let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
- try "garbage".write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8)
- host.honoursStore = false
- let changed = try simctl(host).ensure(set: "default", udid: udid, desired: profileLabels)
- XCTAssertTrue(changed)
- XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels)
+ for (name, text) in [
+ ("truncated xml", "a"),
+ ("old-style text", "garbage"),
+ ("old-style dictionary", "{ a = b; }"),
+ ] {
+ let host = host()
+ try text.write(toFile: dir + "/disabled.plist", atomically: true, encoding: .utf8)
+ let lines = Log()
+ let changed = try simctl(host).ensure(
+ set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) })
+ XCTAssertTrue(changed, name)
+ XCTAssertFalse(lines.all.contains { $0.hasPrefix("Reconfiguring") }, name)
+ XCTAssertTrue(lines.all.contains { $0.hasPrefix("Could not apply") }, name)
+ XCTAssertEqual(
+ try String(contentsOfFile: dir + "/disabled.plist", encoding: .utf8), text, name)
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), profileLabels, name)
+ }
+ }
+
+ func testAnEmptyStoreFileIsAnEmptyStoreAndTakesTheOfflineRoute() throws {
+ let dir = root + "/store/com.apple.CoreSimulator.SimDevice.\(udid)"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ FileManager.default.createFile(atPath: dir + "/disabled.plist", contents: Data())
+ let host = host()
+ let lines = Log()
+ try simctl(host).ensure(
+ set: "default", udid: udid, desired: profileLabels, reporter: { lines.add($0) })
+ XCTAssertTrue(lines.all.contains { $0.hasPrefix("Reconfiguring") })
+ XCTAssertFalse(lines.all.contains { $0.hasPrefix("Could not apply") })
+ XCTAssertEqual(try DisabledStore(root: root + "/store").readDisabled(udid: udid), profileLabels)
}
// MARK: - applyDelta
@@ -474,6 +504,20 @@ final class SlimTests: XCTestCase {
}
}
+ func testRetrySleepsNeverOutlastTheDeadline() throws {
+ let host = host(state: "Booted")
+ host.queueSpawnResults(
+ udid: udid, [CommandResult(status: 124, stderr: Data("Domain is tearing down".utf8))])
+ var ctl = simctl(host)
+ ctl.retryDelays = [100]
+ ctl.deadline = Date(timeIntervalSinceNow: 5)
+ let slept = Log()
+ ctl.sleep = { slept.add("\($0)") }
+ _ = try ctl.readDisabled(set: "default", udid: udid)
+ let seconds = try XCTUnwrap(slept.all.first.flatMap(Double.init))
+ XCTAssertLessThanOrEqual(seconds, 5)
+ }
+
func testWaitShutdownTimesOut() throws {
let host = host(state: "Booted")
host.stuckBooted = true
diff --git a/swift/Tests/TestSupport/FakeHost.swift b/swift/Tests/TestSupport/FakeHost.swift
index e81d4a9..91b486a 100644
--- a/swift/Tests/TestSupport/FakeHost.swift
+++ b/swift/Tests/TestSupport/FakeHost.swift
@@ -68,6 +68,9 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
/// Fails `simctl boot` / `shutdown` / `bootstatus` with this stderr when set.
public var bootFailure: String?
public var shutdownFailure: String?
+ /// Fails `simctl bootstatus` but leaves the device Booted, as a boot that
+ /// started and never became ready.
+ public var bootstatusFailure: String?
/// Makes the device ignore shutdown, to exercise the shutdown timeout.
public var stuckBooted = false
/// Called at the start of every command, with the arguments; lets a test
@@ -128,42 +131,41 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
{
return printDisabled(udid: rest[1])
}
- if let result = mutating(rest) { return result }
+ if let result = mutating(rest, token: token) { return result }
return failure("FakeHost: unhandled simctl \(rest)")
}
// MARK: - State changes
- private func setState(_ udid: String, _ state: String) -> Bool {
- if let i = devices.firstIndex(where: { $0.udid == udid }) {
+ /// Like simctl, a device is only visible through the `--set` it lives in.
+ private func setState(_ udid: String, _ state: String, token: String) -> Bool {
+ if token.isEmpty {
+ guard let i = devices.firstIndex(where: { $0.udid == udid }) else { return false }
devices[i].state = state
return true
}
- for (token, list) in sets {
- if let i = list.firstIndex(where: { $0.udid == udid }) {
- sets[token]![i].state = state
- return true
- }
- }
- return false
+ guard let i = sets[token]?.firstIndex(where: { $0.udid == udid }) else { return false }
+ sets[token]![i].state = state
+ return true
}
- private func stateOf(_ udid: String) -> String? {
- (devices + sets.values.flatMap { $0 }).first { $0.udid == udid }?.state
+ private func stateOf(_ udid: String, token: String) -> String? {
+ (token.isEmpty ? devices : sets[token] ?? []).first { $0.udid == udid }?.state
}
- private func storeDisabled(_ udid: String) -> Set {
- guard let storeRoot else { return [] }
+ /// The boolean entries launchd_sim would read from the store at start.
+ private func storeEntries(_ udid: String) -> [String: Bool] {
+ guard let storeRoot else { return [:] }
let path = "\(storeRoot)/com.apple.CoreSimulator.SimDevice.\(udid)/disabled.plist"
guard let data = FileManager.default.contents(atPath: path),
let object = try? PropertyListSerialization.propertyList(
from: data, options: [], format: nil),
- let dict = object as? [String: Bool]
- else { return [] }
- return Set(dict.filter { $0.value }.keys)
+ let dict = object as? [String: Any]
+ else { return [:] }
+ return dict.compactMapValues { $0 as? Bool }
}
- private func mutating(_ rest: [String]) -> CommandResult? {
+ private func mutating(_ rest: [String], token: String) -> CommandResult? {
lock.lock()
defer { lock.unlock() }
guard let verb = rest.first else { return nil }
@@ -171,37 +173,50 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
case "boot" where rest.count == 2:
let udid = rest[1]
if let bootFailure { return CommandResult(status: 1, stderr: Data(bootFailure.utf8)) }
- guard let state = stateOf(udid) else { return failure("Invalid device: \(udid)") }
+ guard let state = stateOf(udid, token: token) else {
+ return failure("Invalid device: \(udid)")
+ }
if state == "Booted" {
return CommandResult(
status: 149, stderr: Data("Unable to boot device in current state: Booted".utf8))
}
- _ = setState(udid, "Booted")
+ _ = setState(udid, "Booted", token: token)
var live = persistsOverrides ? (disabled[udid] ?? []) : []
- if honoursStore { live.formUnion(storeDisabled(udid)) }
+ if honoursStore {
+ // The store is authoritative: an explicit true disables, an explicit
+ // false enables even what was disabled before.
+ for (label, off) in storeEntries(udid) {
+ if off { live.insert(label) } else { live.remove(label) }
+ }
+ }
disabled[udid] = live
loaded[udid] = loaded[udid] ?? Self.defaultLoaded
loaded[udid]!.subtract(live)
return CommandResult(status: 0)
case "bootstatus" where rest.count == 3:
- return stateOf(rest[1]) == "Booted"
+ if let bootstatusFailure {
+ return CommandResult(status: 1, stderr: Data(bootstatusFailure.utf8))
+ }
+ return stateOf(rest[1], token: token) == "Booted"
? CommandResult(status: 0) : CommandResult(status: 1, stderr: Data("not booted".utf8))
case "shutdown" where rest.count == 2:
let udid = rest[1]
if let shutdownFailure { return CommandResult(status: 1, stderr: Data(shutdownFailure.utf8)) }
- guard let state = stateOf(udid) else { return failure("Invalid device: \(udid)") }
+ guard let state = stateOf(udid, token: token) else {
+ return failure("Invalid device: \(udid)")
+ }
if state != "Booted" {
return CommandResult(
status: 149, stderr: Data("Unable to shutdown device in current state: Shutdown".utf8))
}
- if !stuckBooted { _ = setState(udid, "Shutdown") }
+ if !stuckBooted { _ = setState(udid, "Shutdown", token: token) }
return CommandResult(status: 0)
case "list" where rest == ["list", "runtimes", "-j"]:
let runtimes = runtimeRoots.map { ["identifier": $0.key, "runtimeRoot": $0.value] }
let data = try! JSONSerialization.data(withJSONObject: ["runtimes": runtimes])
return CommandResult(status: 0, stdout: data)
case "spawn" where rest.count >= 4 && rest[2] == "launchctl":
- return launchctl(udid: rest[1], Array(rest.dropFirst(3)))
+ return launchctl(udid: rest[1], token: token, Array(rest.dropFirst(3)))
default:
return nil
}
@@ -210,8 +225,8 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
/// Labels loaded in a freshly booted simulator.
public static var defaultLoaded: Set { [] }
- private func launchctl(udid: String, _ args: [String]) -> CommandResult? {
- guard stateOf(udid) == "Booted" else {
+ private func launchctl(udid: String, token: String, _ args: [String]) -> CommandResult? {
+ guard stateOf(udid, token: token) == "Booted" else {
return CommandResult(status: 1, stderr: Data("Unable to spawn: not booted".utf8))
}
switch args[0] {
From 770a8be444cc1931f8435345ab247706043bc168 Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 03:15:42 -0700
Subject: [PATCH 07/32] feat(swift): live enable/disable with --save
Batched load/unload, per-label fallbacks, neighbour-category and platform rules,
atomic profile writes. Verified on a throwaway simulator.
---
docs/swift-port-plan.md | 2 +-
swift/Sources/SimSlimCLI/CLI.swift | 6 +-
swift/Sources/SimSlimCLI/Mutations.swift | 85 ++++
swift/Sources/SimSlimCLI/Usage.swift | 4 +-
swift/Sources/SimSlimKit/Live.swift | 300 ++++++++++++
swift/Sources/SimSlimKit/Output.swift | 50 ++
swift/Sources/SimSlimKit/ProfileSave.swift | 111 +++++
.../SimSlimCLITests/LiveCommandTests.swift | 124 +++++
swift/Tests/SimSlimKitTests/LiveTests.swift | 435 ++++++++++++++++++
swift/Tests/TestSupport/FakeHost.swift | 15 +
10 files changed, 1128 insertions(+), 4 deletions(-)
create mode 100644 swift/Sources/SimSlimKit/Live.swift
create mode 100644 swift/Sources/SimSlimKit/ProfileSave.swift
create mode 100644 swift/Tests/SimSlimCLITests/LiveCommandTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/LiveTests.swift
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
index 2f95511..6734d5d 100644
--- a/docs/swift-port-plan.md
+++ b/docs/swift-port-plan.md
@@ -162,6 +162,6 @@ These are not in the first release. The SwiftUI app depends on several of them,
- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first.
- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Also run against a live throwaway simulator in an isolated device set (Xcode 27.2, iOS 27.2).
- **M3a** Slimming: `on`, `off`, `on --no-reboot`, `boot`, `shutdown`, offline fast path, batch unload, 8-worker pool. **Done** (222 tests; 12 mutations in the slimming core, all caught; live run on a throwaway simulator: 246 to 83 processes, about 10.5 GB to 2.7 GB, slim persists across shutdown and boot, `off` restores stock). Awaiting the independent review of this core.
-- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): not started.
+- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): **Done** (14 mutations in the new code caught after two added tests; run live on a throwaway simulator). Awaiting independent review.
- **M4** `watch`.
- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/swift/Sources/SimSlimCLI/CLI.swift b/swift/Sources/SimSlimCLI/CLI.swift
index ff1c36b..4a47b9b 100644
--- a/swift/Sources/SimSlimCLI/CLI.swift
+++ b/swift/Sources/SimSlimCLI/CLI.swift
@@ -41,7 +41,7 @@ public struct CLI {
/// Commands that exist in the Go CLI but are not in the Swift port yet.
static let notYetPorted: Set = [
- "profile", "enable", "disable", "watch", "top", "size", "disk-categories",
+ "profile", "watch", "top", "size", "disk-categories",
"disk-plan", "disk-clean", "clone", "repair-clone", "rename", "erase", "delete",
]
@@ -65,6 +65,8 @@ public struct CLI {
.bool("preserve-boot-state"),
],
"off": [.bool("preserve-boot-state")],
+ "enable": [.bool("json", onlyOnce: true), .string("save")],
+ "disable": [.bool("json", onlyOnce: true), .string("save")],
]
/// Runs the command line (without the program name) and returns the exit status.
@@ -154,6 +156,8 @@ public struct CLI {
case "shutdown": return try cmdShutdown(context)
case "on": return try cmdOn(context)
case "off": return try cmdOff(context)
+ case "enable": return try cmdEnable(context)
+ case "disable": return try cmdDisable(context)
default: preconditionFailure("command \(command) has specs but no handler")
}
}
diff --git a/swift/Sources/SimSlimCLI/Mutations.swift b/swift/Sources/SimSlimCLI/Mutations.swift
index 3e377b6..e68fae2 100644
--- a/swift/Sources/SimSlimCLI/Mutations.swift
+++ b/swift/Sources/SimSlimCLI/Mutations.swift
@@ -200,4 +200,89 @@ extension CLI {
}
return 0
}
+
+ // MARK: - enable / disable
+
+ /// ` [ids...]`, where each ID argument may itself be a comma-separated
+ /// list, as in `simslim enable icloud,photos`.
+ private func udidAndIDs(_ args: [String]) throws -> (udid: String, ids: [String]) {
+ guard let udid = args.first else {
+ throw SimSlimError(
+ "expected a simulator UDID (see `simslim list`), then category IDs or launchd labels (see `simslim profiles`)"
+ )
+ }
+ return (udid, args.dropFirst().flatMap { splitList($0) })
+ }
+
+ /// Progress goes to stderr, except under --json, where a consumer reading a
+ /// combined stream must get clean JSON.
+ private func quietIfJSON(_ context: Context) -> Reporter? {
+ context.parsed.bool("json") ? nil : progress(context)
+ }
+
+ func cmdEnable(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let (udid, ids) = try udidAndIDs(context.parsed.positionals)
+ let out = try bounded(context.simctl, by: context.bootTimeout).enableServices(
+ udid: udid, ids: ids, save: context.parsed.string("save"),
+ reporter: quietIfJSON(context))
+ if json {
+ context.stdout(try jsonText(out))
+ return 0
+ }
+ if out.live {
+ context.stdout("Enabled \(out.labels.count) services on \(udid) without a reboot.\n")
+ }
+ if !out.notStarted.isEmpty {
+ context.stdout(
+ " launchd starts \(out.notStarted.count) of them at the next boot, not in this one: \(out.notStarted.joined(separator: ", "))\n"
+ )
+ }
+ printSaved(context, out)
+ return 0
+ }
+
+ func cmdDisable(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let (udid, ids) = try udidAndIDs(context.parsed.positionals)
+ let out = try bounded(context.simctl, by: context.bootTimeout).disableServices(
+ udid: udid, ids: ids, save: context.parsed.string("save"),
+ reporter: quietIfJSON(context))
+ if json {
+ context.stdout(try jsonText(out))
+ return 0
+ }
+ if out.live {
+ if out.labels.isEmpty {
+ context.stdout("Nothing to stop on \(udid).\n")
+ } else {
+ context.stdout("Stopped \(out.labels.count) services on \(udid) without a reboot.\n")
+ }
+ }
+ if !out.stillEnabled.isEmpty {
+ context.stdout(
+ " \(out.stillEnabled.count) stay enabled for another fully enabled category or the platform: \(out.stillEnabled.joined(separator: ", "))\n"
+ )
+ }
+ printSaved(context, out)
+ return 0
+ }
+
+ /// Closes enable and disable with what persists: the saved profile, or a
+ /// reminder that the next `on` or `watch` pass applies its profile again.
+ private func printSaved(_ context: Context, _ out: ServicesOutput) {
+ if out.saved.isEmpty {
+ context.stdout(
+ "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n"
+ )
+ } else if out.live {
+ context.stdout(
+ "Saved to \(out.saved). Apply it later with `simslim on \(out.udid) --profile \(out.saved)`.\n"
+ )
+ } else {
+ context.stdout(
+ "Saved to \(out.saved); nothing was applied, the simulator is not booted. Apply it with `simslim on \(out.udid) --profile \(out.saved)`.\n"
+ )
+ }
+ }
}
diff --git a/swift/Sources/SimSlimCLI/Usage.swift b/swift/Sources/SimSlimCLI/Usage.swift
index f86bb0c..ebd888d 100644
--- a/swift/Sources/SimSlimCLI/Usage.swift
+++ b/swift/Sources/SimSlimCLI/Usage.swift
@@ -30,8 +30,8 @@ let usageText = """
profile [path] † Interactively build a --profile JSON file
on Slim a simulator (persist disables + reboot slim)
off Restore a simulator to stock (re-enable + reboot)
- enable † Re-enable categories or daemons on a booted simulator now
- disable † Stop categories or daemons on a booted simulator now
+ enable Re-enable categories or daemons on a booted simulator now
+ disable Stop categories or daemons on a booted simulator now
watch † Slim every simulator until Ctrl-C
status Report how slim a booted simulator is
--dropped Also list the disabled daemons grouped by category
diff --git a/swift/Sources/SimSlimKit/Live.swift b/swift/Sources/SimSlimKit/Live.swift
new file mode 100644
index 0000000..00ed538
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Live.swift
@@ -0,0 +1,300 @@
+import Foundation
+
+// `enable` / `disable`: change categories or daemons on a booted simulator now,
+// without a reboot, keeping no state of their own. The profile file given with
+// --save is the only thing that persists.
+
+extension Simctl {
+ /// Re-enables categories (IDs from `simslim profiles`) and individual managed
+ /// daemons on a booted simulator: each disable override is lifted and each job
+ /// loaded into the running boot session. With `save`, the change is also
+ /// written to that profile file once the live change succeeded; a simulator
+ /// that is not booted only gets the file, and without `save` it is an error.
+ public func enableServices(
+ udid: String, ids: [String], save: String = "", reporter: Reporter? = nil
+ ) throws -> ServicesOutput {
+ let (categories, labels) = try resolveServiceIDs(ids)
+ if categories.count + labels.count == 0 {
+ throw SimSlimError(
+ "name at least one category ID or managed daemon to enable (see `simslim profiles`)")
+ }
+ try checkSave(save, categories: categories, labels: labels, enable: true)
+ let device = try serviceTarget(udid: udid, save: save)
+ var out = ServicesOutput(action: "enable", udid: device.udid, live: device.state == "Booted")
+ if out.live {
+ out.labels = Catalog.covered(categories: categories, labels: labels).sorted()
+ report(reporter, "Starting \(out.labels.count) background services without a reboot...")
+ do {
+ out.notStarted = try startServices(device: device, labels: out.labels, reporter: reporter)
+ } catch {
+ throw unsaved(error, save: save)
+ }
+ }
+ try saveServices(&out, save: save, categories: categories, labels: labels, enable: true)
+ return out
+ }
+
+ /// The inverse: stops categories and daemons at once, each one booted out of
+ /// the running boot session with its disable override set. A daemon named on
+ /// its own is always stopped, unless the platform needs it. A daemon a named
+ /// category covers is also kept while another category that lists it is fully
+ /// enabled right now. Both are reported in `stillEnabled`.
+ public func disableServices(
+ udid: String, ids: [String], save: String = "", reporter: Reporter? = nil
+ ) throws -> ServicesOutput {
+ let (categories, labels) = try resolveServiceIDs(ids)
+ if categories.count + labels.count == 0 {
+ throw SimSlimError(
+ "name at least one category ID or managed daemon to disable (see `simslim profiles`)")
+ }
+ for label in labels where !Catalog.slimmableSet.contains(label) {
+ throw SimSlimError(
+ "\(label) is never disabled: simslim keeps it running for compatibility (see `simslim profiles`)"
+ )
+ }
+ try checkSave(save, categories: categories, labels: labels, enable: false)
+ let device = try serviceTarget(udid: udid, save: save)
+ var out = ServicesOutput(action: "disable", udid: device.udid, live: device.state == "Booted")
+ if out.live {
+ do {
+ try stopNamed(
+ device: device, out: &out, categories: categories, labels: labels, reporter: reporter)
+ } catch {
+ throw unsaved(error, save: save)
+ }
+ }
+ try saveServices(&out, save: save, categories: categories, labels: labels, enable: false)
+ return out
+ }
+
+ /// Stops what `disableServices` was told to on a booted simulator, filling
+ /// `out.labels` with what it stops and `out.stillEnabled` with what it keeps.
+ private func stopNamed(
+ device: Device, out: inout ServicesOutput, categories: [String], labels: [String],
+ reporter: Reporter?
+ ) throws {
+ let disabled = try readDisabled(set: device.set, udid: device.udid)
+ let covered = Catalog.covered(categories: categories, labels: labels)
+ let allowed = desiredForDevice(device, covered)
+ let kept = enabledNeighbours(disabling: categories, named: labels, disabled: disabled)
+ for label in covered.sorted() {
+ if allowed.contains(label) && Catalog.slimmableSet.contains(label) && !kept.contains(label) {
+ out.labels.append(label)
+ } else {
+ out.stillEnabled.append(label)
+ }
+ }
+ if out.labels.isEmpty { return }
+ report(reporter, "Stopping \(out.labels.count) background services without a reboot...")
+ try stopServices(device: device, labels: out.labels, reporter: reporter)
+ }
+
+ /// The labels the disabling categories cover that another category, one not
+ /// being disabled and with every label enabled right now, also lists. Only the
+ /// live state says which features are on, so that decides: stopping the store
+ /// keeps the AMS daemons iCloud shares while iCloud is fully running. A label
+ /// named on its own is never kept.
+ func enabledNeighbours(disabling: [String], named: [String], disabled: Set)
+ -> Set
+ {
+ var covered = Catalog.covered(categories: disabling, labels: [])
+ covered.subtract(named)
+ var kept = Set()
+ for category in Catalog.categories where !disabling.contains(category.id) {
+ let enabled = category.labels.allSatisfy { !disabled.contains($0) }
+ let shares = category.labels.contains { covered.contains($0) }
+ if !enabled || !shares { continue }
+ for label in category.labels where covered.contains(label) { kept.insert(label) }
+ }
+ return kept
+ }
+
+ // MARK: - --save
+
+ /// Validates the profile file --save names before anything changes, so a bad
+ /// file fails the command up front.
+ private func checkSave(_ save: String, categories: [String], labels: [String], enable: Bool)
+ throws
+ {
+ if save.isEmpty { return }
+ _ = try updatedProfile(path: save, categories: categories, labels: labels, enable: enable)
+ }
+
+ private func saveServices(
+ _ out: inout ServicesOutput, save: String, categories: [String], labels: [String],
+ enable: Bool
+ ) throws {
+ if save.isEmpty { return }
+ do {
+ try SimSlimKit.saveServices(
+ path: save, categories: categories, labels: labels, enable: enable)
+ } catch {
+ if out.live {
+ throw SimSlimError(
+ "the simulator was changed, but profile \(save) was not: \(error.localizedDescription)")
+ }
+ throw error
+ }
+ out.saved = save
+ }
+
+ /// Notes on a failed live change that --save left the profile alone.
+ private func unsaved(_ error: Error, save: String) -> Error {
+ if save.isEmpty { return error }
+ return SimSlimError("\(error.localizedDescription) (profile \(save) not changed)")
+ }
+
+ /// Resolves the exact simulator `enable` and `disable` act on, so a simctl
+ /// alias such as "all" can never fan out across devices. Only a booted
+ /// simulator can change live; with a profile to save, any simulator is fine.
+ private func serviceTarget(udid: String, save: String) throws -> Device {
+ let device = try findDevice(udid: udid)
+ if device.state != "Booted" && save.isEmpty {
+ throw SimSlimError(
+ "simulator \(device.udid) is not booted (it is \(device.state)): enable and disable change a running simulator only; pass --save to record the change, then apply it with `simslim on \(device.udid) --profile `"
+ )
+ }
+ return device
+ }
+
+ /// Sorts the IDs `enable` and `disable` accept into category IDs and
+ /// individual managed labels, rejecting anything else.
+ func resolveServiceIDs(_ ids: [String]) throws -> (categories: [String], labels: [String]) {
+ var categories: [String] = []
+ var labels: [String] = []
+ var seen = Set()
+ for id in ids {
+ if seen.contains(id) { continue }
+ if Catalog.category(id: id) != nil {
+ categories.append(id)
+ } else if Catalog.managedSet.contains(id) {
+ labels.append(id)
+ } else {
+ throw SimSlimError(
+ "unknown category or managed daemon \"\(id)\" (see `simslim profiles`)")
+ }
+ seen.insert(id)
+ }
+ return (categories.sorted(), labels.sorted())
+ }
+
+ // MARK: - Live transitions
+
+ /// Lifts the disable override of each label and loads its job into the running
+ /// boot session. One `launchctl load -w` per chunk handles every label whose
+ /// job plist is found; what is still disabled afterwards gets a per-label
+ /// `enable`, and what is still not loaded a per-label bootstrap. A label with
+ /// no plist (an XPC service, for example) only needs its override lifted.
+ /// Labels launchd re-enabled but would not load in this boot session are
+ /// returned; they start at the next boot. A label left disabled is an error.
+ func startServices(device: Device, labels: [String], reporter: Reporter?) throws -> [String] {
+ let set = device.set
+ let udid = device.udid
+ var (disabled, loaded) = try serviceState(set: set, udid: udid)
+ let candidates = labels.filter { disabled.contains($0) || !loaded.contains($0) }
+ var plists: [String: String] = [:]
+ var haveRoot = false
+ if !device.runtimeID.isEmpty && !candidates.isEmpty,
+ let root = try? runtimeRoot(runtimeID: device.runtimeID)
+ {
+ plists = launchdJobPlists(
+ root: root, labels: candidates, plistLabel: { try self.readPlistLabel(path: $0) })
+ haveRoot = true
+ }
+ // Without the RuntimeRoot nothing tells a missing plist from an unknown one,
+ // so every unloaded label counts as one launchd should load.
+ let loadable: (String) -> Bool = { plists[$0] != nil || !haveRoot }
+ let pending = candidates.filter { disabled.contains($0) || loadable($0) }
+ if pending.isEmpty {
+ report(reporter, " all \(labels.count) services were already running")
+ return []
+ }
+ let paths = pending.compactMap { plists[$0] }
+ if !paths.isEmpty {
+ batchJobs(set: set, udid: udid, verb: "load", paths: paths)
+ (disabled, loaded) = try serviceState(set: set, udid: udid)
+ let left = stillToStart(pending, disabled: disabled, loaded: loaded, loadable: loadable)
+ report(
+ reporter, " \(pending.count - left.count)/\(pending.count) services started in one batch")
+ }
+ var toEnable: [String] = []
+ var unloaded: [String: String] = [:]
+ for label in pending {
+ if disabled.contains(label) { toEnable.append(label) }
+ if let plist = plists[label], !loaded.contains(label) { unloaded[label] = plist }
+ }
+ if !toEnable.isEmpty {
+ try applyDelta(
+ set: set, udid: udid, toDisable: [], toEnable: toEnable, disableAction: .overrideOnly,
+ reporter: reporter)
+ }
+ if !unloaded.isEmpty { bootstrapJobs(set: set, udid: udid, plists: unloaded) }
+ if toEnable.count + unloaded.count > 0 {
+ (disabled, loaded) = try serviceState(set: set, udid: udid)
+ }
+ var still: [String] = []
+ var notStarted: [String] = []
+ for label in pending {
+ if disabled.contains(label) {
+ still.append(label)
+ } else if !loaded.contains(label) && loadable(label) {
+ notStarted.append(label)
+ }
+ }
+ if !still.isEmpty {
+ throw SimSlimError(
+ "\(still.count) of \(pending.count) services are still disabled: \(still.joined(separator: ", "))"
+ )
+ }
+ return notStarted
+ }
+
+ /// The labels that are still disabled, or still not loaded although launchd
+ /// could load them.
+ func stillToStart(
+ _ labels: [String], disabled: Set, loaded: Set,
+ loadable: (String) -> Bool
+ ) -> [String] {
+ labels.filter { disabled.contains($0) || (!loaded.contains($0) && loadable($0)) }
+ }
+
+ /// One `launchctl bootstrap` per job, for the few the batch load left behind.
+ /// The exit status is not trusted (an already-loaded job exits 37); the
+ /// caller reads the state back.
+ func bootstrapJobs(set: String, udid: String, plists: [String: String]) {
+ for label in plists.keys.sorted() {
+ if deadlineExpired { return }
+ _ = try? exec(
+ .xcrun,
+ simctlArgs(set: set, ["spawn", udid, "launchctl", "bootstrap", "system", plists[label]!]),
+ timeout: spawnTimeout)
+ }
+ }
+
+ /// The disable overrides and the loaded jobs, read together.
+ func serviceState(set: String, udid: String) throws -> (
+ disabled: Set, loaded: Set
+ ) {
+ (
+ try readDisabled(set: set, udid: udid),
+ try loadedLabels(set: set, udid: udid)
+ )
+ }
+
+ /// Disables each label and boots its job out of the running boot session: one
+ /// `launchctl unload -w` per chunk first, then a per-label disable and bootout
+ /// for whatever the batch missed. Every override is read back.
+ func stopServices(device: Device, labels: [String], reporter: Reporter?) throws {
+ let remaining = unloadInBatch(
+ set: device.set, udid: device.udid, runtimeID: device.runtimeID, labels: labels,
+ reporter: reporter)
+ try applyDelta(
+ set: device.set, udid: device.udid, toDisable: remaining, toEnable: [],
+ disableAction: .liveStop, reporter: reporter)
+ let after = try readDisabled(set: device.set, udid: device.udid)
+ let missing = labels.filter { !after.contains($0) }.count
+ if missing > 0 {
+ throw SimSlimError("\(missing) of \(labels.count) disable overrides did not take")
+ }
+ }
+}
diff --git a/swift/Sources/SimSlimKit/Output.swift b/swift/Sources/SimSlimKit/Output.swift
index 0e9c676..f64cf5c 100644
--- a/swift/Sources/SimSlimKit/Output.swift
+++ b/swift/Sources/SimSlimKit/Output.swift
@@ -112,3 +112,53 @@ public struct SimulatorMutationOutput: Codable, Equatable, Sendable {
sourceUdid = try c.decodeIfPresent(String.self, forKey: .sourceUdid) ?? ""
}
}
+
+/// The result of `enable` and `disable`.
+public struct ServicesOutput: Codable, Equatable, Sendable {
+ public var action: String // "enable" or "disable"
+ public var udid: String
+ public var live: Bool // false: the simulator is not booted, only the profile was saved
+ public var labels: [String] // daemons enabled, or stopped by disable
+ public var notStarted: [String] // enable: re-enabled, but launchd starts them at the next boot
+ public var stillEnabled: [String] // disable: kept running for another category or the platform
+ public var saved: String // the profile file --save created or updated
+
+ public init(
+ action: String, udid: String, live: Bool, labels: [String] = [], notStarted: [String] = [],
+ stillEnabled: [String] = [], saved: String = ""
+ ) {
+ self.action = action
+ self.udid = udid
+ self.live = live
+ self.labels = labels
+ self.notStarted = notStarted
+ self.stillEnabled = stillEnabled
+ self.saved = saved
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case action, udid, live, labels, notStarted, stillEnabled, saved
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(action, forKey: .action)
+ try c.encode(udid, forKey: .udid)
+ try c.encode(live, forKey: .live)
+ try c.encode(labels, forKey: .labels) // always present, `[]` when empty
+ if !notStarted.isEmpty { try c.encode(notStarted, forKey: .notStarted) } // Go omitempty
+ if !stillEnabled.isEmpty { try c.encode(stillEnabled, forKey: .stillEnabled) }
+ if !saved.isEmpty { try c.encode(saved, forKey: .saved) }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ action = try c.decode(String.self, forKey: .action)
+ udid = try c.decode(String.self, forKey: .udid)
+ live = try c.decode(Bool.self, forKey: .live)
+ labels = try c.decode([String].self, forKey: .labels)
+ notStarted = try c.decodeIfPresent([String].self, forKey: .notStarted) ?? []
+ stillEnabled = try c.decodeIfPresent([String].self, forKey: .stillEnabled) ?? []
+ saved = try c.decodeIfPresent(String.self, forKey: .saved) ?? ""
+ }
+}
diff --git a/swift/Sources/SimSlimKit/ProfileSave.swift b/swift/Sources/SimSlimKit/ProfileSave.swift
new file mode 100644
index 0000000..c775a10
--- /dev/null
+++ b/swift/Sources/SimSlimKit/ProfileSave.swift
@@ -0,0 +1,111 @@
+import Foundation
+
+// `enable --save` / `disable --save`: record the change in a profile file, the one
+// place that describes a slim simulator, so `on`, `watch` and `verify` with that
+// profile agree with it.
+
+extension Catalog {
+ /// Every managed label the categories and labels name.
+ static func covered(categories ids: [String], labels: [String]) -> Set {
+ var covered = Set()
+ for id in ids {
+ if let category = category(id: id) { covered.formUnion(category.labels) }
+ }
+ for label in labels where managedSet.contains(label) { covered.insert(label) }
+ return covered
+ }
+}
+
+/// Reads and validates a profile file, keeping its entries as written. A missing
+/// file is the default profile.
+func readSlimProfile(path: String) throws -> (profile: SlimProfile, exists: Bool) {
+ guard FileManager.default.fileExists(atPath: path) else { return (SlimProfile(), false) }
+ let data: Data
+ do {
+ data = try Data(contentsOf: URL(fileURLWithPath: path))
+ } catch {
+ throw SimSlimError("read profile \(path): \(error.localizedDescription)")
+ }
+ let profile = try parseSlimProfile(data, path: path)
+ _ = try profile.resolve(path: path)
+ return (profile, true)
+}
+
+/// The profile at `path` with the change applied, and whether anything changed.
+/// Writes nothing. Enabling adds each category to `except` and each daemon to
+/// `keep`, unless an excepted category already keeps it; disabling removes them.
+func updatedProfile(path: String, categories: [String], labels: [String], enable: Bool) throws
+ -> (data: Data?, changed: Bool)
+{
+ var (profile, exists) = try readSlimProfile(path: path)
+ let beforeExcept = profile.except
+ let beforeKeep = profile.keep
+ if enable {
+ for id in categories where !profile.except.contains(id) { profile.except.append(id) }
+ let excepted = Catalog.covered(categories: profile.except, labels: [])
+ for label in labels where !excepted.contains(label) && !profile.keep.contains(label) {
+ profile.keep.append(label)
+ }
+ } else {
+ profile.except.removeAll { categories.contains($0) }
+ profile.keep.removeAll { labels.contains($0) }
+ // Removing a daemon from `keep` is not enough while a category the profile
+ // still excepts lists it.
+ for label in labels {
+ for id in profile.except where Catalog.covered(categories: [id], labels: []).contains(label) {
+ throw SimSlimError(
+ "profile \(path) keeps \(label) enabled through category \"\(id)\"; disable that category instead, or edit the file"
+ )
+ }
+ }
+ }
+ if exists && beforeExcept == profile.except && beforeKeep == profile.keep { return (nil, false) }
+ return (marshalProfile(profile), true)
+}
+
+/// Records an `enable` or `disable` in a profile file. An unchanged profile is
+/// not rewritten; a changed one is replaced atomically.
+public func saveServices(path: String, categories: [String], labels: [String], enable: Bool) throws
+{
+ let (data, changed) = try updatedProfile(
+ path: path, categories: categories, labels: labels, enable: enable)
+ guard changed, let data else { return }
+ try writeFileAtomic(path: path, data: data)
+}
+
+/// Replaces `path` through a temporary file in the same directory, so a
+/// concurrent reader sees the old file or the new one, never half of it. A
+/// symlink is followed, and an existing file keeps its mode.
+func writeFileAtomic(path original: String, data: Data) throws {
+ var path = original
+ var mode = 0o644
+ let resolved = (original as NSString).resolvingSymlinksInPath
+ if FileManager.default.fileExists(atPath: resolved) {
+ path = resolved
+ if let attrs = try? FileManager.default.attributesOfItem(atPath: path),
+ let perm = attrs[.posixPermissions] as? Int
+ {
+ mode = perm & 0o777
+ }
+ }
+ let dir = (path as NSString).deletingLastPathComponent
+ let base = (path as NSString).lastPathComponent
+ let temp = ((dir.isEmpty ? "." : dir) as NSString).appendingPathComponent(
+ ".\(base).\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(atPath: temp) }
+ do {
+ guard FileManager.default.createFile(atPath: temp, contents: nil) else {
+ throw SimSlimError("cannot create \(temp)")
+ }
+ let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: temp))
+ try handle.write(contentsOf: data)
+ try handle.synchronize()
+ try handle.close()
+ try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: temp)
+ } catch {
+ throw SimSlimError("write profile \(path): \(error.localizedDescription)")
+ }
+ guard rename(temp, path) == 0 else {
+ throw SimSlimError("write profile \(path): \(String(cString: strerror(errno)))")
+ }
+}
diff --git a/swift/Tests/SimSlimCLITests/LiveCommandTests.swift b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift
new file mode 100644
index 0000000..cd8444d
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift
@@ -0,0 +1,124 @@
+import SimSlimKit
+import TestSupport
+import XCTest
+
+@testable import SimSlimCLI
+
+final class LiveCommandTests: XCTestCase {
+ private let udid = "AAAAAAAA-0000-0000-0000-000000000001"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-livecli-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ private var search: [String] { Catalog.category(id: "search")!.labels }
+
+ private func host(state: String = "Booted", disabled: Set = []) -> FakeHost {
+ let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: state)])
+ if state == "Booted" {
+ host.disabled[udid] = disabled
+ host.loaded[udid] = Set(search) // loaded but disabled: only the override is lifted
+ }
+ return host
+ }
+
+ func testEnableWithNoUDIDOrNoIDs() {
+ let none = runCLI(["enable"], host: host())
+ XCTAssertEqual(none.status, 1)
+ XCTAssertEqual(
+ none.stderr,
+ "simslim: expected a simulator UDID (see `simslim list`), then category IDs or launchd labels (see `simslim profiles`)\n"
+ )
+ let noIDs = runCLI(["enable", udid], host: host())
+ XCTAssertEqual(noIDs.status, 1)
+ XCTAssertTrue(
+ noIDs.stderr.contains("name at least one category ID or managed daemon to enable"))
+ }
+
+ func testEnableTextOutput() {
+ let host = host(disabled: Set(search))
+ let r = runCLI(["enable", udid, "search"], host: host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(
+ r.stdout,
+ "Enabled \(search.count) services on \(udid) without a reboot.\n"
+ + "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n"
+ )
+ XCTAssertTrue(r.stderr.contains("Starting \(search.count) background services"))
+ }
+
+ func testIDsMayBeCommaSeparatedOrRepeated() {
+ let host = host(disabled: Set(search))
+ let r = runCLI(["enable", udid, "search,siri", "search"], host: host, storeRoot: root)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ let siri = Catalog.category(id: "siri")!.labels
+ XCTAssertTrue(r.stdout.hasPrefix("Enabled \(Set(search + siri).count) services"), r.stdout)
+ }
+
+ func testEnableJSONIsCleanAndQuiet() throws {
+ let host = host(disabled: Set(search))
+ let r = runCLI(["enable", udid, "search", "--json"], host: host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(r.stderr, "")
+ let out = try JSONDecoder().decode(ServicesOutput.self, from: Data(r.stdout.utf8))
+ XCTAssertEqual(out.action, "enable")
+ XCTAssertTrue(out.live)
+ XCTAssertEqual(out.labels, search.sorted())
+ XCTAssertFalse(r.stdout.contains("notStarted"), "omitted when empty")
+ XCTAssertFalse(r.stdout.contains("saved"))
+ }
+
+ func testDisableJSONKeepsLabelsAsAnEmptyArray() {
+ let host = host()
+ let label = Catalog.managedSet.subtracting(Catalog.slimmableSet).sorted()[0]
+ XCTAssertEqual(runCLI(["disable", udid, label, "--json"], host: host).status, 1)
+ // A shutdown simulator with --save: nothing live, labels is still `[]`.
+ let shut = self.host(state: "Shutdown")
+ let r = runCLI(
+ ["disable", udid, "search", "--json", "--save", root + "/p.json"], host: shut)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertTrue(
+ r.stdout.contains("\"labels\" : [\n\n ]") || r.stdout.contains("\"labels\" : [ ]")
+ || r.stdout.contains("\"labels\" : []"), r.stdout)
+ XCTAssertTrue(r.stdout.contains("\"live\" : false"))
+ }
+
+ func testDisableTextOutputAndNothingToStop() {
+ let host = host()
+ host.loaded[udid] = Set(search)
+ let r = runCLI(["disable", udid, "search"], host: host)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertTrue(
+ r.stdout.hasPrefix("Stopped \(search.count) services on \(udid) without a reboot.\n"))
+ }
+
+ func testSaveMessages() {
+ let live = runCLI(
+ ["enable", udid, "search", "--save", root + "/a.json"],
+ host: host(disabled: Set(search)))
+ XCTAssertEqual(live.status, 0, live.stderr)
+ XCTAssertTrue(
+ live.stdout.hasSuffix(
+ "Saved to \(root)/a.json. Apply it later with `simslim on \(udid) --profile \(root)/a.json`.\n"
+ ), live.stdout)
+ let off = runCLI(
+ ["enable", udid, "search", "--save", root + "/b.json"], host: host(state: "Shutdown"))
+ XCTAssertEqual(off.status, 0, off.stderr)
+ XCTAssertEqual(
+ off.stdout,
+ "Saved to \(root)/b.json; nothing was applied, the simulator is not booted. Apply it with `simslim on \(udid) --profile \(root)/b.json`.\n"
+ )
+ }
+
+ func testAliasAndExtraFlagsAreRejected() {
+ XCTAssertEqual(runCLI(["enable", "all", "search"], host: host()).status, 1)
+ XCTAssertEqual(runCLI(["disable", "booted", "search"], host: host()).status, 1)
+ XCTAssertEqual(runCLI(["enable", udid, "search", "--no-such"], host: host()).status, 1)
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/LiveTests.swift b/swift/Tests/SimSlimKitTests/LiveTests.swift
new file mode 100644
index 0000000..9c573df
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/LiveTests.swift
@@ -0,0 +1,435 @@
+import TestSupport
+import XCTest
+
+@testable import SimSlimKit
+
+private final class Lines: @unchecked Sendable {
+ private let lock = NSLock()
+ private var items: [String] = []
+ func add(_ line: String) {
+ lock.lock()
+ items.append(line)
+ lock.unlock()
+ }
+ var all: [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return items
+ }
+}
+
+final class LiveTests: XCTestCase {
+ private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2"
+ private let watch = "com.apple.CoreSimulator.SimRuntime.watchOS-11-5"
+ private let udid = "AAAAAAAA-0000-0000-0000-000000000001"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-live-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ private func host(
+ state: String = "Booted", runtime: String? = nil, disabled: Set = [],
+ loaded: Set = []
+ ) -> FakeHost {
+ let host = FakeHost(devices: [
+ .init(udid: udid, name: "iPhone", runtime: runtime ?? ios, state: state)
+ ])
+ host.storeRoot = root + "/store"
+ if state == "Booted" {
+ host.disabled[udid] = disabled
+ host.loaded[udid] = loaded
+ }
+ return host
+ }
+
+ private func simctl(_ host: FakeHost) -> Simctl {
+ var simctl = Simctl(runner: host)
+ simctl.retryDelays = [0, 0, 0, 0]
+ simctl.sleep = { _ in }
+ return simctl
+ }
+
+ private func installPlists(
+ _ host: FakeHost, labels: [String], missing: Set = []
+ ) throws {
+ let dir = root + "/runtime/System/Library/LaunchDaemons"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ host.runtimeRoots[ios] = root + "/runtime"
+ host.runtimeRoots[watch] = root + "/runtime"
+ for label in labels where !missing.contains(label) {
+ let path = "\(dir)/\(label).plist"
+ FileManager.default.createFile(atPath: path, contents: Data())
+ host.plistLabels[path] = label
+ }
+ }
+
+ private func spawnVerbs(_ host: FakeHost) -> [String] {
+ host.calls.compactMap { call in
+ guard call.executable == .xcrun, call.arguments.count > 4, call.arguments[1] == "spawn"
+ else { return nil }
+ return call.arguments[4]
+ }
+ }
+
+ private func category(_ id: String) -> [String] { Catalog.category(id: id)!.labels }
+
+ private var profilePath: String { root + "/profile.json" }
+
+ private func writeProfile(_ text: String) throws {
+ try text.write(toFile: profilePath, atomically: true, encoding: .utf8)
+ }
+
+ // MARK: - enable
+
+ func testEnableLoadsACategoryInOneBatchAndSortsTheResult() throws {
+ let labels = category("search")
+ let host = host(disabled: Set(labels))
+ try installPlists(host, labels: labels)
+ let lines = Lines()
+ let out = try simctl(host).enableServices(
+ udid: udid, ids: ["search"], reporter: { lines.add($0) })
+ XCTAssertEqual(out.action, "enable")
+ XCTAssertTrue(out.live)
+ XCTAssertEqual(out.labels, labels.sorted())
+ XCTAssertEqual(out.notStarted, [])
+ XCTAssertEqual(host.disabled[udid], [])
+ XCTAssertEqual(host.loaded[udid], Set(labels))
+ XCTAssertEqual(spawnVerbs(host).filter { $0 == "load" }.count, 1)
+ XCTAssertFalse(spawnVerbs(host).contains("enable"), "the batch did everything")
+ XCTAssertTrue(
+ lines.all.contains(" \(labels.count)/\(labels.count) services started in one batch"))
+ }
+
+ func testEnableOnlyLiftsTheOverrideOfALabelWithNoPlist() throws {
+ let label = category("search")[0]
+ let host = host(disabled: [label])
+ try installPlists(host, labels: category("search"), missing: [label])
+ let out = try simctl(host).enableServices(udid: udid, ids: [label])
+ XCTAssertEqual(host.disabled[udid], [])
+ XCTAssertEqual(out.labels, [label])
+ XCTAssertEqual(out.notStarted, [], "launchd starts an on-demand job when asked")
+ XCTAssertEqual(spawnVerbs(host).filter { $0 == "enable" }.count, 1)
+ XCTAssertFalse(spawnVerbs(host).contains("bootstrap"))
+ }
+
+ func testEnableReportsALabelThatOnlyStartsAtTheNextBoot() throws {
+ let labels = category("search")
+ let stubborn = labels[0]
+ let host = host(disabled: Set(labels))
+ try installPlists(host, labels: labels)
+ host.failTransition = { verb, label in
+ label == stubborn && (verb == "load" || verb == "bootstrap")
+ ? CommandResult(status: 1) : nil
+ }
+ let out = try simctl(host).enableServices(udid: udid, ids: ["search"])
+ XCTAssertEqual(out.notStarted, [stubborn])
+ XCTAssertFalse(host.disabled[udid]!.contains(stubborn), "its override is lifted")
+ XCTAssertTrue(spawnVerbs(host).contains("bootstrap"))
+ }
+
+ func testEnableFailsWhenALabelStaysDisabled() throws {
+ let label = category("search")[0]
+ let host = host(disabled: [label])
+ try installPlists(host, labels: [], missing: [])
+ host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil }
+ XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: [label])) {
+ XCTAssertTrue(
+ "\($0)".contains("still disabled") || "\($0)".contains("transitions failed"), "\($0)")
+ }
+ }
+
+ func testEnableFailsWhenTheOverrideIsAcceptedButNeverLifted() throws {
+ let label = category("search")[0]
+ let host = host(disabled: [label])
+ // launchctl exits 0 for `enable` but the override stays: only the read-back sees it.
+ host.failTransition = { verb, l in
+ verb == "enable" && l == label ? CommandResult(status: 0) : nil
+ }
+ XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: [label])) {
+ XCTAssertEqual("\($0)", "1 of 1 services are still disabled: \(label)")
+ }
+ }
+
+ func testEnableOfARunningCategoryChangesNothing() throws {
+ let labels = category("search")
+ let host = host(loaded: Set(labels))
+ try installPlists(host, labels: labels)
+ let lines = Lines()
+ let out = try simctl(host).enableServices(
+ udid: udid, ids: ["search"], reporter: { lines.add($0) })
+ XCTAssertEqual(out.notStarted, [])
+ XCTAssertTrue(lines.all.contains(" all \(labels.count) services were already running"))
+ XCTAssertEqual(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }, [])
+ }
+
+ func testEnableRejectsBadInputBeforeTouchingAnything() throws {
+ let host = host()
+ for (ids, fragment) in [
+ (["no-such-thing"], "unknown category or managed daemon \"no-such-thing\""),
+ (["com.apple.not.managed"], "unknown category or managed daemon"),
+ ([], "name at least one category ID or managed daemon to enable"),
+ ] {
+ XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: ids)) {
+ XCTAssertTrue("\($0)".contains(fragment), "\($0)")
+ }
+ }
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ func testEnableNeverReachesAnAlias() throws {
+ let host = host(disabled: ["com.apple.x"])
+ XCTAssertThrowsError(try simctl(host).enableServices(udid: "all", ids: ["search"])) {
+ XCTAssertEqual("\($0)", "no simulator with udid all")
+ }
+ XCTAssertTrue(spawnVerbs(host).isEmpty)
+ }
+
+ func testEnableOnAShutdownSimulatorNeedsSave() throws {
+ let host = host(state: "Shutdown")
+ XCTAssertThrowsError(try simctl(host).enableServices(udid: udid, ids: ["search"])) {
+ let text = "\($0)"
+ XCTAssertTrue(text.contains("is not booted (it is Shutdown)"), text)
+ XCTAssertTrue(text.contains("pass --save "), text)
+ }
+ XCTAssertTrue(spawnVerbs(host).isEmpty)
+ }
+
+ func testEnableOnAShutdownSimulatorOnlyWritesTheProfile() throws {
+ let host = host(state: "Shutdown")
+ let out = try simctl(host).enableServices(udid: udid, ids: ["search"], save: profilePath)
+ XCTAssertFalse(out.live)
+ XCTAssertEqual(out.labels, [])
+ XCTAssertEqual(out.saved, profilePath)
+ XCTAssertTrue(spawnVerbs(host).isEmpty)
+ XCTAssertEqual(try loadSlimProfile(path: profilePath).exceptCategories, ["search"])
+ }
+
+ // MARK: - disable
+
+ func testDisableStopsACategoryAndReadsItBack() throws {
+ let labels = category("search")
+ let host = host(loaded: Set(labels))
+ try installPlists(host, labels: labels)
+ let out = try simctl(host).disableServices(udid: udid, ids: ["search"])
+ XCTAssertEqual(out.labels, labels.sorted())
+ XCTAssertEqual(out.stillEnabled, [])
+ XCTAssertEqual(host.disabled[udid], Set(labels))
+ XCTAssertEqual(host.loaded[udid], [])
+ }
+
+ /// What stopping `target` must keep, worked out independently: the labels it
+ /// lists that some other category with every daemon enabled also lists.
+ private func expectedKept(stopping target: String, down: Set) -> Set {
+ var kept = Set()
+ for other in Catalog.categories where other.id != target {
+ if !down.isDisjoint(with: other.labels) { continue }
+ kept.formUnion(Set(other.labels).intersection(category(target)))
+ }
+ return kept
+ }
+
+ func testDisableKeepsTheLabelsAnotherEnabledCategoryShares() throws {
+ let shared = Set(category("store")).intersection(category("icloud"))
+ XCTAssertFalse(shared.isEmpty)
+ // iCloud is fully enabled, so stopping the store keeps what they share.
+ let kept = expectedKept(stopping: "store", down: [])
+ XCTAssertTrue(kept.isSuperset(of: shared))
+ let host = host(loaded: Set(category("store")))
+ try installPlists(host, labels: category("store"))
+ let out = try simctl(host).disableServices(udid: udid, ids: ["store"])
+ XCTAssertEqual(Set(out.stillEnabled), kept)
+ XCTAssertEqual(Set(out.labels), Set(category("store")).subtracting(kept))
+ XCTAssertTrue(host.disabled[udid]!.isDisjoint(with: kept))
+
+ // Once iCloud has a daemon down it is no longer "on", so what only it
+ // shared goes too.
+ let down = category("icloud").first { !shared.contains($0) }!
+ let kept2 = expectedKept(stopping: "store", down: [down])
+ XCTAssertTrue(kept2.count < kept.count)
+ let host2 = self.host(disabled: [down], loaded: Set(category("store")))
+ try installPlists(host2, labels: category("store"))
+ let out2 = try simctl(host2).disableServices(udid: udid, ids: ["store"])
+ XCTAssertEqual(Set(out2.stillEnabled), kept2)
+ XCTAssertTrue(host2.disabled[udid]!.isSuperset(of: shared.subtracting(kept2)))
+ }
+
+ func testDisableOfANamedLabelIsAlwaysStopped() throws {
+ let shared = Set(category("store")).intersection(category("icloud")).sorted()[0]
+ let host = host(loaded: [shared])
+ try installPlists(host, labels: [shared])
+ let out = try simctl(host).disableServices(udid: udid, ids: [shared])
+ XCTAssertEqual(out.labels, [shared])
+ XCTAssertEqual(out.stillEnabled, [])
+ }
+
+ func testANamedLabelIsStoppedEvenWhenItsCategoryAlsoNamesItAndANeighbourSharesIt() throws {
+ let shared = Set(category("store")).intersection(category("icloud")).sorted()[0]
+ let host = host(loaded: Set(category("store")))
+ try installPlists(host, labels: category("store"))
+ let out = try simctl(host).disableServices(udid: udid, ids: ["store", shared])
+ XCTAssertTrue(out.labels.contains(shared), "named on its own, so it is stopped")
+ XCTAssertFalse(out.stillEnabled.contains(shared))
+ XCTAssertTrue(host.disabled[udid]!.contains(shared))
+ }
+
+ func testDisableKeepsHomedOnWatchOS() throws {
+ let health = Catalog.categories.first { $0.labels.contains("com.apple.homed") }!
+ let host = host(runtime: watch, loaded: Set(health.labels))
+ try installPlists(host, labels: health.labels)
+ let out = try simctl(host).disableServices(udid: udid, ids: [health.id])
+ XCTAssertTrue(out.stillEnabled.contains("com.apple.homed"))
+ XCTAssertFalse(out.labels.contains("com.apple.homed"))
+ XCTAssertFalse(host.disabled[udid]!.contains("com.apple.homed"))
+ }
+
+ func testDisableRefusesACompatibilityDaemon() throws {
+ let host = host()
+ let compat = Catalog.managedSet.subtracting(Catalog.slimmableSet).sorted()[0]
+ XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [compat])) {
+ XCTAssertEqual(
+ "\($0)",
+ "\(compat) is never disabled: simslim keeps it running for compatibility (see `simslim profiles`)"
+ )
+ }
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ func testDisableReportsOverridesThatDidNotTake() throws {
+ let label = category("search")[0]
+ let host = host(loaded: [label])
+ host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil }
+ XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [label]))
+ }
+
+ func testDisableOnAShutdownSimulatorNeedsSave() throws {
+ let host = host(state: "Shutdown")
+ XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: ["search"]))
+ XCTAssertTrue(spawnVerbs(host).isEmpty)
+ }
+
+ // MARK: - --save
+
+ func testSaveAddsInOrderWithoutDuplicates() throws {
+ try writeProfile(#"{"name":"mine","except":["siri"],"keep":["\#(category("siri")[0])"]}"#)
+ let keepable = category("search")[0]
+ let (data, changed) = try updatedProfile(
+ path: profilePath, categories: ["icloud", "siri"], labels: [keepable], enable: true)
+ XCTAssertTrue(changed)
+ let parsed = try parseSlimProfile(XCTUnwrap(data), path: profilePath)
+ XCTAssertEqual(parsed.except, ["siri", "icloud"])
+ XCTAssertEqual(parsed.name, "mine")
+ }
+
+ func testSaveSkipsADaemonAnExceptedCategoryAlreadyKeeps() throws {
+ try writeProfile(#"{"except":["search"]}"#)
+ let covered = category("search")[0]
+ let (data, changed) = try updatedProfile(
+ path: profilePath, categories: [], labels: [covered], enable: true)
+ XCTAssertFalse(changed)
+ XCTAssertNil(data)
+ }
+
+ func testSaveCreatesAMissingFileFromTheDefaultProfile() throws {
+ XCTAssertFalse(FileManager.default.fileExists(atPath: profilePath))
+ try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true)
+ XCTAssertEqual(try loadSlimProfile(path: profilePath).exceptCategories, ["search"])
+ // Disabling from a missing file still creates it, as the default profile.
+ let other = root + "/other.json"
+ try saveServices(path: other, categories: ["search"], labels: [], enable: false)
+ XCTAssertTrue(FileManager.default.fileExists(atPath: other))
+ }
+
+ func testSaveLeavesAnUnchangedProfileUntouched() throws {
+ try writeProfile(#"{"except":["search"]}"#)
+ let before = try FileManager.default.attributesOfItem(atPath: profilePath)[.systemFileNumber]
+ try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true)
+ let after = try FileManager.default.attributesOfItem(atPath: profilePath)[.systemFileNumber]
+ XCTAssertEqual(before as? UInt64, after as? UInt64, "not rewritten")
+ XCTAssertEqual(
+ try String(contentsOfFile: profilePath, encoding: .utf8), #"{"except":["search"]}"#)
+ }
+
+ func testSaveDisableRemovesAndRefusesToLeaveACategoryKeepingTheDaemon() throws {
+ let label = category("search")[0]
+ try writeProfile(#"{"except":["search","siri"],"keep":["\#(label)"]}"#)
+ XCTAssertThrowsError(
+ try updatedProfile(path: profilePath, categories: [], labels: [label], enable: false)
+ ) {
+ XCTAssertEqual(
+ "\($0)",
+ "profile \(profilePath) keeps \(label) enabled through category \"search\"; disable that category instead, or edit the file"
+ )
+ }
+ try saveServices(path: profilePath, categories: ["search"], labels: [label], enable: false)
+ let profile = try parseSlimProfile(
+ Data(contentsOf: URL(fileURLWithPath: profilePath)), path: profilePath)
+ XCTAssertEqual(profile.except, ["siri"])
+ XCTAssertEqual(profile.keep, [])
+ }
+
+ func testSaveRewritesAtomicallyKeepingModeAndFollowingSymlinks() throws {
+ let real = root + "/real.json"
+ try #"{"except":[]}"#.write(toFile: real, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: real)
+ try FileManager.default.createSymbolicLink(atPath: profilePath, withDestinationPath: real)
+ try saveServices(path: profilePath, categories: ["search"], labels: [], enable: true)
+ let link = try FileManager.default.destinationOfSymbolicLink(atPath: profilePath)
+ XCTAssertEqual(link, real, "the symlink survives")
+ XCTAssertEqual(try loadSlimProfile(path: real).exceptCategories, ["search"])
+ let mode = try FileManager.default.attributesOfItem(atPath: real)[.posixPermissions] as? Int
+ XCTAssertEqual(mode, 0o600)
+ let leftovers = try FileManager.default.contentsOfDirectory(atPath: root).filter {
+ $0.hasPrefix(".")
+ }
+ XCTAssertEqual(leftovers, [])
+ }
+
+ func testAnInvalidProfileFailsBeforeTheSimulatorChanges() throws {
+ try writeProfile(#"{"except":["no-such-category"]}"#)
+ let host = host(disabled: Set(category("search")))
+ XCTAssertThrowsError(
+ try simctl(host).enableServices(udid: udid, ids: ["search"], save: profilePath))
+ XCTAssertEqual(host.disabled[udid], Set(category("search")), "nothing was changed")
+ XCTAssertTrue(spawnVerbs(host).isEmpty)
+ }
+
+ func testAFailedLiveChangeLeavesTheProfileAlone() throws {
+ let label = category("search")[0]
+ try writeProfile(#"{"except":[]}"#)
+ let host = host(disabled: [label])
+ host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil }
+ XCTAssertThrowsError(
+ try simctl(host).enableServices(udid: udid, ids: [label], save: profilePath)
+ ) {
+ XCTAssertTrue("\($0)".hasSuffix("(profile \(profilePath) not changed)"), "\($0)")
+ }
+ XCTAssertEqual(try String(contentsOfFile: profilePath, encoding: .utf8), #"{"except":[]}"#)
+ }
+
+ func testAFailedSaveAfterALiveChangeSaysSo() throws {
+ let host = host(loaded: Set(category("search")))
+ try installPlists(host, labels: category("search"))
+ // The directory vanishes between validation and the write.
+ let ghost = root + "/missing-dir/profile.json"
+ XCTAssertThrowsError(
+ try simctl(host).enableServices(udid: udid, ids: ["search"], save: ghost)
+ ) {
+ XCTAssertTrue(
+ "\($0)".hasPrefix("the simulator was changed, but profile \(ghost) was not: "), "\($0)")
+ }
+ }
+
+ func testIDsAreDeduplicatedAndSorted() throws {
+ let (categories, labels) = try simctl(host()).resolveServiceIDs([
+ "siri", "search", "siri", category("search")[0], category("search")[0],
+ ])
+ XCTAssertEqual(categories, ["search", "siri"])
+ XCTAssertEqual(labels, [category("search")[0]])
+ }
+}
diff --git a/swift/Tests/TestSupport/FakeHost.swift b/swift/Tests/TestSupport/FakeHost.swift
index 91b486a..dfb044c 100644
--- a/swift/Tests/TestSupport/FakeHost.swift
+++ b/swift/Tests/TestSupport/FakeHost.swift
@@ -258,6 +258,21 @@ public final class FakeHost: CommandRunning, @unchecked Sendable {
loaded[udid]?.remove(label)
}
return CommandResult(status: 0)
+ case "load" where args.count >= 3 && args[1] == "-w":
+ // Lifts each job's override and loads it, unless the test makes it fail.
+ for path in args.dropFirst(2) {
+ guard let label = plistLabels[path] else { continue }
+ if failTransition?("load", label) != nil { continue }
+ disabled[udid, default: []].remove(label)
+ loaded[udid, default: []].insert(label)
+ }
+ return CommandResult(status: 0)
+ case "bootstrap" where args.count == 3 && args[1] == "system":
+ guard let label = plistLabels[args[2]] else { return CommandResult(status: 113) }
+ if failTransition?("bootstrap", label) != nil { return CommandResult(status: 5) }
+ if disabled[udid]?.contains(label) == true { return CommandResult(status: 5) }
+ loaded[udid, default: []].insert(label)
+ return CommandResult(status: 0)
default:
return nil
}
From 5de620ff06cf5959f3baeb20e2aa776e5f33d883 Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 03:55:55 -0700
Subject: [PATCH 08/32] feat(swift): watch (kqueue device-set watcher, pre-boot
seeding, --json events); review fixes
Per-device cancellable slim passes, store seeding before boot, directory watcher
on the default/testing/--set sets. Review fixes for --save: follow bare-name
symlinks, trim padded entries, error on unreadable paths, private temp file.
---
docs/swift-port-plan.md | 4 +-
swift/Sources/SimSlimCLI/CLI.swift | 19 +-
swift/Sources/SimSlimCLI/Usage.swift | 2 +-
swift/Sources/SimSlimCLI/WatchCommand.swift | 89 +++
swift/Sources/SimSlimKit/DirWatcher.swift | 90 +++
swift/Sources/SimSlimKit/ProfileFile.swift | 5 +-
swift/Sources/SimSlimKit/ProfileSave.swift | 28 +-
swift/Sources/SimSlimKit/Simctl.swift | 17 +-
swift/Sources/SimSlimKit/Slim.swift | 2 +-
swift/Sources/SimSlimKit/Watch.swift | 415 ++++++++++
.../SimSlimCLITests/LiveCommandTests.swift | 36 +
.../SimSlimCLITests/WatchCommandTests.swift | 134 ++++
swift/Tests/SimSlimKitTests/LiveTests.swift | 98 +++
swift/Tests/SimSlimKitTests/WatchTests.swift | 717 ++++++++++++++++++
14 files changed, 1643 insertions(+), 13 deletions(-)
create mode 100644 swift/Sources/SimSlimCLI/WatchCommand.swift
create mode 100644 swift/Sources/SimSlimKit/DirWatcher.swift
create mode 100644 swift/Sources/SimSlimKit/Watch.swift
create mode 100644 swift/Tests/SimSlimCLITests/WatchCommandTests.swift
create mode 100644 swift/Tests/SimSlimKitTests/WatchTests.swift
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
index 6734d5d..484f357 100644
--- a/docs/swift-port-plan.md
+++ b/docs/swift-port-plan.md
@@ -162,6 +162,6 @@ These are not in the first release. The SwiftUI app depends on several of them,
- **M1** Core model: allowlist, categories, features, delta logic, profile files, with the invariant tests ported first.
- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Also run against a live throwaway simulator in an isolated device set (Xcode 27.2, iOS 27.2).
- **M3a** Slimming: `on`, `off`, `on --no-reboot`, `boot`, `shutdown`, offline fast path, batch unload, 8-worker pool. **Done** (222 tests; 12 mutations in the slimming core, all caught; live run on a throwaway simulator: 246 to 83 processes, about 10.5 GB to 2.7 GB, slim persists across shutdown and boot, `off` restores stock). Awaiting the independent review of this core.
-- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): **Done** (14 mutations in the new code caught after two added tests; run live on a throwaway simulator). Awaiting independent review.
-- **M4** `watch`.
+- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): **Done** (14 mutations in the new code caught after two added tests; run live on a throwaway simulator). Independently reviewed: one real bug (`--save` replaced a symlinked profile named by a bare file name) and several test gaps, all fixed.
+- **M4** `watch`: **Done** (kqueue device-set watcher, pre-boot store seeding, per-device after-boot slim with cancellation, `--json` events; 40 tests, 19 mutations caught or hung). Not run live: `watch` always scans the user's default device set, so a live run would slim their real simulators; run it on a Mac where that is intended. Cancellation stops the next command, not one already running (Go kills it).
- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/swift/Sources/SimSlimCLI/CLI.swift b/swift/Sources/SimSlimCLI/CLI.swift
index 4a47b9b..2bc000d 100644
--- a/swift/Sources/SimSlimCLI/CLI.swift
+++ b/swift/Sources/SimSlimCLI/CLI.swift
@@ -11,6 +11,10 @@ public struct CLI {
public var runner: CommandRunning
/// Where simulators' launchd disable overrides live on the host; tests redirect it.
public var storeRoot: String
+ /// Whose `Library/Developer` holds the device sets `watch` observes.
+ public var home: String
+ /// Set by Ctrl-C; `watch` runs until it is.
+ public var interrupt: InterruptFlag
public var stdout: Sink
public var stderr: Sink
@@ -19,6 +23,8 @@ public struct CLI {
environment: [String: String] = ProcessInfo.processInfo.environment,
runner: CommandRunning = SystemCommandRunner(),
storeRoot: String = "/private/var/tmp",
+ home: String = NSHomeDirectory(),
+ interrupt: InterruptFlag = InterruptFlag(),
stdout: @escaping Sink,
stderr: @escaping Sink
) {
@@ -26,6 +32,8 @@ public struct CLI {
self.environment = environment
self.runner = runner
self.storeRoot = storeRoot
+ self.home = home
+ self.interrupt = interrupt
self.stdout = stdout
self.stderr = stderr
}
@@ -35,13 +43,15 @@ public struct CLI {
var simctl: Simctl
var bootTimeout: TimeInterval
var parsed: ParsedArguments
+ var home: String
+ var interrupt: InterruptFlag
var stdout: Sink
var stderr: Sink
}
/// Commands that exist in the Go CLI but are not in the Swift port yet.
static let notYetPorted: Set = [
- "profile", "watch", "top", "size", "disk-categories",
+ "profile", "top", "size", "disk-categories",
"disk-plan", "disk-clean", "clone", "repair-clone", "rename", "erase", "delete",
]
@@ -65,6 +75,9 @@ public struct CLI {
.bool("preserve-boot-state"),
],
"off": [.bool("preserve-boot-state")],
+ "watch": [
+ .bool("json"), .string("profile"), .string("except"), .string("keep"), .string("interval"),
+ ],
"enable": [.bool("json", onlyOnce: true), .string("save")],
"disable": [.bool("json", onlyOnce: true), .string("save")],
]
@@ -143,7 +156,8 @@ public struct CLI {
simctl.storeRoot = storeRoot
let bootTimeout = try applyGlobalOptions(parsed, to: &simctl)
let context = Context(
- simctl: simctl, bootTimeout: bootTimeout, parsed: parsed, stdout: stdout, stderr: stderr)
+ simctl: simctl, bootTimeout: bootTimeout, parsed: parsed, home: home, interrupt: interrupt,
+ stdout: stdout, stderr: stderr)
switch command {
case "list": return try cmdList(context)
@@ -156,6 +170,7 @@ public struct CLI {
case "shutdown": return try cmdShutdown(context)
case "on": return try cmdOn(context)
case "off": return try cmdOff(context)
+ case "watch": return try cmdWatch(context)
case "enable": return try cmdEnable(context)
case "disable": return try cmdDisable(context)
default: preconditionFailure("command \(command) has specs but no handler")
diff --git a/swift/Sources/SimSlimCLI/Usage.swift b/swift/Sources/SimSlimCLI/Usage.swift
index ebd888d..2b18ea7 100644
--- a/swift/Sources/SimSlimCLI/Usage.swift
+++ b/swift/Sources/SimSlimCLI/Usage.swift
@@ -32,7 +32,7 @@ let usageText = """
off Restore a simulator to stock (re-enable + reboot)
enable Re-enable categories or daemons on a booted simulator now
disable Stop categories or daemons on a booted simulator now
- watch † Slim every simulator until Ctrl-C
+ watch Slim every simulator until Ctrl-C
status Report how slim a booted simulator is
--dropped Also list the disabled daemons grouped by category
verify Check that a booted simulator's disable overrides still
diff --git a/swift/Sources/SimSlimCLI/WatchCommand.swift b/swift/Sources/SimSlimCLI/WatchCommand.swift
new file mode 100644
index 0000000..6fa3faa
--- /dev/null
+++ b/swift/Sources/SimSlimCLI/WatchCommand.swift
@@ -0,0 +1,89 @@
+import Foundation
+import SimSlimKit
+
+/// Set when the user presses Ctrl-C (or a test calls `trigger`). `install` makes
+/// SIGINT and SIGTERM set it instead of killing the process, so `watch` can stop
+/// its in-flight work and return; only `watch` installs it.
+public final class InterruptFlag: @unchecked Sendable {
+ private let lock = NSLock()
+ private var set = false
+ private var sources: [DispatchSourceSignal] = []
+
+ public init() {}
+
+ public var isSet: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return set
+ }
+
+ public func trigger() {
+ lock.lock()
+ set = true
+ lock.unlock()
+ }
+
+ func install() {
+ lock.lock()
+ defer { lock.unlock() }
+ if !sources.isEmpty { return }
+ for sig in [SIGINT, SIGTERM] {
+ signal(sig, SIG_IGN)
+ // The main thread is busy running the command, so handle on a global queue.
+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .global())
+ source.setEventHandler { [weak self] in self?.trigger() }
+ source.resume()
+ sources.append(source)
+ }
+ }
+}
+
+extension CLI {
+ func cmdWatch(_ context: Context) throws -> Int32 {
+ let parsed = context.parsed
+ guard parsed.positionals.isEmpty else { throw SimSlimError("watch takes no arguments") }
+ let profile = try buildProfile(
+ profilePath: parsed.string("profile"), except: parsed.string("except"),
+ keep: parsed.string("keep"))
+ var interval = defaultWatchInterval
+ if parsed.has("interval") {
+ let raw = parsed.string("interval")
+ do {
+ interval = try parseGoDuration(raw)
+ } catch {
+ throw SimSlimError(
+ "invalid value \"\(raw)\" for flag -interval: \((error as? SimSlimError)?.message ?? "parse error")"
+ )
+ }
+ }
+
+ let simctl = context.simctl
+ let interrupt = context.interrupt
+ interrupt.install()
+ let stop: @Sendable () -> Bool = { interrupt.isSet }
+ let stdout = context.stdout
+ let stderr = context.stderr
+
+ let watcher: Watcher
+ if parsed.bool("json") {
+ // One JSON object per event, from several threads at once.
+ let lock = NSLock()
+ watcher = Watcher(
+ simctl: simctl, profile: profile, home: context.home, report: nil,
+ events: { event in
+ lock.lock()
+ stdout(event.jsonLine + "\n")
+ lock.unlock()
+ })
+ } else {
+ let sets = simctl.knownSets.map(\.name)
+ stderr(
+ "Watching device sets [\(sets.joined(separator: ", "))]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n"
+ )
+ watcher = Watcher(
+ simctl: simctl, profile: profile, home: context.home, report: { stderr($0 + "\n") })
+ }
+ watcher.run(interval: interval, stop: stop)
+ return 0
+ }
+}
diff --git a/swift/Sources/SimSlimKit/DirWatcher.swift b/swift/Sources/SimSlimKit/DirWatcher.swift
new file mode 100644
index 0000000..8cd27f4
--- /dev/null
+++ b/swift/Sources/SimSlimKit/DirWatcher.swift
@@ -0,0 +1,90 @@
+import Foundation
+
+/// One device's directory, named by its UDID, in a scanned device set.
+struct DeviceDir: Equatable, Sendable {
+ var path: String
+ var set: String
+}
+
+/// Calls `created` for each directory that appears in one of `setDirs`, until
+/// `stop` returns true. A kqueue NOTE_WRITE on each set directory wakes it within
+/// a millisecond of `simctl create`, and costs nothing while idle. A set
+/// directory that does not exist yet (XCTestDevices before the first
+/// parallel-testing run) is attached again on every pass; its devices count as
+/// new from then on. A deleted device directory is forgotten, so `known` holds
+/// only the devices that exist.
+///
+/// `setDirs` maps a set directory to the set's name. The first listing of each
+/// directory is the baseline, taken at startup: those devices are the first
+/// scan's business, not reported here.
+func watchDeviceDirs(
+ setDirs: [String: String], pollInterval: TimeInterval = 0.25,
+ stop: @Sendable () -> Bool, created: (DeviceDir) -> Void
+) {
+ let kq = kqueue()
+ if kq < 0 { return } // the scan still catches every device, only later
+ defer { close(kq) }
+
+ var fds: [String: Int32] = [:] // attached set directory -> its fd
+ var dirs: [UInt: String] = [:] // fd -> attached set directory
+ var known: [String: Set] = [:] // set directory -> its device directories
+ defer { for fd in fds.values { close(fd) } }
+
+ func list(_ dir: String, report: Bool) {
+ guard let entries = try? FileManager.default.contentsOfDirectory(atPath: dir) else { return }
+ let was = known[dir] ?? []
+ var now = Set()
+ for name in entries.sorted() {
+ var isDirectory: ObjCBool = false
+ let path = (dir as NSString).appendingPathComponent(name)
+ guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory),
+ isDirectory.boolValue
+ else { continue }
+ now.insert(name)
+ if report && !was.contains(name) {
+ created(DeviceDir(path: path, set: setDirs[dir] ?? ""))
+ }
+ }
+ known[dir] = now
+ }
+
+ func attach(report: Bool) {
+ for dir in setDirs.keys.sorted() where fds[dir] == nil {
+ let fd = open(dir, O_EVTONLY | O_DIRECTORY)
+ if fd < 0 { continue }
+ var change = kevent(
+ ident: UInt(fd), filter: Int16(EVFILT_VNODE), flags: UInt16(EV_ADD | EV_CLEAR),
+ fflags: UInt32(NOTE_WRITE | NOTE_DELETE | NOTE_RENAME), data: 0, udata: nil)
+ if kevent(kq, &change, 1, nil, 0, nil) < 0 {
+ close(fd)
+ continue
+ }
+ fds[dir] = fd
+ dirs[UInt(fd)] = dir
+ list(dir, report: report)
+ }
+ }
+
+ attach(report: false)
+ var events: [kevent] = Array(repeating: kevent(), count: max(setDirs.count, 1))
+ var timeout = timespec(
+ tv_sec: Int(pollInterval), tv_nsec: Int((pollInterval - floor(pollInterval)) * 1e9))
+ while !stop() {
+ let n = kevent(kq, nil, 0, &events, Int32(events.count), &timeout)
+ if n < 0 && errno != EINTR { return }
+ for event in events[0.. Profile {
let data: Data
do {
diff --git a/swift/Sources/SimSlimKit/ProfileSave.swift b/swift/Sources/SimSlimKit/ProfileSave.swift
index c775a10..eae8702 100644
--- a/swift/Sources/SimSlimKit/ProfileSave.swift
+++ b/swift/Sources/SimSlimKit/ProfileSave.swift
@@ -19,7 +19,13 @@ extension Catalog {
/// Reads and validates a profile file, keeping its entries as written. A missing
/// file is the default profile.
func readSlimProfile(path: String) throws -> (profile: SlimProfile, exists: Bool) {
- guard FileManager.default.fileExists(atPath: path) else { return (SlimProfile(), false) }
+ var info = stat()
+ if stat(path, &info) != 0 {
+ // Only a missing file starts from the default profile; a loop or a
+ // not-a-directory component is an error, never a reason to overwrite.
+ if errno == ENOENT { return (SlimProfile(), false) }
+ throw SimSlimError("read profile \(path): \(String(cString: strerror(errno)))")
+ }
let data: Data
do {
data = try Data(contentsOf: URL(fileURLWithPath: path))
@@ -38,6 +44,14 @@ func updatedProfile(path: String, categories: [String], labels: [String], enable
-> (data: Data?, changed: Bool)
{
var (profile, exists) = try readSlimProfile(path: path)
+ // Entries are compared as `resolve` reads them: trimmed, blanks ignored. A
+ // padded " search " is the category `search`, so it must be found, not added
+ // again or left behind.
+ func normalised(_ items: [String]) -> [String] {
+ items.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
+ }
+ profile.except = normalised(profile.except)
+ profile.keep = normalised(profile.keep)
let beforeExcept = profile.except
let beforeKeep = profile.keep
if enable {
@@ -79,7 +93,9 @@ public func saveServices(path: String, categories: [String], labels: [String], e
func writeFileAtomic(path original: String, data: Data) throws {
var path = original
var mode = 0o644
- let resolved = (original as NSString).resolvingSymlinksInPath
+ // Absolute against the working directory: a bare file name that is itself a
+ // symlink must be followed too.
+ let resolved = URL(fileURLWithPath: original).resolvingSymlinksInPath().path
if FileManager.default.fileExists(atPath: resolved) {
path = resolved
if let attrs = try? FileManager.default.attributesOfItem(atPath: path),
@@ -94,13 +110,17 @@ func writeFileAtomic(path original: String, data: Data) throws {
".\(base).\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(atPath: temp) }
do {
- guard FileManager.default.createFile(atPath: temp, contents: nil) else {
+ // Created private, so a 0600 profile is never briefly world-readable.
+ guard
+ FileManager.default.createFile(
+ atPath: temp, contents: nil, attributes: [.posixPermissions: 0o600])
+ else {
throw SimSlimError("cannot create \(temp)")
}
let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: temp))
+ defer { try? handle.close() }
try handle.write(contentsOf: data)
try handle.synchronize()
- try handle.close()
try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: temp)
} catch {
throw SimSlimError("write profile \(path): \(error.localizedDescription)")
diff --git a/swift/Sources/SimSlimKit/Simctl.swift b/swift/Sources/SimSlimKit/Simctl.swift
index 78cd70f..c112a6d 100644
--- a/swift/Sources/SimSlimKit/Simctl.swift
+++ b/swift/Sources/SimSlimKit/Simctl.swift
@@ -28,6 +28,10 @@ public struct Simctl: Sendable {
/// deadline: every command is capped to what is left of it, and nothing starts
/// once it has passed.
public var deadline: Date?
+ /// Asked before every command and wait: true once the operation was cancelled
+ /// (a watched device shut down, or the user pressed Ctrl-C). A command already
+ /// running finishes or times out; nothing new starts.
+ public var cancelled: (@Sendable () -> Bool)?
/// The clock the deadline is read from (a test replaces it).
public var now: @Sendable () -> Date = { Date() }
@@ -44,7 +48,15 @@ public struct Simctl: Sendable {
sleep(length)
}
- var deadlineExpired: Bool { deadline.map { now() >= $0 } ?? false }
+ /// True once the operation is over, by deadline or by cancellation.
+ var deadlineExpired: Bool {
+ cancelled?() == true || (deadline.map { now() >= $0 } ?? false)
+ }
+
+ /// What Go's context reports for the reason the operation is over.
+ var contextError: String {
+ cancelled?() == true ? "context canceled" : "context deadline exceeded"
+ }
/// Runs a command under the operation deadline. The per-call `timeout` is
/// capped to what is left of the deadline; a command killed by the deadline
@@ -53,13 +65,14 @@ public struct Simctl: Sendable {
-> CommandResult
{
var limit = timeout
+ if cancelled?() == true { throw SimSlimError("context canceled") }
if let deadline {
let left = deadline.timeIntervalSince(now())
if left <= 0 { throw SimSlimError("context deadline exceeded") }
limit = min(limit ?? left, left)
}
let result = try runner.run(executable, arguments, timeout: limit)
- if result.timedOut, deadlineExpired { throw SimSlimError("context deadline exceeded") }
+ if result.timedOut, deadlineExpired { throw SimSlimError(contextError) }
return result
}
diff --git a/swift/Sources/SimSlimKit/Slim.swift b/swift/Sources/SimSlimKit/Slim.swift
index f00de9c..a6093c1 100644
--- a/swift/Sources/SimSlimKit/Slim.swift
+++ b/swift/Sources/SimSlimKit/Slim.swift
@@ -154,7 +154,7 @@ extension Simctl {
failures = results.failures
if deadlineExpired {
throw SimSlimError(
- "\(total - done)/\(total) launchctl transitions incomplete: context deadline exceeded")
+ "\(total - done)/\(total) launchctl transitions incomplete: \(contextError)")
}
pending = results.failed
pass += 1
diff --git a/swift/Sources/SimSlimKit/Watch.swift b/swift/Sources/SimSlimKit/Watch.swift
new file mode 100644
index 0000000..7a0726b
--- /dev/null
+++ b/swift/Sources/SimSlimKit/Watch.swift
@@ -0,0 +1,415 @@
+import Foundation
+
+/// How often `watch` rescans the device sets.
+public let defaultWatchInterval: TimeInterval = 3
+
+/// How long `watch` waits for a new device directory's device.plist, which
+/// `simctl create` writes just after the directory.
+let newDevicePlistWait: TimeInterval = 2
+
+/// The WatchEvent kinds. A wrapper that boots a device and then changes its
+/// services waits for `slimmed` (or `failed`): after it, the watcher does not
+/// touch that device again until the device shuts down.
+public enum WatchEventKind {
+ public static let slimming = "slimming" // an after-boot pass started
+ public static let slimmed = "slimmed" // the pass for the current boot finished
+ public static let failed = "failed" // the pass failed; the next scan retries it
+ public static let stopped = "stopped" // the device shut down, so its pass was cancelled
+ public static let slimmedBeforeBoot = "slimmed_before_boot" // disables written to a store
+}
+
+/// The stable, machine-readable form of a watcher log line.
+public struct WatchEvent: Equatable, Sendable {
+ public var event: String
+ public var udid: String
+ public var set: String
+ public var services: Int // disables written, for slimmed_before_boot
+ public var error: String // for failed
+
+ public init(event: String, udid: String, set: String, services: Int = 0, error: String = "") {
+ self.event = event
+ self.udid = udid
+ self.set = set
+ self.services = services
+ self.error = error
+ }
+
+ /// One compact JSON object, keys in the Go struct's order, empty `services`
+ /// and `error` omitted.
+ public var jsonLine: String {
+ var fields = [
+ "\"event\":\(WatchEvent.quote(event))", "\"udid\":\(WatchEvent.quote(udid))",
+ "\"set\":\(WatchEvent.quote(set))",
+ ]
+ if services != 0 { fields.append("\"services\":\(services)") }
+ if !error.isEmpty { fields.append("\"error\":\(WatchEvent.quote(error))") }
+ return "{" + fields.joined(separator: ",") + "}"
+ }
+
+ private static func quote(_ text: String) -> String {
+ let data = (try? JSONEncoder().encode(text)) ?? Data("\"\"".utf8)
+ return String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\\/", with: "/")
+ }
+}
+
+/// The device sets' on-disk directories, mapped to each set's name: the default
+/// set, Xcode's parallel-testing set, and any `--set` path.
+func deviceSetDirs(_ simctl: Simctl, home: String) -> [String: String] {
+ var dirs: [String: String] = [:]
+ let developer = ((home as NSString).appendingPathComponent("Library") as NSString)
+ .appendingPathComponent("Developer")
+ for set in simctl.knownSets {
+ switch set.token {
+ case "":
+ dirs[
+ ((developer as NSString).appendingPathComponent("CoreSimulator") as NSString)
+ .appendingPathComponent("Devices")] = set.name
+ case "testing": dirs[(developer as NSString).appendingPathComponent("XCTestDevices")] = set.name
+ default: dirs[set.token] = set.name
+ }
+ }
+ return dirs
+}
+
+/// Reads the device CoreSimulator describes in a device directory's
+/// device.plist: its UDID, runtime and state (1 is Shutdown).
+func readDevicePlist(_ dir: DeviceDir) throws -> Device {
+ let file = (dir.path as NSString).appendingPathComponent("device.plist")
+ let data = try Data(contentsOf: URL(fileURLWithPath: file))
+ let object: Any
+ do {
+ object = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
+ } catch {
+ throw SimSlimError("parse device.plist: \(error.localizedDescription)")
+ }
+ let dict = object as? [String: Any] ?? [:]
+ // Strings and integers both read as text, as in Go.
+ func text(_ key: String) -> String {
+ if let value = dict[key] as? String { return value }
+ if let value = dict[key] as? NSNumber { return value.stringValue }
+ return ""
+ }
+ let runtime = text("runtime")
+ guard let parsed = Simctl.parseRuntime(runtime), !text("UDID").isEmpty else {
+ throw SimSlimError("device.plist names no UDID or supported runtime")
+ }
+ return Device(
+ udid: text("UDID"), state: text("state") == "1" ? "Shutdown" : "Booted",
+ platform: parsed.platform, osVersion: parsed.version, set: dir.set,
+ dataPath: (dir.path as NSString).appendingPathComponent("data"), runtimeID: runtime)
+}
+
+/// Writes the profile's missing disable overrides into a shut-down device's
+/// launchd store and reports how many it added. Like the no-reboot slim `watch`
+/// applies after boot, it only ever adds disables: a service someone disabled
+/// beyond the profile stays disabled, and nothing is re-enabled. A device that is
+/// not shut down, or whose runtime does not persist overrides, is left alone; the
+/// after-boot slim covers it.
+func preslimDevice(_ device: Device, profile: Profile, storeRoot: String) throws -> Int {
+ if device.state != "Shutdown" || !device.supportsPersistentOverrides { return 0 }
+ let store = DisabledStore(root: storeRoot)
+ let current = try store.readDisabled(udid: device.udid)
+ let toDisable = delta(
+ current: current, desired: profile.desired(for: device), managed: Catalog.managedSet
+ ).toDisable
+ if toDisable.isEmpty { return 0 }
+ try store.write(udid: device.udid, toDisable: toDisable, toEnable: [])
+ return toDisable.count
+}
+
+/// Slims every simulator so that none starts the profile's daemons, then leaves
+/// it alone until it boots again. A shut-down simulator on a runtime that
+/// persists overrides is slimmed before it boots: the profile's disable
+/// overrides are written into its launchd store, so its next boot, its very
+/// first included, starts none of those daemons. New devices are caught by a
+/// kqueue watch on the device-set directories, ahead of a tool that creates and
+/// boots at once. Every simulator is still slimmed no-reboot as it boots: that
+/// reads the device back, and it is the only hook for a device that booted before
+/// its store was seeded, on an older runtime, or as an xcodebuild
+/// parallel-testing clone (cloned stock, since overrides do not survive
+/// `simctl clone`, and booted at once).
+public final class Watcher: @unchecked Sendable {
+ /// One boot's after-boot slim. Cancelling it stops it once that boot ends, so
+ /// it cannot keep retrying into the device's next boot.
+ final class Pass: @unchecked Sendable {
+ private let lock = NSLock()
+ private var flag = false
+ var isCancelled: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return flag
+ }
+ func cancel() {
+ lock.lock()
+ flag = true
+ lock.unlock()
+ }
+ }
+
+ public typealias Slimmer = @Sendable (Simctl, String, String, Profile, Reporter?) throws -> Bool
+ public typealias Preslimmer = @Sendable (Device, Profile) throws -> Int
+
+ let profile: Profile
+ var simctl: Simctl
+ let report: Reporter?
+ let events: (@Sendable (WatchEvent) -> Void)?
+ let home: String
+ /// The per-device slim; a field so tests can substitute a fake.
+ var slim: Slimmer
+ /// Seeds a shut-down device before it boots; a field so tests can substitute
+ /// a fake.
+ var preslim: Preslimmer?
+
+ private let lock = NSLock()
+ private var passes: [String: Pass] = [:]
+ private var seeded = Set()
+ private let group = DispatchGroup()
+ private var stopRequested: @Sendable () -> Bool = { false }
+ private var wakeFlag = false
+ private let wakeup = DispatchSemaphore(value: 0)
+
+ public init(
+ simctl: Simctl, profile: Profile, home: String = NSHomeDirectory(),
+ report: Reporter? = nil, events: (@Sendable (WatchEvent) -> Void)? = nil
+ ) {
+ self.simctl = simctl
+ self.profile = profile
+ self.home = home
+ self.report = report
+ self.events = events
+ self.slim = { ctl, set, udid, profile, reporter in
+ try ctl.enableSlimNoReboot(set: set, udid: udid, profile: profile, reporter: reporter)
+ }
+ let root = simctl.storeRoot
+ self.preslim = { device, profile in
+ try preslimDevice(device, profile: profile, storeRoot: root)
+ }
+ }
+
+ /// Watches until `stop` returns true, scanning the default, testing and any
+ /// `--set` device sets every `interval`. Each booted device is slimmed in its
+ /// own thread so one slow reconfigure does not delay catching the next clone,
+ /// and `run` returns once those are done.
+ public func run(
+ interval: TimeInterval = defaultWatchInterval, stop: @escaping @Sendable () -> Bool
+ ) {
+ let interval = interval > 0 ? interval : defaultWatchInterval
+ stopRequested = stop
+ simctl.cancelled = stop
+ let dirs = deviceSetDirs(simctl, home: home)
+ group.enter()
+ Thread.detachNewThread { [self] in
+ defer { group.leave() }
+ watchDeviceDirs(setDirs: dirs, stop: stop) { dir in
+ // seedNew waits for device.plist, so each new device gets its own
+ // thread: a batch of parallel-testing clones seeds at once.
+ group.enter()
+ Thread.detachNewThread { [self] in
+ defer { group.leave() }
+ seedNew(dir)
+ signalScan()
+ }
+ }
+ }
+ while !stop() {
+ scan()
+ var waited = 0.0
+ while waited < interval && !stop() {
+ if wakeup.wait(timeout: .now() + 0.2) == .success {
+ lock.lock()
+ wakeFlag = false
+ lock.unlock()
+ break
+ }
+ waited += 0.2
+ }
+ }
+ // No slim may outlive the call; a stopped run aborts an in-flight slim at
+ // its next command, which keeps the wait short.
+ if group.wait(timeout: .now() + 20) == .timedOut {
+ report?("watch: a slim was still running at exit")
+ }
+ }
+
+ /// Asks the loop to scan now; coalesces while one is already due.
+ private func signalScan() {
+ lock.lock()
+ let already = wakeFlag
+ wakeFlag = true
+ lock.unlock()
+ if !already { wakeup.signal() }
+ }
+
+ /// Blocks until every slim and seed thread started so far has finished.
+ func waitForWork() { group.wait() }
+
+ private func emit(_ event: WatchEvent) { events?(event) }
+
+ /// Slims a just-created device before its first boot, straight from its
+ /// directory and without a `simctl list`, which on a loaded host would still be
+ /// running when a script that boots right after creating has started launchd_sim.
+ func seedNew(_ dir: DeviceDir) {
+ let limit = Date().addingTimeInterval(newDevicePlistWait)
+ var device: Device?
+ while device == nil && Date() < limit {
+ device = try? readDevicePlist(dir)
+ if device == nil {
+ if stopRequested() { return }
+ Thread.sleep(forTimeInterval: 0.01)
+ }
+ }
+ // Not a device, or not one simslim slims; the scan decides.
+ guard let device else { return }
+ seed(device)
+ }
+
+ func scan() {
+ let devices: [Device]
+ do {
+ devices = try simctl.listDevices().sorted { $0.udid < $1.udid }
+ } catch {
+ report?("watch: list devices: \(error.localizedDescription)")
+ return
+ }
+ prune(devices)
+ for device in devices {
+ if device.state != "Booted" {
+ // On iOS below 18.5 the no-reboot slim dies with the boot session, so a
+ // device that shut down comes back stock and needs slimming again.
+ // Re-slimming an already-slim device is a cheap no-op.
+ forget(device.udid)
+ seed(device)
+ continue
+ }
+ // A booted device may change its own store (and `simslim off` may clear
+ // it), so check it again the next time it is shut down.
+ lock.lock()
+ seeded.remove(device.udid)
+ lock.unlock()
+ guard let pass = claim(device.udid) else { continue }
+ group.enter()
+ let stop = stopRequested
+ var ctl = simctl
+ ctl.cancelled = { pass.isCancelled || stop() }
+ Thread.detachNewThread { [self] in
+ defer { group.leave() }
+ report?("watch: slimming \(device.udid) (set \(device.set))")
+ emit(WatchEvent(event: WatchEventKind.slimming, udid: device.udid, set: device.set))
+ var failure: Error?
+ do {
+ _ = try slim(ctl, device.set, device.udid, profile, prefixed(device.udid))
+ } catch {
+ failure = error
+ }
+ finish(device, pass, failure)
+ }
+ }
+ }
+
+ /// Slims a shut-down device ahead of its next boot, once per shutdown. A
+ /// failure is retried on the next scan, and the after-boot slim still covers
+ /// the device if it boots first.
+ func seed(_ device: Device) {
+ guard let preslim else { return }
+ // A device caught Shutting Down or Booting is seeded once it reads Shutdown.
+ if device.state != "Shutdown" { return }
+ lock.lock()
+ defer { lock.unlock() } // serializes the store writes of seedNew and scan
+ if seeded.contains(device.udid) { return }
+ let count: Int
+ do {
+ count = try preslim(device, profile)
+ } catch {
+ report?("watch: \(device.udid): slim before boot: \(error.localizedDescription)")
+ return
+ }
+ seeded.insert(device.udid)
+ if count == 0 { return }
+ // launchd_sim reads the store once, when it starts: a seed that lands after
+ // the boot began only counts from the next boot.
+ if !device.dataPath.isEmpty,
+ let now = try? readDevicePlist(
+ DeviceDir(path: (device.dataPath as NSString).deletingLastPathComponent, set: device.set)),
+ now.state != "Shutdown"
+ {
+ report?(
+ "watch: \(device.udid) booted before its slim (\(count) services) landed; slimming it as it boots"
+ )
+ return
+ }
+ report?(
+ "watch: slimmed \(device.udid) before boot (\(count) services disabled, set \(device.set))")
+ emit(
+ WatchEvent(
+ event: WatchEventKind.slimmedBeforeBoot, udid: device.udid, set: device.set,
+ services: count))
+ }
+
+ /// Reports a pass's outcome. It holds the lock so a superseded pass, whose boot
+ /// ended, can never announce slimmed after a newer boot's pass has started.
+ func finish(_ device: Device, _ pass: Pass, _ failure: Error?) {
+ lock.lock()
+ defer { lock.unlock() }
+ if passes[device.udid] !== pass {
+ report?("watch: \(device.udid) shut down; stopped its slim")
+ emit(WatchEvent(event: WatchEventKind.stopped, udid: device.udid, set: device.set))
+ } else if let failure {
+ // A transient launchctl failure would otherwise leave this clone stock for
+ // the whole test run. The next scan retries it, and a torn-down clone drops
+ // out of simctl list, so this does not loop.
+ passes[device.udid] = nil
+ report?("watch: \(device.udid): \(failure.localizedDescription)")
+ emit(
+ WatchEvent(
+ event: WatchEventKind.failed, udid: device.udid, set: device.set,
+ error: failure.localizedDescription))
+ } else {
+ report?("watch: slimmed \(device.udid)")
+ emit(WatchEvent(event: WatchEventKind.slimmed, udid: device.udid, set: device.set))
+ }
+ }
+
+ /// Starts a pass for a booted UDID, returning nil when one is already done or
+ /// in flight for this boot.
+ func claim(_ udid: String) -> Pass? {
+ lock.lock()
+ defer { lock.unlock() }
+ if passes[udid] != nil { return nil }
+ let pass = Pass()
+ passes[udid] = pass
+ return pass
+ }
+
+ /// Drops the UDIDs of deleted devices, such as finished parallel-testing
+ /// clones, so `passes` and `seeded` do not grow by one entry per clone. A
+ /// device created after the listing started is only seeded again, which is a
+ /// no-op.
+ func prune(_ devices: [Device]) {
+ let listed = Set(devices.map(\.udid))
+ lock.lock()
+ defer { lock.unlock() }
+ for (udid, pass) in passes where !listed.contains(udid) {
+ pass.cancel()
+ passes[udid] = nil
+ }
+ seeded = seeded.intersection(listed)
+ }
+
+ /// Ends a device's boot: its pass, if still running, is cancelled, and its next
+ /// boot gets a pass of its own.
+ func forget(_ udid: String) {
+ lock.lock()
+ if let pass = passes[udid] {
+ pass.cancel()
+ passes[udid] = nil
+ }
+ lock.unlock()
+ }
+
+ /// Tags a device's own progress lines with its UDID, so the interleaved output
+ /// of concurrent slims stays attributable.
+ private func prefixed(_ udid: String) -> Reporter? {
+ guard let report else { return nil }
+ return { report("watch: \(udid): \($0)") }
+ }
+}
diff --git a/swift/Tests/SimSlimCLITests/LiveCommandTests.swift b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift
index cd8444d..78863b7 100644
--- a/swift/Tests/SimSlimCLITests/LiveCommandTests.swift
+++ b/swift/Tests/SimSlimCLITests/LiveCommandTests.swift
@@ -121,4 +121,40 @@ final class LiveCommandTests: XCTestCase {
XCTAssertEqual(runCLI(["disable", "booted", "search"], host: host()).status, 1)
XCTAssertEqual(runCLI(["enable", udid, "search", "--no-such"], host: host()).status, 1)
}
+
+ func testDisableNothingToStopAndStillEnabledLines() {
+ let watch = FakeHost(devices: [
+ .init(
+ udid: udid, name: "Watch", runtime: "com.apple.CoreSimulator.SimRuntime.watchOS-11-5",
+ state: "Booted")
+ ])
+ watch.disabled[udid] = []
+ watch.loaded[udid] = ["com.apple.homed"]
+ let r = runCLI(["disable", udid, "com.apple.homed"], host: watch)
+ XCTAssertEqual(r.status, 0, r.stderr)
+ XCTAssertEqual(
+ r.stdout,
+ "Nothing to stop on \(udid).\n"
+ + " 1 stay enabled for another fully enabled category or the platform: com.apple.homed\n"
+ + "This lasts until the next `on` or `watch` pass; pass --save to keep it in a profile.\n"
+ )
+ }
+
+ func testDisableSaveMessages() {
+ let host = host()
+ host.loaded[udid] = Set(search)
+ let live = runCLI(["disable", udid, "search", "--save", root + "/a.json"], host: host)
+ XCTAssertEqual(live.status, 0, live.stderr)
+ XCTAssertTrue(
+ live.stdout.hasSuffix(
+ "Saved to \(root)/a.json. Apply it later with `simslim on \(udid) --profile \(root)/a.json`.\n"
+ ), live.stdout)
+ }
+
+ func testAnAliasSpawnsNothing() {
+ let host = host()
+ _ = runCLI(["enable", "all", "search"], host: host)
+ _ = runCLI(["disable", "booted", "search"], host: host)
+ XCTAssertFalse(host.calls.contains { $0.arguments.contains("spawn") })
+ }
}
diff --git a/swift/Tests/SimSlimCLITests/WatchCommandTests.swift b/swift/Tests/SimSlimCLITests/WatchCommandTests.swift
new file mode 100644
index 0000000..143ed1b
--- /dev/null
+++ b/swift/Tests/SimSlimCLITests/WatchCommandTests.swift
@@ -0,0 +1,134 @@
+import SimSlimKit
+import TestSupport
+import XCTest
+
+@testable import SimSlimCLI
+
+private final class Sink: @unchecked Sendable {
+ private let lock = NSLock()
+ private var text = ""
+ func append(_ s: String) {
+ lock.lock()
+ text += s
+ lock.unlock()
+ }
+ var value: String {
+ lock.lock()
+ defer { lock.unlock() }
+ return text
+ }
+}
+
+final class WatchCommandTests: XCTestCase {
+ private let udid = "AAAAAAAA-0000-0000-0000-000000000001"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-watchcli-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(
+ atPath: root + "/home/Library/Developer/CoreSimulator/Devices",
+ withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ /// Runs `simslim ` until `until` holds for what it has printed, then
+ /// interrupts it, as Ctrl-C would.
+ private func watch(
+ _ args: [String], host: FakeHost, until: @escaping (String, String) -> Bool
+ ) -> (status: Int32, stdout: String, stderr: String) {
+ let out = Sink()
+ let err = Sink()
+ let flag = InterruptFlag()
+ let cli = CLI(
+ version: "t", environment: [:], runner: host, storeRoot: root + "/store",
+ home: root + "/home", interrupt: flag, stdout: { out.append($0) }, stderr: { err.append($0) })
+ let status = Sink()
+ let done = DispatchSemaphore(value: 0)
+ Thread.detachNewThread {
+ status.append(String(cli.run(args)))
+ done.signal()
+ }
+ let limit = Date().addingTimeInterval(10)
+ while !until(out.value, err.value) && Date() < limit { Thread.sleep(forTimeInterval: 0.01) }
+ flag.trigger()
+ XCTAssertEqual(done.wait(timeout: .now() + 15), .success, "watch stops on interrupt")
+ return (Int32(status.value) ?? -1, out.value, err.value)
+ }
+
+ private func bootedHost() -> FakeHost {
+ let host = FakeHost(devices: [.init(udid: udid, name: "iPhone", state: "Booted")])
+ host.disabled[udid] = []
+ host.loaded[udid] = []
+ return host
+ }
+
+ func testJSONEventsAreOneObjectPerLineAndTheDeviceEndsSlim() throws {
+ let host = bootedHost()
+ let r = watch(["watch", "--json", "--interval", "200ms"], host: host) { out, _ in
+ out.contains("\"slimmed\"")
+ }
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stderr, "", "stderr stays quiet under --json")
+ let lines = r.stdout.split(separator: "\n").map(String.init)
+ XCTAssertEqual(
+ lines,
+ [
+ "{\"event\":\"slimming\",\"udid\":\"\(udid)\",\"set\":\"default\"}",
+ "{\"event\":\"slimmed\",\"udid\":\"\(udid)\",\"set\":\"default\"}",
+ ])
+ for line in lines {
+ XCTAssertNotNil(try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any])
+ }
+ XCTAssertEqual(host.disabled[udid]?.intersection(Catalog.managedSet), Profile().desired())
+ }
+
+ func testTextModeAnnouncesTheSetsAndLogsEachDevice() {
+ let host = bootedHost()
+ let r = watch(
+ ["watch", "--interval", "200ms", "--set", "/custom/set"], host: host
+ ) { _, err in err.contains("watch: slimmed \(self.udid)") }
+ XCTAssertEqual(r.status, 0)
+ XCTAssertEqual(r.stdout, "")
+ XCTAssertTrue(
+ r.stderr.hasPrefix(
+ "Watching device sets [default, testing, /custom/set]; slimming each simulator before it boots where its runtime allows, and no-reboot as it boots. Ctrl-C to stop.\n"
+ ), r.stderr)
+ XCTAssertTrue(r.stderr.contains("watch: slimming \(udid) (set default)\n"))
+ XCTAssertTrue(r.stderr.contains("watch: \(udid): Booting the simulator"))
+ }
+
+ func testExceptKeepsACategoryOutOfTheSlim() {
+ let host = bootedHost()
+ _ = watch(["watch", "--json", "--interval", "200ms", "--except", "search"], host: host) {
+ out, _ in out.contains("\"slimmed\"")
+ }
+ let search = Set(Catalog.category(id: "search")!.labels)
+ XCTAssertTrue(host.disabled[udid]!.isDisjoint(with: search))
+ }
+
+ func testBadArgumentsFailBeforeAnythingRuns() {
+ let host = bootedHost()
+ let flag = InterruptFlag()
+ func run(_ args: [String]) -> CLIResult {
+ let err = Sink()
+ let cli = CLI(
+ version: "t", environment: [:], runner: host, home: root + "/home", interrupt: flag,
+ stdout: { _ in }, stderr: { err.append($0) })
+ let status = cli.run(args)
+ return CLIResult(status: status, stdout: "", stderr: err.value)
+ }
+ let interval = run(["watch", "--interval", "soon"])
+ XCTAssertEqual(interval.status, 1)
+ XCTAssertTrue(interval.stderr.hasPrefix("simslim: invalid value \"soon\" for flag -interval"))
+ XCTAssertTrue(
+ run(["watch", "--profile", "x.json", "--keep", "a"]).stderr.contains(
+ "--profile cannot be combined with --except or --keep"))
+ XCTAssertTrue(run(["watch", "--except", "nope"]).stderr.contains("unknown category \"nope\""))
+ XCTAssertTrue(run(["watch", udid]).stderr.contains("watch takes no arguments"))
+ XCTAssertTrue(host.calls.isEmpty)
+ XCTAssertFalse(flag.isSet)
+ }
+}
diff --git a/swift/Tests/SimSlimKitTests/LiveTests.swift b/swift/Tests/SimSlimKitTests/LiveTests.swift
index 9c573df..ebc0900 100644
--- a/swift/Tests/SimSlimKitTests/LiveTests.swift
+++ b/swift/Tests/SimSlimKitTests/LiveTests.swift
@@ -432,4 +432,102 @@ final class LiveTests: XCTestCase {
XCTAssertEqual(categories, ["search", "siri"])
XCTAssertEqual(labels, [category("search")[0]])
}
+
+ // MARK: - from the independent review
+
+ func testDisableFailsWhenTheOverrideIsAcceptedButNeverAppears() throws {
+ let label = category("search")[0]
+ let host = host(loaded: [label])
+ // launchctl exits 0 for `disable` but nothing changes: only the read-back sees it.
+ host.failTransition = { verb, l in
+ verb == "disable" && l == label ? CommandResult(status: 0) : nil
+ }
+ XCTAssertThrowsError(try simctl(host).disableServices(udid: udid, ids: [label])) {
+ XCTAssertEqual("\($0)", "1 of 1 disable overrides did not take")
+ }
+ }
+
+ func testWithoutARuntimeRootEveryUnloadedLabelCountsAsOneLaunchdShouldLoad() throws {
+ let label = category("search")[0]
+ let host = host(disabled: [label]) // no runtime roots: plists cannot be looked up
+ let out = try simctl(host).enableServices(udid: udid, ids: [label])
+ XCTAssertEqual(host.disabled[udid], [])
+ XCTAssertEqual(out.notStarted, [label], "re-enabled, but not loaded in this boot")
+ }
+
+ func testDisableValidatesTheProfileBeforeTouchingTheSimulator() throws {
+ let label = category("search")[0]
+ try writeProfile(#"{"except":["search"],"keep":["\#(label)"]}"#)
+ let host = host(loaded: Set(category("search")))
+ XCTAssertThrowsError(
+ try simctl(host).disableServices(udid: udid, ids: [label], save: profilePath))
+ XCTAssertEqual(host.disabled[udid], [])
+ XCTAssertTrue(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }.isEmpty)
+ }
+
+ func testAFailedLiveDisableLeavesTheProfileAlone() throws {
+ let label = category("search")[0]
+ try writeProfile(#"{"except":["siri"],"keep":["\#(label)"]}"#)
+ let host = host(loaded: [label])
+ host.failTransition = { _, l in l == label ? CommandResult(status: 1) : nil }
+ XCTAssertThrowsError(
+ try simctl(host).disableServices(udid: udid, ids: [label], save: profilePath)
+ ) {
+ XCTAssertTrue("\($0)".hasSuffix("(profile \(profilePath) not changed)"), "\($0)")
+ }
+ XCTAssertTrue(try String(contentsOfFile: profilePath, encoding: .utf8).contains(label))
+ }
+
+ func testDisablingOnlyWhatThePlatformKeepsStopsNothing() throws {
+ let host = host(runtime: watch, loaded: ["com.apple.homed"])
+ let out = try simctl(host).disableServices(udid: udid, ids: ["com.apple.homed"])
+ XCTAssertEqual(out.labels, [])
+ XCTAssertEqual(out.stillEnabled, ["com.apple.homed"])
+ XCTAssertTrue(spawnVerbs(host).filter { !["print-disabled", "list"].contains($0) }.isEmpty)
+ }
+
+ func testWhitespacePaddedEntriesAreFoundNotDuplicated() throws {
+ try writeProfile(#"{"except":[" search "],"keep":[" "]}"#)
+ // Disabling finds the padded category and removes it.
+ try saveServices(path: profilePath, categories: ["search"], labels: [], enable: false)
+ XCTAssertEqual(
+ try parseSlimProfile(Data(contentsOf: URL(fileURLWithPath: profilePath)), path: "p").except,
+ [])
+ // Enabling a category already present padded does not add it again.
+ try writeProfile(#"{"except":[" search "]}"#)
+ let (data, changed) = try updatedProfile(
+ path: profilePath, categories: ["search"], labels: [], enable: true)
+ XCTAssertFalse(changed)
+ XCTAssertNil(data)
+ }
+
+ func testASymlinkNamedWithABareFileNameIsFollowed() throws {
+ let target = root + "/shared.json"
+ try #"{"except":[]}"#.write(toFile: target, atomically: true, encoding: .utf8)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target)
+ let cwd = FileManager.default.currentDirectoryPath
+ defer { FileManager.default.changeCurrentDirectoryPath(cwd) }
+ FileManager.default.changeCurrentDirectoryPath(root)
+ try FileManager.default.createSymbolicLink(
+ atPath: root + "/link.json", withDestinationPath: "shared.json")
+ try saveServices(path: "link.json", categories: ["search"], labels: [], enable: true)
+ XCTAssertEqual(
+ try FileManager.default.destinationOfSymbolicLink(atPath: root + "/link.json"),
+ "shared.json", "still a symlink")
+ XCTAssertEqual(try loadSlimProfile(path: target).exceptCategories, ["search"])
+ let mode = try FileManager.default.attributesOfItem(atPath: target)[.posixPermissions] as? Int
+ XCTAssertEqual(mode, 0o600)
+ }
+
+ func testAProfilePathThatCannotBeReadIsNeverOverwrittenAsAMissingFile() throws {
+ // A symlink loop is an error (ELOOP), not a missing file to start afresh.
+ try FileManager.default.createSymbolicLink(
+ atPath: root + "/loop.json", withDestinationPath: root + "/loop.json")
+ XCTAssertThrowsError(
+ try saveServices(
+ path: root + "/loop.json", categories: ["search"], labels: [], enable: true))
+ XCTAssertEqual(
+ try FileManager.default.destinationOfSymbolicLink(atPath: root + "/loop.json"),
+ root + "/loop.json", "the symlink was not replaced")
+ }
}
diff --git a/swift/Tests/SimSlimKitTests/WatchTests.swift b/swift/Tests/SimSlimKitTests/WatchTests.swift
new file mode 100644
index 0000000..8a07b53
--- /dev/null
+++ b/swift/Tests/SimSlimKitTests/WatchTests.swift
@@ -0,0 +1,717 @@
+import TestSupport
+import XCTest
+
+@testable import SimSlimKit
+
+private final class Events: @unchecked Sendable {
+ private let lock = NSLock()
+ private var items: [WatchEvent] = []
+ private var texts: [String] = []
+ func add(_ event: WatchEvent) {
+ lock.lock()
+ items.append(event)
+ lock.unlock()
+ }
+ func addText(_ text: String) {
+ lock.lock()
+ texts.append(text)
+ lock.unlock()
+ }
+ var all: [WatchEvent] {
+ lock.lock()
+ defer { lock.unlock() }
+ return items
+ }
+ var kinds: [String] { all.map(\.event) }
+ var lines: [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return texts
+ }
+}
+
+private final class Flag: @unchecked Sendable {
+ private let lock = NSLock()
+ private var value = false
+ var isSet: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return value
+ }
+ func set() {
+ lock.lock()
+ value = true
+ lock.unlock()
+ }
+}
+
+private final class Calls: @unchecked Sendable {
+ private let lock = NSLock()
+ private var items: [String] = []
+ func add(_ item: String) {
+ lock.lock()
+ items.append(item)
+ lock.unlock()
+ }
+ var all: [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return items
+ }
+}
+
+final class WatchTests: XCTestCase {
+ private let ios = "com.apple.CoreSimulator.SimRuntime.iOS-27-2"
+ private let old = "com.apple.CoreSimulator.SimRuntime.iOS-17-0"
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "simslim-watch-\(UUID().uuidString)"
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDown() {
+ try? FileManager.default.removeItem(atPath: root)
+ }
+
+ private func udid(_ n: Int) -> String { String(format: "AAAAAAAA-0000-0000-0000-%012d", n) }
+
+ private func waitFor(_ what: String, timeout: TimeInterval = 5, _ condition: () -> Bool) {
+ let limit = Date().addingTimeInterval(timeout)
+ while !condition() && Date() < limit { Thread.sleep(forTimeInterval: 0.01) }
+ XCTAssertTrue(condition(), "timed out waiting for \(what)")
+ }
+
+ private func makeWatcher(
+ _ host: FakeHost, events: Events, slim: Watcher.Slimmer? = nil,
+ preslim: Watcher.Preslimmer? = nil
+ ) -> Watcher {
+ var ctl = Simctl(runner: host)
+ ctl.retryDelays = [0]
+ ctl.sleep = { _ in }
+ ctl.storeRoot = root + "/store"
+ let watcher = Watcher(
+ simctl: ctl, profile: Profile(), home: root + "/home",
+ report: { events.addText($0) }, events: { events.add($0) })
+ if let slim { watcher.slim = slim }
+ watcher.preslim = preslim
+ return watcher
+ }
+
+ private func booted(_ n: Int, runtime: String? = nil) -> FakeHost.FakeDevice {
+ .init(udid: udid(n), name: "d\(n)", runtime: runtime ?? ios, state: "Booted")
+ }
+
+ private func shutdown(_ n: Int, runtime: String? = nil) -> FakeHost.FakeDevice {
+ .init(udid: udid(n), name: "d\(n)", runtime: runtime ?? ios, state: "Shutdown")
+ }
+
+ // MARK: - after-boot passes
+
+ func testABootedDeviceIsSlimmedOncePerBoot() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let calls = Calls()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { _, set, id, _, _ in
+ calls.add("\(set) \(id)")
+ return true
+ })
+ watcher.scan()
+ watcher.waitForWork()
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(calls.all, ["default \(udid(1))"], "the second scan leaves it alone")
+ XCTAssertEqual(events.kinds, [WatchEventKind.slimming, WatchEventKind.slimmed])
+ XCTAssertEqual(events.all[0], WatchEvent(event: "slimming", udid: udid(1), set: "default"))
+ }
+
+ func testAFailedPassIsRetriedByTheNextScan() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let attempts = Calls()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { _, _, _, _, _ in
+ attempts.add("x")
+ if attempts.all.count == 1 { throw SimSlimError("transient launchctl failure") }
+ return true
+ })
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(events.kinds, ["slimming", "failed"])
+ XCTAssertEqual(events.all[1].error, "transient launchctl failure")
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(events.kinds, ["slimming", "failed", "slimming", "slimmed"])
+ }
+
+ func testAPassIsCancelledWhenItsDeviceShutsDownAndNeverReportsSlimmed() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let started = Flag()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { ctl, _, _, _, _ in
+ started.set()
+ while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) }
+ throw SimSlimError("context canceled")
+ })
+ watcher.scan()
+ waitFor("pass to start") { started.isSet }
+ host.devices[0].state = "Shutdown"
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(events.kinds, ["slimming", "stopped"])
+ XCTAssertFalse(events.kinds.contains("slimmed"))
+ XCTAssertTrue(events.lines.contains("watch: \(udid(1)) shut down; stopped its slim"))
+ }
+
+ func testTheNextBootGetsAFreshPass() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let watcher = makeWatcher(host, events: events, slim: { _, _, _, _, _ in true })
+ watcher.scan()
+ watcher.waitForWork()
+ host.devices[0].state = "Shutdown"
+ watcher.scan()
+ host.devices[0].state = "Booted"
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(events.kinds, ["slimming", "slimmed", "slimming", "slimmed"])
+ }
+
+ func testADeletedDeviceCancelsItsPassAndIsForgotten() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let started = Flag()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { ctl, _, _, _, _ in
+ started.set()
+ while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) }
+ throw SimSlimError("context canceled")
+ })
+ watcher.scan()
+ waitFor("pass to start") { started.isSet }
+ host.devices = []
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertEqual(events.kinds, ["slimming", "stopped"])
+ }
+
+ func testEachDeviceSlimsInItsOwnThreadSoOneSlowPassDoesNotBlockTheOthers() {
+ let host = FakeHost(devices: [booted(1), booted(2)])
+ let events = Events()
+ let release = Flag()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { _, _, id, _, _ in
+ if id == "AAAAAAAA-0000-0000-0000-000000000001" {
+ while !release.isSet { Thread.sleep(forTimeInterval: 0.005) }
+ }
+ return true
+ })
+ watcher.scan()
+ waitFor("the fast device to finish") {
+ events.all.contains { $0.event == "slimmed" && $0.udid == self.udid(2) }
+ }
+ XCTAssertFalse(events.all.contains { $0.event == "slimmed" && $0.udid == udid(1) })
+ release.set()
+ watcher.waitForWork()
+ XCTAssertEqual(events.all.filter { $0.event == "slimmed" }.count, 2)
+ }
+
+ func testAFailedListingIsReportedAndTheLoopCarriesOn() {
+ let host = FakeHost(devices: [booted(1)])
+ host.listFailure = "CoreSimulatorService is not running"
+ let events = Events()
+ let watcher = makeWatcher(host, events: events)
+ watcher.scan()
+ XCTAssertTrue(events.lines.contains { $0.hasPrefix("watch: list devices: ") })
+ XCTAssertEqual(events.kinds, [])
+ }
+
+ func testProgressLinesCarryTheUDID() {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { _, _, _, _, reporter in
+ reporter?("Stopping 173 background services")
+ return true
+ })
+ watcher.scan()
+ watcher.waitForWork()
+ XCTAssertTrue(
+ events.lines.contains("watch: \(udid(1)): Stopping 173 background services"))
+ }
+
+ // MARK: - slimming before boot
+
+ func testAShutdownDeviceIsSeededOncePerShutdown() {
+ let host = FakeHost(devices: [shutdown(1)])
+ let events = Events()
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ host, events: events,
+ preslim: { d, _ in
+ seeds.add(d.udid)
+ return 173
+ })
+ watcher.scan()
+ watcher.scan()
+ XCTAssertEqual(seeds.all, [udid(1)])
+ XCTAssertEqual(
+ events.all,
+ [WatchEvent(event: "slimmed_before_boot", udid: udid(1), set: "default", services: 173)])
+ // It boots (a booted device may rewrite its store), then shuts down again.
+ host.devices[0].state = "Booted"
+ watcher.scan()
+ watcher.waitForWork()
+ host.devices[0].state = "Shutdown"
+ watcher.scan()
+ XCTAssertEqual(seeds.all, [udid(1), udid(1)])
+ }
+
+ func testASeedThatFailsIsRetriedOnTheNextScan() {
+ let host = FakeHost(devices: [shutdown(1)])
+ let events = Events()
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ host, events: events,
+ preslim: { _, _ in
+ seeds.add("x")
+ if seeds.all.count == 1 { throw SimSlimError("disk full") }
+ return 5
+ })
+ watcher.scan()
+ XCTAssertTrue(events.lines.contains("watch: \(udid(1)): slim before boot: disk full"))
+ watcher.scan()
+ XCTAssertEqual(events.kinds, ["slimmed_before_boot"])
+ }
+
+ func testASeedWithNothingToWriteIsSilent() {
+ let host = FakeHost(devices: [shutdown(1)])
+ let events = Events()
+ let watcher = makeWatcher(host, events: events, preslim: { _, _ in 0 })
+ watcher.scan()
+ XCTAssertEqual(events.kinds, [])
+ XCTAssertEqual(events.lines, [])
+ }
+
+ func testASeedThatLandsAfterTheBootBeganIsNotAnnounced() throws {
+ let dir = root + "/devices/\(udid(1))"
+ try FileManager.default.createDirectory(
+ atPath: dir + "/data", withIntermediateDirectories: true)
+ try devicePlist(udid: udid(1), runtime: ios, state: 3).write(
+ toFile: dir + "/device.plist", atomically: true, encoding: .utf8)
+ let events = Events()
+ let watcher = makeWatcher(FakeHost(), events: events, preslim: { _, _ in 12 })
+ var device = Device(
+ udid: udid(1), state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default",
+ dataPath: dir + "/data", runtimeID: ios)
+ watcher.seed(device)
+ XCTAssertEqual(events.kinds, [], "launchd_sim already started")
+ XCTAssertTrue(
+ events.lines.contains { $0.contains("booted before its slim (12 services) landed") })
+
+ // The plist still says shut down: announced.
+ try devicePlist(udid: udid(1), runtime: ios, state: 1).write(
+ toFile: dir + "/device.plist", atomically: true, encoding: .utf8)
+ device.udid = udid(2)
+ watcher.seed(device)
+ XCTAssertEqual(events.kinds, ["slimmed_before_boot"])
+ }
+
+ func testPreslimWritesOnlyMissingDisablesAndLeavesTheRestAlone() throws {
+ let store = DisabledStore(root: root + "/store")
+ let id = udid(1)
+ try store.write(
+ udid: id, toDisable: ["com.apple.unmanaged", "com.apple.extra.disabled"], toEnable: [])
+ let someManaged = Profile().desired().sorted()[0]
+ try store.write(udid: id, toDisable: [someManaged], toEnable: [])
+ let device = Device(
+ udid: id, state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default")
+ let count = try preslimDevice(device, profile: Profile(), storeRoot: root + "/store")
+ XCTAssertEqual(count, Profile().desired().count - 1)
+ let disabled = try store.readDisabled(udid: id)
+ XCTAssertTrue(disabled.isSuperset(of: Profile().desired()))
+ XCTAssertTrue(disabled.contains("com.apple.unmanaged"), "unmanaged entries are untouched")
+ XCTAssertEqual(try preslimDevice(device, profile: Profile(), storeRoot: root + "/store"), 0)
+ }
+
+ func testPreslimNeverEnablesAnything() throws {
+ let store = DisabledStore(root: root + "/store")
+ let id = udid(1)
+ // Disabled beyond the profile: stays disabled.
+ var profile = Profile()
+ let kept = Catalog.categories[0].labels[0]
+ profile.keep = [kept]
+ try store.write(udid: id, toDisable: [kept], toEnable: [])
+ let device = Device(
+ udid: id, state: "Shutdown", platform: "iOS", osVersion: "27.2", set: "default")
+ _ = try preslimDevice(device, profile: profile, storeRoot: root + "/store")
+ XCTAssertTrue(try store.readDisabled(udid: id).contains(kept))
+ }
+
+ func testPreslimSkipsBootedDevicesAndRuntimesWithoutPersistence() throws {
+ let booted = Device(
+ udid: udid(1), state: "Booted", platform: "iOS", osVersion: "27.2", set: "default")
+ let oldRuntime = Device(
+ udid: udid(2), state: "Shutdown", platform: "iOS", osVersion: "17.0", set: "default")
+ XCTAssertEqual(try preslimDevice(booted, profile: Profile(), storeRoot: root + "/store"), 0)
+ XCTAssertEqual(try preslimDevice(oldRuntime, profile: Profile(), storeRoot: root + "/store"), 0)
+ XCTAssertFalse(FileManager.default.fileExists(atPath: root + "/store"))
+ }
+
+ func testPreslimKeepsHomedEnabledOnWatchOS() throws {
+ let watch = Device(
+ udid: udid(1), state: "Shutdown", platform: "watchOS", osVersion: "11.5", set: "default")
+ _ = try preslimDevice(watch, profile: Profile(), storeRoot: root + "/store")
+ let disabled = try DisabledStore(root: root + "/store").readDisabled(udid: udid(1))
+ XCTAssertFalse(disabled.contains("com.apple.homed"))
+ }
+
+ func testAReappearingUDIDIsSeededAgainBecauseDeletedDevicesAreForgotten() {
+ let host = FakeHost(devices: [shutdown(1)])
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ host, events: Events(),
+ preslim: { d, _ in
+ seeds.add(d.udid)
+ return 1
+ })
+ watcher.scan()
+ host.devices = []
+ watcher.scan() // pruned
+ host.devices = [shutdown(1)]
+ watcher.scan()
+ XCTAssertEqual(seeds.all, [udid(1), udid(1)])
+ }
+
+ func testABootedOrBootingDeviceIsNeverSeeded() {
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ FakeHost(), events: Events(),
+ preslim: { d, _ in
+ seeds.add(d.udid)
+ return 1
+ })
+ for state in ["Booted", "Booting", "Shutting Down"] {
+ watcher.seed(
+ Device(udid: udid(1), state: state, platform: "iOS", osVersion: "27.2", set: "default"))
+ }
+ XCTAssertEqual(seeds.all, [])
+ }
+
+ func testACancelledOperationRunsNoCommand() {
+ let host = FakeHost(devices: [booted(1)])
+ var ctl = Simctl(runner: host)
+ ctl.cancelled = { true }
+ XCTAssertThrowsError(try ctl.readDisabled(set: "default", udid: udid(1))) {
+ XCTAssertEqual("\($0)", "launchctl print-disabled: context canceled")
+ }
+ XCTAssertTrue(host.calls.isEmpty)
+ // A slim stops at its next step, saying why.
+ ctl.cancelled = { true }
+ XCTAssertThrowsError(
+ try ctl.applyDelta(
+ set: "default", udid: udid(1), toDisable: ["com.apple.x"], toEnable: [],
+ disableAction: .overrideOnly, reporter: nil)
+ ) {
+ XCTAssertTrue("\($0)".hasSuffix("context canceled"), "\($0)")
+ }
+ XCTAssertTrue(host.calls.isEmpty)
+ }
+
+ // MARK: - device.plist
+
+ private func devicePlist(udid: String, runtime: String, state: Int, stateAsString: Bool = false)
+ -> String
+ {
+ let value = stateAsString ? "\(state)" : "\(state)"
+ return """
+
+
+ UDID\(udid)
+ runtime\(runtime)
+ state\(value)
+ nameiPhone
+
+ """
+ }
+
+ func testReadDevicePlist() throws {
+ let dir = root + "/dev"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ for (state, asString, expected) in [
+ (1, false, "Shutdown"), (3, false, "Booted"), (1, true, "Shutdown"), (2, true, "Booted"),
+ ] {
+ try devicePlist(udid: udid(1), runtime: ios, state: state, stateAsString: asString)
+ .write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8)
+ let device = try readDevicePlist(DeviceDir(path: dir, set: "testing"))
+ XCTAssertEqual(device.state, expected)
+ XCTAssertEqual(device.udid, udid(1))
+ XCTAssertEqual(device.platform, "iOS")
+ XCTAssertEqual(device.osVersion, "27.2")
+ XCTAssertEqual(device.set, "testing")
+ XCTAssertEqual(device.dataPath, dir + "/data")
+ XCTAssertEqual(device.runtimeID, ios)
+ }
+ }
+
+ func testReadDevicePlistRejectsWhatSimslimDoesNotSlim() throws {
+ let dir = root + "/dev"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let cases = [
+ devicePlist(
+ udid: udid(1), runtime: "com.apple.CoreSimulator.SimRuntime.macOS-15-0", state: 1),
+ devicePlist(udid: "", runtime: ios, state: 1),
+ "not a plist",
+ ]
+ for text in cases {
+ try text.write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8)
+ XCTAssertThrowsError(try readDevicePlist(DeviceDir(path: dir, set: "default")), text)
+ }
+ XCTAssertThrowsError(try readDevicePlist(DeviceDir(path: root + "/nowhere", set: "default")))
+ }
+
+ func testSeedNewWaitsForDevicePlistThenSeeds() throws {
+ let dir = root + "/devices/\(udid(1))"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let events = Events()
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ FakeHost(), events: events,
+ preslim: { d, _ in
+ seeds.add("\(d.udid) \(d.state) \(d.set)")
+ return 1
+ })
+ let plist = devicePlist(udid: udid(1), runtime: ios, state: 1)
+ DispatchQueue.global().asyncAfter(deadline: .now() + 0.15) {
+ try? plist.write(toFile: dir + "/device.plist", atomically: true, encoding: .utf8)
+ }
+ watcher.seedNew(DeviceDir(path: dir, set: "default"))
+ XCTAssertEqual(seeds.all, ["\(udid(1)) Shutdown default"])
+ }
+
+ func testSeedNewGivesUpOnADirectoryThatIsNotADevice() throws {
+ let dir = root + "/devices/not-a-device"
+ try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ FakeHost(), events: Events(),
+ preslim: { d, _ in
+ seeds.add(d.udid)
+ return 1
+ })
+ let started = Date()
+ watcher.seedNew(DeviceDir(path: dir, set: "default"))
+ XCTAssertEqual(seeds.all, [])
+ XCTAssertLessThan(Date().timeIntervalSince(started), 4)
+ }
+
+ // MARK: - events and sets
+
+ func testEventJSONLinesFollowTheGoFieldOrderAndOmitEmptyFields() {
+ XCTAssertEqual(
+ WatchEvent(event: "slimmed", udid: "U", set: "default").jsonLine,
+ #"{"event":"slimmed","udid":"U","set":"default"}"#)
+ XCTAssertEqual(
+ WatchEvent(event: "slimmed_before_boot", udid: "U", set: "testing", services: 173).jsonLine,
+ #"{"event":"slimmed_before_boot","udid":"U","set":"testing","services":173}"#)
+ XCTAssertEqual(
+ WatchEvent(event: "failed", udid: "U", set: "/a/b", error: "say \"no\"\nnow").jsonLine,
+ #"{"event":"failed","udid":"U","set":"/a/b","error":"say \"no\"\nnow"}"#)
+ }
+
+ func testDeviceSetDirectories() {
+ var ctl = Simctl(runner: FakeHost())
+ ctl.registerDeviceSet("/custom/set")
+ XCTAssertEqual(
+ deviceSetDirs(ctl, home: "/Users/me"),
+ [
+ "/Users/me/Library/Developer/CoreSimulator/Devices": "default",
+ "/Users/me/Library/Developer/XCTestDevices": "testing",
+ "/custom/set": "/custom/set",
+ ])
+ }
+
+ // MARK: - kqueue
+
+ private func collect(
+ _ dirs: [String: String], during body: () throws -> Void, expecting count: Int
+ ) rethrows -> [DeviceDir] {
+ let found = Calls()
+ let stop = Flag()
+ let done = DispatchSemaphore(value: 0)
+ DispatchQueue.global().async {
+ watchDeviceDirs(
+ setDirs: dirs, pollInterval: 0.05, stop: { stop.isSet },
+ created: { found.add($0.set + "|" + $0.path) })
+ done.signal()
+ }
+ Thread.sleep(forTimeInterval: 0.2) // let the baseline be taken
+ try body()
+ let limit = Date().addingTimeInterval(5)
+ while found.all.count < count && Date() < limit { Thread.sleep(forTimeInterval: 0.01) }
+ Thread.sleep(forTimeInterval: 0.2) // let anything unexpected show up
+ stop.set()
+ done.wait()
+ return found.all.map { entry in
+ let parts = entry.split(separator: "|", maxSplits: 1).map(String.init)
+ return DeviceDir(path: parts[1], set: parts[0])
+ }
+ }
+
+ func testKqueueReportsNewDeviceDirectoriesButNotTheBaseline() throws {
+ let set = root + "/Devices"
+ try FileManager.default.createDirectory(
+ atPath: set + "/EXISTING", withIntermediateDirectories: true)
+ let found = try collect(
+ [set: "default"],
+ during: {
+ try FileManager.default.createDirectory(
+ atPath: set + "/NEW-1", withIntermediateDirectories: true)
+ FileManager.default.createFile(atPath: set + "/a-file", contents: Data())
+ }, expecting: 1)
+ XCTAssertEqual(found, [DeviceDir(path: set + "/NEW-1", set: "default")])
+ }
+
+ func testKqueueReportsABatchOfClones() throws {
+ let set = root + "/Devices"
+ try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true)
+ let found = try collect(
+ [set: "testing"],
+ during: {
+ for n in 0..<5 {
+ try FileManager.default.createDirectory(
+ atPath: set + "/CLONE-\(n)", withIntermediateDirectories: true)
+ }
+ }, expecting: 5)
+ XCTAssertEqual(Set(found.map(\.path)), Set((0..<5).map { set + "/CLONE-\($0)" }))
+ XCTAssertEqual(found.count, 5, "each directory is reported once")
+ }
+
+ func testKqueueAttachesASetDirectoryThatAppearsLater() throws {
+ let set = root + "/XCTestDevices"
+ let found = try collect(
+ [set: "testing"],
+ during: {
+ try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true)
+ Thread.sleep(forTimeInterval: 0.3)
+ try FileManager.default.createDirectory(
+ atPath: set + "/CLONE", withIntermediateDirectories: true)
+ }, expecting: 1)
+ XCTAssertTrue(found.contains(DeviceDir(path: set + "/CLONE", set: "testing")), "\(found)")
+ }
+
+ func testKqueueReattachesWhenTheSetDirectoryIsReplaced() throws {
+ let set = root + "/Devices"
+ try FileManager.default.createDirectory(atPath: set + "/OLD", withIntermediateDirectories: true)
+ let found = try collect(
+ [set: "default"],
+ during: {
+ try FileManager.default.removeItem(atPath: set)
+ Thread.sleep(forTimeInterval: 0.3)
+ try FileManager.default.createDirectory(
+ atPath: set + "/FRESH", withIntermediateDirectories: true)
+ }, expecting: 1)
+ XCTAssertTrue(found.contains(DeviceDir(path: set + "/FRESH", set: "default")), "\(found)")
+ }
+
+ func testKqueueReportsADeletedAndRecreatedDeviceAgain() throws {
+ let set = root + "/Devices"
+ try FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true)
+ let found = try collect(
+ [set: "default"],
+ during: {
+ try FileManager.default.createDirectory(
+ atPath: set + "/X", withIntermediateDirectories: true)
+ Thread.sleep(forTimeInterval: 0.3)
+ try FileManager.default.removeItem(atPath: set + "/X")
+ Thread.sleep(forTimeInterval: 0.3)
+ try FileManager.default.createDirectory(
+ atPath: set + "/X", withIntermediateDirectories: true)
+ }, expecting: 2)
+ XCTAssertEqual(found.count, 2)
+ }
+
+ func testKqueueStopsPromptly() {
+ let stop = Flag()
+ let done = DispatchSemaphore(value: 0)
+ DispatchQueue.global().async {
+ watchDeviceDirs(setDirs: [:], pollInterval: 0.05, stop: { stop.isSet }, created: { _ in })
+ done.signal()
+ }
+ stop.set()
+ XCTAssertEqual(done.wait(timeout: .now() + 2), .success)
+ }
+
+ // MARK: - run
+
+ func testRunSlimsABootedDeviceAndAFreshCloneThenStops() throws {
+ let home = root + "/home"
+ let devices = home + "/Library/Developer/CoreSimulator/Devices"
+ try FileManager.default.createDirectory(atPath: devices, withIntermediateDirectories: true)
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let seeds = Calls()
+ let watcher = makeWatcher(
+ host, events: events, slim: { _, _, _, _, _ in true },
+ preslim: { d, _ in
+ seeds.add(d.udid)
+ return 3
+ })
+ let stop = Flag()
+ let finished = DispatchSemaphore(value: 0)
+ Thread.detachNewThread {
+ watcher.run(interval: 0.2, stop: { stop.isSet })
+ finished.signal()
+ }
+ waitFor("the booted device to be slimmed") { events.kinds.contains("slimmed") }
+
+ // `simctl create` makes the directory, then writes device.plist.
+ let clone = devices + "/\(udid(9))"
+ try FileManager.default.createDirectory(atPath: clone, withIntermediateDirectories: true)
+ try devicePlist(udid: udid(9), runtime: ios, state: 1)
+ .write(toFile: clone + "/device.plist", atomically: true, encoding: .utf8)
+ waitFor("the new device to be seeded before any scan lists it") {
+ seeds.all.contains(self.udid(9))
+ }
+ waitFor("the seed to be announced") {
+ events.all.contains { $0.event == "slimmed_before_boot" && $0.udid == self.udid(9) }
+ }
+
+ stop.set()
+ XCTAssertEqual(finished.wait(timeout: .now() + 10), .success, "run returns once stopped")
+ }
+
+ func testRunReturnsOnlyAfterItsSlimsHaveStopped() throws {
+ let host = FakeHost(devices: [booted(1)])
+ let events = Events()
+ let started = Flag()
+ let exited = Flag()
+ let watcher = makeWatcher(
+ host, events: events,
+ slim: { ctl, _, _, _, _ in
+ started.set()
+ while ctl.cancelled?() != true { Thread.sleep(forTimeInterval: 0.005) }
+ Thread.sleep(forTimeInterval: 0.2)
+ exited.set()
+ throw SimSlimError("context canceled")
+ })
+ let stop = Flag()
+ let finished = DispatchSemaphore(value: 0)
+ Thread.detachNewThread {
+ watcher.run(interval: 0.2, stop: { stop.isSet })
+ XCTAssertTrue(exited.isSet, "no slim outlives the call")
+ finished.signal()
+ }
+ waitFor("the slim to start") { started.isSet }
+ stop.set()
+ XCTAssertEqual(finished.wait(timeout: .now() + 10), .success)
+ }
+}
From ebe1330db2aa79cf831379a7f042c2aa02299095 Mon Sep 17 00:00:00 2001
From: Pavel Akhrameev
Date: Wed, 18 Nov 2026 04:37:22 -0700
Subject: [PATCH 09/32] feat(swift): rename, erase, delete
Exact-UDID resolution before every destructive call, shutdown awaited before
erase/delete, Go-compatible name rules and %q output. Refuses erase/delete on a
Booting or Shutting Down simulator (deliberate divergence from Go).
---
docs/swift-port-plan.md | 1 +
swift/Sources/SimSlimCLI/CLI.swift | 8 +-
swift/Sources/SimSlimCLI/Format.swift | 51 +++++
swift/Sources/SimSlimCLI/Mutations.swift | 41 ++++
swift/Sources/SimSlimKit/Lifecycle.swift | 83 ++++++-
.../ManagementCommandTests.swift | 213 ++++++++++++++++++
.../MutationCommandTests.swift | 2 +-
swift/Tests/TestSupport/FakeHost.swift | 53 +++++
8 files changed, 446 insertions(+), 6 deletions(-)
create mode 100644 swift/Tests/SimSlimCLITests/ManagementCommandTests.swift
diff --git a/docs/swift-port-plan.md b/docs/swift-port-plan.md
index 484f357..5afc216 100644
--- a/docs/swift-port-plan.md
+++ b/docs/swift-port-plan.md
@@ -163,5 +163,6 @@ These are not in the first release. The SwiftUI app depends on several of them,
- **M2** simctl and read-only commands: `list`, `profiles`, `status`, `verify`, `doctor`, `measure`. **Done** (167 tests; every command checked through a fake host; the app's real `gui/Models.swift` decodes the JSON; `measure` cross-checked against `pgrep`/`ps`/`top` on a real Mac). Also run against a live throwaway simulator in an isolated device set (Xcode 27.2, iOS 27.2).
- **M3a** Slimming: `on`, `off`, `on --no-reboot`, `boot`, `shutdown`, offline fast path, batch unload, 8-worker pool. **Done** (222 tests; 12 mutations in the slimming core, all caught; live run on a throwaway simulator: 246 to 83 processes, about 10.5 GB to 2.7 GB, slim persists across shutdown and boot, `off` restores stock). Awaiting the independent review of this core.
- **M3b** Live `enable`/`disable` and `--save` (`live.go`, `profile_save.go`): **Done** (14 mutations in the new code caught after two added tests; run live on a throwaway simulator). Independently reviewed: one real bug (`--save` replaced a symlinked profile named by a bare file name) and several test gaps, all fixed.
+- **M5a** `rename`, `erase`, `delete`: **Done** (reviewed independently; no route for an alias or flag to reach the destructive simctl calls; live run on a throwaway simulator). One deliberate divergence from Go: erase and delete refuse a simulator that is Booting or Shutting Down, where Go runs them. Names print with Go's `%q` rules and trim with Go's space set. Remaining for the app cutover: `size`, `disk-categories`, `disk-plan`, `disk-clean`, `clone`.
- **M4** `watch`: **Done** (kqueue device-set watcher, pre-boot store seeding, per-device after-boot slim with cancellation, `--json` events; 40 tests, 19 mutations caught or hung). Not run live: `watch` always scans the user's default device set, so a live run would slim their real simulators; run it on a Mac where that is intended. Cancellation stops the next command, not one already running (Go kills it).
- **M5** Integration tests on a throwaway simulator, independent review of the mutating core, and parity run against the Go tool.
diff --git a/swift/Sources/SimSlimCLI/CLI.swift b/swift/Sources/SimSlimCLI/CLI.swift
index 2bc000d..f86b40c 100644
--- a/swift/Sources/SimSlimCLI/CLI.swift
+++ b/swift/Sources/SimSlimCLI/CLI.swift
@@ -52,7 +52,7 @@ public struct CLI {
/// Commands that exist in the Go CLI but are not in the Swift port yet.
static let notYetPorted: Set = [
"profile", "top", "size", "disk-categories",
- "disk-plan", "disk-clean", "clone", "repair-clone", "rename", "erase", "delete",
+ "disk-plan", "disk-clean", "clone", "repair-clone",
]
static let globalSpecs: [FlagSpec] = [
@@ -78,6 +78,9 @@ public struct CLI {
"watch": [
.bool("json"), .string("profile"), .string("except"), .string("keep"), .string("interval"),
],
+ "rename": [.bool("json", onlyOnce: true)],
+ "erase": [.bool("json", onlyOnce: true)],
+ "delete": [.bool("json", onlyOnce: true)],
"enable": [.bool("json", onlyOnce: true), .string("save")],
"disable": [.bool("json", onlyOnce: true), .string("save")],
]
@@ -170,6 +173,9 @@ public struct CLI {
case "shutdown": return try cmdShutdown(context)
case "on": return try cmdOn(context)
case "off": return try cmdOff(context)
+ case "rename": return try cmdRename(context)
+ case "erase": return try cmdErase(context)
+ case "delete": return try cmdDelete(context)
case "watch": return try cmdWatch(context)
case "enable": return try cmdEnable(context)
case "disable": return try cmdDisable(context)
diff --git a/swift/Sources/SimSlimCLI/Format.swift b/swift/Sources/SimSlimCLI/Format.swift
index 4e49ec7..63368e4 100644
--- a/swift/Sources/SimSlimCLI/Format.swift
+++ b/swift/Sources/SimSlimCLI/Format.swift
@@ -34,3 +34,54 @@ func jsonText(_ value: T) throws -> String {
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
return String(decoding: try encoder.encode(value), as: UTF8.self) + "\n"
}
+
+/// Go's `%q` (`strconv.Quote`): quote, backslash and the C escapes are
+/// escaped, and so is every scalar Go does not call printable (anything outside
+/// the letter, mark, number, punctuation and symbol categories and the ASCII
+/// space), as `\uXXXX` or `\UXXXXXXXX`. A name such as one with a zero-width
+/// joiner therefore prints visibly escaped, as it does in Go.
+func goQuote(_ text: String) -> String {
+ var out = "\""
+ for ch in text.unicodeScalars {
+ switch ch {
+ case "\"": out += "\\\""
+ case "\\": out += "\\\\"
+ case "\u{07}": out += "\\a"
+ case "\u{08}": out += "\\b"
+ case "\u{0C}": out += "\\f"
+ case "\n": out += "\\n"
+ case "\r": out += "\\r"
+ case "\t": out += "\\t"
+ case "\u{0B}": out += "\\v"
+ default:
+ if isGoPrintable(ch) {
+ out.unicodeScalars.append(ch)
+ } else if ch.value < 0x10000 {
+ out += "\\u" + hex(ch.value, width: 4)
+ } else {
+ out += "\\U" + hex(ch.value, width: 8)
+ }
+ }
+ }
+ return out + "\""
+}
+
+private func hex(_ value: UInt32, width: Int) -> String {
+ let digits = String(value, radix: 16)
+ return String(repeating: "0", count: max(0, width - digits.count)) + digits
+}
+
+private func isGoPrintable(_ scalar: Unicode.Scalar) -> Bool {
+ if scalar == " " { return true }
+ switch scalar.properties.generalCategory {
+ case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter,
+ .nonspacingMark, .spacingMark, .enclosingMark,
+ .decimalNumber, .letterNumber, .otherNumber,
+ .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation,
+ .initialPunctuation, .finalPunctuation, .otherPunctuation,
+ .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/swift/Sources/SimSlimCLI/Mutations.swift b/swift/Sources/SimSlimCLI/Mutations.swift
index e68fae2..7f93f25 100644
--- a/swift/Sources/SimSlimCLI/Mutations.swift
+++ b/swift/Sources/SimSlimCLI/Mutations.swift
@@ -285,4 +285,45 @@ extension CLI {
)
}
}
+
+ // MARK: - rename / erase / delete
+
+ func cmdRename(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let args = context.parsed.positionals
+ guard args.count == 2 else {
+ throw SimSlimError("rename expects a simulator UDID and a new name")
+ }
+ let name = try normalizeSimulatorName(args[1])
+ try bounded(context.simctl, by: Simctl.shutdownTimeout).renameDevice(udid: args[0], name: name)
+ if json {
+ context.stdout(
+ try jsonText(SimulatorMutationOutput(action: "rename", udid: args[0], name: name)))
+ } else {
+ context.stdout("Renamed \(args[0]) to \(goQuote(name)).\n")
+ }
+ return 0
+ }
+
+ func cmdErase(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let udid = try oneUDID(context.parsed.positionals)
+ try bounded(context.simctl, by: context.bootTimeout).eraseDevice(udid: udid)
+ context.stdout(
+ json
+ ? try jsonText(SimulatorMutationOutput(action: "erase", udid: udid))
+ : "Erased simulator \(udid).\n")
+ return 0
+ }
+
+ func cmdDelete(_ context: Context) throws -> Int32 {
+ let json = context.parsed.bool("json")
+ let udid = try oneUDID(context.parsed.positionals)
+ try bounded(context.simctl, by: context.bootTimeout).deleteDevice(udid: udid)
+ context.stdout(
+ json
+ ? try jsonText(SimulatorMutationOutput(action: "delete", udid: udid))
+ : "Deleted simulator \(udid).\n")
+ return 0
+ }
}
diff --git a/swift/Sources/SimSlimKit/Lifecycle.swift b/swift/Sources/SimSlimKit/Lifecycle.swift
index 564c085..ef13d39 100644
--- a/swift/Sources/SimSlimKit/Lifecycle.swift
+++ b/swift/Sources/SimSlimKit/Lifecycle.swift
@@ -7,6 +7,15 @@ public typealias Reporter = @Sendable (String) -> Void
func report(_ reporter: Reporter?, _ message: String) { reporter?(message) }
extension Simctl {
+ /// Runs `xcrun ` and turns a failure into Go's `xcrun : exit status
+ /// N: