Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(ios-simulator): 构建链路优化(arch 预检 + 缓存复用 + 回收) (#2899)
hand16d7a9343aa
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex f5ac0716be..5d7f4c1bf3 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -1,10 +1,43 @@-import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises';+import { spawn } from 'node:child_process';+import {+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ realpath,+ rm,+ stat,+ symlink,+ utimes,+ writeFile,+} from 'node:fs/promises';import { readFileSync } from 'node:fs';+import { createServer } from 'node:net';import os from 'node:os';import path from 'node:path';import { app } from 'electron';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { mockFsCp } = vi.hoisted(() => ({ mockFsCp: vi.fn() }));++vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:fs/promises')>();+ mockFsCp.mockImplementation((...args: Parameters<typeof actual.cp>) => actual.cp(...args));+ return {+ ...actual,+ cp: (...args: Parameters<typeof actual.cp>) => mockFsCp(...args),+ };+});++beforeEach(async () => {+ // The desktop Vitest project resets mocks between tests. Restore the real+ // copy implementation so the one deterministic failure injection below+ // remains local to that test instead of turning every later build copy into+ // a no-op.+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');+ mockFsCp.mockImplementation((...args: Parameters<typeof actual.cp>) => actual.cp(...args));+});import {createIOSSimulatorNativeDevelopmentAdmissionPolicy,@@ -49,11 +82,196 @@ import {getIOSSimulatorPluginStatus,getIOSSimulatorMcpDeps,reconcilePersistedIOSSimulatorOwnership,+ reconcileOrphanedIOSSimulatorArtifactCopies,+ pruneStaleIOSSimulatorBuildCaches,+ touchIOSSimulatorBuildCacheLastUsed,type IOSSimulatorAppLifecycleAdapter,type IOSSimulatorMediaCaptureAdapter,type IOSSimulatorProjectBuilderAdapter,} from '../ios-simulator';+describe('pruneStaleIOSSimulatorBuildCaches', () => {+ it('removes directories older than the max age and keeps fresh ones', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-cache-'));+ try {+ const stale = path.join(root, 'a'.repeat(20));+ const fresh = path.join(root, 'b'.repeat(20));+ await mkdir(stale);+ await mkdir(fresh);+ const now = Date.now();+ const staleTime = new Date(now - 8 * 24 * 60 * 60 * 1000);+ await utimes(stale, staleTime, staleTime);+ await pruneStaleIOSSimulatorBuildCaches([root], 7 * 24 * 60 * 60 * 1000, () => now);+ await expect(stat(stale)).rejects.toThrow();+ await expect(stat(fresh)).resolves.toBeTruthy();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it('ignores a missing root', async () => {+ await expect(+ pruneStaleIOSSimulatorBuildCaches(+ [path.join(os.tmpdir(), 'cindy-does-not-exist-xyz')],+ 1_000,+ ),+ ).resolves.toBeUndefined();+ });++ it('keeps a cache whose directory mtime is old when the last-used marker is fresh', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-cache-'));+ try {+ const used = path.join(root, 'c'.repeat(20));+ const idle = path.join(root, 'd'.repeat(20));+ await mkdir(used);+ await mkdir(idle);+ const now = Date.now();+ const staleTime = new Date(now - 8 * 24 * 60 * 60 * 1000);+ await utimes(used, staleTime, staleTime);+ await utimes(idle, staleTime, staleTime);+ await touchIOSSimulatorBuildCacheLastUsed(used, () => now);+ await utimes(used, staleTime, staleTime);+ await pruneStaleIOSSimulatorBuildCaches([root], 7 * 24 * 60 * 60 * 1000, () => now);+ await expect(stat(used)).resolves.toBeTruthy();+ await expect(stat(idle)).rejects.toThrow();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it('keeps active (skipped) caches even when their mtime is stale', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-cache-'));+ try {+ const activeKey = 'e'.repeat(20);+ const active = path.join(root, activeKey);+ const idle = path.join(root, 'f'.repeat(20));+ await mkdir(active);+ await mkdir(idle);+ const now = Date.now();+ const staleTime = new Date(now - 8 * 24 * 60 * 60 * 1000);+ await utimes(active, staleTime, staleTime);+ await utimes(idle, staleTime, staleTime);+ await pruneStaleIOSSimulatorBuildCaches(+ [root],+ 7 * 24 * 60 * 60 * 1000,+ () => now,+ (name) => name === activeKey,+ );+ await expect(stat(active)).resolves.toBeTruthy();+ await expect(stat(idle)).rejects.toThrow();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it('rechecks live cache use after reading stale metadata', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-cache-'));+ try {+ const racingKey = '1'.repeat(20);+ const cache = path.join(root, racingKey);+ const now = Date.now();+ await touchIOSSimulatorBuildCacheLastUsed(cache, () => now - 8 * 24 * 60 * 60 * 1000);+ let skipChecks = 0;+ await pruneStaleIOSSimulatorBuildCaches(+ [root],+ 7 * 24 * 60 * 60 * 1000,+ () => now,+ (name) => name === racingKey && ++skipChecks >= 2,+ );+ expect(skipChecks).toBe(2);+ await expect(stat(cache)).resolves.toBeTruthy();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it('reclaims abandoned trash without waiting for the cache TTL again', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-cache-'));+ try {+ const trash = path.join(root, `.trash-${'2'.repeat(20)}-${crypto.randomUUID()}`);+ const unmanagedTrash = path.join(root, '.trash-not-managed');+ await mkdir(trash);+ await mkdir(unmanagedTrash);+ await writeFile(path.join(trash, 'partial'), 'left by interrupted deletion');+ await pruneStaleIOSSimulatorBuildCaches([root], 7 * 24 * 60 * 60 * 1000, Date.now);+ await expect(stat(trash)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(unmanagedTrash)).resolves.toBeDefined();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});++describe('reconcileOrphanedIOSSimulatorArtifactCopies', () => {+ it('reclaims stale UUID app copies without deleting fresh or unmanaged entries', async () => {+ const projectsRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-artifact-reconcile-'));+ try {+ const artifactsRoot = path.join(projectsRoot, 'cache-key', 'artifacts');+ await mkdir(artifactsRoot, { recursive: true });+ const now = Date.now();+ const stalePath = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ const freshPath = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ const unmanagedPath = path.join(artifactsRoot, 'not-a-managed-copy.app');+ const managedTrashPath = path.join(+ artifactsRoot,+ `.trash-artifact-${crypto.randomUUID()}.app-${crypto.randomUUID()}`,+ );+ const unmanagedTrashPrefixPath = path.join(artifactsRoot, '.trash-artifact-not-managed');+ await Promise.all([+ mkdir(stalePath),+ mkdir(freshPath),+ mkdir(unmanagedPath),+ mkdir(managedTrashPath),+ mkdir(unmanagedTrashPrefixPath),+ ]);+ const staleTime = new Date(now - 8 * 24 * 60 * 60 * 1000);+ await utimes(stalePath, staleTime, staleTime);++ await expect(+ reconcileOrphanedIOSSimulatorArtifactCopies(+ projectsRoot,+ 7 * 24 * 60 * 60 * 1000,+ () => now,+ ),+ ).resolves.toBe(true);+ await expect(stat(stalePath)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(managedTrashPath)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(freshPath)).resolves.toBeDefined();+ await expect(stat(unmanagedPath)).resolves.toBeDefined();+ await expect(stat(unmanagedTrashPrefixPath)).resolves.toBeDefined();+ } finally {+ await rm(projectsRoot, { recursive: true, force: true });+ }+ });++ it('rechecks live cache use before atomically moving an orphan copy', async () => {+ const projectsRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-artifact-reconcile-race-'));+ try {+ const artifactsRoot = path.join(projectsRoot, 'cache-key', 'artifacts');+ await mkdir(artifactsRoot, { recursive: true });+ const now = Date.now();+ const stalePath = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ await mkdir(stalePath);+ const staleTime = new Date(now - 8 * 24 * 60 * 60 * 1000);+ await utimes(stalePath, staleTime, staleTime);+ let checks = 0;++ await expect(+ reconcileOrphanedIOSSimulatorArtifactCopies(+ projectsRoot,+ 7 * 24 * 60 * 60 * 1000,+ () => now,+ () => ++checks >= 2,+ ),+ ).resolves.toBe(true);+ expect(checks).toBe(2);+ await expect(stat(stalePath)).resolves.toBeDefined();+ } finally {+ await rm(projectsRoot, { recursive: true, force: true });+ }+ });+});+const READY_REPORT: IOSSimulatorEnvironmentReport = {platform: 'darwin',supported: true,@@ -304,9 +522,22 @@ describe('iOS Simulator host', () => {const evidencePath = path.join(root, 'ios-simulator', 'pending-create-evidence.json');await mkdir(path.dirname(evidencePath), { recursive: true });await writeFile(evidencePath, '{"version":1,"armedAt":"2026-08-11T00:00:00.000Z"}');+ const staleArtifact = path.join(+ root,+ 'ios-simulator',+ 'projects',+ 'orphaned-cache',+ 'artifacts',+ `${crypto.randomUUID()}.app`,+ );+ await mkdir(staleArtifact, { recursive: true });+ const staleTime = new Date(Date.now() - 8 * 24 * 60 * 60_000);+ await utimes(staleArtifact, staleTime, staleTime);const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);- let finishRecovery: (value: { recovered: readonly string[]; complete: boolean }) => void =- () => undefined;+ let finishRecovery: (value: {+ recovered: readonly string[];+ complete: boolean;+ }) => void = () => undefined;const recoverPendingCreatesAtStartup = vi.fn((_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>new Promise<{ recovered: readonly string[]; complete: boolean }>((resolve) => {@@ -331,6 +562,7 @@ describe('iOS Simulator host', () => {finishRecovery({ recovered: [], complete: true });await expect(recovering).resolves.toBeUndefined();+ await expect(stat(staleArtifact)).rejects.toMatchObject({ code: 'ENOENT' });expect(competingRegistry.acquireWriterSync()).toBe(true);// A completed sweep retires the breadcrumb, so the next startup has no// reason to touch CoreSimulator at all.@@ -351,6 +583,19 @@ describe('iOS Simulator host', () => {const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);const createLifecycle = vi.fn();+ const artifactsRoot = path.join(+ root,+ 'ios-simulator',+ 'projects',+ 'orphaned-cache',+ 'artifacts',+ );+ const staleArtifact = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ const freshArtifact = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ await mkdir(staleArtifact, { recursive: true });+ await mkdir(freshArtifact, { recursive: true });+ const staleTime = new Date(Date.now() - 8 * 24 * 60 * 60_000);+ await utimes(staleArtifact, staleTime, staleTime);try {await expect(reconcilePersistedIOSSimulatorOwnership({ createLifecycle }),@@ -359,6 +604,8 @@ describe('iOS Simulator host', () => {// No lifecycle means no xcrun/xcodebuild child process, so macOS never// raises an Xcode consent prompt detached from a user action.expect(createLifecycle).not.toHaveBeenCalled();+ await expect(stat(staleArtifact)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(freshArtifact)).resolves.toBeDefined();expect(competingRegistry.acquireWriterSync()).toBe(true);} finally {competingRegistry.releaseWriterSync();@@ -459,8 +706,8 @@ describe('iOS Simulator host', () => {);it('gates an already-created Host on one startup pending-create recovery', async () => {- let finishRecovery: (value: { recovered: readonly string[]; complete: boolean }) => void =- () => undefined;+ let finishRecovery: (value: { recovered: readonly string[]; complete: boolean }) => void = () =>+ undefined;const recoverPendingCreatesAtStartup = vi.fn((_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>new Promise<{ recovered: readonly string[]; complete: boolean }>((resolve) => {@@ -920,9 +1167,7 @@ describe('iOS Simulator host', () => {.recommendedActions;expect(recommended).toContain('list_simulator_devices');for (const action of recommended) {- expect(advertised.has(action) || action === 'create_instance_or_attach_device').toBe(- true,- );+ expect(advertised.has(action) || action === 'create_instance_or_attach_device').toBe(true);}});@@ -966,6 +1211,47 @@ describe('iOS Simulator host', () => {}});+ it('removes stale orphaned immutable app copies during ownership reconciliation', async () => {+ const projectRoot = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'projects',+ `orphan-artifact-reconcile-${crypto.randomUUID()}`,+ );+ const artifactsRoot = path.join(projectRoot, 'artifacts');+ const staleArtifact = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ const freshArtifact = path.join(artifactsRoot, `${crypto.randomUUID()}.app`);+ await mkdir(staleArtifact, { recursive: true });+ await mkdir(freshArtifact, { recursive: true });+ const staleTime = new Date(Date.now() - 8 * 24 * 60 * 60_000);+ await utimes(staleArtifact, staleTime, staleTime);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const host = createIOSSimulatorHost({+ actor,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ });++ try {+ await host.reconcileOwnership();++ await expect(stat(staleArtifact)).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(stat(freshArtifact)).resolves.toBeDefined();+ } finally {+ await host.dispose();+ await rm(projectRoot, { recursive: true, force: true });+ }+ });+it('reconciles a persisted binding with fresh generation and lease on startup', async () => {const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),@@ -2966,6 +3252,9 @@ describe('iOS Simulator host', () => {});it('aborts and drains active xcresult readers before host disposal completes', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-xcresult-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-xcresult-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),bootExact: vi.fn(),@@ -2979,11 +3268,17 @@ describe('iOS Simulator host', () => {});const instance = actor.attach({sessionId: 'force-quit-xcresult-session',- worktreeRoot: '/tmp/force-quit-xcresult-session',+ worktreeRoot: worktree,sourceFingerprint: 'fingerprint-a',device: READY_REPORT.devices[0]!,});- const resultBundlePath = `/tmp/CindyBuild-${crypto.randomUUID()}.xcresult`;+ const resultBundlePath = path.join(+ userData,+ 'ios-simulator',+ 'projects',+ 'fixture',+ `CindyBuild-${crypto.randomUUID()}.xcresult`,+ );const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(async (input) => ({kind: 'xcode-project',worktreeRoot: input.worktreeRoot,@@ -2994,8 +3289,11 @@ describe('iOS Simulator host', () => {resultBundlePath,buildLogTail: 'build succeeded',}));+ // build_app copies the product into an immutable location; `cp` requires+ // the source tree to actually exist.+ await mkdir(path.join(worktree, 'Demo.app'), { recursive: true });let readSignal: AbortSignal | undefined;- let releaseRead!: () => void;+ let releaseRead: (() => void) | undefined;let projectBuilder!: IOSSimulatorProjectBuilderAdapter;const readXcresult = vi.fn(function (this: IOSSimulatorProjectBuilderAdapter,@@ -3019,9 +3317,9 @@ describe('iOS Simulator host', () => {appLifecycle: {inspectArtifact: vi.fn(async () => ({artifactId: 'artifact-xcresult',- worktreeRoot: '/tmp/force-quit-xcresult-session',- authorizedRoot: '/tmp/force-quit-xcresult-session',- appPath: '/tmp/force-quit-xcresult-session/Demo.app',+ worktreeRoot: worktree,+ authorizedRoot: worktree,+ appPath: path.join(worktree, 'Demo.app'),bundleId: 'com.example.demo',createdAt: '2026-08-08T00:00:00.000Z',})),@@ -3034,46 +3332,55 @@ describe('iOS Simulator host', () => {discardInstance: vi.fn(async () => undefined),} as unknown as IOSSimulatorMediaCaptureAdapter,runtime: { inspect: vi.fn(async () => READY_REPORT) },- getSession: vi.fn(async () => localSession('force-quit-xcresult-session')),+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),});- await host.reconcileOwnership();- const current = actor.getOwned('force-quit-xcresult-session', instance.instanceId);- const built = await host.callTool(- 'build_app',- {- instanceId: current.instanceId,- generation: current.generation,- leaseId: current.lease.id,- },- { sessionId: current.sessionId, origin: 'user' },- );- expect(built).toMatchObject({ ok: true });- const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })- .data.diagnostics.diagnosticsId;- const readPromise = host.callTool(- 'read_build_diagnostics',- { diagnosticsId, source: 'xcresult' },- { sessionId: current.sessionId, origin: 'agent' },- );- await vi.waitFor(() => expect(readXcresult).toHaveBeenCalledOnce());+ try {+ await host.reconcileOwnership();+ const current = actor.getOwned('force-quit-xcresult-session', instance.instanceId);+ const built = await host.callTool(+ 'build_app',+ {+ instanceId: current.instanceId,+ generation: current.generation,+ leaseId: current.lease.id,+ },+ { sessionId: current.sessionId, origin: 'user' },+ );+ expect(built).toMatchObject({ ok: true });+ const diagnosticsId = (+ built as { ok: true; data: { diagnostics: { diagnosticsId: string } } }+ ).data.diagnostics.diagnosticsId;+ const readPromise = host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'xcresult' },+ { sessionId: current.sessionId, origin: 'agent' },+ );+ await vi.waitFor(() => expect(readXcresult).toHaveBeenCalledOnce());- expect(() => host.abortOperationsForExit()).not.toThrow();- expect(readSignal?.aborted).toBe(true);- let disposeSettled = false;- const disposePromise = host.dispose().then(() => {- disposeSettled = true;- });- await Promise.resolve();- expect(disposeSettled).toBe(false);+ expect(() => host.abortOperationsForExit()).not.toThrow();+ expect(readSignal?.aborted).toBe(true);+ let disposeSettled = false;+ const disposePromise = host.dispose().then(() => {+ disposeSettled = true;+ });+ await Promise.resolve();+ expect(disposeSettled).toBe(false);- releaseRead();+ releaseRead?.();- await disposePromise;- await expect(readPromise).resolves.toMatchObject({- ok: false,- errorCode: 'MUTATION_CANCELLED',- });- expect(readXcresult).toHaveBeenCalledWith(resultBundlePath, undefined, readSignal);+ await disposePromise;+ await expect(readPromise).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ expect(readXcresult).toHaveBeenCalledWith(resultBundlePath, undefined, readSignal);+ } finally {+ releaseRead?.();+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }});it('synchronously aborts active builds before updater force-quit', async () => {@@ -7925,285 +8232,2031 @@ describe('iOS Simulator host', () => {expect(resourceScheduler.runningCount()).toBe(0);});- it('routes build, install, launch, terminate, and URL actions through injected adapters', async () => {+ it('keeps an admitted build lease alive while project inspection is pending', async () => {+ let now = 0;+ const clock = { now: () => now };+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-build-lease-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-build-lease-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);const actor = new IOSSimulatorInstanceActor({- store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ store: new IOSSimulatorOwnershipStore({+ createId: () => crypto.randomUUID(),+ clock,+ leaseDurationMs: 60_000,+ }),lifecycle: {findExact: vi.fn(),- bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),- shutdownExact: vi.fn(async () => undefined),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),createExact: vi.fn(),deleteExact: vi.fn(),},+ clock,});- const driverManager = {- get: vi.fn(() => null),- start: vi.fn(- async (options) =>- ({- instanceId: options.instanceId,- simulatorUdid: options.simulatorUdid,- pid: 42,- driver: {},- driverSessionId: 'wda-session',- }) as unknown as Promise<WdaRunningInstance>,- ),- stop: vi.fn(async () => undefined),- };- const buildProject = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(- async ({ worktreeRoot, derivedDataPath }) => ({- kind: 'xcode-project' as const,- worktreeRoot,- projectRoot: `${worktreeRoot}/ios`,- containerPath: `${worktreeRoot}/ios/Demo.xcodeproj`,- scheme: 'Demo',- appPath: `${worktreeRoot}/build/Demo.app`,- resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,- buildLogTail:- 'compile /tmp/session-a/secret.swift\\nGH_TOKEN=ghp_1234567890abcdefghijkl\\nwarning: keep this warning',- }),- );- const validateLaunch = vi.fn(async () => ({- healthy: true,- expectedPort: 8081,- expectedSource: 'branch@commit',- currentSourceOnExpectedPort: true,- anyMetro: true,- targetSimulatorUdid: READY_REPORT.devices[0]!.udid,- targetBooted: true,- }));- const projectBuilder: IOSSimulatorProjectBuilderAdapter = {- build: buildProject,- readXcresult: vi.fn(async () =>- JSON.stringify({- issues: [- {- message:- 'failed at /Users/secret/project.swift Authorization: Bearer simulator-diagnostic-secret-123456',- },- ],- }),- ),- validateLaunch,- };- const artifact = {- artifactId: 'artifact-a',- worktreeRoot: '/tmp/session-a',- authorizedRoot: '/tmp/session-a',- appPath: '/tmp/session-a/build/Demo.app',- bundleId: 'com.example.demo',- createdAt: '2026-07-23T00:00:00.000Z',- };- const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(- async () => artifact,- );- const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(- async () => undefined,- );- const appLifecycle: IOSSimulatorAppLifecycleAdapter = {- inspectArtifact,- installExact,- launchExact: vi.fn(async () => undefined),- terminateExact: vi.fn(async () => undefined),- openUrlExact: vi.fn(async () => undefined),- };- const requestViewerFocus = vi.fn();+ let stopInspection: () => void = () => undefined;+ let markInspectionStarted: () => void = () => undefined;+ const inspectionStarted = new Promise<void>((resolve) => {+ markInspectionStarted = resolve;+ });+ const inspectionGate = new Promise<never>((_resolve, reject) => {+ stopInspection = () =>+ reject(+ new IOSSimulatorInstanceError(+ 'MUTATION_CANCELLED',+ 'The project inspection was stopped after lease verification.',+ true,+ ),+ );+ });+ let runHeartbeat: () => void = () => undefined;+ const stopHeartbeat = vi.fn();+ const projectBuilderBuild = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();const host = createIOSSimulatorHost({actor,- driverManager,- projectBuilder,- appLifecycle,+ scheduleBuildLeaseHeartbeat: vi.fn((heartbeat) => {+ runHeartbeat = heartbeat;+ return stopHeartbeat;+ }),+ projectBuilder: {+ inspect: vi.fn(async () => {+ markInspectionStarted();+ return await inspectionGate;+ }),+ build: projectBuilderBuild,+ },+ appLifecycle: {+ inspectArtifact: vi.fn(),+ installExact: vi.fn(),+ launchExact: vi.fn(),+ terminateExact: vi.fn(),+ openUrlExact: vi.fn(),+ },+ mediaCapture: {+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,resourceScheduler: testResourceScheduler(),- requestViewerFocus,- runtime: { inspect: vi.fn(async () => READY_REPORT) },- getSession: vi.fn(async (id) => localSession(id)),- resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' }],+ })),+ },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),});- await host.callTool(- 'attach_device',- { udid: READY_REPORT.devices[0]!.udid },- { sessionId: 'session-a', origin: 'user' },- );- const instance = actor.list('session-a')[0]!;- const route = {- instanceId: instance.instanceId,- generation: instance.generation,- leaseId: instance.lease.id,+ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-slow-build', origin: 'user' },+ );+ const instance = actor.list('session-slow-build')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const build = host.callTool('build_app', route, {+ sessionId: 'session-slow-build',+ origin: 'user',+ });+ await inspectionStarted;+ now = 31_000;+ runHeartbeat();+ expect(Date.parse(actor.list('session-slow-build')[0]!.lease.expiresAt)).toBe(91_000);+ now = 70_000;+ runHeartbeat();+ expect(Date.parse(actor.list('session-slow-build')[0]!.lease.expiresAt)).toBe(130_000);+ expect(() => actor.assertRoute({ ...route, sessionId: 'session-slow-build' })).not.toThrow();+ stopInspection();++ await expect(build).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ const current = actor.list('session-slow-build')[0]!;+ expect(current.lease.id).toBe(route.leaseId);+ expect(Date.parse(current.lease.expiresAt)).toBeGreaterThan(now);+ expect(stopHeartbeat).toHaveBeenCalledOnce();+ expect(projectBuilderBuild).not.toHaveBeenCalled();+ } finally {+ stopInspection();+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('cancels an admitted build when its exact lease is replaced', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-build-stale-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-build-stale-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });+ const actor = new IOSSimulatorInstanceActor({+ store,+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ let markBuildStarted: () => void = () => undefined;+ const buildStarted = new Promise<void>((resolve) => {+ markBuildStarted = resolve;+ });+ let runHeartbeat: () => void = () => undefined;+ const stopHeartbeat = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ scheduleBuildLeaseHeartbeat: vi.fn((heartbeat) => {+ runHeartbeat = heartbeat;+ return stopHeartbeat;+ }),+ projectBuilder: {+ build: vi.fn(async ({ signal }) => {+ markBuildStarted();+ return await new Promise<never>((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('build aborted')), {+ once: true,+ });+ });+ }),+ },+ appLifecycle: {+ inspectArtifact: vi.fn(),+ installExact: vi.fn(),+ launchExact: vi.fn(),+ terminateExact: vi.fn(),+ openUrlExact: vi.fn(),+ },+ mediaCapture: {+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,+ resourceScheduler: testResourceScheduler(),+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' }],+ })),+ },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-stale-build', origin: 'user' },+ );+ const instance = actor.list('session-stale-build')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const build = host.callTool('build_app', route, {+ sessionId: 'session-stale-build',+ origin: 'user',+ });+ await buildStarted;+ const replacement = store.renew(instance.instanceId, instance.sessionId);+ expect(replacement.lease.id).not.toBe(route.leaseId);+ runHeartbeat();++ await expect(build).resolves.toMatchObject({+ ok: false,+ errorCode: 'LEASE_EXPIRED',+ });+ expect(stopHeartbeat).toHaveBeenCalledOnce();+ } finally {+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('routes build, install, launch, terminate, and URL actions through injected adapters', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-routing-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-routing-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),};- const built = await host.callTool(- 'build_app',- { ...route, containerPath: 'ios/Demo.xcodeproj' },- {+ const buildProject = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(+ async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: `${worktreeRoot}/ios`,+ containerPath: `${worktreeRoot}/ios/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: `${worktreeRoot}/build/Demo.app`,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail:+ 'compile /tmp/session-a/secret.swift\\nGH_TOKEN=ghp_1234567890abcdefghijkl\\nwarning: keep this warning',+ }),+ );+ // build_app now copies the product into an immutable location; `cp`+ // requires the source tree to actually exist.+ await mkdir(path.join(worktree, 'build', 'Demo.app'), { recursive: true });+ const validateLaunch = vi.fn(async () => ({+ healthy: true,+ expectedPort: 8081,+ expectedSource: 'branch@commit',+ currentSourceOnExpectedPort: true,+ anyMetro: true,+ targetSimulatorUdid: READY_REPORT.devices[0]!.udid,+ targetBooted: true,+ }));+ const projectBuilder: IOSSimulatorProjectBuilderAdapter = {+ build: buildProject,+ readXcresult: vi.fn(async () =>+ JSON.stringify({+ issues: [+ {+ message:+ 'failed at /Users/secret/project.swift Authorization: Bearer simulator-diagnostic-secret-123456',+ },+ ],+ }),+ ),+ validateLaunch,+ };+ const artifact = {+ artifactId: 'artifact-a',+ worktreeRoot: worktree,+ authorizedRoot: worktree,+ appPath: path.join(worktree, 'build', 'Demo.app'),+ bundleId: 'com.example.demo',+ createdAt: '2026-07-23T00:00:00.000Z',+ };+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async () => artifact,+ );+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(+ async () => undefined,+ );+ const appLifecycle: IOSSimulatorAppLifecycleAdapter = {+ inspectArtifact,+ installExact,+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ };+ const requestViewerFocus = vi.fn();+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder,+ appLifecycle,+ resourceScheduler: testResourceScheduler(),+ requestViewerFocus,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ );+ const instance = actor.list('session-a')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const built = await host.callTool(+ 'build_app',+ { ...route, containerPath: 'ios/Demo.xcodeproj' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ expect(built).toMatchObject({+ ok: true,+ data: {+ artifact: { artifactId: artifact.artifactId, bundleId: artifact.bundleId },+ diagnostics: {+ diagnosticsId: expect.any(String),+ buildLogTail: expect.stringContaining('<redacted-path>'),+ xcresultAvailable: true,+ },+ },+ });+ expect(JSON.stringify(built)).not.toContain('ghp_1234567890abcdefghijkl');+ const diagnosticsId = (+ built as { ok: true; data: { diagnostics: { diagnosticsId: string } } }+ ).data.diagnostics.diagnosticsId;+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log', offset: 0, limit: 20 },+ { sessionId: 'session-a', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: {+ diagnosticsId,+ source: 'build-log',+ offset: 0,+ limit: 20,+ available: true,+ text: expect.any(String),+ nextOffset: 20,+ eof: false,+ },+ });+ const xcresult = await host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'xcresult', offset: 0, limit: 64 * 1024 },+ { sessionId: 'session-a', origin: 'agent' },+ );+ expect(xcresult).toMatchObject({ ok: true, data: { available: true, eof: true } });+ expect(JSON.stringify(xcresult)).not.toContain('/Users/secret');+ expect(JSON.stringify(xcresult)).not.toContain('simulator-diagnostic-secret-123456');+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-b', origin: 'agent' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ expect(projectBuilder.readXcresult).toHaveBeenCalledTimes(1);++ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ ),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: artifact.artifactId, args: ['--uitesting'] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });++ const mobileArtifact = { ...artifact, artifactId: 'mobile-artifact' };+ const mobileAppPath = path.join(worktree, 'apps', 'mobile', 'ios', 'build', 'Cindy.app');+ await mkdir(mobileAppPath, { recursive: true });+ buildProject.mockResolvedValueOnce({+ kind: 'cindy-mobile',+ worktreeRoot: worktree,+ projectRoot: path.join(worktree, 'apps', 'mobile'),+ containerPath: null,+ scheme: 'Cindy',+ appPath: mobileAppPath,+ resultBundlePath: null,+ buildLogTail: '',+ });+ inspectArtifact.mockResolvedValueOnce(mobileArtifact);+ await expect(+ host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'launch_app',+ { ...route, artifactId: mobileArtifact.artifactId, args: [] },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(validateLaunch).toHaveBeenCalledWith(+ worktree,+ READY_REPORT.devices[0]!.udid,+ expect.any(AbortSignal),+ );+ await host.callTool(+ 'terminate_app',+ { ...route, artifactId: artifact.artifactId },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );+ await host.callTool(+ 'open_url',+ { ...route, url: 'demo://home' },+ {+ sessionId: 'session-a',+ origin: 'user',+ },+ );++ expect(projectBuilder.build).toHaveBeenCalledWith(+ expect.objectContaining({+ worktreeRoot: worktree,+ containerPath: 'ios/Demo.xcodeproj',+ }),+ );+ expect(appLifecycle.installExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact,+ expect.any(AbortSignal),+ );+ expect(appLifecycle.launchExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact,+ ['--uitesting'],+ expect.any(AbortSignal),+ );+ expect(appLifecycle.terminateExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ artifact.bundleId,+ expect.any(AbortSignal),+ );+ expect(appLifecycle.openUrlExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ 'demo://home',+ expect.any(AbortSignal),+ );+ expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);++ let installSignal: AbortSignal | undefined;+ installExact.mockImplementationOnce(+ async (_simulatorUdid, _artifact, signal) =>+ new Promise<void>((resolve) => {+ installSignal = signal;+ signal?.addEventListener('abort', () => resolve(), { once: true });+ }),+ );+ const installing = host.callTool(+ 'install_app',+ { ...route, artifactId: artifact.artifactId },+ { sessionId: 'session-a', origin: 'user' },+ );+ await vi.waitFor(() => expect(installSignal).toBeDefined());+ const stopping = host.callTool('stop_instance', route, {sessionId: 'session-a',origin: 'user',+ });+ await vi.waitFor(() => expect(installSignal?.aborted).toBe(true));+ await expect(installing).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(stopping).resolves.toMatchObject({ ok: true });+ } finally {+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('installs the immutable build copy after the source app changes', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-immutable-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-immutable-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ const sourcePayload = path.join(sourceApp, 'Payload.txt');+ await mkdir(sourceApp, { recursive: true });+ await writeFile(sourcePayload, 'version-one');+ let immutableAppPath = '';+ let installedPayload = '';+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ immutableAppPath = appPath;+ return {+ artifactId: 'artifact-immutable',+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 26)).toISOString(),+ };+ },+ );+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(+ async (_simulatorUdid, artifact) => {+ installedPayload = await readFile(path.join(artifact.appPath, 'Payload.txt'), 'utf8');+ },+ );+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: path.join(worktreeRoot, 'Demo.xcodeproj'),+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: path.join(derivedDataPath, 'CindyBuild.xcresult'),+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact,+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-immutable', origin: 'user' },+ );+ const instance = actor.list('session-immutable')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-immutable',+ origin: 'user',+ });+ expect(built).toMatchObject({+ ok: true,+ data: { artifact: { artifactId: 'artifact-immutable' } },+ });+ expect(immutableAppPath).not.toBe(sourceApp);+ expect(+ path.relative(path.join(userData, 'ios-simulator', 'projects'), immutableAppPath),+ ).not.toMatch(/^\.\.(?:[/\\]|$)/);++ await writeFile(sourcePayload, 'version-two');+ await expect(readFile(path.join(immutableAppPath, 'Payload.txt'), 'utf8')).resolves.toBe(+ 'version-one',+ );+ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: 'artifact-immutable' },+ { sessionId: 'session-immutable', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(installExact).toHaveBeenCalledWith(+ READY_REPORT.devices[0]!.udid,+ expect.objectContaining({ appPath: immutableAppPath }),+ expect.any(AbortSignal),+ );+ expect(installedPayload).toBe('version-one');+ } finally {+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('does not evict an artifact while install_app is reading it', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-pin-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-pin-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation((name) => {+ if (name === 'userData') return userData;+ return userData;+ });+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ let createdSeq = 0;+ const inspectedPaths: string[] = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ createdSeq += 1;+ inspectedPaths.push(appPath);+ return {+ artifactId: `artifact-${createdSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18, 0, 0, createdSeq)).toISOString(),+ };+ },+ );+ let releaseInstall: () => void = () => undefined;+ const installGate = new Promise<void>((resolve) => {+ releaseInstall = resolve;+ });+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(async () => {+ if (installExact.mock.calls.length === 1) await installGate;+ });+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact,+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-pin', origin: 'user' },+ );+ const instance = actor.list('session-pin')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const artifactIds: string[] = [];+ for (let i = 0; i < 4; i += 1) {+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-pin',+ origin: 'user',+ });+ expect(built).toMatchObject({ ok: true });+ artifactIds.push(+ (built as { ok: true; data: { artifact: { artifactId: string } } }).data.artifact+ .artifactId,+ );+ }+ const oldestPath = inspectedPaths[0]!;+ await expect(stat(oldestPath)).resolves.toBeDefined();++ const installing = host.callTool(+ 'install_app',+ { ...route, artifactId: artifactIds[0] },+ { sessionId: 'session-pin', origin: 'user' },+ );+ await vi.waitFor(() => expect(installExact).toHaveBeenCalledOnce());++ const fifth = await host.callTool('build_app', route, {+ sessionId: 'session-pin',+ origin: 'user',+ });+ expect(fifth).toMatchObject({ ok: true });+ await expect(stat(oldestPath)).resolves.toBeDefined();++ releaseInstall();+ await expect(installing).resolves.toMatchObject({ ok: true });++ const sixth = await host.callTool('build_app', route, {+ sessionId: 'session-pin',+ origin: 'user',+ });+ expect(sixth).toMatchObject({ ok: true });+ await vi.waitFor(() => expect(stat(oldestPath)).rejects.toMatchObject({ code: 'ENOENT' }));+ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifactIds[0] },+ { sessionId: 'session-pin', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'APP_ARTIFACT_INVALID' });+ } finally {+ releaseInstall();+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('evicts excess artifacts when the last install pin is released', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-unpin-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-unpin-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation((name) => {+ if (name === 'userData') return userData;+ return userData;+ });+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ let createdSeq = 0;+ const inspectedPaths: string[] = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ createdSeq += 1;+ inspectedPaths.push(appPath);+ return {+ artifactId: `artifact-${createdSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18, 0, 0, createdSeq)).toISOString(),+ };+ },+ );+ let releaseOldestInstall: () => void = () => undefined;+ const oldestInstallGate = new Promise<void>((resolve) => {+ releaseOldestInstall = resolve;+ });+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(+ async (_udid, artifact) => {+ if (artifact.artifactId === 'artifact-1') await oldestInstallGate;+ },+ );+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact,+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-unpin', origin: 'user' },+ );+ const instance = actor.list('session-unpin')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const artifactIds: string[] = [];+ for (let i = 0; i < 4; i += 1) {+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-unpin',+ origin: 'user',+ });+ expect(built).toMatchObject({ ok: true });+ artifactIds.push(+ (built as { ok: true; data: { artifact: { artifactId: string } } }).data.artifact+ .artifactId,+ );+ }+ const oldestPath = inspectedPaths[0]!;+ const installs = artifactIds.map((artifactId) =>+ host.callTool(+ 'install_app',+ { ...route, artifactId },+ { sessionId: 'session-unpin', origin: 'user' },+ ),+ );+ await vi.waitFor(() => expect(installExact).toHaveBeenCalledTimes(1));++ const fifth = await host.callTool('build_app', route, {+ sessionId: 'session-unpin',+ origin: 'user',+ });+ expect(fifth).toMatchObject({ ok: true });+ await expect(stat(oldestPath)).resolves.toBeDefined();++ releaseOldestInstall();+ await expect(Promise.all(installs)).resolves.toEqual(+ expect.arrayContaining([expect.objectContaining({ ok: true })]),+ );+ await vi.waitFor(() => expect(stat(oldestPath)).rejects.toMatchObject({ code: 'ENOENT' }));+ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifactIds[0] },+ { sessionId: 'session-unpin', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'APP_ARTIFACT_INVALID' });+ } finally {+ releaseOldestInstall();+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('evicts installed artifacts before uninstalled ones', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-inst-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-inst-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ let createdSeq = 0;+ const inspectedPaths: string[] = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ createdSeq += 1;+ inspectedPaths.push(appPath);+ return {+ artifactId: `artifact-${createdSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18, 0, 0, createdSeq)).toISOString(),+ };+ },+ );+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-inst', origin: 'user' },+ );+ const instance = actor.list('session-inst')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const artifactIds: string[] = [];+ for (let i = 0; i < 4; i += 1) {+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-inst',+ origin: 'user',+ });+ expect(built).toMatchObject({ ok: true });+ artifactIds.push(+ (built as { ok: true; data: { artifact: { artifactId: string } } }).data.artifact+ .artifactId,+ );+ }+ // Install the oldest artifact: it becomes "consumed" and should be the+ // one evicted on the fifth build, not the still-pending second artifact.+ await expect(+ host.callTool(+ 'install_app',+ { ...route, artifactId: artifactIds[0] },+ { sessionId: 'session-inst', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });++ const fifth = await host.callTool('build_app', route, {+ sessionId: 'session-inst',+ origin: 'user',+ });+ expect(fifth).toMatchObject({ ok: true });+ await vi.waitFor(() =>+ expect(stat(inspectedPaths[0])).rejects.toMatchObject({ code: 'ENOENT' }),+ );+ await expect(stat(inspectedPaths[1])).resolves.toBeDefined();+ } finally {+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('does not leave a stuck build when containerPath is invalid', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-arg-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-arg-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ const inspect = vi.fn(async (_worktreeRoot: string, explicitContainerPath?: string) => {+ if (explicitContainerPath === 'Missing.xcodeproj') {+ throw new IOSSimulatorInstanceError(+ 'PROJECT_NOT_FOUND',+ 'The selected Xcode container does not exist.',+ );+ }+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: worktree,+ projectRoot: worktree,+ containerPath: path.join(worktree, 'Demo.xcodeproj'),+ };+ });+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ inspect,+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact: vi.fn(async (_worktreeRoot, appPath) => ({+ artifactId: 'artifact-arg',+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18)).toISOString(),+ })),+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-arg', origin: 'user' },+ );+ const instance = actor.list('session-arg')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ // Invalid containerPath must reject without registering a stuck build.+ await expect(+ host.callTool(+ 'build_app',+ { ...route, containerPath: '' },+ { sessionId: 'session-arg', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });+ // A non-empty but nonexistent container is rejected by canonical+ // inspection before either cache root is created.+ await expect(+ host.callTool(+ 'build_app',+ { ...route, containerPath: 'Missing.xcodeproj' },+ { sessionId: 'session-arg', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'PROJECT_NOT_FOUND' });+ await expect(stat(path.join(userData, 'ios-simulator', 'projects'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ await expect(stat(path.join(userData, 'ios-simulator', 'spm'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ // A subsequent valid build must still be admitted (not DEVICE_BUSY).+ await expect(+ host.callTool('build_app', route, { sessionId: 'session-arg', origin: 'user' }),+ ).resolves.toMatchObject({ ok: true });+ } finally {+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('does not evict an artifact while launch_app is waiting', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-launch-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-launch-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ let createdSeq = 0;+ const inspectedPaths: string[] = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ createdSeq += 1;+ inspectedPaths.push(appPath);+ return {+ artifactId: `artifact-${createdSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18, 0, 0, createdSeq)).toISOString(),+ };+ },+ );+ let releaseLaunch: () => void = () => undefined;+ const launchGate = new Promise<void>((resolve) => {+ releaseLaunch = resolve;+ });+ const launchExact = vi.fn<IOSSimulatorAppLifecycleAdapter['launchExact']>(async () => {+ if (launchExact.mock.calls.length === 1) await launchGate;+ });+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact,+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-launch', origin: 'user' },+ );+ const instance = actor.list('session-launch')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const artifactIds: string[] = [];+ for (let i = 0; i < 4; i += 1) {+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-launch',+ origin: 'user',+ });+ expect(built).toMatchObject({ ok: true });+ artifactIds.push(+ (built as { ok: true; data: { artifact: { artifactId: string } } }).data.artifact+ .artifactId,+ );+ }+ const launching = host.callTool(+ 'launch_app',+ { ...route, artifactId: artifactIds[0], args: [] },+ { sessionId: 'session-launch', origin: 'user' },+ );+ await vi.waitFor(() => expect(launchExact).toHaveBeenCalledOnce());++ // A fifth build evicts the oldest unpinned artifact; the launched (pinned)+ // artifact must survive, so the oldest *unpinned* one goes instead.+ const fifth = await host.callTool('build_app', route, {+ sessionId: 'session-launch',+ origin: 'user',+ });+ expect(fifth).toMatchObject({ ok: true });+ await expect(stat(inspectedPaths[0])).resolves.toBeDefined();+ await vi.waitFor(() =>+ expect(stat(inspectedPaths[1])).rejects.toMatchObject({ code: 'ENOENT' }),+ );++ releaseLaunch();+ await expect(launching).resolves.toMatchObject({ ok: true });+ } finally {+ releaseLaunch();+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ itMac('accepts internal app symlinks and rejects links outside the immutable copy', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-artifact-link-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-artifact-link-wt-'));+ const externalRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-artifact-link-ext-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ const frameworkRoot = path.join(sourceApp, 'Frameworks', 'Demo.framework');+ const frameworkVersions = path.join(frameworkRoot, 'Versions');+ await mkdir(path.join(frameworkVersions, 'A'), { recursive: true });+ await writeFile(path.join(frameworkVersions, 'A', 'Demo'), 'framework');+ await symlink('A', path.join(frameworkVersions, 'Current'), 'dir');+ await symlink('Versions/Current/Demo', path.join(frameworkRoot, 'Demo'), 'file');+ const externalPayload = path.join(externalRoot, 'payload');+ await writeFile(externalPayload, 'external');+ const unsafeLinksRoot = path.join(sourceApp, 'Resources', 'Nested');+ await mkdir(unsafeLinksRoot, { recursive: true });+ const buildInputs: Array<Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]> = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => ({+ artifactId: 'artifact-contained-links',+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 26)).toISOString(),+ }),+ );+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder: {+ build: vi.fn(async (input) => {+ buildInputs.push(input);+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: path.join(input.worktreeRoot, 'Demo.xcodeproj'),+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: path.join(input.derivedDataPath, 'CindyBuild.xcresult'),+ buildLogTail: '',+ };+ }),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-artifact-link', origin: 'user' },+ );+ const instance = actor.list('session-artifact-link')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ await expect(+ host.callTool('build_app', route, {+ sessionId: 'session-artifact-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(inspectArtifact).toHaveBeenCalledOnce();++ const externalLink = path.join(unsafeLinksRoot, 'ExternalPayload');+ await symlink(externalPayload, externalLink, 'file');+ await expect(+ host.callTool('build_app', route, {+ sessionId: 'session-artifact-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'APP_ARTIFACT_INVALID',+ message: expect.stringContaining('symbolic link outside'),+ data: { diagnostics: { diagnosticsId: expect.any(String) } },+ });+ await rm(externalLink, { force: true });++ const danglingLink = path.join(unsafeLinksRoot, 'DanglingPayload');+ await symlink('MissingPayload', danglingLink, 'file');+ await expect(+ host.callTool('build_app', route, {+ sessionId: 'session-artifact-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'APP_ARTIFACT_INVALID',+ message: expect.stringContaining('dangling symbolic link'),+ data: { diagnostics: { diagnosticsId: expect.any(String) } },+ });+ await rm(danglingLink, { force: true });++ const cycleA = path.join(unsafeLinksRoot, 'CycleA');+ const cycleB = path.join(unsafeLinksRoot, 'CycleB');+ await symlink('CycleB', cycleA, 'file');+ await symlink('CycleA', cycleB, 'file');+ await expect(+ host.callTool('build_app', route, {+ sessionId: 'session-artifact-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'APP_ARTIFACT_INVALID',+ data: { diagnostics: { diagnosticsId: expect.any(String) } },+ });+ expect(inspectArtifact).toHaveBeenCalledOnce();+ const artifactsRoot = path.join(buildInputs[0]!.derivedDataPath, 'artifacts');+ await vi.waitFor(async () => {+ expect(await readdir(artifactsRoot)).toHaveLength(1);+ });+ } finally {+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ await rm(externalRoot, { recursive: true, force: true });+ }+ });++ itMac('reclaims symlinked-userData artifacts after detach grace and dispose', async () => {+ const realUserData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-link-real-'));+ const linkUserData = path.join(os.tmpdir(), `cindy-ios-link-${crypto.randomUUID()}`);+ await symlink(realUserData, linkUserData, 'dir');+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-link-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation((name) => {+ if (name === 'userData') return linkUserData;+ return linkUserData;+ });+ let runtimeReport = READY_REPORT;+ const scheduledGrace: Array<{+ task: () => void | Promise<void>;+ cancelled: boolean;+ }> = [];+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),},- );- expect(built).toMatchObject({- ok: true,- data: {- artifact: { artifactId: artifact.artifactId, bundleId: artifact.bundleId },- diagnostics: {- diagnosticsId: expect.any(String),- buildLogTail: expect.stringContaining('<redacted-path>'),- xcresultAvailable: true,+ scheduler: {+ schedule: (_delayMs, task) => {+ const scheduled = { task, cancelled: false };+ scheduledGrace.push(scheduled);+ return () => {+ scheduled.cancelled = true;+ };},},});- expect(JSON.stringify(built)).not.toContain('ghp_1234567890abcdefghijkl');- const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })- .data.diagnostics.diagnosticsId;- await expect(- host.callTool(- 'read_build_diagnostics',- { diagnosticsId, source: 'build-log', offset: 0, limit: 20 },- { sessionId: 'session-a', origin: 'agent' },- ),- ).resolves.toMatchObject({- ok: true,- data: {- diagnosticsId,- source: 'build-log',- offset: 0,- limit: 20,- available: true,- text: expect.any(String),- nextOffset: 20,- eof: false,+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ const resolvedAppPaths: string[] = [];+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ async (_worktreeRoot, appPath) => {+ // Mirror the runtime adapter: it realpaths the copy, so the stored+ // appPath no longer shares the (symlinked) managed root's prefix.+ const resolved = await realpath(appPath);+ resolvedAppPaths.push(resolved);+ return {+ artifactId: 'artifact-link',+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(resolved),+ appPath: resolved,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18)).toISOString(),+ };},- });- const xcresult = await host.callTool(- 'read_build_diagnostics',- { diagnosticsId, source: 'xcresult', offset: 0, limit: 64 * 1024 },- { sessionId: 'session-a', origin: 'agent' },);- expect(xcresult).toMatchObject({ ok: true, data: { available: true, eof: true } });- expect(JSON.stringify(xcresult)).not.toContain('/Users/secret');- expect(JSON.stringify(xcresult)).not.toContain('simulator-diagnostic-secret-123456');- await expect(- host.callTool(- 'read_build_diagnostics',- { diagnosticsId, source: 'build-log' },- { sessionId: 'session-b', origin: 'agent' },- ),- ).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });- expect(projectBuilder.readXcresult).toHaveBeenCalledTimes(1);+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ },+ projectBuilder: {+ build: vi.fn(async ({ worktreeRoot, derivedDataPath }) => ({+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: `${worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ })),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => runtimeReport) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });- await expect(- host.callTool(- 'install_app',- { ...route, artifactId: artifact.artifactId },+ try {+ runtimeReport = {+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: 'Shutdown' }],+ };+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-link', origin: 'user' },+ );+ const instance = actor.list('session-link')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ const built = await host.callTool('build_app', route, {+ sessionId: 'session-link',+ origin: 'user',+ });+ expect(built).toMatchObject({ ok: true });+ const resolvedAppPath = resolvedAppPaths[0]!;+ await expect(stat(resolvedAppPath)).resolves.toBeDefined();++ await expect(+ host.callTool('detach_device', route, {+ sessionId: 'session-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ // Final detach release must clear the unreachable artifact projection;+ // grace-period detach keeps it until the callback actually runs.+ await vi.waitFor(() =>+ expect(stat(resolvedAppPath)).rejects.toMatchObject({ code: 'ENOENT' }),+ );++ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-link', origin: 'user' },+ );+ const reattached = actor.list('session-link')[0]!;+ const reattachedRoute = {+ instanceId: reattached.instanceId,+ generation: reattached.generation,+ leaseId: reattached.lease.id,+ };+ await expect(+ host.callTool('start_instance', reattachedRoute, {+ sessionId: 'session-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ const started = actor.list('session-link')[0]!;+ const startedRoute = {+ instanceId: started.instanceId,+ generation: started.generation,+ leaseId: started.lease.id,+ };+ await expect(+ host.callTool('build_app', startedRoute, {+ sessionId: 'session-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ const graceAppPath = resolvedAppPaths[1]!;+ await expect(stat(graceAppPath)).resolves.toBeDefined();+ await expect(+ host.callTool('detach_device', startedRoute, {+ sessionId: 'session-link',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(scheduledGrace).toHaveLength(1);+ expect(scheduledGrace[0]!.cancelled).toBe(false);+ // Agent-booted detach retains both ownership and the artifact throughout+ // grace; only the final resource-release callback may reclaim the copy.+ await expect(stat(graceAppPath)).resolves.toBeDefined();+ await scheduledGrace[0]!.task();+ await vi.waitFor(() => expect(stat(graceAppPath)).rejects.toMatchObject({ code: 'ENOENT' }));++ runtimeReport = READY_REPORT;+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-link', origin: 'user' },+ );+ const disposable = actor.list('session-link')[0]!;+ await expect(+ host.callTool(+ 'build_app',+ {+ instanceId: disposable.instanceId,+ generation: disposable.generation,+ leaseId: disposable.lease.id,+ },+ { sessionId: 'session-link', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const disposedAppPath = resolvedAppPaths[2]!;+ await expect(stat(disposedAppPath)).resolves.toBeDefined();++ await host.dispose();+ // Cleanup must reclaim the copy via its unresolved path; otherwise the+ // realpathed appPath fails the managed-root comparison and the copy leaks.+ await expect(stat(disposedAppPath)).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ getPath.mockRestore();+ await host.dispose();+ await rm(linkUserData, { recursive: true, force: true });+ await rm(realUserData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('shares one build cache across instances and rejects concurrent writers', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-cache-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-cache-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const firstDevice = {+ ...READY_REPORT.devices[0]!,+ state: 'Shutdown' as const,+ };+ const secondDevice = {+ ...firstDevice,+ udid: 'F05BFC28-5AE5-48C8-97E0-EF064558B4D3',+ name: 'iPhone 17 Pro Max',+ };+ const report = {+ ...READY_REPORT,+ devices: [firstDevice, secondDevice],+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ const canonicalContainerPath = path.join(worktree, 'Demo.xcodeproj');+ await mkdir(sourceApp, { recursive: true });+ let releaseFirstBuild: () => void = () => undefined;+ const firstBuildGate = new Promise<void>((resolve) => {+ releaseFirstBuild = resolve;+ });+ const buildInputs: Array<Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]> = [];+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>(async (input) => {+ buildInputs.push(input);+ if (buildInputs.length === 1) await firstBuildGate;+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: `${input.worktreeRoot}/Demo.xcodeproj`,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${input.derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ };+ });+ const inspect = vi.fn(async () => ({+ kind: 'xcode-project' as const,+ worktreeRoot: worktree,+ projectRoot: worktree,+ containerPath: canonicalContainerPath,+ }));+ let artifactSeq = 0;+ const host = createIOSSimulatorHost({+ actor,+ projectBuilder: { inspect, build },+ appLifecycle: {+ inspectArtifact: vi.fn(async (_worktreeRoot, appPath) => ({+ artifactId: `artifact-cache-${++artifactSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 26, 0, 0, artifactSeq)).toISOString(),+ })),+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => report) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-cache-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool(+ 'attach_device',+ { udid: secondDevice.udid },+ { sessionId: 'session-cache-b', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ const firstInstance = actor.list('session-cache-a')[0]!;+ const secondInstance = actor.list('session-cache-b')[0]!;+ const firstRoute = {+ instanceId: firstInstance.instanceId,+ generation: firstInstance.generation,+ leaseId: firstInstance.lease.id,+ };+ const secondRoute = {+ instanceId: secondInstance.instanceId,+ generation: secondInstance.generation,+ leaseId: secondInstance.lease.id,+ };+ const firstBuild = host.callTool(+ 'build_app',{- sessionId: 'session-a',+ ...firstRoute,+ containerPath: 'Demo.xcodeproj',+ },+ {+ sessionId: 'session-cache-a',origin: 'user',},- ),- ).resolves.toMatchObject({ ok: true });- await expect(- host.callTool(- 'launch_app',- { ...route, artifactId: artifact.artifactId, args: ['--uitesting'] },- { sessionId: 'session-a', origin: 'user' },- ),- ).resolves.toMatchObject({ ok: true });+ );+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());- const mobileArtifact = { ...artifact, artifactId: 'mobile-artifact' };- buildProject.mockResolvedValueOnce({- kind: 'cindy-mobile',- worktreeRoot: '/tmp/session-a',- projectRoot: '/tmp/session-a/apps/mobile',- containerPath: null,- scheme: 'Cindy',- appPath: '/tmp/session-a/apps/mobile/ios/build/Cindy.app',- resultBundlePath: null,- buildLogTail: '',- });- inspectArtifact.mockResolvedValueOnce(mobileArtifact);- await expect(- host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),- ).resolves.toMatchObject({ ok: true });- await expect(- host.callTool(- 'launch_app',- { ...route, artifactId: mobileArtifact.artifactId, args: [] },- { sessionId: 'session-a', origin: 'user' },- ),- ).resolves.toMatchObject({ ok: true });- expect(validateLaunch).toHaveBeenCalledWith(- '/tmp/session-a',- READY_REPORT.devices[0]!.udid,- expect.any(AbortSignal),- );- await host.callTool(- 'terminate_app',- { ...route, artifactId: artifact.artifactId },- {- sessionId: 'session-a',- origin: 'user',+ await expect(+ host.callTool(+ 'build_app',+ { ...secondRoute, containerPath: './Demo.xcodeproj' },+ {+ sessionId: 'session-cache-b',+ origin: 'user',+ },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'DEVICE_BUSY',+ });+ expect(build).toHaveBeenCalledOnce();++ releaseFirstBuild();+ await expect(firstBuild).resolves.toMatchObject({ ok: true });+ await expect(+ host.callTool('build_app', secondRoute, {+ sessionId: 'session-cache-b',+ origin: 'user',+ }),+ ).resolves.toMatchObject({ ok: true });++ expect(buildInputs).toHaveLength(2);+ expect(inspect).toHaveBeenCalledTimes(3);+ expect(buildInputs.map((input) => input.containerPath)).toEqual([+ canonicalContainerPath,+ canonicalContainerPath,+ ]);+ expect(buildInputs.map((input) => input.expectedArch)).toEqual([+ process.arch === 'x64' ? 'x86_64' : 'arm64',+ process.arch === 'x64' ? 'x86_64' : 'arm64',+ ]);+ expect(buildInputs.map((input) => input.simulatorUdid)).toEqual([+ firstDevice.udid,+ secondDevice.udid,+ ]);+ expect(buildInputs[1]!.derivedDataPath).toBe(buildInputs[0]!.derivedDataPath);+ expect(buildInputs[1]!.clonedSourcePackagesDirPath).toBe(+ buildInputs[0]!.clonedSourcePackagesDirPath,+ );+ expect(path.dirname(buildInputs[0]!.derivedDataPath)).toBe(+ path.join(userData, 'ios-simulator', 'projects'),+ );+ expect(path.dirname(buildInputs[0]!.clonedSourcePackagesDirPath!)).toBe(+ path.join(userData, 'ios-simulator', 'spm'),+ );+ expect(path.basename(buildInputs[0]!.derivedDataPath)).toBe(+ path.basename(buildInputs[0]!.clonedSourcePackagesDirPath!),+ );+ } finally {+ releaseFirstBuild();+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ itMac('isolates the build cache by container within a worktree', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-cont-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-cont-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),},+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ const orphanArtifact = path.join(+ userData,+ 'ios-simulator',+ 'projects',+ 'orphan-cache',+ 'artifacts',+ `${crypto.randomUUID()}.app`,);- await host.callTool(- 'open_url',- { ...route, url: 'demo://home' },- {- sessionId: 'session-a',- origin: 'user',+ const derivedDataPaths: string[] = [];+ const containerPaths: Array<string | undefined> = [];+ let markPruneStarted: () => void = () => undefined;+ const pruneStarted = new Promise<void>((resolve) => {+ markPruneStarted = resolve;+ });+ let releasePrune: () => void = () => undefined;+ const pruneGate = new Promise<void>((resolve) => {+ releasePrune = resolve;+ });+ const pruneBuildCaches = vi.fn(async () => {+ markPruneStarted();+ await pruneGate;+ });+ let artifactSeq = 0;+ const host = createIOSSimulatorHost({+ actor,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),},- );-- expect(projectBuilder.build).toHaveBeenCalledWith(- expect.objectContaining({- worktreeRoot: '/tmp/session-a',- containerPath: 'ios/Demo.xcodeproj',- }),- );- expect(appLifecycle.installExact).toHaveBeenCalledWith(- READY_REPORT.devices[0]!.udid,- artifact,- expect.any(AbortSignal),- );- expect(appLifecycle.launchExact).toHaveBeenCalledWith(- READY_REPORT.devices[0]!.udid,- artifact,- ['--uitesting'],- expect.any(AbortSignal),- );- expect(appLifecycle.terminateExact).toHaveBeenCalledWith(- READY_REPORT.devices[0]!.udid,- artifact.bundleId,- expect.any(AbortSignal),- );- expect(appLifecycle.openUrlExact).toHaveBeenCalledWith(- READY_REPORT.devices[0]!.udid,- 'demo://home',- expect.any(AbortSignal),- );- expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);-- let installSignal: AbortSignal | undefined;- installExact.mockImplementationOnce(- async (_simulatorUdid, _artifact, signal) =>- new Promise<void>((resolve) => {- installSignal = signal;- signal?.addEventListener('abort', () => resolve(), { once: true });+ projectBuilder: {+ inspect: vi.fn(async (_worktreeRoot, explicitContainerPath) => ({+ kind: 'xcode-project' as const,+ worktreeRoot: worktree,+ projectRoot: worktree,+ containerPath: path.join(worktree, explicitContainerPath!),+ })),+ build: vi.fn(async ({ worktreeRoot, derivedDataPath, containerPath }) => {+ derivedDataPaths.push(derivedDataPath);+ containerPaths.push(containerPath);+ return {+ kind: 'xcode-project' as const,+ worktreeRoot,+ projectRoot: worktreeRoot,+ containerPath: containerPath!,+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,+ buildLogTail: '',+ };+ }),+ },+ pruneBuildCaches,+ appLifecycle: {+ inspectArtifact: vi.fn(async (_worktreeRoot, appPath) => {+ artifactSeq += 1;+ return {+ artifactId: `artifact-${artifactSeq}`,+ worktreeRoot: worktree,+ authorizedRoot: path.dirname(appPath),+ appPath,+ bundleId: 'com.example.demo',+ createdAt: new Date(Date.UTC(2026, 7, 18, 0, 0, artifactSeq)).toISOString(),+ };}),- );- const installing = host.callTool(- 'install_app',- { ...route, artifactId: artifact.artifactId },- { sessionId: 'session-a', origin: 'user' },- );- await vi.waitFor(() => expect(installSignal).toBeDefined());- const stopping = host.callTool('stop_instance', route, {- sessionId: 'session-a',- origin: 'user',- });- await vi.waitFor(() => expect(installSignal?.aborted).toBe(true));- await expect(installing).resolves.toMatchObject({- ok: false,- errorCode: 'MUTATION_CANCELLED',+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),});- await expect(stopping).resolves.toMatchObject({ ok: true });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-cont', origin: 'user' },+ );+ const instance = actor.list('session-cont')[0]!;+ const route = {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ };+ await expect(+ host.callTool(+ 'build_app',+ { ...route, containerPath: 'Alpha.xcodeproj' },+ { sessionId: 'session-cont', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ await pruneStarted;+ // The startup sweep ran before this crashed-process copy existed. The+ // next lifecycle-owned prune must still reconcile it even though the+ // parent cache key is otherwise fresh and ownership is already latched.+ await mkdir(orphanArtifact, { recursive: true });+ const staleTime = new Date(Date.now() - 8 * 24 * 60 * 60_000);+ await utimes(orphanArtifact, staleTime, staleTime);+ // The lifecycle-owned sweep is still blocked, but a different cache key+ // can build and return without waiting for recursive stale-cache removal.+ await expect(+ host.callTool(+ 'build_app',+ { ...route, containerPath: 'Beta.xcodeproj' },+ { sessionId: 'session-cont', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(derivedDataPaths).toHaveLength(2);+ expect(derivedDataPaths[0]).not.toBe(derivedDataPaths[1]);+ expect(containerPaths).toEqual([+ path.join(worktree, 'Alpha.xcodeproj'),+ path.join(worktree, 'Beta.xcodeproj'),+ ]);+ expect(pruneBuildCaches).toHaveBeenCalledOnce();++ let disposeSettled = false;+ const disposing = host.dispose().then(() => {+ disposeSettled = true;+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(disposeSettled).toBe(false);+ releasePrune();+ await vi.waitFor(async () => {+ await expect(stat(orphanArtifact)).rejects.toMatchObject({ code: 'ENOENT' });+ });+ await disposing;+ } finally {+ releasePrune();+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }});it('returns readable diagnostics when build_app fails', async () => {@@ -8312,21 +10365,378 @@ describe('iOS Simulator host', () => {});itMac(- 'retries persisted removed-task cleanup after another registry writer releases its lease',+ 'returns diagnostics and removes a partial immutable copy when app copying fails',async () => {- const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-persisted-cleanup-'));- const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');- const setupRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath, {- acquireWriterLease: () => {- let held = true;- return {- isHeld: () => held,- release: () => {- held = false;+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-copy-fail-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-copy-fail-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ await writeFile(path.join(sourceApp, 'CopiedBeforeFailure.txt'), 'partial copy evidence');+ const socketPath = path.join(sourceApp, 'Uncopyable.sock');+ const socketServer = createServer();+ await new Promise<void>((resolve, reject) => {+ const onError = (error: Error) => reject(error);+ socketServer.once('error', onError);+ socketServer.listen(socketPath, () => {+ socketServer.off('error', onError);+ resolve();+ });+ });+ let derivedDataPath = '';+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>();+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder: {+ build: vi.fn(async (input) => {+ derivedDataPath = input.derivedDataPath;+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: path.join(input.worktreeRoot, 'Demo.xcodeproj'),+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: null,+ buildLogTail: 'COPY_FAILURE_DIAGNOSTIC_MARKER',+ };+ }),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-copy-fail', origin: 'user' },+ );+ const instance = actor.list('session-copy-fail')[0]!;+ const failed = await host.callTool(+ 'build_app',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-copy-fail', origin: 'user' },+ );++ expect(failed).toMatchObject({+ ok: false,+ errorCode: 'APP_ARTIFACT_INVALID',+ data: {+ diagnostics: {+ diagnosticsId: expect.any(String),+ buildLogTail: expect.stringContaining('COPY_FAILURE_DIAGNOSTIC_MARKER'),},+ },+ });+ expect(inspectArtifact).not.toHaveBeenCalled();+ const diagnosticsId = (+ failed as unknown as { ok: false; data: { diagnostics: { diagnosticsId: string } } }+ ).data.diagnostics.diagnosticsId;+ await expect(+ host.callTool(+ 'read_build_diagnostics',+ { diagnosticsId, source: 'build-log' },+ { sessionId: 'session-copy-fail', origin: 'agent' },+ ),+ ).resolves.toMatchObject({+ ok: true,+ data: { text: expect.stringContaining('COPY_FAILURE_DIAGNOSTIC_MARKER') },+ });+ await expect(readdir(path.join(derivedDataPath, 'artifacts'))).resolves.toEqual([]);+ } finally {+ await new Promise<void>((resolve) => socketServer.close(() => resolve()));+ getPath.mockRestore();+ await host.dispose();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ },+ );++ it('preserves session cancellation when an in-flight artifact copy also fails', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-copy-cancel-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-copy-cancel-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ await writeFile(path.join(sourceApp, 'Info.plist'), 'fixture');+ let buildSignal: AbortSignal | undefined;+ let copyStarted!: () => void;+ const copyStartedPromise = new Promise<void>((resolve) => {+ copyStarted = resolve;+ });+ let rejectCopy!: (error: Error) => void;+ const copyFailure = new Promise<never>((_resolve, reject) => {+ rejectCopy = reject;+ });+ let immutableAppPath = '';+ mockFsCp.mockImplementationOnce(async (_source, destination) => {+ immutableAppPath = String(destination);+ await mkdir(immutableAppPath, { recursive: true });+ await writeFile(path.join(immutableAppPath, 'partial'), 'partial copy');+ copyStarted();+ await copyFailure;+ });+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder: {+ build: vi.fn(async (input) => {+ buildSignal = input.signal;+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: path.join(input.worktreeRoot, 'Demo.xcodeproj'),+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: null,+ buildLogTail: 'COPY_CANCEL_DIAGNOSTIC_MARKER',+ };+ }),+ },+ appLifecycle: {+ inspectArtifact: vi.fn(),+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-copy-cancel', origin: 'user' },+ );+ const instance = actor.list('session-copy-cancel')[0]!;+ const build = host.callTool(+ 'build_app',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,+ },+ { sessionId: 'session-copy-cancel', origin: 'user' },+ );+ await copyStartedPromise;++ const cancellation = host.cancelSessionOperations('session-copy-cancel');+ expect(buildSignal?.aborted).toBe(true);+ rejectCopy(new Error('injected artifact copy failure'));++ await expect(build).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',+ });+ await expect(cancellation).resolves.toBeUndefined();+ await vi.waitFor(() =>+ expect(stat(immutableAppPath)).rejects.toMatchObject({ code: 'ENOENT' }),+ );+ } finally {+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ it('preserves session cancellation when artifact inspection also fails', async () => {+ const userData = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-inspect-cancel-ud-'));+ const worktree = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-inspect-cancel-wt-'));+ const getPath = vi.spyOn(app, 'getPath').mockImplementation(() => userData);+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle: {+ findExact: vi.fn(),+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),+ shutdownExact: vi.fn(async () => undefined),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ },+ });+ const sourceApp = path.join(worktree, 'Demo.app');+ await mkdir(sourceApp, { recursive: true });+ await writeFile(path.join(sourceApp, 'Info.plist'), 'fixture');+ let buildSignal: AbortSignal | undefined;+ let inspectionStarted!: () => void;+ const inspectionStartedPromise = new Promise<void>((resolve) => {+ inspectionStarted = resolve;+ });+ let rejectInspection!: (error: Error) => void;+ const inspectionFailure = new Promise<never>((_resolve, reject) => {+ rejectInspection = reject;+ });+ let immutableAppPath = '';+ const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(+ (_worktreeRoot, appPath) => {+ immutableAppPath = appPath;+ inspectionStarted();+ return inspectionFailure;+ },+ );+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(+ async (options) =>+ ({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ }) as unknown as Promise<WdaRunningInstance>,+ ),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ driverManager,+ projectBuilder: {+ build: vi.fn(async (input) => {+ buildSignal = input.signal;+ return {+ kind: 'xcode-project' as const,+ worktreeRoot: input.worktreeRoot,+ projectRoot: input.worktreeRoot,+ containerPath: path.join(input.worktreeRoot, 'Demo.xcodeproj'),+ scheme: 'Demo',+ appPath: sourceApp,+ resultBundlePath: null,+ buildLogTail: 'INSPECTION_CANCEL_DIAGNOSTIC_MARKER',};+ }),+ },+ appLifecycle: {+ inspectArtifact,+ installExact: vi.fn(async () => undefined),+ launchExact: vi.fn(async () => undefined),+ terminateExact: vi.fn(async () => undefined),+ openUrlExact: vi.fn(async () => undefined),+ },+ resourceScheduler: testResourceScheduler(),+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => ({ id, workDir: worktree, remoteHostId: null })),+ resolveWorktreeRoot: vi.fn(async () => worktree),+ });++ try {+ await host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-inspect-cancel', origin: 'user' },+ );+ const instance = actor.list('session-inspect-cancel')[0]!;+ const build = host.callTool(+ 'build_app',+ {+ instanceId: instance.instanceId,+ generation: instance.generation,+ leaseId: instance.lease.id,},+ { sessionId: 'session-inspect-cancel', origin: 'user' },+ );+ await inspectionStartedPromise;++ const cancellation = host.cancelSessionOperations('session-inspect-cancel');+ expect(buildSignal?.aborted).toBe(true);+ rejectInspection(+ new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'injected artifact inspection failure',+ ),+ );++ await expect(build).resolves.toMatchObject({+ ok: false,+ errorCode: 'MUTATION_CANCELLED',});+ await expect(cancellation).resolves.toBeUndefined();+ await vi.waitFor(() =>+ expect(stat(immutableAppPath)).rejects.toMatchObject({ code: 'ENOENT' }),+ );+ } finally {+ await host.dispose();+ getPath.mockRestore();+ await rm(userData, { recursive: true, force: true });+ await rm(worktree, { recursive: true, force: true });+ }+ });++ itMac(+ 'retries persisted removed-task cleanup after another registry writer releases its lease',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-persisted-cleanup-'));+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const setupRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);expect(setupRegistry.acquireWriterSync()).toBe(true);const persistedInstance = new IOSSimulatorOwnershipStore({createId: () => 'persisted-removed-instance',@@ -8340,52 +10750,114 @@ describe('iOS Simulator host', () => {setupRegistry.releaseWriterSync();const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);- let writerLeaseHeld = false;- let acquireAttempts = 0;- const acquireWriter = vi- .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'acquireWriterSync')- .mockImplementation(() => {- if (writerLeaseHeld) return true;- acquireAttempts += 1;- if (acquireAttempts === 1) return false;- writerLeaseHeld = true;- return true;- });- const isWriter = vi- .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'isWriter', 'get')- .mockImplementation(() => writerLeaseHeld);- const releaseWriter = vi- .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'releaseWriterSync')- .mockImplementation(() => {- writerLeaseHeld = false;- });const cleanupOrphaned = vi.spyOn(WdaProcessManager.prototype, 'cleanupOrphaned').mockResolvedValue();+ const lockHolderSource = `+ const { closeSync, constants, openSync } = require('node:fs');+ const fd = openSync(+ process.argv[1],+ constants.O_CREAT | constants.O_RDWR | constants.O_NONBLOCK | 0x20,+ 0o600,+ );+ process.stdout.write('locked\\n');+ process.stdin.resume();+ process.stdin.once('data', () => {+ closeSync(fd);+ process.exit(0);+ });+ `;+ const lockHolder = spawn(process.execPath, ['-e', lockHolderSource, setupRegistry.lockPath], {+ stdio: ['pipe', 'pipe', 'pipe'],+ });+ let lockHolderReleased = false;+ let lockHolderStderr = '';+ lockHolder.stderr.setEncoding('utf8');+ lockHolder.stderr.on('data', (chunk: string) => {+ lockHolderStderr += chunk;+ });try {+ await new Promise<void>((resolve, reject) => {+ const timeout = setTimeout(+ () => reject(new Error(`Timed out waiting for lock holder: ${lockHolderStderr}`)),+ 2_000,+ );+ const cleanup = () => {+ clearTimeout(timeout);+ lockHolder.stdout.off('data', onData);+ lockHolder.off('error', onError);+ lockHolder.off('exit', onExit);+ };+ const onData = (chunk: Buffer) => {+ if (!chunk.toString('utf8').includes('locked')) return;+ cleanup();+ resolve();+ };+ const onError = (error: Error) => {+ cleanup();+ reject(error);+ };+ const onExit = (code: number | null, signal: NodeJS.Signals | null) => {+ cleanup();+ reject(+ new Error(+ `Lock holder exited before acquisition (code=${String(code)}, signal=${String(signal)}): ${lockHolderStderr}`,+ ),+ );+ };+ lockHolder.stdout.on('data', onData);+ lockHolder.once('error', onError);+ lockHolder.once('exit', onExit);+ });+await expect(cleanupIOSSimulatorRemovedSession('persisted-removed-session'),).rejects.toMatchObject({code: 'DEVICE_BUSY',retryable: true,});- expect(acquireAttempts).toBe(1);+ await expect(stat(path.join(root, 'ios-simulator', 'projects'))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ await expect(stat(path.join(root, 'ios-simulator', 'spm'))).rejects.toMatchObject({+ code: 'ENOENT',+ });++ lockHolder.stdin.end('release\n');+ await new Promise<void>((resolve, reject) => {+ lockHolder.once('error', reject);+ lockHolder.once('exit', (code, signal) => {+ if (code === 0) resolve();+ else {+ reject(+ new Error(+ `Lock holder failed (code=${String(code)}, signal=${String(signal)}): ${lockHolderStderr}`,+ ),+ );+ }+ });+ });+ lockHolderReleased = true;await expect(cleanupIOSSimulatorRemovedSession('persisted-removed-session'),).resolves.toBeUndefined();- expect(acquireAttempts).toBe(2);const persisted = JSON.parse(await readFile(registryPath, 'utf8')) as {instances: unknown[];};expect(persisted.instances).toEqual([]);+ expect(setupRegistry.acquireWriterSync()).toBe(false);++ await disposeIOSSimulatorHost();+ expect(setupRegistry.acquireWriterSync()).toBe(true);+ setupRegistry.releaseWriterSync();} finally {+ if (!lockHolderReleased && lockHolder.exitCode === null) {+ lockHolder.stdin.end('release\n');+ lockHolder.kill();+ }await disposeIOSSimulatorHost();- expect(writerLeaseHeld).toBe(false);- releaseWriter.mockRestore();- isWriter.mockRestore();- acquireWriter.mockRestore();cleanupOrphaned.mockRestore();getPath.mockRestore();await rm(root, { recursive: true, force: true });diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 47a31b19de..8dfad77e02 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -1,6 +1,18 @@import { createHash, randomUUID } from 'node:crypto';+import { renameSync } from 'node:fs';import type { Dirent } from 'node:fs';-import { readdir, realpath, rm, stat } from 'node:fs/promises';+import {+ cp,+ lstat,+ mkdir,+ readFile,+ readdir,+ readlink,+ realpath,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises';import { release as hostOsRelease } from 'node:os';import path from 'node:path';@@ -110,6 +122,7 @@ import {const logger = createLogger('mcp/cindy_ios_simulator');const BUILD_DIAGNOSTICS_TTL_MS = 30 * 60_000;+const BUILD_LEASE_HEARTBEAT_MS = 20_000;const PLUGIN_ENVIRONMENT_CACHE_MS = 30_000;const MAX_BUILD_DIAGNOSTICS = 32;const MANAGED_BUILD_RESULT_BUNDLE_PATTERN = /^CindyBuild(?:-[0-9a-f-]+)?\.xcresult$/i;@@ -117,6 +130,308 @@ const DEFAULT_DEVICE_LIVENESS_INTERVAL_MS = 1_000;const MAX_WDA_VIEWER_FRAMES_PER_SECOND = 20;const MAX_NATIVE_H264_VIEWER_FRAMES_PER_SECOND = 60;const MAX_INSTANCES_PER_SESSION = 4;+const MAX_ARTIFACTS_PER_INSTANCE = 4;+const IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;+const IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE = '.cindy-last-used';+const IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY = 4;+const UUID_V4_PATTERN_SOURCE =+ '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';+const MANAGED_BUILD_CACHE_KEY_PATTERN = /^[0-9a-f]{20}$/i;+const MANAGED_BUILD_CACHE_TRASH_PATTERN = new RegExp(+ `^\\.trash-[0-9a-f]{20}-${UUID_V4_PATTERN_SOURCE}$`,+ 'i',+);+const MANAGED_ARTIFACT_COPY_PATTERN = new RegExp(`^${UUID_V4_PATTERN_SOURCE}\\.app$`, 'i');+const ARTIFACT_COPY_TRASH_PREFIX = '.trash-artifact-';+const MANAGED_ARTIFACT_COPY_TRASH_PATTERN = new RegExp(+ `^\\.trash-artifact-${UUID_V4_PATTERN_SOURCE}\\.app-${UUID_V4_PATTERN_SOURCE}$`,+ 'i',+);++/**+ * Record the last time this cache key was admitted or finished a build.+ * Xcode writes DerivedData/SPM descendants and does not refresh the cache-key+ * directory mtime, so opportunistic 7-day reclaim must not use that mtime.+ */+export async function touchIOSSimulatorBuildCacheLastUsed(+ cacheDir: string,+ now: () => number = Date.now,+): Promise<void> {+ await mkdir(cacheDir, { recursive: true });+ await writeFile(+ path.join(cacheDir, IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE),+ `${now()}\n`,+ 'utf8',+ );+}++function isPathInside(root: string, candidate: string): boolean {+ const relative = path.relative(root, candidate);+ return (+ relative === '' ||+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))+ );+}++/**+ * An immutable app copy must not retain a symlink into mutable DerivedData,+ * the worktree, or any other external location. Validate links without+ * traversing them: real directories are walked once, while each link's final+ * target must resolve inside the copied `.app` tree. Dangling links fail too.+ */+async function assertIOSSimulatorArtifactSymlinksContained(appPath: string): Promise<void> {+ let root: string;+ try {+ root = await realpath(appPath);+ } catch {+ throw new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The immutable app artifact could not be inspected.',+ );+ }+ const pending = [root];+ while (pending.length > 0) {+ const directory = pending.pop()!;+ let entries: Dirent[];+ try {+ entries = await readdir(directory, { withFileTypes: true });+ } catch {+ throw new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The immutable app artifact could not be inspected.',+ );+ }+ for (const entry of entries) {+ const entryPath = path.join(directory, entry.name);+ if (entry.isSymbolicLink()) {+ let linkTargetPath: string;+ let target: string;+ try {+ const rawTarget = await readlink(entryPath);+ linkTargetPath = path.resolve(path.dirname(entryPath), rawTarget);+ target = await realpath(entryPath);+ } catch {+ throw new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The immutable app artifact contains a dangling symbolic link.',+ );+ }+ if (!isPathInside(root, linkTargetPath) || !isPathInside(root, target)) {+ throw new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The immutable app artifact contains a symbolic link outside its copy.',+ );+ }+ } else if (entry.isDirectory()) {+ pending.push(entryPath);+ }+ }+ }+}++async function readIOSSimulatorBuildCacheLastUsedMs(cacheDir: string): Promise<number | null> {+ try {+ const raw = await readFile(+ path.join(cacheDir, IOS_SIMULATOR_BUILD_CACHE_LAST_USED_FILE),+ 'utf8',+ );+ const parsed = Number.parseInt(raw.trim(), 10);+ return Number.isFinite(parsed) ? parsed : null;+ } catch {+ return null;+ }+}++/**+ * Opportunistic cold-cache reclaim for per-worktree DerivedData + SPM+ * checkouts. This is a 7-day unused TTL, not a disk quota: it cannot cap+ * total size. Age comes from the explicit last-used marker, not the+ * cache-key directory mtime. Because an in-flight build does not keep that+ * parent mtime fresh, `isSkip` must answer live (not from a snapshot)+ * whether a key is actively used, so a build admitted mid-sweep is never+ * removed. Best-effort: a read/stat/rm failure on one entry never blocks a+ * build.+ */+export async function pruneStaleIOSSimulatorBuildCaches(+ roots: readonly string[],+ maxAgeMs: number,+ now: () => number = Date.now,+ isSkip?: (name: string) => boolean,+): Promise<void> {+ const deadline = now() - maxAgeMs;+ for (const root of roots) {+ let entries: Dirent[];+ try {+ entries = await readdir(root, { withFileTypes: true });+ } catch {+ continue;+ }+ const candidates = entries.filter((entry) => {+ if (!entry.isDirectory()) return false;+ if (MANAGED_BUILD_CACHE_TRASH_PATTERN.test(entry.name)) return true;+ return MANAGED_BUILD_CACHE_KEY_PATTERN.test(entry.name) && !isSkip?.(entry.name);+ });+ let cursor = 0;+ const pruneNext = async (): Promise<void> => {+ while (cursor < candidates.length) {+ const entry = candidates[cursor++]!;+ const full = path.join(root, entry.name);+ try {+ // A crash or force-quit may interrupt deletion after the atomic+ // rename. Trash names are never cache keys, so resume them without+ // another seven-day wait.+ if (MANAGED_BUILD_CACHE_TRASH_PATTERN.test(entry.name)) {+ await rm(full, { recursive: true, force: true }).catch(() => undefined);+ continue;+ }+ const lastUsedMs = await readIOSSimulatorBuildCacheLastUsedMs(full);+ const info = lastUsedMs === null ? await stat(full) : null;+ // Re-check after the await: another build may have admitted this+ // key while the marker/stat was in flight. The sync check-then-rename+ // below is atomic (no yield), so a key admitted after this point+ // cannot be removed under an active build.+ if (isSkip?.(entry.name)) continue;+ const ageSourceMs = lastUsedMs ?? info?.mtimeMs;+ if (ageSourceMs === undefined || ageSourceMs >= deadline) continue;+ // Atomically move the key aside before the (async, slow) recursive+ // delete. A build admitted during deletion recreates the original key+ // instead of racing the in-progress rm.+ const trash = path.join(root, `.trash-${entry.name}-${randomUUID()}`);+ try {+ renameSync(full, trash);+ } catch {+ // Losing the atomic rename (ENOENT from a concurrent sweep, or any+ // transient error) abandons this prune attempt. Never remove the+ // original path here: a build admitted during the failed rename may+ // already be using the directory, and a sibling rename cannot be+ // cross-device.+ continue;+ }+ await rm(trash, { recursive: true, force: true }).catch(() => undefined);+ } catch {+ // Best-effort per entry.+ }+ }+ };+ await Promise.all(+ Array.from(+ {+ length: Math.min(IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY, candidates.length),+ },+ () => pruneNext(),+ ),+ );+ }+}++/**+ * Reclaim immutable app copies left behind by a crashed/force-quit Host.+ *+ * App handles are intentionally process-local, so a new Host cannot rebuild+ * the in-memory registry that normally protects those copies from eviction.+ * Treat each UUID-shaped copy as independently TTL-managed instead of using+ * the parent cache key's last-used marker: a later build can keep that key+ * fresh forever while old copies remain unreachable. The final live check and+ * synchronous rename make the slow recursive delete safe against a build or+ * artifact operation admitted during the scan.+ *+ * Returns false when a filesystem operation should be retried on a later+ * ownership reconciliation pass. Missing paths and benign races count as+ * complete because another actor already performed the cleanup.+ */+export async function reconcileOrphanedIOSSimulatorArtifactCopies(+ projectsRoot: string,+ maxAgeMs: number,+ now: () => number = Date.now,+ isSkip?: (cacheKey: string, artifactPath: string) => boolean,+): Promise<boolean> {+ const deadline = now() - maxAgeMs;+ let complete = true;+ let projectEntries: Dirent[];+ try {+ projectEntries = await readdir(projectsRoot, { withFileTypes: true });+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'ENOENT';+ }++ const cacheEntries = projectEntries.filter(+ (entry) => entry.isDirectory() && !entry.name.startsWith('.trash-'),+ );+ let cursor = 0;+ const reconcileNext = async (): Promise<void> => {+ while (cursor < cacheEntries.length) {+ const cacheEntry = cacheEntries[cursor++]!;+ const cacheKey = cacheEntry.name;+ const artifactsRoot = path.join(projectsRoot, cacheKey, 'artifacts');+ try {+ // Never follow a user-created `artifacts` symlink while cleaning up.+ // The build path is a real directory created by this module; a+ // symlink here could otherwise redirect recursive rm outside the+ // managed projects root.+ const artifactsRootMetadata = await lstat(artifactsRoot);+ if (!artifactsRootMetadata.isDirectory()) continue;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;+ continue;+ }+ let artifactEntries: Dirent[];+ try {+ artifactEntries = await readdir(artifactsRoot, { withFileTypes: true });+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT') complete = false;+ continue;+ }++ for (const artifactEntry of artifactEntries) {+ if (!artifactEntry.isDirectory()) continue;+ const artifactPath = path.join(artifactsRoot, artifactEntry.name);+ if (MANAGED_ARTIFACT_COPY_TRASH_PATTERN.test(artifactEntry.name)) {+ await rm(artifactPath, { recursive: true, force: true }).catch((error) => {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;+ });+ continue;+ }+ if (!MANAGED_ARTIFACT_COPY_PATTERN.test(artifactEntry.name)) continue;+ try {+ if (isSkip?.(cacheKey, artifactPath)) continue;+ const metadata = await stat(artifactPath);+ if (!metadata.isDirectory() || metadata.mtimeMs >= deadline) continue;+ // The copy may have become live while stat() was in flight. The+ // check must happen immediately before the synchronous rename.+ if (isSkip?.(cacheKey, artifactPath)) continue;+ const trashPath = path.join(+ artifactsRoot,+ `${ARTIFACT_COPY_TRASH_PREFIX}${artifactEntry.name}-${randomUUID()}`,+ );+ try {+ renameSync(artifactPath, trashPath);+ } catch (error) {+ // A concurrent cleanup/build may have won the rename. Do not+ // remove the original path after losing that atomic race.+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;+ continue;+ }+ await rm(trashPath, { recursive: true, force: true }).catch((error) => {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;+ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false;+ }+ }+ }+ };++ await Promise.all(+ Array.from(+ {+ length: Math.min(IOS_SIMULATOR_BUILD_CACHE_PRUNE_CONCURRENCY, cacheEntries.length),+ },+ () => reconcileNext(),+ ),+ );+ return complete;+}interface IOSSimulatorSessionSnapshot {id: string;@@ -174,6 +489,7 @@ export type IOSSimulatorAppLifecycleAdapter = Pick<>;export type IOSSimulatorProjectBuilderAdapter = Pick<IOSSimulatorProjectBuilder, 'build'> & {+ inspect?: IOSSimulatorProjectBuilder['inspect'];readXcresult?: IOSSimulatorProjectBuilder['readXcresult'];validateLaunch?: IOSSimulatorProjectBuilder['validateLaunch'];};@@ -208,6 +524,10 @@ export interface IOSSimulatorHostOptions {h264FramePump?: IOSSimulatorH264FramePump;appLifecycle?: IOSSimulatorAppLifecycleAdapter;projectBuilder?: IOSSimulatorProjectBuilderAdapter;+ /** Test seam for scheduling the active-build lease heartbeat. */+ scheduleBuildLeaseHeartbeat?: (heartbeat: () => void) => () => void;+ /** Test seam for lifecycle-owned opportunistic cache pruning. */+ pruneBuildCaches?: typeof pruneStaleIOSSimulatorBuildCaches;mediaCapture?: IOSSimulatorMediaCaptureAdapter;diagnosticsStore?: IOSSimulatorDiagnosticsStore;resourceScheduler?: IOSSimulatorResourceScheduler;@@ -1021,14 +1341,40 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I});const appLifecycle = options.appLifecycle ?? new IOSSimulatorAppLifecycle();const projectBuilder = options.projectBuilder ?? new IOSSimulatorProjectBuilder();+ const scheduleBuildLeaseHeartbeat =+ options.scheduleBuildLeaseHeartbeat ??+ ((heartbeat: () => void) => {+ const timer = setInterval(heartbeat, BUILD_LEASE_HEARTBEAT_MS);+ timer.unref?.();+ return () => clearInterval(timer);+ });const appArtifacts = new Map<string,{instanceId: string;projectKind: IOSSimulatorProjectBuildResult['kind'];artifact: IOSSimulatorAppArtifact;+ /**+ * The unresolved copy path under `managedBuildResultsRoot()`. `artifact.appPath`+ * is realpathed by `inspectArtifact`, so when `userData` sits behind a symlink+ * the two no longer share a prefix; lifecycle bookkeeping must compare against+ * this path, not the resolved one.+ */+ immutableAppPath: string;+ /** True once install_app has consumed this copy; eviction prefers installed copies. */+ installed: boolean;}>();+ // installExact re-reads Info.plist and runs simctl install against the+ // immutable copy. Builds are admitted on a separate track from+ // actor.runMutation, so a fifth build must not reclaim a copy that an+ // in-flight install is still reading. Refcount: JS is single-threaded, so+ // incrementing with no await between lookup and pin is atomic with eviction.+ const pinnedArtifactIds = new Map<string, number>();+ // Removals started by discardArtifactCopy that are still in flight. dispose+ // awaits these so quit cannot end the process while a recursive rm — e.g. an+ // eviction triggered just before shutdown — is still running.+ const inFlightArtifactRemovals = new Set<Promise<void>>();type BuildDiagnosticRecord = {sessionId: string;instanceId: string;@@ -1047,6 +1393,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst pendingBuildDiagnosticRemoval = new Map<string, BuildDiagnosticRecord>();let buildResultBundlesReconciled = false;let buildResultBundlesReconcilePromise: Promise<void> | null = null;+ let artifactCopiesReconcilePromise: Promise<boolean> | null = null;type ActiveBuild = {sessionId: string;controller: AbortController;@@ -1054,6 +1401,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IresolveSettled: () => void;};const activeBuilds = new Map<string, ActiveBuild>();+ // Shared per-worktree+arch build cache keys serialize builds across instances:+ // two sessions on the same worktree must not run two xcodebuild processes+ // against one DerivedData/SPM checkout. beginBuild only serializes per instance.+ const activeBuildCacheKeys = new Set<string>();+ const pruneBuildCaches = options.pruneBuildCaches ?? pruneStaleIOSSimulatorBuildCaches;+ let buildCachePrunePromise: Promise<void> | null = null;const sessionOperationAdmissionEpochs = new Map<string, number>();const sessionRemovalAdmissionEpochs = new Map<string, number>();const activeSessionRemovalBarrierOperations = new Map<@@ -1110,8 +1463,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I}>();const getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;- const isOwnerBoundaryPending =- options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;+ const isOwnerBoundaryPending = options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;const pendingCreateEvidence = options.pendingCreateEvidence ?? null;let ownershipReconciledScopeKey: string | null = null;// Persisted `viewerState` can only be stale on the first sweep that actually@@ -1397,6 +1749,76 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I});});}+ /**+ * Reclaim a per-build immutable artifact copy. Only paths shaped like+ * `projects/<cacheKey>/artifacts/<uuid>.app` are removed; anything else is+ * left untouched. Returns the removal promise so teardown can await it;+ * best-effort callers may ignore the returned promise.+ */+ function discardArtifactCopy(appPath: string): Promise<void> {+ const managedRoot = managedBuildResultsRoot();+ const relative = path.relative(managedRoot, appPath);+ const segments = relative.split(path.sep);+ if (+ relative === '' ||+ relative === '..' ||+ relative.startsWith(`..${path.sep}`) ||+ path.isAbsolute(relative) ||+ segments.length !== 3 ||+ segments[1] !== 'artifacts' ||+ !MANAGED_BUILD_CACHE_KEY_PATTERN.test(segments[0] ?? '') ||+ !MANAGED_ARTIFACT_COPY_PATTERN.test(segments[2] ?? '')+ ) {+ return Promise.resolve();+ }+ const removal = rm(appPath, { recursive: true, force: true }).catch(() => undefined);+ inFlightArtifactRemovals.add(removal);+ void removal.finally(() => inFlightArtifactRemovals.delete(removal));+ return removal;+ }+ /**+ * Cache keys that still have a live artifact handle. Installed artifacts+ * remain addressable until normal per-instance eviction, so the stale sweep+ * must not remove either kind while its handle is registered.+ */+ function liveArtifactCacheKeys(): Set<string> {+ const keys = new Set<string>();+ const managedRoot = managedBuildResultsRoot();+ for (const stored of appArtifacts.values()) {+ const relative = path.relative(managedRoot, stored.immutableAppPath);+ const segments = relative.split(path.sep);+ if (segments.length >= 2 && segments[0]) keys.add(segments[0]);+ }+ return keys;+ }+ function scheduleBuildCachePrune(): void {+ if (disposePromise || buildCachePrunePromise) return;+ const prune = Promise.resolve()+ .then(async () => {+ // Reconcile immutable copies after the cache-key sweep as well as at+ // ownership startup. A crashed Host loses its in-memory artifact map;+ // future builds can keep the parent cache key fresh indefinitely, so a+ // startup-only pass is not enough for a long-lived Host.+ try {+ await pruneBuildCaches(+ [+ path.join(app.getPath('userData'), 'ios-simulator', 'projects'),+ path.join(app.getPath('userData'), 'ios-simulator', 'spm'),+ ],+ IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS,+ undefined,+ (key) => activeBuildCacheKeys.has(key) || liveArtifactCacheKeys().has(key),+ );+ } finally {+ await reconcileOrphanedArtifactCopies();+ }+ })+ .catch(() => undefined)+ .finally(() => {+ if (buildCachePrunePromise === prune) buildCachePrunePromise = null;+ });+ buildCachePrunePromise = prune;+ }async function removeBuildDiagnostic(diagnosticsId: string,diagnostic: BuildDiagnosticRecord,@@ -1509,6 +1931,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I});return buildResultBundlesReconcilePromise;}+ async function reconcileOrphanedArtifactCopies(): Promise<boolean> {+ if (artifactCopiesReconcilePromise) return artifactCopiesReconcilePromise;+ const reconciliation = (async () => {+ const complete = await reconcileOrphanedIOSSimulatorArtifactCopies(+ managedBuildResultsRoot(),+ IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS,+ Date.now,+ (cacheKey, artifactPath) =>+ activeBuildCacheKeys.has(cacheKey) ||+ [...appArtifacts.values()].some((stored) => stored.immutableAppPath === artifactPath),+ );+ return complete;+ })().finally(() => {+ if (artifactCopiesReconcilePromise === reconciliation) {+ artifactCopiesReconcilePromise = null;+ }+ });+ artifactCopiesReconcilePromise = reconciliation;+ return reconciliation;+ }async function storeBuildDiagnostics(input: {sessionId: string;instanceId: string;@@ -1778,10 +2220,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst nativeDiagnostics = manager.diagnostics?.(instance.instanceId)?.nativeSidecar;const nativeRecoveryAvailable = Boolean(manager.recoverNativeSidecar &&- nativeFallback &&- (stream.reasonCode === 'native-stream-disconnected' ||- (nativeDiagnostics?.recoveryEligible === true &&- nativeDiagnostics.admission?.launch.allowed === true)),+ nativeFallback &&+ (stream.reasonCode === 'native-stream-disconnected' ||+ (nativeDiagnostics?.recoveryEligible === true &&+ nativeDiagnostics.admission?.launch.allowed === true)),);return {sessionId: instance.sessionId,@@ -1966,10 +2408,18 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ifunction clearRemovedInstanceProjection(instanceId: string): void {agentControlLeases.delete(instanceId);for (const [artifactId, stored] of appArtifacts) {- if (stored.instanceId === instanceId) appArtifacts.delete(artifactId);+ if (stored.instanceId === instanceId) {+ appArtifacts.delete(artifactId);+ void discardArtifactCopy(stored.immutableAppPath);+ }}}+ function finalizeDetachedResourceRelease(instance: IOSSimulatorInstance): void {+ resourceScheduler.markStopped(instance.instanceId);+ clearRemovedInstanceProjection(instance.instanceId);+ }+async function cleanupOrphanedDriverRuntime(instance: IOSSimulatorInstance): Promise<boolean> {if (!driverManager?.cleanupOrphaned) return true;try {@@ -2495,8 +2945,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I{ preserveDetachGrace: shouldResumeDetachGrace, normalizeViewerState },);if (shouldResumeDetachGrace && driverRuntimeRecovered && complete) {- await actor.resumeDetachGrace(reconciled.instanceId, reconciled.sessionId, () =>- resourceScheduler.markStopped(reconciled.instanceId),+ await actor.resumeDetachGrace(+ reconciled.instanceId,+ reconciled.sessionId,+ finalizeDetachedResourceRelease,);}return { complete, viewerStateHandled: true };@@ -2504,8 +2956,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ifunction isViewerStateNormalized(scopeKey: string, instanceId: string): boolean {return (- viewerStateNormalizedScopeKey === scopeKey &&- viewerStateNormalizedInstanceIds.has(instanceId)+ viewerStateNormalizedScopeKey === scopeKey && viewerStateNormalizedInstanceIds.has(instanceId));}@@ -2626,6 +3077,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iif (disposePromise) return;await reconcileOrphanedBuildResultBundles();if (disposePromise) return;+ if (!(await reconcileOrphanedArtifactCopies())) complete = false;+ if (disposePromise) return;const environment = await inspectRuntime();if (disposePromise) return;if (!environment?.ready) return;@@ -3410,6 +3863,55 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn stored.artifact;}+ function pinArtifact(artifactId: string): void {+ pinnedArtifactIds.set(artifactId, (pinnedArtifactIds.get(artifactId) ?? 0) + 1);+ }++ /**+ * Reclaim oldest unpinned copies until this instance is back at+ * MAX_ARTIFACTS_PER_INSTANCE. Pinned copies stay; the bound may+ * temporarily exceed MAX while an app lifecycle operation is using them.+ */+ function evictUnpinnedArtifactsForInstance(instanceId: string, keepExtra = 0): void {+ const instanceArtifacts = [...appArtifacts.entries()]+ .filter(([, stored]) => stored.instanceId === instanceId)+ .sort((a, b) => {+ // Evict installed (already consumed) copies before uninstalled ones so a+ // caller's pending artifact handle survives as long as possible.+ if (a[1].installed !== b[1].installed) return a[1].installed ? -1 : 1;+ return a[1].artifact.createdAt.localeCompare(b[1].artifact.createdAt);+ });+ const overflow = instanceArtifacts.length + keepExtra - MAX_ARTIFACTS_PER_INSTANCE;+ let evicted = 0;+ for (const [oldArtifactId, oldStored] of instanceArtifacts) {+ if (evicted >= overflow) break;+ if ((pinnedArtifactIds.get(oldArtifactId) ?? 0) > 0) continue;+ void discardArtifactCopy(oldStored.immutableAppPath);+ appArtifacts.delete(oldArtifactId);+ evicted += 1;+ }+ }++ function unpinArtifact(artifactId: string): void {+ const remaining = (pinnedArtifactIds.get(artifactId) ?? 1) - 1;+ if (remaining > 0) {+ pinnedArtifactIds.set(artifactId, remaining);+ return;+ }+ pinnedArtifactIds.delete(artifactId);+ const stored = appArtifacts.get(artifactId);+ if (stored) evictUnpinnedArtifactsForInstance(stored.instanceId);+ }++ function requireAndPinArtifact(+ instance: IOSSimulatorInstance,+ artifactId: string,+ ): IOSSimulatorAppArtifact {+ const artifact = requireArtifact(instance, artifactId);+ pinArtifact(artifactId);+ return artifact;+ }+function cancelIdleRecycle(instanceId: string): void {const timer = idleRecycleTimers.get(instanceId);if (timer) clearTimeout(timer);@@ -4721,9 +5223,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn {ok: true,data: {- ...instanceData(- await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),- ),+ ...instanceData(await actor.detach(route, finalizeDetachedResourceRelease)),...(mediaCleanupWarning ? { mediaCleanupWarning } : {}),},};@@ -5620,20 +6120,102 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IassertHostActive();const route = readMutationRoute(buildSession.sessionId, args);const instance = actor.assertRoute(route);+ // Validate before beginBuild: a rejected argument must not leave a+ // build registered that never reaches the cleanup finally below.+ const containerPath = readOptionalString(args, 'containerPath', 4_096);const activeBuild = beginBuild(instance, buildAdmissionEpoch);- const derivedDataPath = path.join(- app.getPath('userData'),- 'ios-simulator',- 'projects',- createHash('sha256').update(instance.instanceId).digest('hex').slice(0, 20),- );+ let buildLeaseHeartbeatError: unknown = null;+ let stopBuildLeaseHeartbeat: (() => void) | null = null;+ const expectedArch = process.arch === 'x64' ? 'x86_64' : 'arm64';+ let ownedBuildCacheKey: string | null = null;+ let derivedDataPath: string | null = null;+ let clonedSourcePackagesDirPath: string | null = null;try {+ // A build can legitimately outlive the one-minute control lease.+ // Keep the admitted route alive while the Host owns this build;+ // a replaced generation/lease still cancels the operation instead+ // of being silently renewed under different authority.+ actor.heartbeat(route);+ stopBuildLeaseHeartbeat = scheduleBuildLeaseHeartbeat(() => {+ if (activeBuild.controller.signal.aborted || buildLeaseHeartbeatError) return;+ try {+ actor.heartbeat(route);+ } catch (error) {+ buildLeaseHeartbeatError = error;+ activeBuild.controller.abort();+ }+ });+ // Resolve the project before any cache I/O. Equivalent spellings+ // (`Demo.xcodeproj`, `./Demo.xcodeproj`, absolute paths, or the+ // implicit single-container selection) must share one identity,+ // while an invalid container must not create empty cache trees.+ const inspectedProject = projectBuilder.inspect+ ? await projectBuilder.inspect(instance.worktreeRoot, containerPath)+ : null;+ if (disposePromise) throw new IOSSimulatorHostDisposedError();+ if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;+ if (activeBuild.controller.signal.aborted) {+ throw new IOSSimulatorInstanceError(+ 'MUTATION_CANCELLED',+ 'The app build was cancelled because its simulator session ended.',+ true,+ );+ }+ actor.assertRoute(route);+ const canonicalWorktreeRoot = inspectedProject?.worktreeRoot ?? instance.worktreeRoot;+ const canonicalContainerPath = inspectedProject+ ? (inspectedProject.containerPath ?? undefined)+ : containerPath;+ const containerIdentity = inspectedProject+ ? `${inspectedProject.kind}\0${+ inspectedProject.containerPath ?? inspectedProject.projectRoot+ }`+ : (containerPath ?? '');+ // Share DerivedData + SPM checkouts across sessions for the same+ // canonical worktree+arch+container, so repeated builds are+ // incremental instead of re-cloning and recompiling per session.+ const buildCacheKey = createHash('sha256')+ .update(canonicalWorktreeRoot)+ .update('\0')+ .update(expectedArch)+ .update('\0')+ .update(containerIdentity)+ .digest('hex')+ .slice(0, 20);+ if (activeBuildCacheKeys.has(buildCacheKey)) {+ throw new IOSSimulatorInstanceError(+ 'DEVICE_BUSY',+ 'Another simulator is already building this worktree for the same architecture.',+ true,+ );+ }+ activeBuildCacheKeys.add(buildCacheKey);+ ownedBuildCacheKey = buildCacheKey;+ derivedDataPath = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'projects',+ buildCacheKey,+ );+ clonedSourcePackagesDirPath = path.join(+ app.getPath('userData'),+ 'ios-simulator',+ 'spm',+ buildCacheKey,+ );+ await Promise.all([+ touchIOSSimulatorBuildCacheLastUsed(derivedDataPath),+ touchIOSSimulatorBuildCacheLastUsed(clonedSourcePackagesDirPath),+ ]).catch(() => undefined);let built: IOSSimulatorProjectBuildResult;try {built = await projectBuilder.build({- worktreeRoot: instance.worktreeRoot,+ worktreeRoot: canonicalWorktreeRoot,derivedDataPath,- containerPath: readOptionalString(args, 'containerPath', 4_096),+ simulatorUdid: instance.simulatorUdid,+ expectedArch,+ clonedSourcePackagesDirPath,+ containerPath: canonicalContainerPath,scheme: typeof args.scheme === 'string' ? args.scheme : undefined,signal: activeBuild.controller.signal,});@@ -5644,6 +6226,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I);throw new IOSSimulatorHostDisposedError();}+ if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;if (activeBuild.controller.signal.aborted) {throw new IOSSimulatorInstanceError('MUTATION_CANCELLED',@@ -5665,6 +6248,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iawait discardManagedBuildResultBundle(built.resultBundlePath ?? null);throw new IOSSimulatorHostDisposedError();}+ if (buildLeaseHeartbeatError) {+ await discardManagedBuildResultBundle(built.resultBundlePath ?? null);+ throw buildLeaseHeartbeatError;+ }if (activeBuild.controller.signal.aborted) {await discardManagedBuildResultBundle(built.resultBundlePath ?? null);throw new IOSSimulatorInstanceError(@@ -5682,63 +6269,127 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IoutputTruncated: built.outputTruncated,});assertHostActive();- let artifact: IOSSimulatorAppArtifact;+ // Copy the product out of mutable DerivedData into a per-build+ // immutable location. Under the shared worktree cache a later build+ // would otherwise overwrite the same `.app` path and corrupt a+ // still-pending artifact handle (install would ship the newer build).+ const immutableArtifactRoot = path.join(derivedDataPath, 'artifacts');+ const immutableAppPath = path.join(immutableArtifactRoot, `${randomUUID()}.app`);try {+ await mkdir(immutableArtifactRoot, { recursive: true });+ await cp(built.appPath, immutableAppPath, {+ recursive: true,+ verbatimSymlinks: true,+ });+ } catch (error) {+ // A partially completed copy must not survive as an orphan, and+ // the diagnostics already captured for this build must remain+ // reachable to the caller even when managed artifact storage+ // itself fails.+ await discardArtifactCopy(immutableAppPath);+ if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {+ throw new IOSSimulatorHostDisposedError();+ }+ if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;+ if (activeBuild.controller.signal.aborted) {+ throw new IOSSimulatorInstanceError(+ 'MUTATION_CANCELLED',+ 'The app build was cancelled because its simulator session ended.',+ true,+ );+ }+ return buildFailureWithDiagnostics(+ new IOSSimulatorInstanceError(+ 'APP_ARTIFACT_INVALID',+ 'The built app could not be copied into managed storage.',+ ),+ sessionId,+ diagnostics,+ );+ }+ let artifactRegistered = false;+ try {+ let artifact: IOSSimulatorAppArtifact;try {+ await assertIOSSimulatorArtifactSymlinksContained(immutableAppPath);artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot,- built.appPath,- undefined,+ immutableAppPath,+ derivedDataPath,activeBuild.controller.signal,);} catch (error) {- if (- !(error instanceof IOSSimulatorInstanceError) ||- error.code !== 'APP_ARTIFACT_INVALID'- ) {- throw error;+ if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {+ throw new IOSSimulatorHostDisposedError();}- artifact = await appLifecycle.inspectArtifact(- instance.worktreeRoot,- built.appPath,- derivedDataPath,- activeBuild.controller.signal,- );+ if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;+ if (activeBuild.controller.signal.aborted) {+ throw new IOSSimulatorInstanceError(+ 'MUTATION_CANCELLED',+ 'The app build was cancelled because its simulator session ended.',+ true,+ );+ }+ return buildFailureWithDiagnostics(error, sessionId, diagnostics);}- } catch (error) {- if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {- throw new IOSSimulatorHostDisposedError();+ assertHostActive();+ if (buildLeaseHeartbeatError) throw buildLeaseHeartbeatError;+ if (activeBuild.controller.signal.aborted) {+ throw new IOSSimulatorInstanceError(+ 'MUTATION_CANCELLED',+ 'The app build was cancelled because its simulator session ended.',+ true,+ );}- return buildFailureWithDiagnostics(error, sessionId, diagnostics);- }- assertHostActive();- if (activeBuild.controller.signal.aborted) {- throw new IOSSimulatorInstanceError(- 'MUTATION_CANCELLED',- 'The app build was cancelled because its simulator session ended.',- true,- );- }- actor.assertRoute(route);- appArtifacts.set(artifact.artifactId, {- instanceId: instance.instanceId,- projectKind: built.kind,- artifact,- });- return {- ok: true,- data: {- artifact: {- artifactId: artifact.artifactId,- bundleId: artifact.bundleId,- projectKind: built.kind,- scheme: built.scheme,- createdAt: artifact.createdAt,+ actor.assertRoute(route);+ // Bound retained artifacts per instance so iterative builds+ // cannot accumulate one immutable .app per build (which+ // liveArtifactCacheKeys would then keep from being swept).+ // Skip copies an in-flight install is still reading; the bound+ // may temporarily exceed MAX until those pins drop.+ evictUnpinnedArtifactsForInstance(instance.instanceId, 1);+ appArtifacts.set(artifact.artifactId, {+ instanceId: instance.instanceId,+ projectKind: built.kind,+ artifact,+ immutableAppPath,+ installed: false,+ });+ artifactRegistered = true;+ return {+ ok: true,+ data: {+ artifact: {+ artifactId: artifact.artifactId,+ bundleId: artifact.bundleId,+ projectKind: built.kind,+ scheme: built.scheme,+ createdAt: artifact.createdAt,+ },+ diagnostics,},- diagnostics,- },- };+ };+ } finally {+ // Reclaim the copy on any pre-registration exit (inspection+ // failure, disposal, cancellation, or a lost route). Only a+ // registered artifact keeps its immutable copy.+ if (!artifactRegistered) void discardArtifactCopy(immutableAppPath);+ }} finally {+ stopBuildLeaseHeartbeat?.();+ if (derivedDataPath && clonedSourcePackagesDirPath) {+ await Promise.all([+ touchIOSSimulatorBuildCacheLastUsed(derivedDataPath),+ touchIOSSimulatorBuildCacheLastUsed(clonedSourcePackagesDirPath),+ ]).catch(() => undefined);+ }+ if (ownedBuildCacheKey) {+ activeBuildCacheKeys.delete(ownedBuildCacheKey);+ // Cache reclaim is opportunistic and must not extend build_app's+ // critical path. Keep one lifecycle-owned sweep in flight; its+ // live skip callback still protects builds admitted mid-sweep.+ scheduleBuildCachePrune();+ }finishBuild(instance.instanceId, activeBuild);}}@@ -5841,14 +6492,25 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iif (name === 'install_app') {const route = readMutationRoute(sessionId, args);const artifactId = readString(args, 'artifactId');- await runHostMutation(route, context, async (instance, signal) => {- requireControlGrant(instance, context);- await appLifecycle.installExact(- instance.simulatorUdid,- requireArtifact(instance, artifactId),- signal,- );- });+ // Pin before awaiting the mutation queue: a concurrent build can+ // finish (and evict) while this call is still waiting on+ // actor.runMutation. Lookup+pin is sync, so it cannot interleave+ // with the eviction loop on this thread.+ requireAndPinArtifact(actor.assertRoute(route), artifactId);+ try {+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ await appLifecycle.installExact(+ instance.simulatorUdid,+ requireArtifact(instance, artifactId),+ signal,+ );+ const stored = appArtifacts.get(artifactId);+ if (stored) stored.installed = true;+ });+ } finally {+ unpinArtifact(artifactId);+ }return { ok: true, data: { artifactId, installed: true } };}if (name === 'launch_app') {@@ -5858,36 +6520,48 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iif (!Array.isArray(launchArgs) || launchArgs.some((value) => typeof value !== 'string')) {throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'args must be a string array');}- await runHostMutation(route, context, async (instance, signal) => {- requireControlGrant(instance, context);- const stored = appArtifacts.get(artifactId);- if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {- await projectBuilder.validateLaunch(- stored.artifact.worktreeRoot,+ // Pin before awaiting the mutation queue (same as install_app): a+ // concurrent build can evict the artifact while this call waits.+ requireAndPinArtifact(actor.assertRoute(route), artifactId);+ try {+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const stored = appArtifacts.get(artifactId);+ if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {+ await projectBuilder.validateLaunch(+ stored.artifact.worktreeRoot,+ instance.simulatorUdid,+ signal,+ );+ }+ await appLifecycle.launchExact(instance.simulatorUdid,+ requireArtifact(instance, artifactId),+ launchArgs,signal,);- }- await appLifecycle.launchExact(- instance.simulatorUdid,- requireArtifact(instance, artifactId),- launchArgs,- signal,- );- screenMaps.invalidate(instance.instanceId);- });+ screenMaps.invalidate(instance.instanceId);+ });+ } finally {+ unpinArtifact(artifactId);+ }requestViewerFocus(sessionId, route.instanceId);return { ok: true, data: { artifactId, launched: true } };}if (name === 'terminate_app') {const route = readMutationRoute(sessionId, args);const artifactId = readString(args, 'artifactId');- await runHostMutation(route, context, async (instance, signal) => {- requireControlGrant(instance, context);- const artifact = requireArtifact(instance, artifactId);- await appLifecycle.terminateExact(instance.simulatorUdid, artifact.bundleId, signal);- screenMaps.invalidate(instance.instanceId);- });+ requireAndPinArtifact(actor.assertRoute(route), artifactId);+ try {+ await runHostMutation(route, context, async (instance, signal) => {+ requireControlGrant(instance, context);+ const artifact = requireArtifact(instance, artifactId);+ await appLifecycle.terminateExact(instance.simulatorUdid, artifact.bundleId, signal);+ screenMaps.invalidate(instance.instanceId);+ });+ } finally {+ unpinArtifact(artifactId);+ }return { ok: true, data: { artifactId, terminated: true } };}if (name === 'open_url') {@@ -6171,10 +6845,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iif (environment.ready && instances.length === 0) {// Advertised names only: a recommendation the model cannot find in// list_tools sends it back to the ambiguous superseded name.- recommendedActions.push(- 'list_simulator_devices',- 'create_instance_or_attach_device',- );+ recommendedActions.push('list_simulator_devices', 'create_instance_or_attach_device');}if (instances.some((entry) => !entry.running)) recommendedActions.push('start_instance');if (@@ -6379,6 +7050,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst lifecycleStarts = actor.cancelAllLifecycleStarts();const mutations = actor.cancelAllMutations();const builds = [...activeBuilds.values()];+ const buildCachePrune = buildCachePrunePromise;+ const artifactCopiesReconcile = artifactCopiesReconcilePromise;for (const build of builds) build.controller.abort();// Close the recording start gate immediately, before waiting for a// potentially slow xcodebuild process to acknowledge cancellation.@@ -6392,6 +7065,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IlifecycleStarts,mutations,...builds.map((build) => build.settled),+ ...(buildCachePrune ? [buildCachePrune] : []),+ ...(artifactCopiesReconcile ? [artifactCopiesReconcile] : []),Promise.allSettled(buildDiagnosticReads).then(() => undefined),]);clearVisualBaselines();@@ -6400,7 +7075,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IremoveBuildDiagnostic(diagnosticsId, diagnostic),),);+ for (const stored of appArtifacts.values()) {+ void discardArtifactCopy(stored.immutableAppPath);+ }appArtifacts.clear();+ pinnedArtifactIds.clear();+ // Await every in-flight removal (the ones started above plus any+ // eviction that was still running when quit began).+ await Promise.all([...inFlightArtifactRemovals]);for (const timer of idleRecycleTimers.values()) clearTimeout(timer);idleRecycleTimers.clear();const instances = actor.listAll();@@ -6504,10 +7186,8 @@ async function readPassiveIOSSimulatorPluginStatus(}try {const getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;- const isOwnerBoundaryPending =- options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;- const isHostClosing =- options.isHostClosing ?? (() => defaultIOSSimulatorRuntimeClosing);+ const isOwnerBoundaryPending = options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;+ const isHostClosing = options.isHostClosing ?? (() => defaultIOSSimulatorRuntimeClosing);if (isHostClosing() || isOwnerBoundaryPending()) {return {ok: false,@@ -6527,11 +7207,7 @@ async function readPassiveIOSSimulatorPluginStatus(};});const session = await getSession(normalizedSessionId);- if (- isHostClosing() ||- isOwnerBoundaryPending() ||- getOwnerScopeKey() !== ownerScopeKey- ) {+ if (isHostClosing() || isOwnerBoundaryPending() || getOwnerScopeKey() !== ownerScopeKey) {return {ok: false,errorCode: 'IOS_SIMULATOR_HOST_ERROR',@@ -6555,11 +7231,7 @@ async function readPassiveIOSSimulatorPluginStatus(const environment = options.inspectEnvironment? projectPluginEnvironment(await options.inspectEnvironment()): await readPassivePluginEnvironment();- if (- isHostClosing() ||- isOwnerBoundaryPending() ||- getOwnerScopeKey() !== ownerScopeKey- ) {+ if (isHostClosing() || isOwnerBoundaryPending() || getOwnerScopeKey() !== ownerScopeKey) {return {ok: false,errorCode: 'IOS_SIMULATOR_HOST_ERROR',@@ -6654,12 +7326,7 @@ export function initializeIOSSimulatorHost(): IOSSimulatorHost {const pendingCreateEvidence = createDefaultPendingCreateEvidence(registry);const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry, pendingCreateEvidence);const persistedActor = createDefaultActor(lifecycle, registry);- return installDefaultIOSSimulatorHost(- lifecycle,- persistedActor,- registry,- pendingCreateEvidence,- );+ return installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry, pendingCreateEvidence);}function currentIOSSimulatorHost(): IOSSimulatorHost | null {@@ -6805,6 +7472,14 @@ export async function reconcilePersistedIOSSimulatorOwnership(const persistedInstances = registry.loadSync();const pendingCreateEvidence = createDefaultPendingCreateEvidence(registry);if (persistedInstances.length === 0 && !pendingCreateEvidence.isArmed()) {+ // Artifact copies are filesystem-owned state, independent of the+ // persisted simulator bindings. A crash can leave them behind even+ // after the last binding is removed, so reclaim stale copies without+ // installing a Host or probing CoreSimulator on a never-used profile.+ await reconcileOrphanedIOSSimulatorArtifactCopies(+ path.join(app.getPath('userData'), 'ios-simulator', 'projects'),+ IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS,+ );// Nothing owned and no interrupted create: sweeping here would spawn// xcrun on a profile that never used the simulator, which is exactly the// startup-time Xcode permission prompt users report.@@ -6819,6 +7494,14 @@ export async function reconcilePersistedIOSSimulatorOwnership(await recoverProfilePendingCreatesAtStartup(lifecycle, persistedInstances, {evidence: pendingCreateEvidence,});+ // Pending-create recovery intentionally releases the lease without+ // installing a Host. Artifact copies are independent filesystem state,+ // so this startup path must still reclaim stale copies left by a prior+ // crashed Host before returning.+ await reconcileOrphanedIOSSimulatorArtifactCopies(+ path.join(app.getPath('userData'), 'ios-simulator', 'projects'),+ IOS_SIMULATOR_BUILD_CACHE_MAX_AGE_MS,+ );registry.releaseWriterSync();return;}@@ -6954,9 +7637,7 @@ export function getIOSSimulatorMcpDeps(options: IOSSimulatorMcpDepsOptions = {},): IOSSimulatorMcpDeps {const getHost = (): IOSSimulatorHost => options.host ?? initializeIOSSimulatorHost();- const resolveAccess = (- context?: IOSSimulatorMcpCallContext,- ): IOSSimulatorMcpAccessDecision => {+ const resolveAccess = (context?: IOSSimulatorMcpCallContext): IOSSimulatorMcpAccessDecision => {const decision = options.resolveAccess?.(context);if (decision) return decision;if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled(context)) {diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex df5facb91e..345c2a5b0b 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -167,6 +167,7 @@ export type IpcErrorCode =| 'AMBIGUOUS_XCODE_PROJECT'| 'APP_BUILD_FAILED'| 'APP_ARTIFACT_INVALID'+ | 'APP_ARCH_MISMATCH'| 'APP_INSTALL_FAILED'| 'APP_LAUNCH_FAILED'| 'METRO_NOT_READY'@@ -376,6 +377,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['AMBIGUOUS_XCODE_PROJECT','APP_BUILD_FAILED','APP_ARTIFACT_INVALID',+ 'APP_ARCH_MISMATCH','APP_INSTALL_FAILED','APP_LAUNCH_FAILED','METRO_NOT_READY',diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjsindex 21591ab757..f29f589169 100644--- a/apps/mobile/scripts/sim-rebuild.mjs+++ b/apps/mobile/scripts/sim-rebuild.mjs@@ -7,9 +7,10 @@// 为什么不用 `expo run:ios`:Xcode 26.5 上 expo 的 devicectl / 设备解析坏掉,// xcodebuild 枚举不出具体模拟器,会报// `xcodebuild: error: Unable to find a destination matching ... { id:<udid> }`。-// 这里改用 `generic/platform=iOS Simulator` 通用目标编译(不需要枚举具体设备),-// 再用 `simctl` 把产物装到当前 booted 的模拟器。架构交给 Pods/Xcode 决定,-// 避免覆盖原生 SDK 自己声明的 simulator exclusions。+// 日常独立调用默认用 `generic/platform=iOS Simulator` 通用目标编译(不需要枚举+// 具体设备)。Cindy Host 会把 `--udid` 与 `--build-only` 一起传入,让 xcodebuild+// 绑定精确 destination;后续安装和启动由 Host 自己的精确实例生命周期完成。+// 架构交给 Pods/Xcode 决定,避免覆盖原生 SDK 自己声明的 simulator exclusions。//// 两个提速机制(2026-07 加,背景:每任务一个新 worktree 的工作流让"从零冷构建"// 成为高频成本,一次约 12 分钟;外加一次 pod CDN 挂死 20 分钟的事故):@@ -34,6 +35,8 @@// node scripts/sim-rebuild.mjs --force-build # 跳过 fingerprint 产物缓存,强制完整重编// node scripts/sim-rebuild.mjs --build-only # 只构建 + 入产物缓存,不装/不启动模拟器// #(预热缓存,或模拟器正被别的验证占用时)+// node scripts/sim-rebuild.mjs --build-only --udid <UUID>+// # Cindy Host 的精确 destination 构建路径// 或仓库根:pnpm mobile:sim:rebuild [-- --region=cn] [-- --clean] [-- --force-build] [-- --build-only]import { execFileSync, spawnSync } from 'node:child_process';@@ -79,6 +82,17 @@ const { region, passthrough } = extractMobileDevRegionArgs(process.argv.slice(2)const clean = passthrough.includes('--clean');const forceBuild = passthrough.includes('--force-build');const buildOnly = passthrough.includes('--build-only');+const simulatorUdidIndex = passthrough.indexOf('--udid');+const simulatorUdid = simulatorUdidIndex >= 0+ ? passthrough[simulatorUdidIndex + 1]?.trim().toUpperCase()+ : null;+if (+ simulatorUdidIndex >= 0+ && !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(simulatorUdid ?? '')+) {+ console.error('✗ --udid 必须是精确的 Simulator UUID。');+ process.exit(1);+}const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);if (localConfigStatus) console.log(localConfigStatus);@@ -173,12 +187,15 @@ if (!app) {}const scheme = workspace.replace(/\.xcworkspace$/, '');- console.log(`› 编译 ${scheme}(generic iOS Simulator destination)…`);+ const simulatorDestination = simulatorUdid+ ? `platform=iOS Simulator,id=${simulatorUdid}`+ : 'generic/platform=iOS Simulator';+ console.log(`› 编译 ${scheme}(${simulatorUdid ? 'exact' : 'generic'} iOS Simulator destination)…`);run('xcodebuild', ['-workspace', join(iosDir, workspace),'-scheme', scheme,'-configuration', 'Debug',- '-destination', 'generic/platform=iOS Simulator',+ '-destination', simulatorDestination,'-derivedDataPath', buildDir,'-quiet','build',diff --git a/apps/mobile/src/__tests__/simRebuildScript.test.ts b/apps/mobile/src/__tests__/simRebuildScript.test.tsindex 6aa7617091..ab7b898cb0 100644--- a/apps/mobile/src/__tests__/simRebuildScript.test.ts+++ b/apps/mobile/src/__tests__/simRebuildScript.test.ts@@ -51,4 +51,11 @@ describe('sim-rebuild script invariants', () => {expect(source).toContain('entries.slice(APP_CACHE_KEEP)');expect(source).toContain('APP_CACHE_PRUNE_MIN_AGE_MS) continue;');});++ it('uses an exact simulator destination when the Host supplies a UDID', () => {+ expect(source).toContain("passthrough.indexOf('--udid')");+ expect(source).toContain('Simulator UUID');+ expect(source).toContain('`platform=iOS Simulator,id=${simulatorUdid}`');+ expect(source).toContain("'-destination', simulatorDestination");+ });});diff --git a/packages/ios-simulator-runtime/src/instance-errors.ts b/packages/ios-simulator-runtime/src/instance-errors.tsindex 490f989630..ca92065271 100644--- a/packages/ios-simulator-runtime/src/instance-errors.ts+++ b/packages/ios-simulator-runtime/src/instance-errors.ts@@ -27,6 +27,7 @@ export const IOS_SIMULATOR_INSTANCE_ERROR_CODES = ["AMBIGUOUS_XCODE_PROJECT","APP_BUILD_FAILED","APP_ARTIFACT_INVALID",+ "APP_ARCH_MISMATCH","APP_INSTALL_FAILED","APP_LAUNCH_FAILED","METRO_NOT_READY",diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.tsindex 07dd4c0e9a..5fdd37fab2 100644--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts@@ -19,6 +19,7 @@ import type { IOSSimulatorCommandRunner } from "./types.js";const roots: string[] = [];const SIMULATOR_UDID = "A1B2C3D4-E5F6-47A8-9B0C-D1E2F3A4B5C6";+const RESOLVED_FILE_PIN = "-onlyUsePackageVersionsFromResolvedFile";afterEach(async () => {await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),@@ -44,6 +45,51 @@ describe("IOSSimulatorProjectBuilder", () => {});});+ it("binds a Cindy Mobile build to the exact simulator destination", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const mobile = path.join(root, "apps", "mobile");+ const appPath = path.join(+ mobile,+ "ios",+ "build",+ "Build",+ "Products",+ "Debug-iphonesimulator",+ "Cindy.app",+ );+ await mkdir(appPath, { recursive: true });+ await writeFile(path.join(mobile, "app.config.js"), "export default {};");+ await writeFile(+ path.join(mobile, "package.json"),+ JSON.stringify({ name: "mobile" }),+ );+ const run = vi.fn(async () => ({ stdout: "", stderr: "", exitCode: 0 }));++ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID.toLowerCase(),+ }),+ ).resolves.toMatchObject({+ kind: "cindy-mobile",+ appPath: await realpath(appPath),+ });+ expect(run).toHaveBeenCalledWith(+ "pnpm",+ [+ "mobile:sim:rebuild",+ "--",+ "--force-build",+ "--build-only",+ "--udid",+ SIMULATOR_UDID,+ ],+ expect.objectContaining({ cwd: await realpath(root) }),+ );+ });+it("reuses the repository Metro ownership check for Cindy Mobile launch", async () => {const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));roots.push(root);@@ -240,6 +286,7 @@ describe("IOSSimulatorProjectBuilder", () => {worktreeRoot: root,containerPath: "Examples/Selected.xcworkspace",derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,}),).resolves.toMatchObject({kind: "xcode-workspace",@@ -310,6 +357,7 @@ describe("IOSSimulatorProjectBuilder", () => {builder.build({worktreeRoot: root,derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,}),).rejects.toMatchObject({code: "AMBIGUOUS_XCODE_PROJECT",@@ -317,7 +365,25 @@ describe("IOSSimulatorProjectBuilder", () => {});});- it("builds one generic shared scheme and resolves its app product", async () => {+ it("rejects a non-exact simulator destination before invoking Xcode", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>();++ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: "booted",+ }),+ ).rejects.toMatchObject({+ code: "INVALID_ARGUMENT",+ message: "simulatorUdid must be an exact simulator UUID",+ });+ expect(run).not.toHaveBeenCalled();+ });++ it("builds one shared scheme for the exact simulator and resolves its app product", async () => {const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));roots.push(root);const workspace = path.join(root, "Example.xcworkspace");@@ -361,6 +427,7 @@ describe("IOSSimulatorProjectBuilder", () => {}).build({worktreeRoot: root,derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID.toLowerCase(),});expect(result).toMatchObject({kind: "xcode-workspace",@@ -371,7 +438,7 @@ describe("IOSSimulatorProjectBuilder", () => {"xcodebuild",expect.arrayContaining(["-destination",- "generic/platform=iOS Simulator",+ `platform=iOS Simulator,id=${SIMULATOR_UDID}`,"build",]),expect.any(Object),@@ -429,6 +496,7 @@ describe("IOSSimulatorProjectBuilder", () => {const input = {worktreeRoot: root,derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,};const first = await builder.build(input);@@ -469,6 +537,7 @@ describe("IOSSimulatorProjectBuilder", () => {.build({worktreeRoot: root,derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,}).then(() => null,@@ -529,6 +598,7 @@ describe("IOSSimulatorProjectBuilder", () => {}).build({worktreeRoot: root,derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,signal: controller.signal,});await vi.waitFor(() => expect(resultBundlePath).not.toBe(""));@@ -549,6 +619,63 @@ describe("IOSSimulatorProjectBuilder", () => {});});+ it("removes the xcresult when cancellation interrupts final build settings", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ await mkdir(workspace);+ const controller = new AbortController();+ let resultBundlePath = "";+ let finalSettingsStarted = false;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args, options) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("build")) {+ const resultBundleIndex = args.indexOf("-resultBundlePath");+ resultBundlePath = args[resultBundleIndex + 1]!;+ await mkdir(resultBundlePath, { recursive: true });+ return { stdout: "build succeeded", stderr: "", exitCode: 0 };+ }+ if (args.includes("-showBuildSettings")) {+ finalSettingsStarted = true;+ await new Promise<void>((resolve) => {+ if (options?.signal?.aborted) resolve();+ else+ options?.signal?.addEventListener("abort", () => resolve(), {+ once: true,+ });+ });+ return { stdout: "", stderr: "", exitCode: null };+ }+ throw new Error("unexpected xcodebuild invocation");+ },+ );+ const buildPromise = new IOSSimulatorProjectBuilder({+ commandRunner: { run },+ }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ signal: controller.signal,+ });+ await vi.waitFor(() => expect(finalSettingsStarted).toBe(true));++ controller.abort();++ await expect(buildPromise).rejects.toMatchObject({+ code: "MUTATION_CANCELLED",+ });+ await expect(realpath(resultBundlePath)).rejects.toMatchObject({+ code: "ENOENT",+ });+ });+it("cancels an in-flight xcresult read through the command runner", async () => {const controller = new AbortController();const run = vi.fn(@@ -596,4 +723,699 @@ describe("IOSSimulatorProjectBuilder", () => {}),);});++ it("retries an xcresult read with the explicit legacy object command when Xcode requires it", async () => {+ const run = vi.fn(async (_command: string, args: readonly string[]) => {+ if (args.includes("--legacy")) {+ return {+ stdout: '{"issues":[]}',+ stderr: "",+ exitCode: 0,+ };+ }+ return {+ stdout: "",+ stderr:+ "Error: This command is deprecated and will be removed in a future release, --legacy flag is required to use it.",+ exitCode: 64,+ };+ });+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });+ const resultBundlePath = "/tmp/CindyBuild-xcode-26.xcresult";++ await expect(builder.readXcresult(resultBundlePath, 1024)).resolves.toBe(+ '{"issues":[]}\n',+ );+ expect(run).toHaveBeenNthCalledWith(+ 1,+ "xcrun",+ ["xcresulttool", "get", "--path", resultBundlePath, "--format", "json"],+ expect.objectContaining({ maxBufferBytes: 1024 }),+ );+ expect(run).toHaveBeenNthCalledWith(+ 2,+ "xcrun",+ [+ "xcresulttool",+ "get",+ "object",+ "--legacy",+ "--path",+ resultBundlePath,+ "--format",+ "json",+ ],+ expect.objectContaining({ maxBufferBytes: 1024 }),+ );+ });++ it("does not retry an unrelated xcresult read failure", async () => {+ const run = vi.fn(async () => ({+ stdout: "",+ stderr: "Error: the result bundle is unreadable",+ exitCode: 1,+ }));+ const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });++ await expect(+ builder.readXcresult("/tmp/CindyBuild-unreadable.xcresult"),+ ).rejects.toMatchObject({ code: "APP_BUILD_FAILED" });+ expect(run).toHaveBeenCalledOnce();+ });++ it("pre-flights the target architecture before building when arm64 is excluded", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ await mkdir(workspace);+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ ARCHS: "arm64 x86_64",+ EXCLUDED_ARCHS: "arm64",+ TARGET_BUILD_DIR: path.join(root, "derived", "Build"),+ WRAPPER_NAME: "Example.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ }),+ ).rejects.toMatchObject({+ code: "APP_ARCH_MISMATCH",+ message: expect.stringMatching(+ /app target would produce architectures \[x86_64\].*needs arm64.*ARCHS and EXCLUDED_ARCHS/s,+ ),+ });+ // The build command must never run when the preflight rejects.+ expect(run.mock.calls.some(([, args]) => args.includes("build"))).toBe(+ false,+ );+ });++ it("proceeds to build when the target architecture is available", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ const clonedSourcePackagesDirPath = path.join(root, "spm");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ ARCHS: "arm64 x86_64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ WRAPPER_NAME: "Example.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ const inspectionTimeoutMs = 5 * 60_000;+ const buildTimeoutMs = 30 * 60_000;+ const result = await new IOSSimulatorProjectBuilder({+ commandRunner: { run },+ inspectionTimeoutMs,+ buildTimeoutMs,+ }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ clonedSourcePackagesDirPath,+ });+ expect(result).toMatchObject({ scheme: "Example" });+ const xcodeCalls = run.mock.calls.map(([, args]) => args);+ expect(xcodeCalls).toHaveLength(4);+ expect(xcodeCalls.every((args) => args.includes(RESOLVED_FILE_PIN))).toBe(+ true,+ );+ expect(+ xcodeCalls.every((args) => {+ const index = args.indexOf("-clonedSourcePackagesDirPath");+ return index >= 0 && args[index + 1] === clonedSourcePackagesDirPath;+ }),+ ).toBe(true);+ expect(xcodeCalls[0]).toEqual(expect.arrayContaining(["-list", "-json"]));+ expect(xcodeCalls[1]).toEqual(+ expect.arrayContaining(["-showBuildSettings", "-json"]),+ );+ expect(xcodeCalls[2]).toContain("build");+ expect(xcodeCalls[3]).toEqual(+ expect.arrayContaining(["-showBuildSettings", "-json"]),+ );+ for (const [, args, options] of run.mock.calls) {+ expect(options?.timeoutMs).toBe(+ args.includes("build") ? buildTimeoutMs : inspectionTimeoutMs,+ );+ }+ });++ it("disables the resolved-file pin for the remaining build after Xcode 26.5 rejects -list", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ let listAttempts = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ listAttempts += 1;+ if (args.includes(RESOLVED_FILE_PIN)) {+ return {+ stdout: "",+ stderr:+ "xcodebuild: error: a resolved file is required when automatic dependency resolution is disabled and should be placed at /tmp/Example.xcworkspace/xcshareddata/swiftpm/Package.resolved",+ exitCode: 74,+ };+ }+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ ARCHS: "arm64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ WRAPPER_NAME: "Example.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );++ await new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ });++ expect(listAttempts).toBe(2);+ expect(run.mock.calls[0]![1]).toContain(RESOLVED_FILE_PIN);+ expect(run.mock.calls[1]![1]).not.toContain(RESOLVED_FILE_PIN);+ expect(+ run.mock.calls+ .slice(1)+ .every(([, args]) => !args.includes(RESOLVED_FILE_PIN)),+ ).toBe(true);+ expect(run.mock.calls.map(([, args]) => args)).toEqual([+ expect.arrayContaining(["-list", "-json", RESOLVED_FILE_PIN]),+ expect.arrayContaining(["-list", "-json"]),+ expect.arrayContaining(["-showBuildSettings", "-json"]),+ expect.arrayContaining(["build"]),+ expect.arrayContaining(["-showBuildSettings", "-json"]),+ ]);+ });++ it("retries a missing Package.resolved build with a fresh xcresult path", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ ARCHS: "arm64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ WRAPPER_NAME: "Example.app",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ const resultBundleIndex = args.indexOf("-resultBundlePath");+ if (args.includes("build") && resultBundleIndex >= 0) {+ await mkdir(args[resultBundleIndex + 1]!, { recursive: true });+ }+ if (args.includes("build") && args.includes(RESOLVED_FILE_PIN)) {+ return {+ stdout: "",+ stderr:+ "xcodebuild: error: a resolved file is required when automatic dependency resolution is disabled and should be placed at /tmp/Example.xcworkspace/xcshareddata/swiftpm/Package.resolved",+ exitCode: 65,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ await new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ });+ const buildCalls = run.mock.calls.filter(([, args]) =>+ args.includes("build"),+ );+ expect(buildCalls).toHaveLength(2);+ expect(buildCalls[0]![1]).toContain(RESOLVED_FILE_PIN);+ expect(buildCalls[1]![1]).not.toContain(RESOLVED_FILE_PIN);+ const firstResultBundleIndex =+ buildCalls[0]![1].indexOf("-resultBundlePath");+ const secondResultBundleIndex =+ buildCalls[1]![1].indexOf("-resultBundlePath");+ expect(firstResultBundleIndex).toBeGreaterThanOrEqual(0);+ expect(secondResultBundleIndex).toBeGreaterThanOrEqual(0);+ expect(buildCalls[1]![1][secondResultBundleIndex + 1]).not.toBe(+ buildCalls[0]![1][firstResultBundleIndex + 1],+ );+ expect(+ run.mock.calls+ .slice(run.mock.calls.indexOf(buildCalls[1]!))+ .every(([, args]) => !args.includes(RESOLVED_FILE_PIN)),+ ).toBe(true);+ });++ it("does not retry when a compile failure only mentions Package.resolved", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ await mkdir(path.join(root, "Example.xcworkspace"));+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("build")) {+ return {+ stdout: "Compile Swift source files",+ stderr:+ "error: cannot find 'Resolved' in scope\nnote: see Package.resolved for locked versions",+ exitCode: 65,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ }),+ ).rejects.toMatchObject({ code: "APP_BUILD_FAILED" });+ expect(+ run.mock.calls.filter(([, args]) => args.includes("build")),+ ).toHaveLength(1);+ });++ it("does not retry when Package.resolved and a missing-file error are on different lines", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ await mkdir(path.join(root, "Example.xcworkspace"));+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("build")) {+ return {+ stdout: "note: resolved versions are listed in Package.resolved",+ stderr:+ "error: 'Header.h' file not found\nNo such file or directory: Foo.swift",+ exitCode: 65,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ }),+ ).rejects.toMatchObject({ code: "APP_BUILD_FAILED" });+ expect(+ run.mock.calls.filter(([, args]) => args.includes("build")),+ ).toHaveLength(1);+ });++ it("does not retry when unable to load a different resolved file", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ await mkdir(path.join(root, "Example.xcworkspace"));+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("build")) {+ return {+ stdout: "",+ stderr:+ "error: unable to load the resolved file of Foo.xcframework",+ exitCode: 65,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ }),+ ).rejects.toMatchObject({ code: "APP_BUILD_FAILED" });+ expect(+ run.mock.calls.filter(([, args]) => args.includes("build")),+ ).toHaveLength(1);+ });++ it("selects the primary application when a scheme builds auxiliary app products", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ // App Clip and Watch targets also produce `.app` wrappers. Both the+ // architecture preflight and final artifact lookup must select the+ // primary iOS application by PRODUCT_TYPE, not wrapper extension.+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ PRODUCT_TYPE: "com.apple.product-type.app-extension",+ WRAPPER_NAME: "ExampleExtension.appex",+ ARCHS: "x86_64",+ },+ },+ {+ buildSettings: {+ PRODUCT_TYPE:+ "com.apple.product-type.application.on-demand-install-capable",+ WRAPPER_NAME: "ExampleClip.app",+ ARCHS: "x86_64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ },+ },+ {+ buildSettings: {+ PRODUCT_TYPE: "com.apple.product-type.application.watchapp2",+ WRAPPER_NAME: "ExampleWatch.app",+ ARCHS: "x86_64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ },+ },+ {+ buildSettings: {+ PRODUCT_TYPE: "com.apple.product-type.application",+ WRAPPER_NAME: "Example.app",+ ARCHS: "arm64 x86_64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ const result = await new IOSSimulatorProjectBuilder({+ commandRunner: { run },+ }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ });+ expect(result).toMatchObject({ scheme: "Example" });+ });++ it("fails open when architecture preflight cannot identify one unique .app target", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ let settingsCalls = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ settingsCalls += 1;+ return {+ stdout: JSON.stringify(+ settingsCalls === 1+ ? [+ {+ buildSettings: {+ WRAPPER_NAME: "Example.app",+ ARCHS: "x86_64",+ },+ },+ {+ buildSettings: {+ WRAPPER_NAME: "ExampleHelper.app",+ ARCHS: "arm64",+ },+ },+ ]+ : [+ {+ buildSettings: {+ WRAPPER_NAME: "Example.app",+ TARGET_BUILD_DIR: path.dirname(appPath),+ },+ },+ ],+ ),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );++ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ }),+ ).resolves.toMatchObject({ scheme: "Example" });+ expect(run.mock.calls.some(([, args]) => args.includes("build"))).toBe(+ true,+ );+ });++ it("does not guess when a scheme contains multiple primary application targets", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const products = path.join(root, "derived", "Build");+ await mkdir(workspace);+ await mkdir(path.join(products, "Example.app"), { recursive: true });+ await mkdir(path.join(products, "ExampleAdmin.app"), { recursive: true });+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ PRODUCT_TYPE: "com.apple.product-type.application",+ WRAPPER_NAME: "Example.app",+ TARGET_BUILD_DIR: products,+ ARCHS: "x86_64",+ },+ },+ {+ buildSettings: {+ PRODUCT_TYPE: "com.apple.product-type.application",+ WRAPPER_NAME: "ExampleAdmin.app",+ TARGET_BUILD_DIR: products,+ ARCHS: "arm64",+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );++ await expect(+ new IOSSimulatorProjectBuilder({ commandRunner: { run } }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ }),+ ).rejects.toMatchObject({+ code: "APP_ARTIFACT_INVALID",+ message: "The Xcode build did not produce one unambiguous app artifact.",+ });+ // Ambiguous target selection must fail open during the architecture+ // preflight, then fail closed only after the actual build cannot identify+ // one installable product.+ expect(run.mock.calls.some(([, args]) => args.includes("build"))).toBe(+ true,+ );+ expect(+ run.mock.calls.filter(([, args]) => args.includes("-showBuildSettings")),+ ).toHaveLength(2);+ });++ it("ignores arch exclusions from targets not embedded in the app", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));+ roots.push(root);+ const workspace = path.join(root, "Example.xcworkspace");+ const appPath = path.join(root, "derived", "Build", "Example.app");+ await mkdir(workspace);+ await mkdir(appPath, { recursive: true });+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args.includes("-list")) {+ return {+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args.includes("-showBuildSettings")) {+ // 测试 bundle (.xctest) 排除 arm64 不影响主 app 的预检。+ return {+ stdout: JSON.stringify([+ {+ buildSettings: {+ WRAPPER_NAME: "ExampleTests.xctest",+ ARCHS: "arm64 x86_64",+ EXCLUDED_ARCHS: "arm64",+ },+ },+ {+ buildSettings: {+ WRAPPER_NAME: "Example.app",+ ARCHS: "arm64 x86_64",+ TARGET_BUILD_DIR: path.dirname(appPath),+ },+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ },+ );+ const result = await new IOSSimulatorProjectBuilder({+ commandRunner: { run },+ }).build({+ worktreeRoot: root,+ derivedDataPath: path.join(root, "derived"),+ simulatorUdid: SIMULATOR_UDID,+ expectedArch: "arm64",+ });+ expect(result).toMatchObject({ scheme: "Example" });+ });});diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.tsindex c922617d67..e97ef0622d 100644--- a/packages/ios-simulator-runtime/src/project-adapter.ts+++ b/packages/ios-simulator-runtime/src/project-adapter.ts@@ -31,7 +31,7 @@ export interface IOSSimulatorProjectBuildResult extends IOSSimulatorProjectDescr/** Build failure that retains bounded diagnostics without exposing raw process state. */export class IOSSimulatorProjectBuildError extends IOSSimulatorInstanceError {constructor(- code: "APP_BUILD_FAILED" | "APP_ARTIFACT_INVALID",+ code: "APP_BUILD_FAILED" | "APP_ARTIFACT_INVALID" | "APP_ARCH_MISMATCH",message: string,readonly buildLogTail: string,readonly resultBundlePath: string | null,@@ -46,6 +46,8 @@ export class IOSSimulatorProjectBuildError extends IOSSimulatorInstanceError {export interface IOSSimulatorProjectBuilderOptions {commandRunner?: IOSSimulatorCommandRunner;buildTimeoutMs?: number;+ /** Xcode project queries may resolve a cold SPM graph before compilation starts. */+ inspectionTimeoutMs?: number;/** Test/integration seam; only the shared child-process allowlist is retained. */environment?: NodeJS.ProcessEnv;}@@ -96,6 +98,55 @@ function tail(value: string, maxBytes = 32 * 1024): string {: bytes.subarray(-maxBytes).toString("utf8");}+const PACKAGE_RESOLVED_ON_LINE = /\bPackage\.resolved\b/i;+const PACKAGE_RESOLVED_UNUSABLE_ON_LINE =+ /\b(missing|does not exist|couldn't be opened|could not be opened|unable to read|no such file|unable to load the resolved file)\b/i;+const PACKAGE_RESOLVED_REQUIRED_DIAGNOSTIC =+ /\ba resolved file is required when automatic dependency resolution is disabled and should be placed at .*?\bPackage\.resolved\b/i;+const RESOLVED_FILE_PIN = "-onlyUsePackageVersionsFromResolvedFile";+const PRIMARY_APPLICATION_PRODUCT_TYPE = "com.apple.product-type.application";+const XCRESULT_LEGACY_OBJECT_REQUIRED = /--legacy flag is required/i;+const EXACT_SIMULATOR_UDID = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;++function normalizeExactSimulatorUdid(simulatorUdid: string): string {+ const exactSimulatorUdid = simulatorUdid.trim().toUpperCase();+ if (!EXACT_SIMULATOR_UDID.test(exactSimulatorUdid)) {+ throw new IOSSimulatorInstanceError(+ "INVALID_ARGUMENT",+ "simulatorUdid must be an exact simulator UUID",+ );+ }+ return exactSimulatorUdid;+}++/**+ * Retry the resolved-file pin only when one diagnostic line names+ * Package.resolved and says that file is missing or unusable. Two+ * independent whole-log matches would retry a compile/link failure that+ * mentions the lockfile on one line and a missing header on another.+ */+function isMissingPackageResolvedDiagnostic(+ result: IOSSimulatorCommandResult,+): boolean {+ const output = `${result.stdout}\n${result.stderr}`;+ if (+ output+ .split(/\r?\n/)+ .some(+ (line) =>+ PACKAGE_RESOLVED_ON_LINE.test(line) &&+ PACKAGE_RESOLVED_UNUSABLE_ON_LINE.test(line),+ )+ ) {+ return true;+ }+ // Xcode 26.5 uses this wording for every xcodebuild action, including+ // `-list` and `-showBuildSettings`. Normalize whitespace so a wrapped+ // diagnostic remains one logical record without broadening the fallback to+ // unrelated failures that merely mention Package.resolved.+ return PACKAGE_RESOLVED_REQUIRED_DIAGNOSTIC.test(output.replace(/\s+/g, " "));+}+function commandLogTail(results: readonly IOSSimulatorCommandResult[],maxBytes = 32 * 1024,@@ -134,9 +185,82 @@ function summarize(values: readonly string[], limit = 8): string {return `${bounded.join(", ")}${remaining > 0 ? `, and ${remaining} more` : ""}`;}+function entryBuildSettings(entry: unknown): Record<string, unknown> | null {+ if (typeof entry !== "object" || entry === null) return null;+ const buildSettings = (entry as { buildSettings?: unknown }).buildSettings;+ return typeof buildSettings === "object" && buildSettings !== null+ ? (buildSettings as Record<string, unknown>)+ : null;+}++/**+ * Pick the build settings of the primary installable application target.+ * App Clips and Watch apps also use `.app` wrappers, so PRODUCT_TYPE is the+ * authoritative discriminator when Xcode provides it. The wrapper-only path+ * is retained for older/synthetic output that omits PRODUCT_TYPE entirely.+ */+function primaryApplicationBuildSettings(+ parsed: unknown,+): Record<string, unknown> | null {+ if (!Array.isArray(parsed) || parsed.length === 0) return null;+ const entries = parsed.flatMap((entry) => {+ const settings = entryBuildSettings(entry);+ return settings ? [settings] : [];+ });+ const typedEntries = entries.filter(+ (settings) => typeof settings.PRODUCT_TYPE === "string",+ );+ if (typedEntries.length > 0) {+ const primaryApplications = typedEntries.filter(+ (settings) => settings.PRODUCT_TYPE === PRIMARY_APPLICATION_PRODUCT_TYPE,+ );+ return primaryApplications.length === 1 ? primaryApplications[0]! : null;+ }+ const legacyAppTargets = entries.filter((settings) => {+ const wrapper = settings.WRAPPER_NAME;+ return typeof wrapper === "string" && wrapper.endsWith(".app");+ });+ // No unique primary target could be identified. Do NOT guess: the first app+ // may be a helper whose ARCHS differs from the installable product. The+ // actual build/artifact validation remains authoritative.+ return legacyAppTargets.length === 1 ? legacyAppTargets[0]! : null;+}++/**+ * Derive the effective arch set from the installable `.app` target's own+ * `ARCHS − EXCLUDED_ARCHS`. Dependency targets (frameworks, extensions, Pods)+ * are deliberately not modeled: `-showBuildSettings` exposes no reliable+ * dependency graph, and a dependency that excludes an arch fails the build+ * itself with a linker error — a heuristic here would only add false positives+ * (test bundles, independent frameworks). Returns `null` when the output cannot+ * be trusted.+ */+function effectiveArchitectures(+ showBuildSettingsJson: string,+): string[] | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(showBuildSettingsJson);+ } catch {+ return null;+ }+ const settings = primaryApplicationBuildSettings(parsed);+ if (!settings) return null;+ const archs = String(settings.ARCHS ?? "")+ .split(/\s+/)+ .map((value) => value.trim())+ .filter(Boolean);+ const excluded = String(settings.EXCLUDED_ARCHS ?? "")+ .split(/\s+/)+ .map((value) => value.trim())+ .filter(Boolean);+ if (archs.length === 0) return null;+ return archs.filter((arch) => !excluded.includes(arch));+}+async function throwIfBuildCancelled(signal?: AbortSignal,- resultBundlePath?: string,+ resultBundlePath?: string | null,): Promise<void> {if (!signal?.aborted) return;if (resultBundlePath) {@@ -164,12 +288,14 @@ function throwIfLaunchValidationCancelled(signal?: AbortSignal): void {export class IOSSimulatorProjectBuilder {readonly #runner: IOSSimulatorCommandRunner;readonly #buildTimeoutMs: number;+ readonly #inspectionTimeoutMs: number;readonly #childEnvironment: NodeJS.ProcessEnv;constructor(options: IOSSimulatorProjectBuilderOptions = {}) {this.#runner =options.commandRunner ?? createNodeIOSSimulatorCommandRunner();this.#buildTimeoutMs = options.buildTimeoutMs ?? 30 * 60_000;+ this.#inspectionTimeoutMs = options.inspectionTimeoutMs ?? 5 * 60_000;this.#childEnvironment = createWdaChildEnvironment(options.environment ?? process.env,);@@ -284,17 +410,30 @@ export class IOSSimulatorProjectBuilder {async build(input: {worktreeRoot: string;derivedDataPath: string;+ simulatorUdid: string;containerPath?: string;scheme?: string;signal?: AbortSignal;+ /** Target simulator architecture; when set, the build is pre-flighted so an unmatchable artifact fails before compiling. */+ expectedArch?: "arm64" | "x86_64";+ /** Shared SPM checkout root; reuses cloned packages across sessions instead of re-cloning per build. */+ clonedSourcePackagesDirPath?: string;}): Promise<IOSSimulatorProjectBuildResult> {await throwIfBuildCancelled(input.signal);+ const exactSimulatorUdid = normalizeExactSimulatorUdid(input.simulatorUdid);const project = await this.inspect(input.worktreeRoot, input.containerPath);await throwIfBuildCancelled(input.signal);if (project.kind === "cindy-mobile") {const result = await this.#runner.run("pnpm",- ["mobile:sim:rebuild", "--", "--force-build", "--build-only"],+ [+ "mobile:sim:rebuild",+ "--",+ "--force-build",+ "--build-only",+ "--udid",+ exactSimulatorUdid,+ ],{cwd: project.worktreeRoot,timeoutMs: this.#buildTimeoutMs,@@ -349,25 +488,64 @@ export class IOSSimulatorProjectBuilder {const containerFlag =project.kind === "xcode-workspace" ? "-workspace" : "-project";- const list = await this.#runner.run(- "xcodebuild",- ["-list", "-json", containerFlag, project.containerPath!],+ const clonedSourcePackagesArgs = input.clonedSourcePackagesDirPath+ ? ["-clonedSourcePackagesDirPath", input.clonedSourcePackagesDirPath]+ : [];+ let useResolvedFilePin = true;+ const runXcodeWithResolvedFilePolicy = async (+ args: readonly string[],+ options: Parameters<IOSSimulatorCommandRunner["run"]>[2],+ cancellationResultBundlePath?: string | null,+ ): Promise<{+ result: IOSSimulatorCommandResult;+ attempts: IOSSimulatorCommandResult[];+ }> => {+ const attempts: IOSSimulatorCommandResult[] = [];+ const run = (pinned: boolean) =>+ this.#runner.run(+ "xcodebuild",+ pinned ? [...args, RESOLVED_FILE_PIN] : args,+ options,+ );+ let result = await run(useResolvedFilePin);+ attempts.push(result);+ await throwIfBuildCancelled(input.signal, cancellationResultBundlePath);+ if (+ useResolvedFilePin &&+ result.exitCode !== 0 &&+ isMissingPackageResolvedDiagnostic(result)+ ) {+ useResolvedFilePin = false;+ result = await run(false);+ attempts.push(result);+ await throwIfBuildCancelled(input.signal, cancellationResultBundlePath);+ }+ return { result, attempts };+ };+ const listRun = await runXcodeWithResolvedFilePolicy(+ [+ "-list",+ "-json",+ containerFlag,+ project.containerPath!,+ ...clonedSourcePackagesArgs,+ ],{cwd: project.projectRoot,- timeoutMs: 60_000,+ timeoutMs: this.#inspectionTimeoutMs,maxBufferBytes: 1024 * 1024,signal: input.signal,env: this.#childEnvironment,},);- await throwIfBuildCancelled(input.signal);+ const list = listRun.result;if (list.exitCode !== 0 || list.outputTruncated) {throw new IOSSimulatorProjectBuildError("APP_BUILD_FAILED","Xcode could not inspect the project.",- commandLogTail([list]),+ commandLogTail(listRun.attempts),null,- Boolean(list.outputTruncated),+ listRun.attempts.some((attempt) => Boolean(attempt.outputTruncated)),true,);}@@ -411,17 +589,53 @@ export class IOSSimulatorProjectBuilder {"-configuration","Debug","-destination",- "generic/platform=iOS Simulator",+ `platform=iOS Simulator,id=${exactSimulatorUdid}`,"-derivedDataPath",input.derivedDataPath,+ ...clonedSourcePackagesArgs,];- const resultBundlePath = path.join(- input.derivedDataPath,- `CindyBuild-${randomUUID()}.xcresult`,- );- const build = await this.#runner.run(+ if (input.expectedArch) {+ const archSettingsRun = await runXcodeWithResolvedFilePolicy(+ [...commonArgs, "-showBuildSettings", "-json"],+ {+ cwd: project.projectRoot,+ timeoutMs: this.#inspectionTimeoutMs,+ maxBufferBytes: 4 * 1024 * 1024,+ signal: input.signal,+ env: this.#childEnvironment,+ },+ );+ const archSettings = archSettingsRun.result;+ const effective =+ archSettings.exitCode === 0 && !archSettings.outputTruncated+ ? effectiveArchitectures(archSettings.stdout)+ : null;+ if (effective && !effective.includes(input.expectedArch)) {+ throw new IOSSimulatorProjectBuildError(+ "APP_ARCH_MISMATCH",+ `The app target would produce architectures [${effective.join(", ")}], but the target simulator needs ${input.expectedArch}. Check the app target's ARCHS and EXCLUDED_ARCHS.`,+ commandLogTail(archSettingsRun.attempts),+ null,+ archSettingsRun.attempts.some((attempt) =>+ Boolean(attempt.outputTruncated),+ ),+ );+ }+ }+ const nextResultBundlePath = () =>+ path.join(input.derivedDataPath, `CindyBuild-${randomUUID()}.xcresult`);+ let resultBundlePath = nextResultBundlePath();+ const buildAttempts: IOSSimulatorCommandResult[] = [];+ const buildArgs = (bundlePath: string, pinned: boolean) => [+ ...commonArgs,+ ...(pinned ? [RESOLVED_FILE_PIN] : []),+ "-resultBundlePath",+ bundlePath,+ "build",+ ];+ let build = await this.#runner.run("xcodebuild",- [...commonArgs, "-resultBundlePath", resultBundlePath, "build"],+ buildArgs(resultBundlePath, useResolvedFilePin),{cwd: project.projectRoot,timeoutMs: this.#buildTimeoutMs,@@ -430,7 +644,39 @@ export class IOSSimulatorProjectBuilder {env: this.#childEnvironment,},);+ buildAttempts.push(build);await throwIfBuildCancelled(input.signal, resultBundlePath);+ if (+ useResolvedFilePin &&+ build.exitCode !== 0 &&+ isMissingPackageResolvedDiagnostic(build)+ ) {+ // Only retry when Xcode says the resolved file is missing or unusable.+ // A generic compile/link failure that happens to mention Package.resolved+ // must not pay for a second full build. Always allocate a new bundle path:+ // Xcode rejects an existing -resultBundlePath, so a best-effort cleanup+ // failure must not make the fallback deterministically fail again.+ useResolvedFilePin = false;+ const failedResultBundlePath = resultBundlePath;+ resultBundlePath = nextResultBundlePath();+ await rm(failedResultBundlePath, { recursive: true, force: true }).catch(+ () => undefined,+ );+ await throwIfBuildCancelled(input.signal, resultBundlePath);+ build = await this.#runner.run(+ "xcodebuild",+ buildArgs(resultBundlePath, false),+ {+ cwd: project.projectRoot,+ timeoutMs: this.#buildTimeoutMs,+ maxBufferBytes: 1024 * 1024,+ signal: input.signal,+ env: this.#childEnvironment,+ },+ );+ buildAttempts.push(build);+ await throwIfBuildCancelled(input.signal, resultBundlePath);+ }const availableResultBundlePath = (await exists(resultBundlePath))? resultBundlePath: null;@@ -439,47 +685,51 @@ export class IOSSimulatorProjectBuilder {throw new IOSSimulatorProjectBuildError("APP_BUILD_FAILED","The Xcode project could not be built.",- commandLogTail([build]),+ commandLogTail(buildAttempts),availableResultBundlePath,- Boolean(build.outputTruncated),+ buildAttempts.some((attempt) => Boolean(attempt.outputTruncated)),true,);}- const settings = await this.#runner.run(- "xcodebuild",+ const settingsRun = await runXcodeWithResolvedFilePolicy([...commonArgs, "-showBuildSettings", "-json"],{cwd: project.projectRoot,- timeoutMs: 60_000,+ timeoutMs: this.#inspectionTimeoutMs,maxBufferBytes: 4 * 1024 * 1024,signal: input.signal,env: this.#childEnvironment,},+ resultBundlePath,);- await throwIfBuildCancelled(input.signal, resultBundlePath);+ const settings = settingsRun.result;if (settings.exitCode !== 0 || settings.outputTruncated) {throw new IOSSimulatorProjectBuildError("APP_ARTIFACT_INVALID","Xcode build settings are unavailable.",- commandLogTail([build, settings]),+ commandLogTail([build, ...settingsRun.attempts]),availableResultBundlePath,- Boolean(build.outputTruncated || settings.outputTruncated),+ Boolean(+ build.outputTruncated ||+ settingsRun.attempts.some((attempt) =>+ Boolean(attempt.outputTruncated),+ ),+ ),);}let appPaths: string[] = [];try {- const parsed = JSON.parse(settings.stdout) as Array<{- buildSettings?: Record<string, unknown>;- }>;- appPaths = parsed.flatMap((entry) => {- const directory = entry.buildSettings?.TARGET_BUILD_DIR;- const wrapper = entry.buildSettings?.WRAPPER_NAME;- return typeof directory === "string" &&- typeof wrapper === "string" &&- wrapper.endsWith(".app")+ const primarySettings = primaryApplicationBuildSettings(+ JSON.parse(settings.stdout),+ );+ const directory = primarySettings?.TARGET_BUILD_DIR;+ const wrapper = primarySettings?.WRAPPER_NAME;+ appPaths =+ typeof directory === "string" &&+ typeof wrapper === "string" &&+ wrapper.endsWith(".app")? [path.join(directory, wrapper)]: [];- });} catch {appPaths = [];}@@ -520,15 +770,7 @@ export class IOSSimulatorProjectBuilder {const project = await this.inspect(worktreeRoot);throwIfLaunchValidationCancelled(signal);if (project.kind !== "cindy-mobile") return null;- const exactSimulatorUdid = simulatorUdid.trim().toUpperCase();- if (- !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(exactSimulatorUdid)- ) {- throw new IOSSimulatorInstanceError(- "INVALID_ARGUMENT",- "simulatorUdid must be an exact simulator UUID",- );- }+ const exactSimulatorUdid = normalizeExactSimulatorUdid(simulatorUdid);const result = await this.#runner.run("pnpm",["mobile:sim:whoami", "--", "--json", "--udid", exactSimulatorUdid],@@ -584,15 +826,16 @@ export class IOSSimulatorProjectBuilder {maxBufferBytes = 2 * 1024 * 1024,signal?: AbortSignal,): Promise<string> {- const result = await this.#runner.run(+ const options = {+ timeoutMs: 60_000,+ maxBufferBytes,+ env: this.#childEnvironment,+ signal,+ };+ let result = await this.#runner.run("xcrun",["xcresulttool", "get", "--path", resultBundlePath, "--format", "json"],- {- timeoutMs: 60_000,- maxBufferBytes,- env: this.#childEnvironment,- signal,- },+ options,);if (signal?.aborted) {throw new IOSSimulatorInstanceError(@@ -601,6 +844,36 @@ export class IOSSimulatorProjectBuilder {true,);}+ if (+ result.exitCode !== 0 &&+ XCRESULT_LEGACY_OBJECT_REQUIRED.test(`${result.stdout}\n${result.stderr}`)+ ) {+ // Xcode 26.5 rejects the historical default-object spelling unless the+ // deprecated object reader is made explicit. Retry only that exact+ // compatibility diagnostic so older Xcode releases keep their existing+ // command path and unrelated xcresult failures are not doubled.+ result = await this.#runner.run(+ "xcrun",+ [+ "xcresulttool",+ "get",+ "object",+ "--legacy",+ "--path",+ resultBundlePath,+ "--format",+ "json",+ ],+ options,+ );+ if (signal?.aborted) {+ throw new IOSSimulatorInstanceError(+ "MUTATION_CANCELLED",+ "The Xcode result bundle read was cancelled because the simulator host is shutting down.",+ true,+ );+ }+ }if (result.exitCode !== 0) {throw new IOSSimulatorInstanceError("APP_BUILD_FAILED",