From a819acf0b496c9cb78b335fb9d7dc065f5dcfebf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:00:45 +0100 Subject: [PATCH 01/11] refactor(ios): slim test helpers move to test-slim.ts for the except tests (#1329) --- src/drivers/ios/index.test.ts | 242 +++------------------------------ src/drivers/ios/test-slim.ts | 249 ++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+), 221 deletions(-) create mode 100644 src/drivers/ios/test-slim.ts diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 6153c0d9a..67de79faa 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -11,7 +11,6 @@ import { DriverCrashError, OwnedRootError, OWNED_ROOT_MARKER_FILE, - type OwnedRootMarker, PassthroughRefusedError, RuntimeMissingError, UnknownModelError, @@ -36,18 +35,36 @@ import { SLIM_CATEGORIES, supportsPersistentSlim, type SilenceFailedFact, - type SlimmedFact, type SlimSkippedFact, } from "./index.js"; import { memorySourceDatabase, plantReadySeed, plantSource } from "./testing.js"; +import { + FaultyFilesystem, + createSlimDriver, + dataPath, + deviceRoot, + driverData, + instanceId, + overridesFolder, + overridesPath, + overridesPlist, + overridesRoot, + parseOverrides, + plantManagedDevice, + prepareSlim, + prepareSlimWith, + printDisabled, + simctl, + simctlArgs, + slimBootCalls, + waitForCalls, +} from "./test-slim.js"; const listFixture = readFileSync(new URL("./fixtures/simctl-list.json", import.meta.url), "utf8"); const listDevicesFixture = readFileSync( new URL("./fixtures/simctl-list-devices.json", import.meta.url), "utf8", ); -const deviceRoot = "/Devices"; -const instanceId = "instance-1"; const listInvocation = simctl("list", "-j", "devicetypes", "runtimes"); const listDevicesInvocation = simctl("list", "-j", "devices"); @@ -120,22 +137,11 @@ const listFixtureAfterDownload = JSON.stringify({ ], }); const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; -const driverData = { - deviceTypeId: "com.apple.CoreSimulator.SimDeviceType.iPhone-16", - name: "simlock-device-1", - runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-26-5", - udid: "00000000-0000-0000-0000-000000000001", -} as const; -const dataPath = `${deviceRoot}/${driverData.udid}/data`; const durableMarkPath = `${deviceRoot}/${driverData.udid}/simlock-mark.json`; const erasableMarkPath = `${dataPath}/simlock-mark.json`; /** why: Every simctl call the driver makes is scoped to its device set; so is every expectation. */ -function simctlArgs(...args: readonly string[]): string[] { - return ["simctl", "--set", deviceRoot, ...args]; -} - const scopedRunners: ScriptedProcessRunner[] = []; const legacyUdid = "00000000-0000-0000-0000-0000000000ff"; @@ -202,10 +208,6 @@ async function seededDatabase( }); } -function simctl(...args: readonly string[]): { readonly command: string; readonly args: string[] } { - return { args: simctlArgs(...args), command: "xcrun" }; -} - function deviceListResponse(state: string): string { return JSON.stringify({ devices: { @@ -4897,48 +4899,6 @@ async function createDriver( }); } -/** - * why: Bounded on purpose. An unexpected invocation makes `ScriptedProcessRunner.spawn` throw - * synchronously, `#invokeSimctl` turns that into a `DriverCrashError`, and the call this - * is waiting for never arrives -- an unbounded spin then hangs the whole suite instead of - * reporting which argv the driver actually produced. - */ -async function waitForCalls(runner: ScriptedProcessRunner, count: number): Promise { - for (let tick = 0; tick < 1_000 && runner.calls.length < count; tick += 1) { - await Promise.resolve(); - } - - expect( - runner.calls.map((call) => call.args), - `simctl never reached ${String(count)} calls`, - ).toHaveLength(count); -} - -/** - * why: Plants a managed device in the root the way a real one arrives: inside a root Simlock - * already owns and marked as such. - * - * A bare `mkdirp(dataPath)` describes a state that cannot occur -- `ensureOwnedRoot` creates - * a root empty and marks it in the same publish, so a root holding a device always carries - * the marker. Without it the fixture is a non-empty unmarked root, which the driver is - * required to refuse (ADR 0001, decision 2), and every test built on it fails at `create` - * for a reason that has nothing to do with what it set out to prove. - */ -async function plantManagedDevice(filesystem: Filesystem): Promise { - const marker: OwnedRootMarker = { - instanceId, - owner: "simlock", - platform: "ios", - schemaVersion: 1, - }; - await filesystem.mkdirp(deviceRoot); - await filesystem.writeFileAtomic( - `${deviceRoot}/${OWNED_ROOT_MARKER_FILE}`, - JSON.stringify(marker), - ); - await filesystem.mkdirp(dataPath); -} - /** why: the state a case starts from, with the writes and modes the planting made forgotten. */ async function plantOverrides( filesystem: FaultyFilesystem, @@ -4971,37 +4931,6 @@ function runnerReadingFileAtBoot(filesystem: FaultyFilesystem, clock: FakeClock) return { fileAtBoot: () => contents, runner }; } -async function createSlimDriver( - runner: ScriptedProcessRunner, - filesystem: Filesystem, - slim: { - readonly categories?: readonly string[]; - readonly bootTimeoutMs: number; - }, - onSlimmed?: (fact: SlimmedFact) => void, - onSlimSkipped?: (fact: SlimSkippedFact) => void, - slimByDefault = false, - clock = new FakeClock(), -): Promise { - return await IosSimctlDriver.create({ - database: await memorySourceDatabase(), - driverConfig: { deviceRoot }, - instanceId, - simlockHome: "/home/.simlock", - clock, - filesystem, - idGenerator: { generate: () => "device-1" }, - ...(onSlimmed === undefined ? {} : { onSlimmed }), - ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), - launchdOverridesRoot: overridesRoot, - processRunner: runner, - config: { slim }, - slimByDefault, - }); -} - -const overridesRoot = "/private/var/tmp"; - /** why: a LaunchServices database file and a neighbour that must stay, in the device folder `device`. */ async function plantLaunchServices(filesystem: MemoryFilesystem, device: string): Promise { const folder = `${device}/data/var/db/lsd`; @@ -5020,21 +4949,6 @@ async function launchServicesFiles( return (await filesystem.readdir(`${device}/data/var/db/lsd`)).sort(); } -function overridesFolder(udid: string): string { - return `${overridesRoot}/com.apple.CoreSimulator.SimDevice.${udid}`; -} - -function overridesPath(udid: string): string { - return `${overridesFolder(udid)}/disabled.plist`; -} - -function overridesPlist(entries: Readonly>): string { - const lines = Object.entries(entries).map( - ([label, off]) => `${label}<${String(off)}/>`, - ); - return `\n${lines.join("")}\n`; -} - /** why: Records every `warn` message, so the destroy's log line is asserted on its text. */ class RecordingLogger implements Logger { readonly warnings: string[] = []; @@ -5063,45 +4977,6 @@ class ModeRecordingFilesystem extends MemoryFilesystem { } } -/** why: Records what is written and fails the one operation a test names, as a full or unwritable store would. */ -class FaultyFilesystem extends MemoryFilesystem { - readonly writes: string[] = []; - readonly modes: { folder?: number | undefined; file?: number | undefined } = {}; - failing: "writeFileAtomic" | "mkdirp" | "rm" | "copyFile" | undefined; - failureMessage = "disk full"; - - override async writeFileAtomic( - path: string, - contents: string, - options?: Parameters[2], - ): Promise { - if (this.failing === "writeFileAtomic" && path.endsWith("disabled.plist")) { - throw new Error(this.failureMessage); - } - await super.writeFileAtomic(path, contents, options); - this.writes.push(path); - if (path.endsWith("disabled.plist")) this.modes.file = options?.mode; - } - - override async mkdirp(path: string, options?: Parameters[1]) { - if (this.failing === "mkdirp" && path.includes("CoreSimulator.SimDevice")) { - throw new Error(this.failureMessage); - } - await super.mkdirp(path, options); - if (path.includes("CoreSimulator.SimDevice")) this.modes.folder = options?.mode; - } - - override async copyFile(from: string, to: string): Promise { - if (this.failing === "copyFile") throw new Error(this.failureMessage); - await super.copyFile(from, to); - } - - override async rm(path: string): Promise { - if (this.failing === "rm") throw new Error(this.failureMessage); - await super.rm(path); - } -} - // why: spelled out here, not imported: the labels simslim v0.13.0 never disables (ADR 0060 §1). const neverDisabled = ["com.apple.assistantd", "com.apple.gamed", "com.apple.sharingd"]; @@ -5122,20 +4997,6 @@ function widgetsLabelList(): readonly string[] { return SLIM_CATEGORIES.find((category) => category.name === "widgets")?.labels ?? []; } -function parseOverrides(plist: string): Record { - const entries: Record = {}; - for (const match of plist.matchAll(/([^<]*)<\/key>\s*<(true|false)\/>/g)) { - entries[match[1] ?? ""] = match[2] === "true"; - } - return entries; -} - -/** why: `launchctl print-disabled system` as launchd prints it: one `"label" => state` line per entry. */ -function printDisabled(entries: Readonly>): string { - const lines = Object.entries(entries).map(([label, state]) => `\t"${label}" => ${state}`); - return ["disabled services = {", ...lines, "}", ""].join("\n"); -} - /** why: The readback of a boot that honoured every label as written. */ function wantedReadback(): string { return printDisabled( @@ -5148,66 +5009,6 @@ function wantedReadback(): string { ); } -/** why: The calls of one slim boot: the boot, its wait, the installer poll, then the readback. */ -function slimBootCalls(udid: string, readback: string) { - return [ - { match: simctl("boot", udid) }, - { match: simctl("bootstatus", udid, "-b") }, - { match: simctl("listapps", udid) }, - { - match: simctl("spawn", udid, "launchctl", "print-disabled", "system"), - result: { code: 0, stderr: "", stdout: readback }, - }, - ]; -} - -type ReadbackScript = - | { readonly stdout: string } - | { readonly code: number; readonly stderr: string } - | "hangs"; - -/** why: One slim `prepare` of the 18.5 device, with the readback scripted; the 120 s limit runs on a fake clock. */ -async function prepareSlimWith( - filesystem: FaultyFilesystem, - readback: ReadbackScript, - slimOptions: { readonly categories?: readonly string[]; readonly bootTimeoutMs: number }, -) { - const udid = "00000000-0000-0000-0000-000000000001"; - const runtimeId = "com.apple.CoreSimulator.SimRuntime.iOS-18-5"; - const calls = slimBootCalls(udid, ""); - const readbackCall = - readback === "hangs" - ? { hangs: true, match: calls[3]!.match } - : "stdout" in readback - ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } - : { - match: calls[3]!.match, - result: { code: readback.code, stderr: readback.stderr, stdout: "" }, - }; - const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); - const clock = new FakeClock(); - const onSlimmed = vi.fn(); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - filesystem, - slimOptions, - onSlimmed, - onSlimSkipped, - false, - clock, - ); - const ready = driver.makeReady( - { address: udid, deviceId: udid, driverData: { ...driverData, runtimeId } }, - prepareSlim, - ); - if (readback === "hangs") { - await waitForCalls(runner, 4); - clock.advance(120_000); - } - return { onSlimSkipped, onSlimmed, result: await ready, runner }; -} - /** why: The readback of a boot that honoured every label, with the given labels changed or dropped (`undefined`). */ function readbackWith(changes: Readonly>): string { const entries: Record = Object.fromEntries( @@ -5274,7 +5075,6 @@ function assetInfoPlist(simulatorVersion: string, build: string): string { } const prepareFull = { mode: "full", purpose: "prepare" } as const; -const prepareSlim = { mode: "slim", purpose: "prepare" } as const; const recoverFull = { mode: "full", purpose: "recover" } as const; const recoverSlim = { mode: "slim", purpose: "recover" } as const; diff --git a/src/drivers/ios/test-slim.ts b/src/drivers/ios/test-slim.ts new file mode 100644 index 000000000..81057cf17 --- /dev/null +++ b/src/drivers/ios/test-slim.ts @@ -0,0 +1,249 @@ +import { expect, vi, type Mock } from "vitest"; + +import { + OWNED_ROOT_MARKER_FILE, + type DriverDevice, + type OwnedRootMarker, +} from "../../core/index.js"; +import { + FakeClock, + MemoryFilesystem, + ScriptedProcessRunner, + type Filesystem, +} from "../../ports/index.js"; +import { IosSimctlDriver, type SlimmedFact, type SlimSkippedFact } from "./index.js"; +import { memorySourceDatabase } from "./testing.js"; + +// why: the slim boot's fixtures, shared by the driver's two test files (index.test.ts is at its size limit). + +export const deviceRoot = "/Devices"; + +export const instanceId = "instance-1"; + +export const driverData = { + deviceTypeId: "com.apple.CoreSimulator.SimDeviceType.iPhone-16", + name: "simlock-device-1", + runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-26-5", + udid: "00000000-0000-0000-0000-000000000001", +} as const; + +export const dataPath = `${deviceRoot}/${driverData.udid}/data`; + +export function simctlArgs(...args: readonly string[]): string[] { + return ["simctl", "--set", deviceRoot, ...args]; +} + +export function simctl(...args: readonly string[]): { + readonly command: string; + readonly args: string[]; +} { + return { args: simctlArgs(...args), command: "xcrun" }; +} + +/** + * why: Bounded on purpose. An unexpected invocation makes `ScriptedProcessRunner.spawn` throw + * synchronously, `#invokeSimctl` turns that into a `DriverCrashError`, and the call this + * is waiting for never arrives -- an unbounded spin then hangs the whole suite instead of + * reporting which argv the driver actually produced. + */ +export async function waitForCalls(runner: ScriptedProcessRunner, count: number): Promise { + for (let tick = 0; tick < 1_000 && runner.calls.length < count; tick += 1) { + await Promise.resolve(); + } + + expect( + runner.calls.map((call) => call.args), + `simctl never reached ${String(count)} calls`, + ).toHaveLength(count); +} + +/** + * why: Plants a managed device in the root the way a real one arrives: inside a root Simlock + * already owns and marked as such. + * + * A bare `mkdirp(dataPath)` describes a state that cannot occur -- `ensureOwnedRoot` creates + * a root empty and marks it in the same publish, so a root holding a device always carries + * the marker. Without it the fixture is a non-empty unmarked root, which the driver is + * required to refuse (ADR 0001, decision 2), and every test built on it fails at `create` + * for a reason that has nothing to do with what it set out to prove. + */ +export async function plantManagedDevice(filesystem: Filesystem): Promise { + const marker: OwnedRootMarker = { + instanceId, + owner: "simlock", + platform: "ios", + schemaVersion: 1, + }; + await filesystem.mkdirp(deviceRoot); + await filesystem.writeFileAtomic( + `${deviceRoot}/${OWNED_ROOT_MARKER_FILE}`, + JSON.stringify(marker), + ); + await filesystem.mkdirp(dataPath); +} + +export async function createSlimDriver( + runner: ScriptedProcessRunner, + filesystem: Filesystem, + slim: { + readonly categories?: readonly string[]; + readonly bootTimeoutMs: number; + }, + onSlimmed?: (fact: SlimmedFact) => void, + onSlimSkipped?: (fact: SlimSkippedFact) => void, + slimByDefault = false, + clock = new FakeClock(), +): Promise { + return await IosSimctlDriver.create({ + database: await memorySourceDatabase(), + driverConfig: { deviceRoot }, + instanceId, + simlockHome: "/home/.simlock", + clock, + filesystem, + idGenerator: { generate: () => "device-1" }, + ...(onSlimmed === undefined ? {} : { onSlimmed }), + ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), + launchdOverridesRoot: overridesRoot, + processRunner: runner, + config: { slim }, + slimByDefault, + }); +} + +export const overridesRoot = "/private/var/tmp"; + +export function overridesFolder(udid: string): string { + return `${overridesRoot}/com.apple.CoreSimulator.SimDevice.${udid}`; +} + +export function overridesPath(udid: string): string { + return `${overridesFolder(udid)}/disabled.plist`; +} + +export function overridesPlist(entries: Readonly>): string { + const lines = Object.entries(entries).map( + ([label, off]) => `${label}<${String(off)}/>`, + ); + return `\n${lines.join("")}\n`; +} + +/** why: Records what is written and fails the one operation a test names, as a full or unwritable store would. */ +export class FaultyFilesystem extends MemoryFilesystem { + readonly writes: string[] = []; + readonly modes: { folder?: number | undefined; file?: number | undefined } = {}; + failing: "writeFileAtomic" | "mkdirp" | "rm" | "copyFile" | undefined; + failureMessage = "disk full"; + + override async writeFileAtomic( + path: string, + contents: string, + options?: Parameters[2], + ): Promise { + if (this.failing === "writeFileAtomic" && path.endsWith("disabled.plist")) { + throw new Error(this.failureMessage); + } + await super.writeFileAtomic(path, contents, options); + this.writes.push(path); + if (path.endsWith("disabled.plist")) this.modes.file = options?.mode; + } + + override async mkdirp(path: string, options?: Parameters[1]) { + if (this.failing === "mkdirp" && path.includes("CoreSimulator.SimDevice")) { + throw new Error(this.failureMessage); + } + await super.mkdirp(path, options); + if (path.includes("CoreSimulator.SimDevice")) this.modes.folder = options?.mode; + } + + override async copyFile(from: string, to: string): Promise { + if (this.failing === "copyFile") throw new Error(this.failureMessage); + await super.copyFile(from, to); + } + + override async rm(path: string): Promise { + if (this.failing === "rm") throw new Error(this.failureMessage); + await super.rm(path); + } +} + +export function parseOverrides(plist: string): Record { + const entries: Record = {}; + for (const match of plist.matchAll(/([^<]*)<\/key>\s*<(true|false)\/>/g)) { + entries[match[1] ?? ""] = match[2] === "true"; + } + return entries; +} + +/** why: `launchctl print-disabled system` as launchd prints it: one `"label" => state` line per entry. */ +export function printDisabled(entries: Readonly>): string { + const lines = Object.entries(entries).map(([label, state]) => `\t"${label}" => ${state}`); + return ["disabled services = {", ...lines, "}", ""].join("\n"); +} + +/** why: The calls of one slim boot: the boot, its wait, the installer poll, then the readback. */ +export function slimBootCalls(udid: string, readback: string) { + return [ + { match: simctl("boot", udid) }, + { match: simctl("bootstatus", udid, "-b") }, + { match: simctl("listapps", udid) }, + { + match: simctl("spawn", udid, "launchctl", "print-disabled", "system"), + result: { code: 0, stderr: "", stdout: readback }, + }, + ]; +} + +export type ReadbackScript = + | { readonly stdout: string } + | { readonly code: number; readonly stderr: string } + | "hangs"; + +/** why: One slim `prepare` of the 18.5 device, with the readback scripted; the 120 s limit runs on a fake clock. */ +export async function prepareSlimWith( + filesystem: FaultyFilesystem, + readback: ReadbackScript, + slimOptions: { readonly categories?: readonly string[]; readonly bootTimeoutMs: number }, +): Promise<{ + readonly onSlimSkipped: Mock<(fact: SlimSkippedFact) => void>; + readonly onSlimmed: Mock<(fact: SlimmedFact) => void>; + readonly result: DriverDevice; + readonly runner: ScriptedProcessRunner; +}> { + const udid = "00000000-0000-0000-0000-000000000001"; + const runtimeId = "com.apple.CoreSimulator.SimRuntime.iOS-18-5"; + const calls = slimBootCalls(udid, ""); + const readbackCall = + readback === "hangs" + ? { hangs: true, match: calls[3]!.match } + : "stdout" in readback + ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } + : { + match: calls[3]!.match, + result: { code: readback.code, stderr: readback.stderr, stdout: "" }, + }; + const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); + const clock = new FakeClock(); + const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); + const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); + const driver = await createSlimDriver( + runner, + filesystem, + slimOptions, + onSlimmed, + onSlimSkipped, + false, + clock, + ); + const ready = driver.makeReady( + { address: udid, deviceId: udid, driverData: { ...driverData, runtimeId } }, + prepareSlim, + ); + if (readback === "hangs") { + await waitForCalls(runner, 4); + clock.advance(120_000); + } + return { onSlimSkipped, onSlimmed, result: await ready, runner }; +} + +export const prepareSlim = { mode: "slim", purpose: "prepare" } as const; From 422a71759437a154985fb35d869417027edb1a15 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:01:17 +0100 Subject: [PATCH 02/11] test: the iOS driver boots a slim device with an except list and grants only when every kept label reads back enabled (#1329) --- src/core/driver.ts | 1 + src/drivers/ios/index.ts | 6 +- src/drivers/ios/slim-except.test.ts | 94 +++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 src/drivers/ios/slim-except.test.ts diff --git a/src/core/driver.ts b/src/core/driver.ts index 468254d46..c207f1ba2 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -301,6 +301,7 @@ export interface Driver { options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode; + readonly except?: readonly string[]; }, ): Promise; reclaim( diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 2fef99e0d..c7446d941 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1145,7 +1145,11 @@ export class IosSimctlDriver implements Driver { async makeReady( device: DriverDevice, - options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, + options: { + readonly purpose: "prepare" | "recover"; + readonly mode: DeviceMode; + readonly except?: readonly string[]; + }, ): Promise { const data = iosDriverData(device); const { plan, bootstatusTimeoutMs } = planSlimBoot( diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts new file mode 100644 index 000000000..64c01467f --- /dev/null +++ b/src/drivers/ios/slim-except.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it, vi } from "vitest"; + +import { FakeClock, ScriptedProcessRunner } from "../../ports/index.js"; +import { SLIM_CATEGORIES, type SlimmedFact, type SlimSkippedFact } from "./index.js"; +import { + createSlimDriver, + driverData, + FaultyFilesystem, + overridesPath, + parseOverrides, + plantManagedDevice, + printDisabled, + slimBootCalls, +} from "./test-slim.js"; + +const slim18_5 = { ...driverData, runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-18-5" }; +// why: spelled out, not imported: the labels simslim never disables (ADR 0060 §1). +const neverDisabled = ["com.apple.assistantd", "com.apple.gamed", "com.apple.sharingd"]; + +function labelsOf(names: readonly string[]): ReadonlySet { + return new Set( + SLIM_CATEGORIES.filter((category) => names.includes(category.name)).flatMap( + (category) => category.labels, + ), + ); +} + +/** why: What the driver must write: a label of a slimmed category and of no kept one is off (`true`), every other managed label on. */ +function expectedWrite(slimmed: readonly string[], kept: readonly string[]): Map { + const off = labelsOf(slimmed); + const keep = labelsOf(kept); + const wanted = new Map(); + for (const category of SLIM_CATEGORIES) { + for (const label of category.labels) { + wanted.set(label, off.has(label) && !keep.has(label) && !neverDisabled.includes(label)); + } + } + for (const label of neverDisabled) wanted.set(label, false); + return wanted; +} + +function readbackOf(wanted: ReadonlyMap): string { + return printDisabled( + Object.fromEntries([...wanted].map(([label, off]) => [label, off ? "disabled" : "enabled"])), + ); +} + +async function bootWithExcept(options: { + readonly categories?: readonly string[]; + readonly except: readonly string[]; + readonly readback: string; +}) { + const filesystem = new FaultyFilesystem(); + await plantManagedDevice(filesystem); + const runner = new ScriptedProcessRunner(slimBootCalls(slim18_5.udid, options.readback)); + const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); + const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); + const driver = await createSlimDriver( + runner, + filesystem, + { + bootTimeoutMs: 300_000, + ...(options.categories === undefined ? {} : { categories: options.categories }), + }, + onSlimmed, + onSlimSkipped, + false, + new FakeClock(), + ); + const result = await driver.makeReady( + { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, + { except: options.except, mode: "slim", purpose: "prepare" }, + ); + const written = parseOverrides(await filesystem.readFile(overridesPath(slim18_5.udid))); + return { onSlimSkipped, onSlimmed, result, written }; +} + +describe("IosSimctlDriver makeReady with an except list", () => { + it("boots a slim device with an except list and grants only when every kept label reads back enabled", async () => { + const allNames = SLIM_CATEGORIES.map((category) => category.name); + const wanted = expectedWrite(allNames, ["store", "other"]); + + const { onSlimSkipped, result, written } = await bootWithExcept({ + except: ["store", "other"], + readback: readbackOf(wanted), + }); + + expect(written).toEqual(Object.fromEntries(wanted)); + expect(written["com.apple.amsaccountsd"]).toBe(false); + expect(written["com.apple.passd"]).toBe(false); + expect(result.mode).toBe("slim"); + expect(onSlimSkipped).not.toHaveBeenCalled(); + }); +}); From b2f800e258aa01f68f3c92545afadcf94de8d4cb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:01:47 +0100 Subject: [PATCH 03/11] feat(ios): a slim boot writes the slim set minus the except list (#1329) --- src/drivers/ios/index.ts | 17 +++++++++++++---- src/drivers/ios/slim-except.ts | 15 +++++++++++++++ src/drivers/ios/slim-labels.ts | 10 ++++++++-- 3 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 src/drivers/ios/slim-except.ts diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index c7446d941..d54894058 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -81,6 +81,7 @@ import { IosSourceTable, type ReadySeed, type SourceRow } from "./source-data.js import { createIosScreenCapture } from "./screen-capture.js"; import type { IosDriverConfig } from "./definition.js"; import { overridesFor, resolveSlimCategories, slimSignature } from "./slim-labels.js"; +import { splitByExcept } from "./slim-except.js"; import { parseOverridesPlist, parsePrintDisabled, renderOverridesPlist } from "./slim-overrides.js"; /** why: ADR 0061 §1: a `making` row of this process older than this is a make that never ended. */ @@ -1159,7 +1160,9 @@ export class IosSimctlDriver implements Driver { options, ); const write = - plan.kind === "apply" ? await this.#writeOverrides(data.udid, plan.slim) : undefined; + plan.kind === "apply" + ? await this.#writeOverrides(data.udid, plan.slim, options.except) + : undefined; await this.#bootAndWait(data.udid, device.deviceId, bootstatusTimeoutMs); await runAfterBoot(this.#afterBoot, data.udid, device.deviceId); @@ -1236,8 +1239,14 @@ export class IosSimctlDriver implements Driver { return false; } - async #writeOverrides(udid: string, slim: SlimOptions): Promise { - const resolved = resolveSlimCategories(slim.categories); + async #writeOverrides( + udid: string, + slim: SlimOptions, + except: readonly string[] = [], + ): Promise { + const configured = resolveSlimCategories(slim.categories); + const { kept, slimmed } = splitByExcept(configured.categories, except); + const resolved = { categories: slimmed, unknown: configured.unknown }; if (resolved.categories.length === 0) { return { detail: `none of the configured slim categories (${(slim.categories ?? []).join(", ")}) are known`, @@ -1246,7 +1255,7 @@ export class IosSimctlDriver implements Driver { } const startedAt = this.#clock.now(); - const wanted = overridesFor(resolved.categories); + const wanted = overridesFor(resolved.categories, kept); let writeError: string | undefined; try { const folder = this.#overridesFolder(udid); diff --git a/src/drivers/ios/slim-except.ts b/src/drivers/ios/slim-except.ts new file mode 100644 index 000000000..7587aa75c --- /dev/null +++ b/src/drivers/ios/slim-except.ts @@ -0,0 +1,15 @@ +import type { SlimCategory } from "./slim-labels.js"; + +/** + * why: A lease's except list (ADR 0066 §2) takes categories out of the worker's slim set: the + * categories left are the ones to turn off, the excepted ones are the ones to keep on. + */ +export function splitByExcept( + categories: readonly SlimCategory[], + except: readonly string[], +): { readonly slimmed: readonly SlimCategory[]; readonly kept: readonly SlimCategory[] } { + return { + kept: categories.filter((category) => except.includes(category.name)), + slimmed: categories.filter((category) => !except.includes(category.name)), + }; +} diff --git a/src/drivers/ios/slim-labels.ts b/src/drivers/ios/slim-labels.ts index 7a9645be2..8d75b0eed 100644 --- a/src/drivers/ios/slim-labels.ts +++ b/src/drivers/ios/slim-labels.ts @@ -343,9 +343,13 @@ export const NEVER_DISABLE_LABELS: readonly string[] = [ /** * why: Every managed label (all categories plus the never-disable labels) mapped to what the overrides - * file must say: `true` (off) for a label of a configured category, `false` for the rest. + * file must say: `true` (off) for a label of a configured category, `false` for the rest and for + * every label of a kept category. */ -export function overridesFor(categories: readonly SlimCategory[]): ReadonlyMap { +export function overridesFor( + categories: readonly SlimCategory[], + keep: readonly SlimCategory[] = [], +): ReadonlyMap { const wanted = new Map(); for (const category of SLIM_CATEGORIES) { for (const label of category.labels) wanted.set(label, false); @@ -354,6 +358,8 @@ export function overridesFor(categories: readonly SlimCategory[]): ReadonlyMap Date: Fri, 6 Nov 2026 08:02:44 +0100 Subject: [PATCH 04/11] test: a kept label read back disabled, a failed write or a failed readback refuses the device (#1329) --- src/core/driver.ts | 8 +++ src/core/index.ts | 1 + src/drivers/ios/slim-except.test.ts | 78 ++++++++++++++++++++++------- 3 files changed, 69 insertions(+), 18 deletions(-) diff --git a/src/core/driver.ts b/src/core/driver.ts index c207f1ba2..7e5932f7e 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -599,6 +599,14 @@ export class UnsupportedRequestOptionError extends Error { } } +/** why: A device booted with a lease's except list but a kept category's service is not running, or that could not be shown (ADR 0066 §2): the driver refuses the device rather than tell the lease it is on. */ +export class KeptCategoriesError extends Error { + constructor(message: string) { + super(message); + this.name = "KeptCategoriesError"; + } +} + export class UnknownModelError extends Error { readonly class: DeviceClass | undefined; readonly model: string | undefined; diff --git a/src/core/index.ts b/src/core/index.ts index 1114df4b5..f87d8f7b1 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -107,6 +107,7 @@ export { UnknownModelError, BaselineMismatchError, BaselineStaleError, + KeptCategoriesError, UnsupportedRequestOptionError, } from "./driver.js"; export { diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts index 64c01467f..b93f5bf0e 100644 --- a/src/drivers/ios/slim-except.test.ts +++ b/src/drivers/ios/slim-except.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from "vitest"; +import { KeptCategoriesError } from "../../core/index.js"; import { FakeClock, ScriptedProcessRunner } from "../../ports/index.js"; import { SLIM_CATEGORIES, type SlimmedFact, type SlimSkippedFact } from "./index.js"; import { @@ -48,11 +49,21 @@ function readbackOf(wanted: ReadonlyMap): string { async function bootWithExcept(options: { readonly categories?: readonly string[]; readonly except: readonly string[]; - readonly readback: string; + readonly readback: string | { readonly code: number; readonly stderr: string }; + readonly writeFails?: boolean; }) { const filesystem = new FaultyFilesystem(); await plantManagedDevice(filesystem); - const runner = new ScriptedProcessRunner(slimBootCalls(slim18_5.udid, options.readback)); + if (options.writeFails === true) filesystem.failing = "writeFileAtomic"; + const calls = slimBootCalls(slim18_5.udid, ""); + const readbackCall = + typeof options.readback === "string" + ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: options.readback } } + : { + match: calls[3]!.match, + result: { code: options.readback.code, stderr: options.readback.stderr, stdout: "" }, + }; + const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); const driver = await createSlimDriver( @@ -67,28 +78,59 @@ async function bootWithExcept(options: { false, new FakeClock(), ); - const result = await driver.makeReady( - { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, - { except: options.except, mode: "slim", purpose: "prepare" }, - ); - const written = parseOverrides(await filesystem.readFile(overridesPath(slim18_5.udid))); - return { onSlimSkipped, onSlimmed, result, written }; + const outcome = await driver + .makeReady( + { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, + { except: options.except, mode: "slim", purpose: "prepare" }, + ) + .then( + (result) => ({ result }) as const, + (error: unknown) => ({ error }) as const, + ); + const file = overridesPath(slim18_5.udid); + const written = (await filesystem.exists(file)) + ? parseOverrides(await filesystem.readFile(file)) + : undefined; + return { onSlimSkipped, onSlimmed, outcome, written }; } describe("IosSimctlDriver makeReady with an except list", () => { + const allNames = SLIM_CATEGORIES.map((category) => category.name); + it("boots a slim device with an except list and grants only when every kept label reads back enabled", async () => { - const allNames = SLIM_CATEGORIES.map((category) => category.name); const wanted = expectedWrite(allNames, ["store", "other"]); + const kept = readbackOf(wanted); + const firstKept = [...labelsOf(["store", "other"])].sort()[0]!; + const keptDisabled = readbackOf(new Map([...wanted, [firstKept, true]])); - const { onSlimSkipped, result, written } = await bootWithExcept({ - except: ["store", "other"], - readback: readbackOf(wanted), - }); + const granted = await bootWithExcept({ except: ["store", "other"], readback: kept }); + expect(granted.written).toEqual(Object.fromEntries(wanted)); + expect(granted.written?.["com.apple.amsaccountsd"]).toBe(false); + expect(granted.written?.["com.apple.passd"]).toBe(false); + expect(granted.outcome).toEqual({ result: expect.objectContaining({ mode: "slim" }) }); + expect(granted.onSlimSkipped).not.toHaveBeenCalled(); - expect(written).toEqual(Object.fromEntries(wanted)); - expect(written["com.apple.amsaccountsd"]).toBe(false); - expect(written["com.apple.passd"]).toBe(false); - expect(result.mode).toBe("slim"); - expect(onSlimSkipped).not.toHaveBeenCalled(); + const refusals = [ + { + name: "a kept label reads back disabled", + run: { except: ["store", "other"], readback: keptDisabled }, + message: `1 kept labels are not enabled; first: ${firstKept}`, + }, + { + name: "the overrides write fails", + run: { except: ["store", "other"], readback: kept, writeFails: true }, + message: "could not write the launchd overrides file: disk full", + }, + { + name: "the readback fails", + run: { except: ["store", "other"], readback: { code: 1, stderr: "boom\n" } }, + message: "could not read back the launchd overrides: exit 1: boom", + }, + ]; + for (const refusal of refusals) { + const { outcome, onSlimmed } = await bootWithExcept(refusal.run); + expect(outcome, refusal.name).toEqual({ error: new KeptCategoriesError(refusal.message) }); + expect(onSlimmed, refusal.name).not.toHaveBeenCalled(); + } }); }); From 319ea4946fd21ae4b159fb88f5ffc5f54d900fa8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:03:16 +0100 Subject: [PATCH 05/11] feat(ios): a kept label not enabled, a failed write or a failed readback refuses the device (#1329) --- src/drivers/ios/index.ts | 20 +++++++++++++++++--- src/drivers/ios/slim-except.ts | 16 +++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index d54894058..0c828748a 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -2,6 +2,7 @@ import { dirname, join } from "node:path"; import { BootTimeoutError, + KeptCategoriesError, type ComponentInstallProgress, type ComponentInstallResult, type ComponentReceipt, @@ -80,8 +81,13 @@ import { iosRuntimeVersionFromId } from "./runtime-version.js"; import { IosSourceTable, type ReadySeed, type SourceRow } from "./source-data.js"; import { createIosScreenCapture } from "./screen-capture.js"; import type { IosDriverConfig } from "./definition.js"; -import { overridesFor, resolveSlimCategories, slimSignature } from "./slim-labels.js"; -import { splitByExcept } from "./slim-except.js"; +import { + overridesFor, + resolveSlimCategories, + slimSignature, + type SlimCategory, +} from "./slim-labels.js"; +import { keptLabelsFailure, splitByExcept } from "./slim-except.js"; import { parseOverridesPlist, parsePrintDisabled, renderOverridesPlist } from "./slim-overrides.js"; /** why: ADR 0061 §1: a `making` row of this process older than this is a make that never ended. */ @@ -242,6 +248,7 @@ type SlimWrite = readonly kind: "written"; readonly resolved: ReturnType; readonly wanted: ReadonlyMap; + readonly kept: readonly SlimCategory[]; readonly startedAt: number; readonly writeError: string | undefined; }; @@ -1270,7 +1277,7 @@ export class IosSimctlDriver implements Driver { writeError = `could not write the launchd overrides file: ${errorMessage(error)}`; } - return { kind: "written", resolved, startedAt, wanted, writeError }; + return { kept, kind: "written", resolved, startedAt, wanted, writeError }; } async #readOverrides(file: string): Promise> { @@ -1290,6 +1297,10 @@ export class IosSimctlDriver implements Driver { data: IosDriverData, write: Extract, ): Promise { + // why: with an except list the lease is told a category is on, so a write that failed refuses the device. + if (write.kept.length > 0 && write.writeError !== undefined) { + throw new KeptCategoriesError(write.writeError); + } const outcome = await this.#invokeSimctl( ["spawn", data.udid, "launchctl", "print-disabled", "system"], READBACK_TIMEOUT_MS, @@ -1302,10 +1313,13 @@ export class IosSimctlDriver implements Driver { ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; details.push(`could not read back the launchd overrides: ${reason}`); + if (write.kept.length > 0) throw new KeptCategoriesError(details.join("; ")); return this.#skipApply(device, data, details.join("; "), "slim"); } const read = parsePrintDisabled(outcome.result.stdout); + const keptFailure = keptLabelsFailure(write.kept, read); + if (keptFailure !== undefined) throw new KeptCategoriesError(keptFailure); const mismatched = [...write.wanted.keys()] .sort() .filter((label) => (read.get(label) ?? false) !== write.wanted.get(label)); diff --git a/src/drivers/ios/slim-except.ts b/src/drivers/ios/slim-except.ts index 7587aa75c..ff9cd5f28 100644 --- a/src/drivers/ios/slim-except.ts +++ b/src/drivers/ios/slim-except.ts @@ -1,4 +1,4 @@ -import type { SlimCategory } from "./slim-labels.js"; +import { labelsFor, type SlimCategory } from "./slim-labels.js"; /** * why: A lease's except list (ADR 0066 §2) takes categories out of the worker's slim set: the @@ -13,3 +13,17 @@ export function splitByExcept( slimmed: categories.filter((category) => !except.includes(category.name)), }; } + +/** + * why: A kept category's service must be running (ADR 0066 §2): the first kept label the readback + * does not show enabled, as the message the refusal carries; `undefined` when every one is. + */ +export function keptLabelsFailure( + kept: readonly SlimCategory[], + read: ReadonlyMap, +): string | undefined { + const notEnabled = labelsFor(kept).filter((label) => read.get(label) === true); + return notEnabled.length === 0 + ? undefined + : `${String(notEnabled.length)} kept labels are not enabled; first: ${notEnabled[0] ?? ""}`; +} From 06f0ff4c34c05e3202a507cb569fbde2e839b4fd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:04:35 +0100 Subject: [PATCH 06/11] feat(ios): an except list naming the whole slim set writes every label on and grants full (#1329) --- src/drivers/ios/index.ts | 11 +++++---- src/drivers/ios/slim-except.test.ts | 37 ++++++++++++++++++++++++++++- src/drivers/ios/slim-except.ts | 14 +++++++---- 3 files changed, 52 insertions(+), 10 deletions(-) diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 0c828748a..2cd06ef58 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1252,9 +1252,8 @@ export class IosSimctlDriver implements Driver { except: readonly string[] = [], ): Promise { const configured = resolveSlimCategories(slim.categories); - const { kept, slimmed } = splitByExcept(configured.categories, except); - const resolved = { categories: slimmed, unknown: configured.unknown }; - if (resolved.categories.length === 0) { + const { kept, resolved } = splitByExcept(configured, except); + if (configured.categories.length === 0) { return { detail: `none of the configured slim categories (${(slim.categories ?? []).join(", ")}) are known`, kind: "no-categories", @@ -1297,7 +1296,6 @@ export class IosSimctlDriver implements Driver { data: IosDriverData, write: Extract, ): Promise { - // why: with an except list the lease is told a category is on, so a write that failed refuses the device. if (write.kept.length > 0 && write.writeError !== undefined) { throw new KeptCategoriesError(write.writeError); } @@ -1333,6 +1331,9 @@ export class IosSimctlDriver implements Driver { return this.#skipApply(device, data, details.join("; "), "slim"); } + // why: an except list naming the whole slim set slims nothing: full, no `device.slimmed`. + if (write.resolved.categories.length === 0) return this.#asIs(device, data, "full"); + const labelCount = [...write.wanted.values()].filter(Boolean).length; this.#onSlimmed?.({ address: data.udid, @@ -2696,4 +2697,4 @@ export { type IosDriverConfig, iosDriverConfig } from "./definition.js"; export { iosDeviceDataTable } from "./device-data.js"; export { iosSourceDataOwner } from "./source-data.js"; export { iosPrerequisites } from "./prerequisites.js"; -export { labelsFor, SLIM_CATEGORIES } from "./slim-labels.js"; +export { labelsFor, SLIM_CATEGORIES, slimSignature } from "./slim-labels.js"; diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts index b93f5bf0e..cb140b5b5 100644 --- a/src/drivers/ios/slim-except.test.ts +++ b/src/drivers/ios/slim-except.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { KeptCategoriesError } from "../../core/index.js"; import { FakeClock, ScriptedProcessRunner } from "../../ports/index.js"; -import { SLIM_CATEGORIES, type SlimmedFact, type SlimSkippedFact } from "./index.js"; +import { SLIM_CATEGORIES, slimSignature, type SlimmedFact, type SlimSkippedFact } from "./index.js"; import { createSlimDriver, driverData, @@ -127,6 +127,41 @@ describe("IosSimctlDriver makeReady with an except list", () => { message: "could not read back the launchd overrides: exit 1: boom", }, ]; + const nonKept = [...labelsOf(["widgets"])].find((label) => wanted.get(label) === true)!; + const mismatched = await bootWithExcept({ + except: ["store", "other"], + readback: readbackOf(new Map([...wanted, [nonKept, false]])), + }); + expect(mismatched.outcome).toEqual({ result: expect.objectContaining({ mode: "full" }) }); + expect(mismatched.onSlimmed).not.toHaveBeenCalled(); + + const wholeSet = await bootWithExcept({ + categories: ["store"], + except: ["store"], + readback: readbackOf(expectedWrite(["store"], ["store"])), + }); + expect(wholeSet.written).toEqual(Object.fromEntries(expectedWrite([], []))); + expect(wholeSet.outcome).toEqual({ result: expect.objectContaining({ mode: "full" }) }); + expect(wholeSet.onSlimmed).not.toHaveBeenCalled(); + + const sharedLabel = expectedWrite(["store", "icloud"], ["store"]); + const shared = await bootWithExcept({ + categories: ["store", "icloud"], + except: ["store"], + readback: readbackOf(sharedLabel), + }); + const icloud = SLIM_CATEGORIES.filter((category) => category.name === "icloud"); + expect(shared.written?.["com.apple.amsaccountsd"]).toBe(false); + expect(shared.written).toEqual(Object.fromEntries(sharedLabel)); + expect(shared.outcome).toEqual({ result: expect.objectContaining({ mode: "slim" }) }); + expect(shared.onSlimmed).toHaveBeenCalledWith( + expect.objectContaining({ + categories: ["icloud"], + labelCount: [...sharedLabel.values()].filter(Boolean).length, + signature: slimSignature(icloud), + }), + ); + for (const refusal of refusals) { const { outcome, onSlimmed } = await bootWithExcept(refusal.run); expect(outcome, refusal.name).toEqual({ error: new KeptCategoriesError(refusal.message) }); diff --git a/src/drivers/ios/slim-except.ts b/src/drivers/ios/slim-except.ts index ff9cd5f28..1a64b81fd 100644 --- a/src/drivers/ios/slim-except.ts +++ b/src/drivers/ios/slim-except.ts @@ -1,16 +1,22 @@ -import { labelsFor, type SlimCategory } from "./slim-labels.js"; +import { labelsFor, type resolveSlimCategories, type SlimCategory } from "./slim-labels.js"; + +type ResolvedCategories = ReturnType; /** * why: A lease's except list (ADR 0066 §2) takes categories out of the worker's slim set: the * categories left are the ones to turn off, the excepted ones are the ones to keep on. */ export function splitByExcept( - categories: readonly SlimCategory[], + configured: ResolvedCategories, except: readonly string[], -): { readonly slimmed: readonly SlimCategory[]; readonly kept: readonly SlimCategory[] } { +): { readonly kept: readonly SlimCategory[]; readonly resolved: ResolvedCategories } { + const { categories, unknown } = configured; return { kept: categories.filter((category) => except.includes(category.name)), - slimmed: categories.filter((category) => !except.includes(category.name)), + resolved: { + categories: categories.filter((category) => !except.includes(category.name)), + unknown, + }, }; } From 22216b8cd28287453eec5c0a7a862cab09648751 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:06:06 +0100 Subject: [PATCH 07/11] test: the iOS driver refuses an except list it cannot serve at resolve (#1329) --- src/core/driver.ts | 9 +++++ src/core/index.ts | 1 + src/drivers/ios/slim-except.test.ts | 54 +++++++++++++++++++++++++++-- 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/core/driver.ts b/src/core/driver.ts index 7e5932f7e..a36948241 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -29,6 +29,7 @@ export interface ExactDeviceRequest { readonly osVersion?: string; readonly mode?: DeviceMode; readonly imageTag?: string; + readonly except?: readonly string[]; } export interface DeviceRequest extends Omit { @@ -599,6 +600,14 @@ export class UnsupportedRequestOptionError extends Error { } } +/** why: A refusal that carries its own message, where `UnsupportedRequestOptionError` builds a fixed one. */ +export class BadDeviceRequestError extends Error { + constructor(message: string) { + super(message); + this.name = "BadDeviceRequestError"; + } +} + /** why: A device booted with a lease's except list but a kept category's service is not running, or that could not be shown (ADR 0066 §2): the driver refuses the device rather than tell the lease it is on. */ export class KeptCategoriesError extends Error { constructor(message: string) { diff --git a/src/core/index.ts b/src/core/index.ts index f87d8f7b1..f7c1bfd3b 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -107,6 +107,7 @@ export { UnknownModelError, BaselineMismatchError, BaselineStaleError, + BadDeviceRequestError, KeptCategoriesError, UnsupportedRequestOptionError, } from "./driver.js"; diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts index cb140b5b5..30587568c 100644 --- a/src/drivers/ios/slim-except.test.ts +++ b/src/drivers/ios/slim-except.test.ts @@ -1,7 +1,9 @@ +import { readFileSync } from "node:fs"; + import { describe, expect, it, vi } from "vitest"; -import { KeptCategoriesError } from "../../core/index.js"; -import { FakeClock, ScriptedProcessRunner } from "../../ports/index.js"; +import { BadDeviceRequestError, KeptCategoriesError } from "../../core/index.js"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { SLIM_CATEGORIES, slimSignature, type SlimmedFact, type SlimSkippedFact } from "./index.js"; import { createSlimDriver, @@ -11,6 +13,7 @@ import { parseOverrides, plantManagedDevice, printDisabled, + simctl, slimBootCalls, } from "./test-slim.js"; @@ -169,3 +172,50 @@ describe("IosSimctlDriver makeReady with an except list", () => { } }); }); + +describe("IosSimctlDriver resolveSpec with an except list", () => { + const listFixture = readFileSync(new URL("./fixtures/simctl-list.json", import.meta.url), "utf8"); + + async function resolveWith(categories: readonly string[] | undefined, except: readonly string[]) { + const driver = await createSlimDriver( + new ScriptedProcessRunner([ + { + match: simctl("list", "-j", "devicetypes", "runtimes"), + result: { code: 0, stderr: "", stdout: listFixture }, + }, + ]), + new MemoryFilesystem(), + { bootTimeoutMs: 300_000, ...(categories === undefined ? {} : { categories }) }, + ); + return await driver + .resolveSpec({ + except, + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }) + .then( + (spec) => ({ spec }) as const, + (error: unknown) => ({ error }) as const, + ); + } + + it("refuses an except list it cannot serve at resolve", async () => { + const names = SLIM_CATEGORIES.map((category) => category.name); + for (const name of [names[0]!, names.at(-1)!]) { + const accepted = await resolveWith(undefined, [name]); + expect(accepted, name).toEqual({ spec: expect.objectContaining({ mode: "slim" }) }); + } + expect(await resolveWith(["store"], ["store"])).toEqual({ + spec: expect.objectContaining({ mode: "slim" }), + }); + + expect(await resolveWith(["store"], ["wallet"])).toEqual({ + error: new BadDeviceRequestError('unknown slim category "wallet"'), + }); + expect(await resolveWith(["store"], ["mdm"])).toEqual({ + error: new BadDeviceRequestError('"mdm" is not in this worker\'s slim categories (store)'), + }); + }); +}); From 5d3369b513f3d7fc0b011c9e5d95bf37a9a44cb2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:07:21 +0100 Subject: [PATCH 08/11] feat(ios): resolve refuses an except list naming an unknown category or one the worker does not slim (#1329) --- src/daemon/error-code.test.ts | 13 ++++++++++- src/daemon/error-code.ts | 3 ++- src/drivers/ios/index.ts | 6 ++--- src/drivers/ios/slim-except.ts | 42 +++++++++++++++++++++++++++------- 4 files changed, 51 insertions(+), 13 deletions(-) diff --git a/src/daemon/error-code.test.ts b/src/daemon/error-code.test.ts index 35e0e58eb..2027c49d1 100644 --- a/src/daemon/error-code.test.ts +++ b/src/daemon/error-code.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { ComponentInstallerClosedError, UnsupportedRequestOptionError } from "../core/index.js"; +import { + BadDeviceRequestError, + ComponentInstallerClosedError, + UnsupportedRequestOptionError, +} from "../core/index.js"; import { NoCapacityError, ProvisionFailedError, @@ -57,5 +61,12 @@ describe("classifyError on a request option the driver does not have", () => { code: "BAD_REQUEST", message: "ios lease requests do not take imageTag", }); + + const bad = new BadDeviceRequestError('unknown slim category "wallet"'); + expect(classifyError(bad)).toBe("BAD_REQUEST"); + expect(describeLeaseRequestFailure(bad)).toEqual({ + code: "BAD_REQUEST", + message: 'unknown slim category "wallet"', + }); }); }); diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index bbb0fb05d..0e25d31f5 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -35,6 +35,7 @@ import { UnknownLeaseError, UnknownModelError, UnknownPassthroughToolError, + BadDeviceRequestError, UnsupportedRequestOptionError, type LeaseRequestFailure, } from "../core/index.js"; @@ -153,7 +154,7 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { } // A request option the platform's driver does not have: the request itself is wrong, and // asking again unchanged can never succeed. - if (error instanceof UnsupportedRequestOptionError) { + if (error instanceof UnsupportedRequestOptionError || error instanceof BadDeviceRequestError) { return "BAD_REQUEST"; } if (error instanceof InsufficientDiskSpaceError) { diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 2cd06ef58..a745b3608 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -87,7 +87,7 @@ import { slimSignature, type SlimCategory, } from "./slim-labels.js"; -import { keptLabelsFailure, splitByExcept } from "./slim-except.js"; +import { assertKeptEnabled, checkExcept, splitByExcept } from "./slim-except.js"; import { parseOverridesPlist, parsePrintDisabled, renderOverridesPlist } from "./slim-overrides.js"; /** why: ADR 0061 §1: a `making` row of this process older than this is a make that never ended. */ @@ -439,6 +439,7 @@ export class IosSimctlDriver implements Driver { if (request.imageTag !== undefined) { throw new UnsupportedRequestOptionError("ios", "imageTag"); } + checkExcept(request.except ?? [], resolveSlimCategories(this.#slim?.categories)); const catalog = await this.#loadCatalog(); const deviceType = findDeviceType(catalog, request.model); @@ -1316,8 +1317,7 @@ export class IosSimctlDriver implements Driver { } const read = parsePrintDisabled(outcome.result.stdout); - const keptFailure = keptLabelsFailure(write.kept, read); - if (keptFailure !== undefined) throw new KeptCategoriesError(keptFailure); + assertKeptEnabled(write.kept, read); const mismatched = [...write.wanted.keys()] .sort() .filter((label) => (read.get(label) ?? false) !== write.wanted.get(label)); diff --git a/src/drivers/ios/slim-except.ts b/src/drivers/ios/slim-except.ts index 1a64b81fd..1552913bd 100644 --- a/src/drivers/ios/slim-except.ts +++ b/src/drivers/ios/slim-except.ts @@ -1,4 +1,10 @@ -import { labelsFor, type resolveSlimCategories, type SlimCategory } from "./slim-labels.js"; +import { BadDeviceRequestError, KeptCategoriesError } from "../../core/index.js"; +import { + labelsFor, + SLIM_CATEGORIES, + type resolveSlimCategories, + type SlimCategory, +} from "./slim-labels.js"; type ResolvedCategories = ReturnType; @@ -21,15 +27,35 @@ export function splitByExcept( } /** - * why: A kept category's service must be running (ADR 0066 §2): the first kept label the readback - * does not show enabled, as the message the refusal carries; `undefined` when every one is. + * why: A kept category's service must be running (ADR 0066 §2): the device is refused when the + * readback does not show every kept label enabled. */ -export function keptLabelsFailure( +export function assertKeptEnabled( kept: readonly SlimCategory[], read: ReadonlyMap, -): string | undefined { +): void { const notEnabled = labelsFor(kept).filter((label) => read.get(label) === true); - return notEnabled.length === 0 - ? undefined - : `${String(notEnabled.length)} kept labels are not enabled; first: ${notEnabled[0] ?? ""}`; + if (notEnabled.length > 0) { + throw new KeptCategoriesError( + `${String(notEnabled.length)} kept labels are not enabled; first: ${notEnabled[0] ?? ""}`, + ); + } +} + +/** + * why: A lease's except list is checked at resolve (ADR 0066 §2), before any device is made: a + * name no category has, or a category this worker does not slim, can never be served. + */ +export function checkExcept(except: readonly string[], slimSet: ResolvedCategories): void { + const slimmed = slimSet.categories.map((category) => category.name); + for (const name of except) { + if (!SLIM_CATEGORIES.some((category) => category.name === name)) { + throw new BadDeviceRequestError(`unknown slim category "${name}"`); + } + if (!slimmed.includes(name)) { + throw new BadDeviceRequestError( + `"${name}" is not in this worker's slim categories (${slimmed.join(", ")})`, + ); + } + } } From 75ff5cbc7ce98b2622e14337aec6f18f9b555c9c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:08:23 +0100 Subject: [PATCH 09/11] docs(ios): Boot steps 2-3 and the device.slimmed row describe the except list (#1329) --- docs/internal/EVENTS.md | 2 +- src/drivers/ios/AGENTS.md | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 8b88151e7..4d121b978 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -103,7 +103,7 @@ Simlock registry (ADR 0002, `docs/internal/adr/0002-opt-in-slim-ios-simulators.m only") is satisfied by waiting for that commit to become observable, not by waiting on a registry write: the driver writes the launchd overrides file while the simulator is shut down, boots it once, and only fires `onSlimmed` once the readback shows the overrides in force. The registry's own `device.ready` for that same boot is a separate, -later event, emitted through the normal readiness path once the driver call returns. A slim +later event, emitted through the normal readiness path once the driver call returns. A boot with a lease's except list (ADR 0066) reports `categories` as the smaller list (the worker's slim set minus the excepted categories), `signature` as that list's signature and `labelCount` as the labels written `true`, so a kept label that a slimmed category also lists is not counted; a boot whose smaller list is empty is granted `full` and emits none. A slim request on a runtime older than iOS 18.5 is resolved to a full spec before planning (ADR 0007 §4), so it never reaches a slim boot. A *skipped* slim on a slim-spec device -- its runtime id didn't parse, the overrides file could not be written, or the readback disagreed or failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 22a6633ff..c0f69c8e7 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -51,11 +51,17 @@ Boot — `makeReady`: labels into `/private/var/tmp/com.apple.CoreSimulator.SimDevice./disabled.plist` (labels of the configured categories `true`, every other managed label `false`, other entries kept), skipped when the file already says so. A failed write is logged and the boot goes on. - Too old → skipped, returned `full`. + Too old → skipped, returned `full`. With an `except` list (ADR 0066, `slim-except.ts`) the + categories written `true` are the configured ones minus the excepted; every label of an excepted + category is written `false`, also one a slimmed category lists. A name the worker does not slim + is refused at `resolveSpec` (`BadDeviceRequestError`, `BAD_REQUEST`). An except list naming the + whole slim set still writes the file, every managed label `false`. 3. After the boot, `simctl spawn launchctl print-disabled system` (120 s) is compared with what was written. A label not as written → `full`; a readback that fails → `slim`; both → `onSlimSkipped` (logged only). Every label as written, and the write ok → `slim`, `onSlimmed` → - `device.slimmed`. + `device.slimmed`. With an except list a failed write, a failed readback, or a kept label not read + back enabled throws `KeptCategoriesError` instead; any other mismatch is `full` as above, and so is + a boot whose smaller list is empty (no `device.slimmed`). 4. `purpose: "recover"`: boot only, no write, no readback. 5. With `ios.simulator.audio: false`, after every boot (prepare and recover, slim or full) and before the readback: `simctl spawn notifyutil -s com.apple.springboard.volumestate 0`, then `-p` (30 s each). The first call that exits non-zero, times out or cannot start stops the step: the device stays in use and `onSilenceFailed` gets `{ deviceId, detail }` (stderr, `timed out`, or the spawn error), which the daemon logs at `warn` as `Could not silence iOS simulator`. Nothing is read back; apps keep playing at volume 0. A baseline source's boot is not silenced: a copy's own `makeReady` does. From 0730ac4e143dba4e7b226309e312e0378a6858b5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 10:41:48 +0100 Subject: [PATCH 10/11] refactor(ios): move the simctl JSON parsers out of index.ts into simctl-parse.ts (ADR 0063) (#1329) --- src/drivers/ios/AGENTS.md | 12 +-- src/drivers/ios/index.ts | 153 ++------------------------------ src/drivers/ios/simctl-parse.ts | 145 ++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 153 deletions(-) create mode 100644 src/drivers/ios/simctl-parse.ts diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index c4aeb4210..a74ebb6de 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -72,9 +72,7 @@ Seeds (ADR 0061) — a simulator is a copy of the kind's seed, a shut-down simul Reclaim — a simulator is never reclaimed: `reclaim` and `reclaimStrategy` throw, and a lease's end destroys it. Physical → `devicectl device uninstall app` for every app not enrolled → `ready` / `uninstall`. `destroy` / `destroyLegacy`: shut down, `simctl delete`, then remove the overrides folder (a failed removal is logged). `listManaged`: `simctl list -j devices` in the set, plus marks. -Catalog — models are device type names; class from product family (iPhone `phone`, iPad -`tablet`, Apple Watch `watch`, Apple TV `tv`, Apple Vision `vision`); `modelRuntimes` = paired -installed versions. No aliases, no images. +Catalog — models are device type names; class from product family (iPhone `phone`, iPad `tablet`, Apple Watch `watch`, Apple TV `tv`, Apple Vision `vision`); `modelRuntimes` = paired installed versions. No aliases, no images. Components — a component is a runtime version or `latest`. `installComponent`: `xcodebuild -downloadPlatform iOS [-buildVersion ]`, 8 GiB reserved under @@ -82,10 +80,7 @@ Components — a component is a runtime version or `latest`. while it deletes, reports any download left in the asset store as `residue`. `foreignDevices` counts devices in the default set (under `deviceSet: default`, those this instance's mark does not name). -Physical — `devicectl list devices` with `--json-output` to `$SIMLOCK_HOME/devicectl/` -(file deleted after). Id matches identifier, UDID, serial or ECID; wired only. -Refused: simulator, network-only, not iPhone/iPad, below iOS 17, untrusted, Developer Mode -off, locked. Present = listed, paired, unlocked. +Physical — `devicectl list devices` with `--json-output` to `$SIMLOCK_HOME/devicectl/` (file deleted after). Id matches identifier, UDID, serial or ECID; wired only. Refused: simulator, network-only, not iPhone/iPad, below iOS 17, untrusted, Developer Mode off, locked. Present = listed, paired, unlocked. Passthrough — @@ -106,8 +101,7 @@ The config is always `portrait`, a rotation included, with `keyboardUnavailable: Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`, `tcpProbe` and `tcpStreamConnector`; `supports` is true for a simulator, false for an iPhone. A simulator has no network of its own: its sockets are the worker's loopback sockets. `connect` (one 5 s limit from the caller's `OPEN`, then `timeout`) runs `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` through the `ProcessRunner`, then `ps eww -p ` per listener, and a process is the lease's only when a word of its environment is exactly `SIMULATOR_UDID=` (not a substring of an argument). It dials `127.0.0.1` when a lease process holds `127.0.0.1:`, or holds `*:` while no other process holds `127.0.0.1:`; else `[::1]` by the same rule; never an address another process holds more specifically. Checked on every connection. No listener, none of the lease's, or both addresses refused: `nothing on the lease's simulator listens on port `; a lookup that fails: `could not check the port's owner: `. `reverse` is refused `TUNNEL_PORT_IN_USE` when a connect to `127.0.0.1:` or `[::1]:` is answered (a wildcard listener included; 250 ms each), else listens on exactly the device port on both loopbacks (one in use at bind: `TUNNEL_PORT_IN_USE`, the other closed; another error: `TUNNEL_FAILED`). Its `close` closes both listeners and sets `holdsDeviceRule: false`, so a lease end with an aborted signal runs it. `sweep` does nothing: no rule sits on a simulator. -Advisories — `runtime-cache-unreclaimable` (asset bundles no installed runtime mounts); -`slim-runtime-unsupported` (installed runtimes below 18.5, only when `ios.defaultMode` is `slim`). +Advisories — `runtime-cache-unreclaimable` (asset bundles no installed runtime mounts); `slim-runtime-unsupported` (installed runtimes below 18.5, only when `ios.defaultMode` is `slim`). ## State and timers diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index ec70deace..fcd941713 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -36,7 +36,6 @@ import { type PassthroughCommand, type PassthroughContext, PassthroughRefusedError, - type ObservedRunState, removeListedComponent, RuntimeMissingError, sameReceipt, @@ -93,6 +92,15 @@ import { type SlimCategory, } from "./slim-labels.js"; import { assertKeptEnabled, checkExcept, splitByExcept } from "./slim-except.js"; +import { + isRecord, + parseCatalog, + parseManagedDevices, + type DeviceType, + type Runtime, + type SimctlCatalog, + UNBOUNDED_VERSION, +} from "./simctl-parse.js"; import { parseOverridesPlist, parsePrintDisabled, renderOverridesPlist } from "./slim-overrides.js"; /** why: ADR 0061 §1: a `making` row of this process older than this is a make that never ended. */ @@ -108,9 +116,6 @@ const PROVISION_ESTIMATE_MS = 500; // being deleted, which it does for a few seconds after `simctl runtime delete` answers (#259). const DELETING_POLL_MS = 1_000; const LATEST_COMPONENT = "latest"; -// why: `simctl`'s `minRuntimeVersion` / `maxRuntimeVersion` encode "no bound" as 0xFFFFFF -// (255.255.255) rather than omitting the field. -const UNBOUNDED_VERSION = 0xff_ff_ff; // why: `xcodebuild -downloadPlatform iOS -buildVersion` only reaches back to iOS 16.0 (Xcode // 16.1+); older runtimes must be installed through Xcode itself. const IOS_DOWNLOAD_FLOOR: readonly [number, number, number] = [16, 0, 0]; @@ -270,34 +275,12 @@ const PRODUCT_FAMILY_CLASSES: ReadonlyMap = new ["Apple Vision", "vision"], ]); -interface DeviceType { - readonly identifier: string; - readonly name: string; - readonly minRuntimeVersion: number; - readonly maxRuntimeVersion: number; - readonly productFamily: string | undefined; -} - -interface Runtime { - readonly identifier: string; - readonly name: string; - readonly version: string; - readonly build?: string; - readonly isAvailable: boolean; - readonly supportedDeviceTypeIds: ReadonlySet; -} - interface RuntimeAsset { readonly path: string; readonly version: string; readonly build: string; } -interface SimctlCatalog { - readonly deviceTypes: readonly DeviceType[]; - readonly runtimes: readonly Runtime[]; -} - interface ResolvedIosSpec { readonly deviceType: DeviceType; readonly runtime: Runtime; @@ -2163,105 +2146,6 @@ function configuredDeviceRoot(options: IosSimctlDriverOptions): string { return configured ?? join(options.simlockHome, "devices", "ios"); } -interface ParsedManagedDevice { - readonly dataPath?: string; - readonly name: string; - readonly runState: ObservedRunState; - readonly udid: string; -} - -function parseManagedDevices(value: unknown): ParsedManagedDevice[] { - if (!isRecord(value) || !isRecord(value.devices)) { - throw new DriverCrashError("Invalid simctl device list JSON"); - } - return Object.values(value.devices).flatMap((runtimeDevices) => - Array.isArray(runtimeDevices) ? runtimeDevices.flatMap(parseManagedDevice) : [], - ); -} - -function parseManagedDevice(value: unknown): readonly ParsedManagedDevice[] { - if (!isRecord(value) || typeof value.name !== "string" || typeof value.udid !== "string") { - return []; - } - - return [ - { - name: value.name, - runState: simctlRunState(value.state), - udid: value.udid, - ...(typeof value.dataPath === "string" ? { dataPath: value.dataPath } : {}), - }, - ]; -} - -function simctlRunState(state: unknown): ObservedRunState { - if (state === "Booted") return "running"; - if (state === "Shutdown") return "stopped"; - return "transitioning"; -} - -function parseCatalog(value: unknown): SimctlCatalog { - if (!isRecord(value) || !Array.isArray(value.devicetypes) || !Array.isArray(value.runtimes)) { - throw new DriverCrashError( - "Invalid simctl list JSON: expected devicetypes and runtimes arrays", - ); - } - - const deviceTypes = value.devicetypes.flatMap(parseDeviceType); - const runtimes = value.runtimes.flatMap(parseRuntime); - - // why: Device types come from the Xcode install itself and are never empty on a working - // toolchain, so an empty list here means the JSON was malformed. Runtimes are different: a - // fresh Xcode with zero simulator runtimes installed is a normal, if unusual, starting state - // -- and it must be able to reach the download-latest path in `#resolveDefaultRuntime` rather - // than being rejected here before any resolution is attempted. - if (deviceTypes.length === 0) { - throw new DriverCrashError("Invalid simctl list JSON: no usable device types"); - } - - return { deviceTypes, runtimes }; -} - -function parseDeviceType(value: unknown): readonly DeviceType[] { - if (!isRecord(value) || typeof value.identifier !== "string" || typeof value.name !== "string") { - return []; - } - - return [ - { - identifier: value.identifier, - maxRuntimeVersion: versionIntOr(value.maxRuntimeVersion, UNBOUNDED_VERSION), - minRuntimeVersion: versionIntOr(value.minRuntimeVersion, 0), - name: value.name, - productFamily: typeof value.productFamily === "string" ? value.productFamily : undefined, - }, - ]; -} - -function parseRuntime(value: unknown): readonly Runtime[] { - if ( - !isRecord(value) || - typeof value.identifier !== "string" || - typeof value.name !== "string" || - typeof value.version !== "string" || - typeof value.isAvailable !== "boolean" || - !value.name.toLocaleLowerCase().startsWith("ios ") - ) { - return []; - } - - return [ - { - ...(typeof value.buildversion === "string" ? { build: value.buildversion } : {}), - identifier: value.identifier, - isAvailable: value.isAvailable, - name: value.name, - supportedDeviceTypeIds: parseSupportedDeviceTypeIds(value.supportedDeviceTypes), - version: value.version, - }, - ]; -} - function runtimeMountsAsset(runtime: Runtime, asset: RuntimeAsset): boolean { return runtime.build === undefined ? runtime.version === asset.version @@ -2284,21 +2168,6 @@ function parseRuntimeAsset(path: string, plist: string): RuntimeAsset | undefine return build === undefined || version === undefined ? undefined : { build, path, version }; } -function versionIntOr(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} - -function parseSupportedDeviceTypeIds(value: unknown): ReadonlySet { - if (!Array.isArray(value)) { - return new Set(); - } - const ids = value - .filter(isRecord) - .map((entry) => entry.identifier) - .filter((identifier): identifier is string => typeof identifier === "string"); - return new Set(ids); -} - interface RuntimeImage { readonly identifier: string; readonly runtimeIdentifier: string; @@ -2696,10 +2565,6 @@ function specKey(spec: VirtualSpec): string { return `${spec.model.toLocaleLowerCase()}\u0000${spec.osVersion}`; } -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null; -} - function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } diff --git a/src/drivers/ios/simctl-parse.ts b/src/drivers/ios/simctl-parse.ts new file mode 100644 index 000000000..b9b822316 --- /dev/null +++ b/src/drivers/ios/simctl-parse.ts @@ -0,0 +1,145 @@ +import { DriverCrashError, type ObservedRunState } from "../../core/index.js"; + +export function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +// why: `simctl`'s `minRuntimeVersion` / `maxRuntimeVersion` encode "no bound" as 0xFFFFFF +// (255.255.255) rather than omitting the field. +export const UNBOUNDED_VERSION = 0xff_ff_ff; + +export interface DeviceType { + readonly identifier: string; + readonly name: string; + readonly minRuntimeVersion: number; + readonly maxRuntimeVersion: number; + readonly productFamily: string | undefined; +} + +export interface Runtime { + readonly identifier: string; + readonly name: string; + readonly version: string; + readonly build?: string; + readonly isAvailable: boolean; + readonly supportedDeviceTypeIds: ReadonlySet; +} + +export interface SimctlCatalog { + readonly deviceTypes: readonly DeviceType[]; + readonly runtimes: readonly Runtime[]; +} + +interface ParsedManagedDevice { + readonly dataPath?: string; + readonly name: string; + readonly runState: ObservedRunState; + readonly udid: string; +} + +export function parseManagedDevices(value: unknown): ParsedManagedDevice[] { + if (!isRecord(value) || !isRecord(value.devices)) { + throw new DriverCrashError("Invalid simctl device list JSON"); + } + return Object.values(value.devices).flatMap((runtimeDevices) => + Array.isArray(runtimeDevices) ? runtimeDevices.flatMap(parseManagedDevice) : [], + ); +} + +function parseManagedDevice(value: unknown): readonly ParsedManagedDevice[] { + if (!isRecord(value) || typeof value.name !== "string" || typeof value.udid !== "string") { + return []; + } + + return [ + { + name: value.name, + runState: simctlRunState(value.state), + udid: value.udid, + ...(typeof value.dataPath === "string" ? { dataPath: value.dataPath } : {}), + }, + ]; +} + +function simctlRunState(state: unknown): ObservedRunState { + if (state === "Booted") return "running"; + if (state === "Shutdown") return "stopped"; + return "transitioning"; +} + +export function parseCatalog(value: unknown): SimctlCatalog { + if (!isRecord(value) || !Array.isArray(value.devicetypes) || !Array.isArray(value.runtimes)) { + throw new DriverCrashError( + "Invalid simctl list JSON: expected devicetypes and runtimes arrays", + ); + } + + const deviceTypes = value.devicetypes.flatMap(parseDeviceType); + const runtimes = value.runtimes.flatMap(parseRuntime); + + // why: Device types come from the Xcode install itself and are never empty on a working + // toolchain, so an empty list here means the JSON was malformed. Runtimes are different: a + // fresh Xcode with zero simulator runtimes installed is a normal, if unusual, starting state + // -- and it must be able to reach the download-latest path in `#resolveDefaultRuntime` rather + // than being rejected here before any resolution is attempted. + if (deviceTypes.length === 0) { + throw new DriverCrashError("Invalid simctl list JSON: no usable device types"); + } + + return { deviceTypes, runtimes }; +} + +function parseDeviceType(value: unknown): readonly DeviceType[] { + if (!isRecord(value) || typeof value.identifier !== "string" || typeof value.name !== "string") { + return []; + } + + return [ + { + identifier: value.identifier, + maxRuntimeVersion: versionIntOr(value.maxRuntimeVersion, UNBOUNDED_VERSION), + minRuntimeVersion: versionIntOr(value.minRuntimeVersion, 0), + name: value.name, + productFamily: typeof value.productFamily === "string" ? value.productFamily : undefined, + }, + ]; +} + +function parseRuntime(value: unknown): readonly Runtime[] { + if ( + !isRecord(value) || + typeof value.identifier !== "string" || + typeof value.name !== "string" || + typeof value.version !== "string" || + typeof value.isAvailable !== "boolean" || + !value.name.toLocaleLowerCase().startsWith("ios ") + ) { + return []; + } + + return [ + { + ...(typeof value.buildversion === "string" ? { build: value.buildversion } : {}), + identifier: value.identifier, + isAvailable: value.isAvailable, + name: value.name, + supportedDeviceTypeIds: parseSupportedDeviceTypeIds(value.supportedDeviceTypes), + version: value.version, + }, + ]; +} + +function versionIntOr(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +function parseSupportedDeviceTypeIds(value: unknown): ReadonlySet { + if (!Array.isArray(value)) { + return new Set(); + } + const ids = value + .filter(isRecord) + .map((entry) => entry.identifier) + .filter((identifier): identifier is string => typeof identifier === "string"); + return new Set(ids); +} From 1fffd568df6c3e481292ef61588341175d02a6aa Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 11:39:34 +0100 Subject: [PATCH 11/11] refactor(ios): split #readBack into helpers to lower its CRAP score (#1329) --- src/drivers/ios/index.ts | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index fcd941713..2d1425596 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1301,16 +1301,21 @@ export class IosSimctlDriver implements Driver { const details = write.writeError === undefined ? [] : [write.writeError]; if (outcome.kind === "timed-out" || outcome.result.code !== 0) { - const reason = - outcome.kind === "timed-out" - ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` - : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; - details.push(`could not read back the launchd overrides: ${reason}`); + details.push(`could not read back the launchd overrides: ${readBackFailure(outcome)}`); if (write.kept.length > 0) throw new KeptCategoriesError(details.join("; ")); return this.#skipApply(device, data, details.join("; "), "slim"); } + return this.#judgeReadBack(device, data, write, details, outcome.result.stdout); + } - const read = parsePrintDisabled(outcome.result.stdout); + #judgeReadBack( + device: DriverDevice, + data: IosDriverData, + write: Extract, + details: string[], + stdout: string, + ): DriverDevice { + const read = parsePrintDisabled(stdout); assertKeptEnabled(write.kept, read); const mismatched = [...write.wanted.keys()] .sort() @@ -1327,19 +1332,24 @@ export class IosSimctlDriver implements Driver { // why: an except list naming the whole slim set slims nothing: full, no `device.slimmed`. if (write.resolved.categories.length === 0) return this.#asIs(device, data, "full"); + this.#reportSlimmed(device, data, write); + return this.#asIs(device, data, "slim"); + } - const labelCount = [...write.wanted.values()].filter(Boolean).length; + #reportSlimmed( + device: DriverDevice, + data: IosDriverData, + write: Extract, + ): void { this.#onSlimmed?.({ address: data.udid, categories: write.resolved.categories.map((category) => category.name), deviceId: device.deviceId, durationMs: this.#clock.now() - write.startedAt, - labelCount, + labelCount: [...write.wanted.values()].filter(Boolean).length, signature: slimSignature(write.resolved.categories), unknownLabels: [...write.resolved.unknown], }); - - return this.#asIs(device, data, "slim"); } #skipApply( @@ -2530,6 +2540,16 @@ function unknownDevice(result: ProcessResult): boolean { return /^Invalid device:/m.test(result.stderr); } +function readBackFailure( + outcome: + | { readonly kind: "timed-out" } + | { readonly kind: "finished"; readonly result: { code: number | null; stderr: string } }, +): string { + return outcome.kind === "timed-out" + ? `timed out after ${String(READBACK_TIMEOUT_MS)}ms` + : `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; +} + function alreadyBooted(stderr: string): boolean { return /current state:\s*Booted|already booted/i.test(stderr); }