The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep model launch requests durable and protect starting sessions (#1157)
Dee10adc628d160
diff --git a/cli/e2e/serviceProcesses.e2e.ts b/cli/e2e/serviceProcesses.e2e.tsindex 93a8761fc..10a4c4a1d 100644--- a/cli/e2e/serviceProcesses.e2e.ts+++ b/cli/e2e/serviceProcesses.e2e.ts@@ -15,6 +15,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient, type Frame } from './harness/client.js'import { IsolatedDaemon, until } from './harness/daemon.js'+import { fakeJwt, installFakeGrid } from '../src/lib/__fixtures__/fakeGrid.js'type Engine = 'claude' | 'codex'@@ -492,6 +493,74 @@ describe('models in its own process', () => {} finally { rmSync(holdDir, { recursive: true, force: true }) }})+ it('keeps manual model requests through an outage and core crash, cancels durably, then launches each remaining ID once', async () => {+ const holdDir = mkdtempSync(join(tmpdir(), 'models-intent-hold-'))+ const hold = join(holdDir, 'hold')+ const gridName = 'fixture-grid'+ const token = fakeJwt({ exp: Math.floor(Date.now() / 1000) + 86400 * 300, sub: 'fixture' })+ const grid = installFakeGrid({+ ls: { stdout: JSON.stringify([{ grid: gridName, id: 'fixture-grid-id', type: 'permissioned-public' }]) },+ // No network address for inventory: the reader uses the fake CLI only.+ info: { stdout: '{}' },+ [`info ${gridName} --env`]: { stdout: `export OPENAI_BASE_URL="http://127.0.0.1:9/v1"\nexport OPENAI_API_KEY="${token}"\n` },+ models: { stdout: JSON.stringify([{ model: 'Fixture-Q4', node: 'fixture-node', engine: 'llama' }]) },+ mcp: { stdout: JSON.stringify({ server: 'grid-web', url: 'http://127.0.0.1:9/mcp', authorization: `Bearer ${token}` }) },+ })+ try {+ const d = await fresh({ HARNESSD_TEST_HOLD_CONNECT: `models:${hold}`,+ HARNESS_GRID_BIN: process.env.HARNESS_GRID_BIN!, FAKE_GRID_PLAN: process.env.FAKE_GRID_PLAN!, FAKE_GRID_LOG: process.env.FAKE_GRID_LOG! })+ let client = await LocalClient.connect(d)+ writeFileSync(hold, '')+ for (const pid of modelsPids(d)) process.kill(pid, 'SIGKILL')+ await until('models disconnected for the saved request', () => d.log().includes('[services] models disconnected') || null)+ const payloads = ['claude', 'codex', 'claude'].map((engine, n) => {+ const cwd = join(d.projectsDir, `saved-model-${n}`)+ mkdirSync(cwd)+ return { creationId: `saved-model-request-${n}`, engine, cwd, gridModel: 'Fixture-Q4', gridName, bypassPermission: true }+ })+ for (const payload of payloads) {+ expect(await client.request('agent_create', payload, 15_000)).toMatchObject({ creationId: payload.creationId, state: 'pending', held: { service: 'models' } })+ }+ expect((await client.request('agents_list', { includeStopped: true })).agents).toHaveLength(0)+ const before = d.log().length+ const asked = Date.now()+ process.kill(d.corePid()!, 'SIGKILL')+ client.close()+ await until('the replacement core ready while models is unavailable', () => d.log().slice(before).includes('[cli] ready') || null, 15_000)+ expect(Date.now() - asked).toBeLessThan(15_000)+ client = await LocalClient.connect(d)+ for (const { creationId } of payloads) {+ expect(await client.request('agent_create_status', { creationId })).toMatchObject({ state: 'pending', held: { service: 'models' } })+ }+ const cancelled = payloads[2]!+ expect(await client.request('agent_create_cancel', { creationId: cancelled.creationId })).toMatchObject({ state: 'cancelled' })+ expect(await client.request('agent_create', cancelled)).toMatchObject({ state: 'cancelled' })+ const plain = await create(d, client, 'claude', 'unrelated-during-held-request')+ await turn(client, plain.id, 'the held requests do not block my turn')+ rmSync(hold)+ const completed: Record<string, any>[] = []+ for (const payload of payloads.slice(0, 2)) {+ const result = await until(`${payload.engine} saved model request to complete`, async () => {+ const reply = await client.request('agent_create_status', { creationId: payload.creationId })+ return reply.state === 'created' ? reply : null+ }, 60_000, 250)+ completed.push(result.agent)+ expect(await client.request('agent_create', payload)).toMatchObject({ state: 'created', agent: { id: result.agent.id } })+ await until(`${payload.engine} recovered model to bind`, async () => (await row(client, result.agent.id))?.sessionId || null)+ await turn(client, result.agent.id, 'exactly one saved launch recovered')+ }+ const rows = (await client.request('agents_list', { includeStopped: true })).agents as Array<Record<string, any>>+ expect(rows.map(agent => agent.id).sort()).toEqual([plain.id, ...completed.map(agent => agent.id)].sort())+ expect(await client.request('agent_create_status', { creationId: cancelled.creationId })).toMatchObject({ state: 'cancelled' })+ expect(d.coresStarted()).toBe(2)+ client.close()+ } finally {+ await daemon?.close(); daemon = undefined+ grid.dispose()+ rmSync(holdDir, { recursive: true, force: true })+ }+ })+/*** Two grid agents, then a reboot with models held off the core (`HARNESSD_TEST_HOLD_CONNECT`): running, and not* there. `meanwhile` does to its process what the test is about. The core comes up ready at once, both agents waitdiff --git a/cli/e2e/viewersProcess.e2e.ts b/cli/e2e/viewersProcess.e2e.tsindex 399535c97..cefc56b08 100644--- a/cli/e2e/viewersProcess.e2e.ts+++ b/cli/e2e/viewersProcess.e2e.ts@@ -145,6 +145,12 @@ describe('the DSH viewers in their own process', () => {installHarness(d)onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })await d.start()+ // Core readiness never waits for Store. These viewer scenarios start with a+ // prepared harness, so their setup waits for Store in the viewers process.+ if (services.split(',').includes('viewers')) {+ await until('the Store to connect before preparing the viewer fixture',+ () => d.log().includes('[services] store connected') || null, 30_000, 100)+ }return d}diff --git a/cli/scripts/handoff-2026-10-08/initial-launch-cost.mjs b/cli/scripts/handoff-2026-10-08/initial-launch-cost.mjsnew file mode 100644index 000000000..6d5001aa2--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/initial-launch-cost.mjs@@ -0,0 +1,33 @@+// Pass a bundled reconciler module; every probe and row belongs to this process.+import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';++const root = mkdtempSync(join(tmpdir(), 'initial-launch-cost-'));+try {+ for (const name of Object.keys(process.env)) if (name.startsWith('HARNESSD_')) delete process.env[name];+ for (const name of ['CLAUDE_PROJECTS_DIR', 'GROK_HOME', 'COPILOT_HOME', 'CURSOR_HOME', 'CURSOR_CONFIG_DIR',+ 'CURSOR_DATA_DIR', 'HERMES_HOME', 'PI_HOME', 'PI_CODING_AGENT_DIR', 'PI_CODING_AGENT_SESSION_DIR',+ 'COMMANDCODE_HOME', 'AGY_HOME', 'AGY_CONFIG_DIR', 'OPENCODE_DB', 'KILO_DB', 'XDG_CONFIG_HOME',+ 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'TMUX', 'TMUX_PANE']) delete process.env[name];+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME',+ 'ZDOTDIR', 'HARNESS_AUTH_DIR', 'DSH_DIR', 'HARNESS_HOOK_ROUTES_DIR', 'TMUX_TMPDIR']) {+ process.env[name] = join(root, name);+ mkdirSync(process.env[name]);+ }+ const { TerminalAgentReconciler } = await import(pathToFileURL(process.argv[2]).href);+ const runtime = { backend: 'tmux', paneId: '%fixture' };+ const current = { agentId: 'fixture', engine: 'codex', sessionId: '', active: true,+ processIdentity: null, launch: { state: 'starting' }, runtimes: [runtime], cwd: '/fixture/project' };+ const snapshot = { processTableAvailable: true, agents: [], ambiguousPlacements: new Set(),+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime, rootPid: 1, cwd: current.cwd }] } }] };+ const reconciler = new TerminalAgentReconciler({ current: () => [current], backends: [], backendOrder: ['tmux'],+ probe: async () => snapshot, onObserved() {}, onDiscovered() {}, onRemoved() {}, onDormant() {} });+ const count = 10000, cpu = process.cpuUsage(), rss = process.memoryUsage().rss, began = performance.now();+ for (let n = 0; n < count; n++) await reconciler.trigger();+ const elapsedMs = performance.now() - began, used = process.cpuUsage(cpu);+ reconciler.stop();+ console.log(JSON.stringify({ count, elapsedMs, cpuMs: (used.user + used.system) / 1000,+ rssDeltaMiB: (process.memoryUsage().rss - rss) / 1048576 }));+} finally { rmSync(root, { recursive: true, force: true }); }diff --git a/cli/scripts/handoff-2026-10-08/mutate-launch-intents.py b/cli/scripts/handoff-2026-10-08/mutate-launch-intents.pynew file mode 100644index 000000000..22c44e6a3--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-launch-intents.py@@ -0,0 +1,63 @@+#!/usr/bin/env python3+"""Run in a disposable worktree: healthy golden and durable-authority mutations."""+from pathlib import Path+import os+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+golden = 'src/core/agents/launchRequests.golden.spec.ts'+receipt = 'src/lib/agentCreationReceipt.spec.ts'+requests = 'src/core/agents/launches.spec.ts'+scheduler = 'src/core/agents/pendingLaunches.spec.ts'+startup = 'src/startupOrder.spec.ts'+initial = 'src/lib/initialLaunch.golden.spec.ts'+reconciler = 'src/lib/terminalAgentReconciler.spec.ts'+mutations = [+ ('drop resolved model', 'src/core/agents/launches.ts', ' input.grid = target\n return () => executeCreate', ' input.grid = null\n return () => executeCreate', golden),+ ('drop Codex profile', 'src/core/agents/launches.ts', ' codexHome,\n dsh,', ' codexHome: null,\n dsh,', golden),+ ('wrong project label', 'src/core/agents/launches.ts', '?? engineLabel(input.engine)', "?? 'Wrong fixture label'", golden),+ ('lose created identity', 'src/core/agents/launches.ts', 'byAgent(status.agentId)', "byAgent('missing-created-agent')", golden),+ ('omit legacy reservation', 'src/lib/agentCreationReceipt.ts', "this.write(id, { version: 1, fingerprint, outcome: { state: 'pending' } }, true)", 'void id', golden),+ ('forget saved authorization', 'src/core/agents/launches.ts', 'saved.local as boolean, invoke)', 'true, invoke)', requests),+ ('forget intent identity after await', 'src/lib/agentCreationReceipt.ts', 'const current = this.read(id)', 'const current = saved', receipt),+ ('forget directory identity', 'src/lib/agentCreationReceipt.ts', ' directory.verify()', ' void directory', receipt),+ ('hide conflicting disk result', 'src/lib/agentCreationReceipt.ts', ' if (result) {\n if (result.fingerprint', ' if (known) return known.outcome\n if (result) {\n if (result.fingerprint', receipt),+ ('forget completion before missing evidence', 'src/lib/agentCreationReceipt.ts', 'const completedIntent = this.intentResults.has(id)', 'const completedIntent = false', receipt),+ ('drop cancellation claim', 'src/lib/agentCreationReceipt.ts', "this.publish(this.intentFile(id, 'claim'), { fingerprint: receipt.fingerprint, token: randomUUID(), kind: 'cancel' }, true)", 'void receipt', receipt),+ ('unbounded retry window', 'src/core/agents/pendingLaunches.ts', 'const windowSize = 128', 'const windowSize = 1_000_000', scheduler),+ ('omit retry read budget', 'src/core/agents/pendingLaunches.ts', 'started < 4 && !stopped && performance.now() - began < 20', 'started < 4 && !stopped', scheduler),+ ('recover manual launches before readiness', 'src/core/main.ts', ' coreLink.ready()', ' launches.open()\n coreLink.ready()', startup),+ ('misroute confirmed engine exits', 'src/lib/terminalAgentReconciler.ts', 'await this.deps.onDormant(current,', 'await this.deps.onRemoved(current,', initial),+ ('retire an initial launch before its engine exists', 'src/lib/terminalAgentReconciler.ts', "if (observed || (processKey === null && (current.launch?.state === 'starting' || probed?.starting)))", 'if (observed)', reconciler),+ ('apply a pre-start miss after readiness changes', 'src/lib/terminalAgentReconciler.ts', "current.launch?.state === 'starting' || probed?.starting", "current.launch?.state === 'starting'", reconciler),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+for name in ['TMUX', 'TMUX_PANE', 'RECORD_LAUNCH_REQUESTS_GOLDEN']:+ env.pop(name, None)+++def run(specs):+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=1'],+ cwd=cli, env=env, capture_output=True, text=True, timeout=180)+++baseline = run([golden, receipt, requests, scheduler, startup, initial, reconciler])+if baseline.returncode:+ print(baseline.stdout + baseline.stderr)+ raise SystemExit('baseline failed; no mutants ran')+print('unchanged baseline passed', flush=True)+for label, relative, before, after, spec in mutations:+ path = cli / relative+ original = path.read_text()+ assert original.count(before) == 1, (label, original.count(before))+ try:+ path.write_text(original.replace(before, after))+ result = run([spec])+ output = result.stdout + result.stderr+ if result.returncode == 0 or 'AssertionError' not in output:+ print(output)+ raise SystemExit(f'{label}: not caught by an assertion')+ print(f'{label}: caught by assertion', flush=True)+ finally:+ path.write_text(original)diff --git a/cli/scripts/handoff-2026-10-08/receipt-cost.mjs b/cli/scripts/handoff-2026-10-08/receipt-cost.mjsnew file mode 100644index 000000000..edb74b9c9--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/receipt-cost.mjs@@ -0,0 +1,23 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pathToFileURL } from 'node:url';+const { AgentCreationReceipts, creationFingerprint } = await import(pathToFileURL(process.argv[2]).href);+const root = mkdtempSync(join(tmpdir(), 'receipt-cost-'));+try {+ const store = new AgentCreationReceipts(join(root, 'receipts'));+ const request = { kind:'model-create-v1', local:false, input:{engine:'claude',cwd:'/fixture/project',grid:null}, selection:{model:'fixture-model',grid:'fixture-grid'} };+ const fp = creationFingerprint(request), held = { service:'models', detail:'Waiting for the selected model.' };+ const samples = [], cpu = process.cpuUsage(), rss = process.memoryUsage().rss;+ for(let n=0;n<60;n++) {+ const id = `fixture-creation-${n}`, effect = async()=>({state:'created',agentId:`fixture-agent-${n}`});+ const start = performance.now();+ if (process.argv[3] === 'intent') await store.runIntent(id, fp, request, held, async()=>effect);+ else await store.run(id, fp, effect);+ new AgentCreationReceipts(join(root,'receipts')).status(id);+ samples.push(performance.now()-start);+ }+ const used = process.cpuUsage(cpu);+ samples.sort((a,b)=>a-b);+ console.log(JSON.stringify({ mode:process.argv[3], count:samples.length, medianMs:samples[30], p95Ms:samples[57], totalMs:samples.reduce((a,b)=>a+b,0), cpuMs:(used.user+used.system)/1000, rssDeltaMiB:(process.memoryUsage().rss-rss)/1048576 }));+} finally { rmSync(root,{recursive:true,force:true}); }diff --git a/cli/src/backendSocket.models.spec.ts b/cli/src/backendSocket.models.spec.tsindex d50ae1374..2f24ff939 100644--- a/cli/src/backendSocket.models.spec.ts+++ b/cli/src/backendSocket.models.spec.ts@@ -49,10 +49,10 @@ it.each([null, new Error('private error')])('refuses resolution failure before aexpect(await ask({})).toMatchObject({ error: 'GRID_UNAVAILABLE' })expect(socket.onCreateAgent).not.toHaveBeenCalled()})-it('refuses the create while models is off, as GRID_UNAVAILABLE', async () => {+it('holds an identified create while models is off and preserves the legacy refusal', async () => {bindLaunchRequests(socket, { modelTarget: null })expect(await ask({})).toMatchObject({ error: 'GRID_UNAVAILABLE' })- expect(await ask({ creationId: 'model-launch-00000003' })).toMatchObject({ state: 'failed', failure: { code: 'GRID_UNAVAILABLE' } })+ expect(await ask({ creationId: 'model-launch-00000003' })).toMatchObject({ state: 'pending', held: { service: 'models' } })expect(socket.onCreateAgent).not.toHaveBeenCalled()})it('refuses malformed model selections before creating a receipt', async () => {@@ -71,10 +71,10 @@ it('receipts retain semantic model identity across retries, never credentials',const receipts = readdirSync(join(root, 'agent-creations')).map(name => readFileSync(join(root, 'agent-creations', name), 'utf8')).join('')expect(receipts).not.toMatch(/fixture-secret|rotated-secret|apiKey/)})-it.each([null, new Error('private error')])('records a safe model failure before folder creation: %j', async value => {+it.each([null, new Error('private error')])('holds the semantic request before folder creation: %j', async value => {if (value instanceof Error) vi.mocked(resolveNewAgentModel).mockRejectedValue(value)else vi.mocked(resolveNewAgentModel).mockResolvedValue(value)const answer = await ask({ creationId: 'model-launch-00000002', cwd: undefined, projectSource: 'new', projectName: 'unused' })- expect(answer).toMatchObject({ state: 'failed', failure: { code: 'GRID_UNAVAILABLE' } })+ expect(answer).toMatchObject({ state: 'pending', held: { service: 'models' } })expect(socket.onCreateAgent).not.toHaveBeenCalled()})diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 10f17df5b..07d0a78cc 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -2231,6 +2231,18 @@ describe('BackendSocket outbound queue', () => {await vi.waitFor(() => expect(frames).toContainEqual({type: 'agent_create_status_result', payload: { requestId: 'missing', creationId, state: 'missing' },}))+ socket.handleLocalFrame('local:missing-receipt', {+ type: 'agent_create_cancel', payload: { requestId: 'cancel', creationId },+ })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_create_cancel_result', payload: { requestId: 'cancel', creationId, state: 'cancelled' },+ }))+ socket.handleLocalFrame('local:missing-receipt', {+ type: 'agent_create', payload: { requestId: 'late', creationId, engine: 'claude', cwd: '/tmp/work' },+ })+ await vi.waitFor(() => expect(frames).toContainEqual({+ type: 'agent_create_result', payload: { requestId: 'late', creationId, state: 'cancelled' },+ }))socket.handleLocalFrame('local:missing-receipt', {type: 'agent_create', payload: { requestId: 'invalid', creationId: '../bad', engine: 'claude', cwd: '/tmp/work' },})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 5915a54c0..52fb1efaa 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -210,6 +210,7 @@ export class BackendSocket {* core/agents/launches.ts). Null answers UNSUPPORTED_ON_REMOTE, or UNSUPPORTED for a status. */createProvider: ((payload: Record<string, unknown>, asker: { local: boolean; owner: boolean }, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = nullcreateStatusProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ cancelCreateProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = nullrestartProvider: ((type: string, payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = nullforkProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null/** Opens a NEW agent that starts with `agentId`'s whole history (lib/forkAgent.ts), exactly as@@ -984,6 +985,11 @@ export class BackendSocket {else answer({ error: 'UNSUPPORTED' })return+ case 'agent_create_cancel':+ if (this.cancelCreateProvider) await this.cancelCreateProvider(payload, answer)+ else answer({ error: 'UNSUPPORTED' })+ return+// A new agent (core/agents/launches.ts, bound by cli.ts).case 'agent_create':if (this.createProvider) await this.createProvider(payload, asker, answer)diff --git a/cli/src/core/agents/__fixtures__/launch-requests.golden.json b/cli/src/core/agents/__fixtures__/launch-requests.golden.jsonnew file mode 100644index 000000000..6a904d5cc--- /dev/null+++ b/cli/src/core/agents/__fixtures__/launch-requests.golden.json@@ -0,0 +1,918 @@+{+ "linux:create": {+ "events": [+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/create/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-create",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ }+ ]+ },+ "linux:codex": {+ "events": [+ [+ "dispatch",+ "create",+ {+ "engine": "codex",+ "cwd": "<root>/codex/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": "<root>/CODEX_HOME",+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-codex",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ }+ ]+ },+ "linux:model": {+ "events": [+ [+ "models",+ {+ "model": "fixture-model",+ "grid": "fixture-grid"+ }+ ],+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/model/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": {+ "networkId": "fixture-grid",+ "networkName": "Fixture",+ "baseUrl": "http://fixture.invalid/v1",+ "apiKey": "fixture-key",+ "model": "fixture-model"+ },+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-model",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ }+ ]+ },+ "linux:project": {+ "events": [+ [+ "prepare-folder",+ {+ "source": "new",+ "name": "Fixture"+ },+ "Claude"+ ],+ [+ "trust",+ "claude",+ null,+ "<root>/project/prepared"+ ],+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/project/prepared",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null,+ "scmLaunchRecord": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-project",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ }+ ]+ },+ "linux:fork": {+ "events": [+ [+ "dispatch",+ "fork",+ {+ "agentId": "fixture-agent",+ "name": "Fork",+ "prompt": "Try another approach"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-fork",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ }+ ]+ },+ "linux:resume": {+ "events": [+ [+ "dispatch",+ "resume",+ {+ "agentId": "fixture-agent",+ "permissionMode": "ask"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-resume",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ }+ ]+ },+ "linux:restart": {+ "events": [+ [+ "dispatch",+ "restart",+ {+ "agentId": "fixture-agent"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-restart",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ }+ ]+ },+ "darwin:create": {+ "events": [+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/create/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-create",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ },+ {+ "creationId": "fixture-creation-create",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/create/work"+ }+ }+ ]+ },+ "darwin:codex": {+ "events": [+ [+ "dispatch",+ "create",+ {+ "engine": "codex",+ "cwd": "<root>/codex/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": "<root>/CODEX_HOME",+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-codex",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ },+ {+ "creationId": "fixture-creation-codex",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "codex",+ "cwd": "<root>/codex/work"+ }+ }+ ]+ },+ "darwin:model": {+ "events": [+ [+ "models",+ {+ "model": "fixture-model",+ "grid": "fixture-grid"+ }+ ],+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/model/work",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": {+ "networkId": "fixture-grid",+ "networkName": "Fixture",+ "baseUrl": "http://fixture.invalid/v1",+ "apiKey": "fixture-key",+ "model": "fixture-model"+ },+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-model",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ },+ {+ "creationId": "fixture-creation-model",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/model/work"+ }+ }+ ]+ },+ "darwin:project": {+ "events": [+ [+ "prepare-folder",+ {+ "source": "new",+ "name": "Fixture"+ },+ "Claude"+ ],+ [+ "trust",+ "claude",+ null,+ "<root>/project/prepared"+ ],+ [+ "dispatch",+ "create",+ {+ "engine": "claude",+ "cwd": "<root>/project/prepared",+ "bypassPermission": false,+ "permissionMode": "ask",+ "grid": null,+ "codexHome": null,+ "dsh": null,+ "prompt": "First request",+ "name": "Fixture",+ "agent": null,+ "resumeSessionId": null,+ "takeOver": null,+ "scmLaunchRecord": null+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-project",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ },+ {+ "creationId": "fixture-creation-project",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/project/work"+ }+ }+ ]+ },+ "darwin:fork": {+ "events": [+ [+ "dispatch",+ "fork",+ {+ "agentId": "fixture-agent",+ "name": "Fork",+ "prompt": "Try another approach"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-fork",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ },+ {+ "creationId": "fixture-creation-fork",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/fork/work"+ },+ "level": "native"+ }+ ]+ },+ "darwin:resume": {+ "events": [+ [+ "dispatch",+ "resume",+ {+ "agentId": "fixture-agent",+ "permissionMode": "ask"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-resume",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ },+ {+ "creationId": "fixture-creation-resume",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/resume/work"+ },+ "resumed": true+ }+ ]+ },+ "darwin:restart": {+ "events": [+ [+ "dispatch",+ "restart",+ {+ "agentId": "fixture-agent"+ }+ ]+ ],+ "replies": [+ {+ "creationId": "fixture-creation-restart",+ "state": "pending"+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ },+ {+ "creationId": "fixture-creation-restart",+ "state": "created",+ "agent": {+ "id": "fixture-agent",+ "engine": "claude",+ "cwd": "<root>/restart/work"+ },+ "resumed": false+ }+ ]+ }+}diff --git a/cli/src/core/agents/launchRequests.golden.spec.ts b/cli/src/core/agents/launchRequests.golden.spec.tsnew file mode 100644index 000000000..2090db3b0--- /dev/null+++ b/cli/src/core/agents/launchRequests.golden.spec.ts@@ -0,0 +1,120 @@+/** Public launch receipts and dispatch inputs, recorded from main before durable retry changes. */+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { AgentFrame } from '../../lib/agentFrame.js'+import type { LaunchRequestDeps } from './launches.js'++const fixture = vi.hoisted(() => ({ root: '', events: [] as unknown[] }))+vi.mock('node:child_process', () => {+ const forbidden = () => { throw Error('Host binaries are forbidden in this golden') }+ return { exec: forbidden, execSync: forbidden, execFile: forbidden, execFileSync: forbidden, spawn: forbidden, spawnSync: forbidden }+})+vi.mock('../../engines/inProcess.js', async original => ({ ...await original<object>(),+ loadEngine: () => { throw Error('Launch requests cannot load an optional interpreter') },+}))+vi.mock('../../engines/launchPrep.js', () => ({ folderTrust: (engine: string, profile: string | null) => ({+ trusts: () => false,+ record: (path: string) => fixture.events.push(['trust', engine, profile, path]),+}) }))+vi.mock('../../lib/projectFolder.js', async original => ({ ...await original<object>(),+ projectsRoot: () => join(fixture.root, 'projects'),+ prepareProjectFolder: async (request: unknown, options: { label: string }) => {+ fixture.events.push(['prepare-folder', request, options.label])+ const path = join(fixture.root, 'prepared'); mkdirSync(path); return path+ },+}))++const GOLDEN = fileURLToPath(new URL('./__fixtures__/launch-requests.golden.json', import.meta.url))+const record = process.env.RECORD_LAUNCH_REQUESTS_GOLDEN === '1'+const observations: Record<string, unknown> = {}+const former = record ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))+const kinds = ['create', 'codex', 'model', 'project', 'fork', 'resume', 'restart'] as const++it.each(['linux', 'darwin'])('preserves healthy launch requests and durable receipt replies on %s', async platform => {+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'launch-requests-golden-')))+ try {+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T17:00:00Z') })+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME']) {+ const path = join(root, name); mkdirSync(path); vi.stubEnv(name, path)+ }+ vi.stubEnv('TZ', 'UTC'); vi.stubEnv('CLAUDE_PATH', '/fixture/bin/claude'); vi.stubEnv('CODEX_PATH', '/fixture/bin/codex')+ vi.resetModules()+ const { AgentCreationReceipts } = await import('../../lib/agentCreationReceipt.js')+ const { createLaunchRequests } = await import('./launches.js')+ for (const kind of kinds) {+ fixture.root = join(root, kind); mkdirSync(fixture.root); fixture.events = []+ const cwd = join(fixture.root, 'work'); mkdirSync(cwd)+ const directory = join(fixture.root, 'receipts')+ const creationId = `fixture-creation-${kind}`+ const replies: Record<string, unknown>[] = []+ const reply = (value: Record<string, unknown>) => { replies.push(value) }+ const engine = kind === 'codex' ? 'codex' : 'claude'+ const session = { agentId: 'fixture-agent', sessionId: 'fixture-conversation', engine, cwd } as RegisteredSession+ let finish!: () => void+ const dispatch = async (operation: string, input: unknown) => {+ fixture.events.push(['dispatch', operation, input])+ await new Promise<void>(done => { finish = done })+ return { ok: true as const, session, level: 'native' as const, resumed: operation === 'resume' }+ }+ const deps: LaunchRequestDeps = {+ receipts: new AgentCreationReceipts(directory),+ createAgent: () => input => dispatch('create', input),+ forkAgent: () => input => dispatch('fork', input),+ resumeAgent: () => (agentId, permissionMode) => dispatch('resume', { agentId, permissionMode }),+ restartAgent: () => agentId => dispatch('restart', { agentId }),+ byAgent: agentId => agentId === session.agentId ? session : undefined,+ // The frame formatter is another boundary; retain recognizable fields+ // to detect a wrong agent or a dropped reply without invoking services.+ toProject: async row => ({ id: row.agentId, engine: row.engine, cwd: row.cwd } as unknown as AgentFrame),+ modelTarget: async selection => {+ fixture.events.push(['models', selection])+ return { networkId: 'fixture-grid', networkName: 'Fixture', baseUrl: 'http://fixture.invalid/v1', apiKey: 'fixture-key', model: 'fixture-model' }+ },+ }+ const requests = createLaunchRequests(deps)+ const payload: Record<string, unknown> = kind === 'fork'+ ? { creationId, agentId: session.agentId, name: 'Fork', prompt: 'Try another approach' }+ : kind === 'resume' || kind === 'restart'+ ? { creationId, agentId: session.agentId, ...(kind === 'resume' ? { permissionMode: 'ask' } : {}) }+ : { creationId, engine, permissionMode: 'ask', prompt: 'First request', name: 'Fixture',+ ...(kind === 'codex' ? { codexHome: join(root, 'CODEX_HOME') } : {}),+ ...(kind === 'project' ? { projectSource: 'new', projectName: 'Fixture' } : { cwd }),+ ...(kind === 'model' ? { gridModel: 'fixture-model', gridName: 'fixture-grid' } : {}) }+ const invoke = () => kind === 'fork' ? requests.fork(payload, reply)+ : kind === 'resume' || kind === 'restart' ? requests.relaunch(`agent_${kind}`, payload, reply)+ : requests.create(payload, { local: true }, reply)+ await invoke()+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))+ await requests.createStatus({ creationId }, reply)+ await invoke() // A duplicate in flight joins the same operation.+ finish()+ await vi.waitFor(() => expect(replies).toHaveLength(3))+ await invoke() // A duplicate after completion only returns the receipt.+ await vi.waitFor(() => expect(replies).toHaveLength(4))+ const recovered = createLaunchRequests({ ...deps, receipts: new AgentCreationReceipts(directory) })+ await recovered.createStatus({ creationId }, reply)+ expect(fixture.events.filter(value => Array.isArray(value) && value[0] === 'dispatch')).toHaveLength(1)+ const key = `${platform}:${kind}`+ observations[key] = JSON.parse(JSON.stringify({ events: fixture.events, replies }).split(root).join('<root>'))+ if (!record) expect({ key, value: observations[key] }).toEqual({ key, value: former[key] })+ }+ } finally {+ vi.useRealTimers(); vi.unstubAllEnvs(); vi.resetModules()+ Object.defineProperty(process, 'platform', descriptor)+ rmSync(root, { recursive: true, force: true })+ }+}, 30_000)++afterAll(() => {+ if (record) writeFileSync(GOLDEN, JSON.stringify(observations, null, 2) + '\n')+ else {+ expect(Object.keys(observations).sort()).toEqual(Object.keys(former).sort())+ expect(readFileSync(GOLDEN, 'utf8')).not.toMatch(/\/Users\/|\/home\/runner|launch-requests-golden-/)+ }+})diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 5d7bb8f0c..8feccfc5f 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -6,7 +6,7 @@ import { installedDsh } from '../../dsh/installed.js'import { dshSupportedEngines } from '../../dsh/manifest.js'import { loadEngine } from '../../engines/inProcess.js'import { opencodeMajorVersion } from '../../engines/launchControl.js'-import { AgentCreationReceiptError, AgentCreationReceipts, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'+import { AgentCreationReceiptError, AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'import type { AgentFrame } from '../../lib/agentFrame.js'import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from '../../lib/engineLaunch.js'import { parseGridLaunchOverride } from '../../lib/gridLaunchWire.js'@@ -62,12 +62,14 @@ const settle = () => new Promise((resolve) => setTimeout(resolve, 0))let dir: stringlet stores = 0+const stopRequests: Array<() => void> = []beforeEach(() => {dir = mkdtempSync(join(tmpdir(), 'launches-'))root.projects = join(dir, 'harnesses')mkdirSync(root.projects)})afterEach(() => {+ stopRequests.splice(0).forEach(stop => stop())rmSync(dir, { recursive: true, force: true })vi.restoreAllMocks()vi.resetAllMocks()@@ -87,6 +89,7 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat...over,}const requests = createLaunchRequests(deps)+ stopRequests.push(requests.stop)const replies: Array<Record<string, unknown>> = []const reply = (result: Record<string, unknown>) => { replies.push(result) }return {@@ -195,7 +198,7 @@ describe('agent_create, refused before any pane exists', () => {expect(await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION, resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)- vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'ok', selection: { model: 'm' } } as never)+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'ok', selection: { model: 'm', grid: 'fixture-grid' } } as never)expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)@@ -235,7 +238,7 @@ describe('agent_create, launched', () => {it('points a model picked by name at its grid as read now, or says the model is unavailable', async () => {const { ask, create } = setup()- vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm', grid: 'fixture-grid' } } as never)resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error('offline'))await ask({ engine: 'claude', cwd: '/w' })expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })@@ -254,6 +257,74 @@ describe('agent_create, launched', () => {})describe('agent_create with a receipt', () => {+ it('keeps a temporary model outage pending across receipt readers instead of completing it as failed', async () => {+ const { ask, create, replies, status } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })+ resolveNewAgentModel.mockRejectedValueOnce(new Error('fixture models disconnected'))+ await ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(create).not.toHaveBeenCalled()+ expect(replies[0]).toMatchObject({ creationId: CREATION, state: 'pending', held: { service: 'models', detail: expect.any(String) } })+ expect(await status({ creationId: CREATION })).toMatchObject({ state: 'pending', held: { service: 'models' } })+ const recovered = new AgentCreationReceipts(join(dir, `receipts-${stores}`))+ expect(recovered.status(CREATION)).toMatchObject({ state: 'pending', held: { service: 'models' } })+ })++ it('recovers the original request and authorization after restart, then returns the same created agent', async () => {+ const { ask, replies, deps, create } = setup()+ const cwd = join(root.projects, 'remote-request'); mkdirSync(cwd)+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })+ resolveNewAgentModel.mockRejectedValueOnce(new Error('disconnected'))+ await ask({ engine: 'claude', cwd, prompt: 'Keep this task', creationId: CREATION }, false)+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ const recovered = createLaunchRequests({ ...deps, receipts: new AgentCreationReceipts(join(dir, `receipts-${stores}`)) })+ stopRequests.push(recovered.stop)+ const target = { networkId: 'fixture-grid', networkName: 'Fixture', baseUrl: 'http://fixture.invalid/v1', apiKey: 'rotated-key' }+ resolveNewAgentModel.mockResolvedValue(target)+ await recovered.recover()+ expect(create).not.toHaveBeenCalled()+ recovered.open()+ await recovered.recover()+ await vi.waitFor(() => expect(create).toHaveBeenCalledOnce())+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ cwd, prompt: 'Keep this task', grid: target }))+ expect(preTrustClaudeProject).not.toHaveBeenCalled()+ const answer = vi.fn()+ await recovered.createStatus({ creationId: CREATION }, answer)+ expect(answer).toHaveBeenCalledWith({ creationId: CREATION, state: 'created', agent: { id: 'new-agent' } })+ await recovered.recover()+ expect(create).toHaveBeenCalledOnce()+ })++ it('cancels an undispatched model request durably and refuses a late create with the same ID', async () => {+ const { ask, requests, create, replies } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })+ resolveNewAgentModel.mockResolvedValue(null)+ await ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ const answer = vi.fn()+ await requests.cancelCreate({ creationId: CREATION }, answer)+ expect(answer).toHaveBeenLastCalledWith({ creationId: CREATION, state: 'cancelled' })+ resolveNewAgentModel.mockResolvedValue({ networkId: 'fixture-grid' } as never)+ requests.open(); await requests.recover()+ await ask({ engine: 'claude', cwd: '/fixture/work', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(replies[1]).toEqual({ creationId: CREATION, state: 'cancelled' })+ expect(create).not.toHaveBeenCalled()+ })++ it('reads a completed receipt before checking mutable package or native version state', async () => {+ const { ask, replies, create } = setup()+ vi.mocked(installedDsh).mockReturnValue({ id: 'fixture/package', manifest: { kind: 'agent', name: 'Fixture' } } as never)+ await ask({ engine: 'claude', cwd: '/fixture/work', dsh: 'fixture/package', agent: 'named', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ vi.mocked(installedDsh).mockReturnValue(undefined)+ vi.mocked(supportsNamedAgent).mockReturnValue(false)+ await ask({ engine: 'claude', cwd: '/fixture/work', dsh: 'fixture/package', agent: 'named', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(replies[1]).toEqual(replies[0])+ expect(create).toHaveBeenCalledOnce()+ })+it('answers outside the connection\'s line, with the creation id and the new agent, and a retry is the same launch', async () => {let finish!: (value: { ok: true; session: RegisteredSession }) => voidconst create = vi.fn(() => new Promise<{ ok: true; session: RegisteredSession }>((resolve) => { finish = resolve }))@@ -396,22 +467,21 @@ describe('agent_create with a receipt', () => {expect(warn).toHaveBeenCalledWith(`[agent] pre-trust ${empty} · busy`)})- it('resolves a model picked by name inside the receipt, and records it unavailable when it cannot be read', async () => {+ it('resolves a model picked by name inside the receipt, and holds it when it cannot be read', async () => {const { ask, create, replies } = setup()- vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm', grid: 'fixture-grid' } } as never)resolveNewAgentModel.mockResolvedValueOnce({ networkId: 'resolved' } as never).mockRejectedValueOnce(new Error('offline'))await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-2` })await vi.waitFor(() => expect(replies).toHaveLength(2))expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })- expect(replies[1]).toStrictEqual({ creationId: `${CREATION}-2`, state: 'failed',- failure: { code: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' } })+ expect(replies.find(reply => reply.creationId === `${CREATION}-2`)).toMatchObject({ creationId: `${CREATION}-2`, state: 'pending', held: { service: 'models' } })})it('says why a receipt could not be kept, and answers INTERNAL when the answer cannot be put together', async () => {- const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })expect(await storage.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })- const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })expect(await broken.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })await frameless.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })@@ -419,6 +489,83 @@ describe('agent_create with a receipt', () => {})})+describe('durable model request validation', () => {+ it('retains canonical DSH identity for old-name requests and existing v1 fingerprints', async () => {+ const { ask, deps, create, replies } = setup()+ vi.mocked(installedDsh).mockReturnValue({ id: 'acme/current', manifest: { kind: 'agent', formerly: ['acme/former'] } } as never)+ const input = { engine: 'claude', cwd: '/w', bypassPermission: false, permissionMode: null,+ grid: null, codexHome: null, dsh: 'acme/current', prompt: null, name: null, agent: null, resumeSessionId: null, takeOver: null }+ await deps.receipts.run(CREATION, creationFingerprint(input), async () => ({ state: 'created', agentId: 'new-agent' }))+ const payload = { engine: 'claude', cwd: '/w', dsh: 'acme/former', creationId: CREATION, bypassPermission: false }+ await ask(payload)+ await vi.waitFor(() => expect(replies.at(-1)).toMatchObject({ state: 'created' }))+ expect(create).not.toHaveBeenCalled()+ await ask({ ...payload, creationId: `${CREATION}-new` })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(create).toHaveBeenCalledWith(input)+ })+ it('keeps fresh legacy installation refusals correctable with the same ID', async () => {+ const { ask, replies, deps } = setup()+ const payload = { engine: 'claude', cwd: '/w', dsh: 'acme/notes', creationId: CREATION }+ expect(await ask(payload)).toMatchObject({ error: 'INVALID_DSH' })+ expect(deps.receipts.status(CREATION)).toEqual({ state: 'missing' })+ vi.mocked(installedDsh).mockReturnValue({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)+ await ask(payload)+ await vi.waitFor(() => expect(replies.at(-1)).toMatchObject({ state: 'created' }))+ })++ it('reports a current installation refusal after the model becomes available', async () => {+ const { ask, replies, create } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm', grid: 'fixture-grid' } })+ resolveNewAgentModel.mockResolvedValue({ networkId: 'resolved' } as never)+ await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes', creationId: CREATION })+ await vi.waitFor(() => expect(replies.at(-1)).toMatchObject({ state: 'failed', failure: { code: 'INVALID_DSH' } }))+ expect(create).not.toHaveBeenCalled()+ })++ it('holds unfamiliar or incomplete saved intent without preparing a project or dispatching', async () => {+ const { deps, requests, create } = setup()+ const records = [{ kind: 'future-kind' }, { kind: 'model-create-v1', local: true, input: {}, selection: {} }]+ const held = { service: 'models', detail: 'Waiting for the model.' }+ for (const [n, request] of records.entries()) {+ await deps.receipts.runIntent(`${CREATION}-${n}`, creationFingerprint(request), request, held, async () => null)+ }+ const retry = vi.spyOn(deps.receipts, 'runIntent')+ requests.open(); await requests.recover()+ await vi.waitFor(() => expect(retry).toHaveBeenCalledTimes(records.length))+ for (let n = 0; n < records.length; n++) expect(deps.receipts.status(`${CREATION}-${n}`)).toEqual({ state: 'pending', held })+ expect(resolveNewAgentModel).not.toHaveBeenCalled()+ expect(prepareProjectFolder).not.toHaveBeenCalled()+ expect(create).not.toHaveBeenCalled()+ })++ it('holds recovery while no local creator is available', async () => {+ const { deps, requests } = setup({}, { create: null })+ const request = { kind: 'model-create-v1', local: true, input: { engine: 'claude', cwd: '/w', grid: null }, selection: { grid: 'fixture-grid', model: 'm' } }+ const held = { service: 'models', detail: 'Waiting for the model.' }+ await deps.receipts.runIntent(CREATION, creationFingerprint(request), request, held, async () => null)+ const retry = vi.spyOn(deps.receipts, 'runIntent')+ requests.open(); await requests.recover()+ await vi.waitFor(() => expect(retry).toHaveBeenCalledOnce())+ expect(deps.receipts.status(CREATION)).toEqual({ state: 'pending', held })+ expect(resolveNewAgentModel).not.toHaveBeenCalled()+ })++ it('rejects invalid cancellation IDs and reports storage uncertainty without acknowledging cancellation', async () => {+ const { deps, requests } = setup()+ const answer = vi.fn()+ await requests.cancelCreate({ creationId: '../invalid' }, answer)+ expect(answer).toHaveBeenLastCalledWith({ error: 'INVALID_CREATION_ID' })+ const cancel = vi.spyOn(deps.receipts, 'cancelIntent')+ cancel.mockImplementationOnce(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') })+ await requests.cancelCreate({ creationId: CREATION }, answer)+ expect(answer).toHaveBeenLastCalledWith({ error: 'CREATION_STORAGE_FAILED' })+ cancel.mockImplementationOnce(() => { throw new Error('unknown') })+ await requests.cancelCreate({ creationId: CREATION }, answer)+ expect(answer).toHaveBeenLastCalledWith({ error: 'INTERNAL' })+ })+})+describe('agent_create_status', () => {it('names a launch by a valid creation id, and says what became of it', async () => {const { status, deps } = setup()@@ -438,9 +585,9 @@ describe('agent_create_status', () => {})it('says why a receipt could not be read', async () => {- const storage = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })expect(await storage.status({ creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })- const broken = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })+ const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })expect(await broken.status({ creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })})})@@ -495,9 +642,9 @@ describe('agent_resume and agent_restart', () => {})it('say why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {- const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })expect(await storage.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })- const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })expect(await broken.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })await frameless.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })@@ -553,9 +700,9 @@ describe('agent_fork', () => {})it('says why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {- const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })+ const storage = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })expect(await storage.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_CONFLICT' })- const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ const broken = setup({ receipts: { has: vi.fn(() => false), runIntent: vi.fn(), pendingIntents: vi.fn(), pendingIntent: vi.fn(), cancelIntent: vi.fn(), status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })expect(await broken.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })await frameless.forkAsk({ agentId: 'a1', creationId: CREATION })diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 5771e9fe4..5e2539f7f 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -17,7 +17,7 @@ import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'import { folderTrust } from '../../engines/launchPrep.js'import * as opencodeLaunch from '../../engines/launchControl.js'import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'-import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'+import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'import type { AgentFrame } from '../../lib/agentFrame.js'import { engineLabel } from '../../lib/agentNames.js'import {@@ -26,9 +26,10 @@ import {} from '../../lib/engineLaunch.js'import { parseGridLaunchOverride, type GridLaunchOverride } from '../../lib/gridLaunchWire.js'import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.js'-import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from '../../lib/projectFolder.js'+import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, type ProjectFolder } from '../../lib/projectFolder.js'import type { ScmLaunchRecord } from '../../scm/types.js'import type { RegisteredSession } from '../../lib/registry.js'+import { createPendingLaunches } from './pendingLaunches.js'/** Creates an agent (core/agents/create.ts). The orchestrator creates through the same one. */export type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>@@ -48,7 +49,7 @@ export type ResumeAgent = (agentId: string, permissionMode?: string) => ReturnTyexport interface LaunchRequestDeps {/** The receipts of launches asked for with a `creationId`. */- receipts: Pick<AgentCreationReceipts, 'run' | 'status'>+ receipts: Pick<AgentCreationReceipts, 'run' | 'status' | 'has' | 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>/** Each launch, read when a request comes in: null on a machine that cannot launch agents. */createAgent: () => CreateAgent | nullforkAgent: () => ForkAgent | null@@ -58,14 +59,103 @@ export interface LaunchRequestDeps {/** An agent's frame, as the socket builds it for every reply. */toProject: (s: RegisteredSession) => Promise<AgentFrame>/** Where a new agent on a grid model sends its inference: the models service's to resolve, on this- * machine (core/api.ts `ModelsPort.launchTarget`). Null, or a rejection while models is down, refuses- * the create with GRID_UNAVAILABLE rather than start it anywhere else. */+ * machine (core/api.ts `ModelsPort.launchTarget`). Null or a rejection holds a durable model request;+ * resolving the semantic choice may renew service-owned credentials, but never dispatches a launch. */modelTarget: (selection: NewAgentModel) => Promise<GridLaunchOverride | null>}type Reply = (result: Record<string, unknown>) => voidexport function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {+ type CreateInput = Parameters<CreateAgent>[0]+ const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {+ if (input.dsh) {+ const installed = known ?? installedDsh(input.dsh)+ if (!installed) return { error: 'INVALID_DSH', detail: `${input.dsh} is not installed on this machine` }+ if (installed.manifest.kind === 'viewer') return { error: 'INVALID_DSH', detail: `${input.dsh} is a viewer package, not an agent` }+ if (!dshSupportedEngines(installed.manifest).includes(input.engine)) return { error: 'INVALID_DSH',+ detail: `${input.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${input.engine} is not compatible` }+ }+ if (input.agent && !supportsNamedAgent(input.engine, input.engine === 'opencode' ? await opencodeLaunch.opencodeMajorVersion() : null)) {+ return { error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(input.engine).message }+ }+ return null+ }++ const executeCreate = async (input: CreateInput, projectFolder: ProjectFolder | null, local: boolean, invoke: CreateAgent, validated = false): Promise<AgentCreationOutcome> => {+ if (!validated) {+ const refusal = await validateInstalled(input)+ if (refusal) return { state: 'failed', ...refusal }+ }+ const { dsh, resumeSessionId } = input+ let preparedFolder: string | undefined+ let scmLaunchRecord: ScmLaunchRecord | null = null+ if (projectFolder) {+ try {+ preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),+ onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })+ }+ catch (error) {+ return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',+ detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }+ }+ // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or+ // the person's own repo is theirs to answer for (engines/kit/folderTrust.ts); a worktree gets only+ // the answer its source repo already has. `branch` IS the source folder: nothing to record.+ try {+ // A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.+ const engineTrust = folderTrust(input.engine, input.codexHome)+ if (engineTrust && (projectFolder.source === 'new'+ || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {+ engineTrust.record(preparedFolder)+ }+ } catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }+ } else if (!dsh && !resumeSessionId && local && dirname(input.cwd) === projectsRoot()) {+ // On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain+ // cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a+ // `new` project is — but only on evidence, and only where those workspaces live:+ //+ // · directly inside the projects root, which is the one folder the app and this daemon+ // create workspaces in. Claude Code's trust INHERITS downward, so recording it for a+ // folder the person merely browsed to — an empty `~/code`, or a home with nothing in it —+ // would silently cover every repo cloned under it later: OH-14 again by another door.+ // · empty as read from disk, never on the client's word. A clone, a worktree or the+ // person's own repo has content, so it stays the engine's question (engines/kit/folderTrust.ts).+ // · from a LOCAL frame. agent_create is not backend-only, so a relayed peer would otherwise+ // name an empty path on this host and have it trusted.+ //+ // DSH trust is decided in cli.ts, where the template count is known; leave that to it.+ try {+ const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)+ if (empty) folderTrust(input.engine, input.codexHome)?.record(input.cwd)+ } catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }+ }+ const result = await invoke(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)+ if (result.ok) return { state: 'created', agentId: result.session.agentId }+ // tmux may have executed before a timeout; registration cleanup is best-effort.+ // Neither can prove that no process started, so never encourage another launch.+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }+ return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }+ }++ const modelHold = { service: 'models', detail: 'Waiting for the selected model. This request is saved and will continue when it is available.' }+ const pending = createPendingLaunches({ receipts, prepare: async saved => {+ // A future intent kind cannot be interpreted as this one. Keep unknown or+ // damaged requests held instead of guessing at their launch choices.+ if (saved.kind !== 'model-create-v1' || typeof saved.local !== 'boolean'+ || !saved.input || typeof saved.input !== 'object' || !saved.selection || typeof saved.selection !== 'object') return null+ const input = structuredClone(saved.input) as CreateInput+ const selection = saved.selection as NewAgentModel+ if (!ENGINES.includes(input.engine) || typeof input.cwd !== 'string' || input.resumeSessionId+ || input.grid !== null || typeof selection.model !== 'string' || typeof selection.grid !== 'string') return null+ const invoke = createAgent()+ if (!invoke) return null+ const target = await modelTarget(selection)+ if (!target) return null+ input.grid = target+ return () => executeCreate(input, (saved.projectFolder ?? null) as ProjectFolder | null, saved.local as boolean, invoke)+ } })+/** Recover by stable runtime identity; a deleted agent must never become a fresh launch. */const creationStatusPayload = async (status: AgentCreationStatus): Promise<Record<string, unknown>> => {if (status.state === 'created') {@@ -142,21 +232,16 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA// A DSH is refused, never approximated: an agent created as its plain base engine would look// like it worked and have none of the skills the user picked the tile for.let dsh: string | null = null+ let installed: ReturnType<typeof installedDsh>if (payload.dsh !== undefined && payload.dsh !== null) {if (typeof payload.dsh !== 'string' || !DSH_ID_RE.test(payload.dsh)) {reply({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' }); return}- const installed = installedDsh(payload.dsh)- if (!installed) {- reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is not installed on this machine` }); return- }- if (installed.manifest.kind === 'viewer') {- reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is a viewer package, not an agent` }); return- }- if (!dshSupportedEngines(installed.manifest).includes(engine)) {- reply({ error: 'INVALID_DSH', detail: `${payload.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${engine} is not compatible` }); return- }- dsh = installed.id+ installed = installedDsh(payload.dsh)+ // Formerly-named packages used their canonical ID in both launch input+ // and v1 fingerprints. Resolve aliases without refusing a known receipt+ // merely because the package is no longer installed.+ dsh = installed?.id ?? payload.dsh}// A first prompt is refused BEFORE any pane exists: an engine with no way to take one would// otherwise open on an empty input and look like the person's request had been heard. The@@ -184,11 +269,6 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAif (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {reply({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return}- // v2's TUI cannot open a named agent. Its native version control is eager.- const opencode = engine === 'opencode' ? opencodeLaunch : null- if (!supportsNamedAgent(engine, opencode ? await opencode.opencodeMajorVersion() : null)) {- reply({ error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return- }agent = payload.agent}// A permission mode picked in New Harness. A client that predates the choice sends only@@ -244,61 +324,15 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA// on this connection, just as engines_probe is detached above.const create = onCreateAgenttry {- void receipts.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {- if (model.state === 'ok') {- const target = await modelTarget(model.selection).catch(() => null)- if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }- input.grid = target- }- let preparedFolder: string | undefined- let scmLaunchRecord: ScmLaunchRecord | null = null- if (projectFolder) {- try {- preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),- onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })- }- catch (error) {- return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',- detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }- }- // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or- // the person's own repo is theirs to answer for (engines/kit/folderTrust.ts); a worktree gets only- // the answer its source repo already has. `branch` IS the source folder: nothing to record.- try {- // A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.- const engineTrust = folderTrust(input.engine, input.codexHome)- if (engineTrust && (projectFolder.source === 'new'- || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {- engineTrust.record(preparedFolder)- }- } catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }- } else if (!dsh && !resumeSessionId && asker.local && dirname(input.cwd) === projectsRoot()) {- // On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain- // cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a- // `new` project is — but only on evidence, and only where those workspaces live:- //- // · directly inside the projects root, which is the one folder the app and this daemon- // create workspaces in. Claude Code's trust INHERITS downward, so recording it for a- // folder the person merely browsed to — an empty `~/code`, or a home with nothing in it —- // would silently cover every repo cloned under it later: OH-14 again by another door.- // · empty as read from disk, never on the client's word. A clone, a worktree or the- // person's own repo has content, so it stays the engine's question (engines/kit/folderTrust.ts).- // · from a LOCAL frame. agent_create is not backend-only, so a relayed peer would otherwise- // name an empty path on this host and have it trusted.- //- // DSH trust is decided in cli.ts, where the template count is known; leave that to it.- try {- const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)- if (empty) folderTrust(input.engine, input.codexHome)?.record(input.cwd)- } catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }- }- const result = await create(preparedFolder ? { ...input, cwd: preparedFolder, scmLaunchRecord } : input)- if (result.ok) return { state: 'created', agentId: result.session.agentId }- // tmux may have executed before a timeout; registration cleanup is best-effort.- // Neither can prove that no process started, so never encourage another launch.- if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }- return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }- }).then(async (status) => {+ const fingerprint = creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput)+ if (model.state !== 'ok' && !receipts.has(creationId, fingerprint)) {+ const refusal = await validateInstalled(input, installed)+ if (refusal) { reply(refusal); return }+ }+ const operation = model.state === 'ok'+ ? pending.start(creationId, fingerprint, { kind: 'model-create-v1', input, selection: model.selection, projectFolder, local: asker.local }, modelHold)+ : receipts.run(creationId, fingerprint, () => executeCreate(input, projectFolder, asker.local, create, true))+ void operation.then(async (status) => {reply({ creationId, ...await creationStatusPayload(status) })}).catch(() => reply({ error: 'INTERNAL' }))} catch (error) {@@ -307,6 +341,8 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAreturn}// Clients predating receipts retain their existing response shape.+ const refusal = await validateInstalled(input, installed)+ if (refusal) { reply(refusal); return }if (model.state === 'ok') {const target = await modelTarget(model.selection).catch(() => null)if (!target) { reply({ error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }@@ -404,5 +440,11 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAreply({ agent: await toProject(result.session), level: result.level })}- return { createStatus, create, relaunch, fork }+ const cancelCreate = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {+ if (!validCreationId(payload.creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }+ try { reply({ creationId: payload.creationId, ...await creationStatusPayload(receipts.cancelIntent(payload.creationId)) }) }+ catch (error) { reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' }) }+ }++ return { createStatus, cancelCreate, create, relaunch, fork, open: pending.open, stop: pending.stop, recover: pending.recover }}diff --git a/cli/src/core/agents/pendingLaunches.spec.ts b/cli/src/core/agents/pendingLaunches.spec.tsnew file mode 100644index 000000000..cd343fbe7--- /dev/null+++ b/cli/src/core/agents/pendingLaunches.spec.ts@@ -0,0 +1,240 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import { AgentCreationReceipts, creationFingerprint } from '../../lib/agentCreationReceipt.js'+import { createPendingLaunches, type IntentReceipts, type PreparedCreation } from './pendingLaunches.js'++const roots: string[] = []+const stops: Array<() => void> = []+const held = { service: 'models', detail: 'Waiting for the model.' }+const request = { kind: 'fixture' }+const fingerprint = creationFingerprint(request)+const id = (n: number) => `fixture-creation-${n}`+const created = { state: 'created' as const, agentId: 'fixture-agent' }+afterEach(() => {+ stops.splice(0).forEach(stop => stop())+ vi.useRealTimers()+ vi.restoreAllMocks()+ roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true }))+})+function setup(prepare = vi.fn<Parameters<typeof createPendingLaunches>[0]['prepare']>(), receipts?: IntentReceipts) {+ const root = mkdtempSync(join(tmpdir(), 'pending-launches-')); roots.push(root)+ const store = new AgentCreationReceipts(join(root, 'receipts'))+ const pending = createPendingLaunches({ receipts: receipts ?? store, prepare })+ stops.push(pending.stop)+ return { pending, store, prepare }+}++it('opens recovery after readiness, preserves pending intent and completes it once', async () => {+ const effect = vi.fn(async () => created)+ const prepare = vi.fn(async () => effect)+ const { pending, store } = setup(prepare)+ await store.runIntent(id(0), fingerprint, request, held, async () => null)+ await pending.recover()+ expect(prepare).not.toHaveBeenCalled()+ pending.open()+ pending.open()+ expect(pending.recover()).toBe(pending.recover())+ await pending.recover()+ await vi.waitFor(() => expect(store.status(id(0))).toEqual(created))+ await pending.recover()+ expect(effect).toHaveBeenCalledOnce()+ pending.stop()+ await pending.recover()+ pending.open()+ expect(effect).toHaveBeenCalledOnce()+})++it('bounds stalled preparations and retains their slots instead of accumulating promises', async () => {+ vi.useFakeTimers()+ const finish: Array<(value: PreparedCreation) => void> = []+ const prepare = vi.fn(() => new Promise<PreparedCreation>(resolve => finish.push(resolve)))+ const { pending, store } = setup(prepare)+ const jobs = Array.from({ length: 8 }, (_, n) => pending.start(id(n), fingerprint, request, held))+ await vi.advanceTimersByTimeAsync(5_000)+ expect(await Promise.all(jobs)).toEqual(Array.from({ length: 8 }, () => ({ state: 'pending', held })))+ expect(prepare).toHaveBeenCalledTimes(4)+ expect(await pending.start(id(8), fingerprint, request, held)).toEqual({ state: 'pending', held })+ expect(prepare).toHaveBeenCalledTimes(4)+ const effect = vi.fn(async () => created)+ finish.splice(0).forEach(resolve => resolve(effect))+ await vi.advanceTimersByTimeAsync(0)+ expect(effect).toHaveBeenCalledTimes(4)+ prepare.mockResolvedValue(effect)+ expect(await pending.start(id(0), fingerprint, request, held)).toEqual(created)+ expect(store.status(id(1))).toEqual(created)+})++it('retries rejected dependencies on its timer and stops old preflight completions', async () => {+ vi.useFakeTimers()+ const prepare = vi.fn().mockRejectedValueOnce(new Error('service disconnected'))+ const { pending, store } = setup(prepare)+ expect(await pending.start(id(0), fingerprint, request, held)).toEqual({ state: 'pending', held })+ pending.open()+ // Recovery starts after opendir; the explicit pass joins it.+ await pending.recover()+ let finish!: (value: PreparedCreation) => void+ prepare.mockImplementationOnce(() => new Promise<PreparedCreation>(resolve => { finish = resolve }))+ const running = pending.start(id(1), fingerprint, request, held)+ await vi.advanceTimersByTimeAsync(0)+ pending.stop()+ const effect = vi.fn(async () => created)+ finish(effect)+ expect(await running).toEqual({ state: 'pending', held })+ expect(effect).not.toHaveBeenCalled()+ expect(store.status(id(1))).toEqual({ state: 'pending', held })+ expect(await pending.start(id(2), fingerprint, request, held)).toEqual({ state: 'pending', held })+ await vi.advanceTimersByTimeAsync(2_000)+})++it('runs a streaming recovery four at a time and isolates a failed journal or request', async () => {+ const callbacks: Array<() => void> = []+ const prepare = vi.fn(() => new Promise<PreparedCreation>(resolve => callbacks.push(() => resolve(async () => created))))+ const { pending, store } = setup(prepare)+ for (let n = 0; n < 6; n++) await store.runIntent(id(n), fingerprint, request, held, async () => null)+ pending.open()+ await vi.waitFor(() => expect(callbacks).toHaveLength(4))+ expect(prepare).toHaveBeenCalledTimes(4)+ callbacks.splice(0).forEach(done => done())+ await vi.waitFor(() => expect(callbacks).toHaveLength(2), { timeout: 4_000 })+ callbacks.splice(0).forEach(done => done())+ await pending.recover()+ expect(prepare).toHaveBeenCalledTimes(6)+ await vi.waitFor(() => expect(store.status(id(5))).toEqual(created))++ const refused = vi.fn(() => { throw new Error('disk failed') })+ const damaged = setup(vi.fn(), { runIntent: refused, cancelIntent: vi.fn(), pendingIntent: vi.fn(() => ({ id: id(9), fingerprint, request, held })),+ pendingIntents: async function* () { yield { id: id(9), fingerprint, request, held }; throw new Error('directory unavailable') } })+ damaged.pending.open()+ await damaged.pending.recover()+ await vi.waitFor(() => expect(refused).toHaveBeenCalledOnce())+ damaged.pending.stop()+})++it('does not claim work yielded after shutdown or execute work stopped just after preparation', async () => {+ let yielded!: () => void+ const waiting = new Promise<void>(resolve => { yielded = resolve })+ const receipts: IntentReceipts = { runIntent: vi.fn(), cancelIntent: vi.fn(), pendingIntent: vi.fn(() => ({ id: id(9), fingerprint, request, held })), pendingIntents: async function* () {+ await waiting+ yield { id: id(0), fingerprint, request, held }+ } }+ const first = setup(vi.fn(), receipts)+ first.pending.open()+ first.pending.stop()+ yielded()+ await first.pending.recover()+ await vi.waitFor(() => expect(receipts.runIntent).not.toHaveBeenCalled())++ const effect = vi.fn(async () => created)+ const second = setup(vi.fn(async () => effect), { ...receipts, runIntent: async (_id, _fingerprint, request, _held, prepare) => {+ const ready = await prepare(request)+ second.pending.stop()+ return ready!()+ } })+ expect(await second.pending.start(id(1), fingerprint, request, held)).toEqual({ state: 'unconfirmed' })+ expect(effect).not.toHaveBeenCalled()+})++it('keeps one preparation per ID even after the service deadline, then retries after settlement', async () => {+ vi.useFakeTimers()+ let finish!: (value: PreparedCreation) => void+ const prepare = vi.fn(() => new Promise<PreparedCreation>(resolve => { finish = resolve }))+ const { pending } = setup(prepare)+ const first = pending.start(id(0), fingerprint, request, held)+ await vi.advanceTimersByTimeAsync(185_000)+ expect(await first).toEqual({ state: 'pending', held })+ expect(await pending.start(id(0), fingerprint, request, held)).toEqual({ state: 'pending', held })+ expect(prepare).toHaveBeenCalledOnce()+ const effect = vi.fn(async () => created)+ finish(effect)+ await vi.advanceTimersByTimeAsync(0)+ expect(effect).not.toHaveBeenCalled()+ prepare.mockResolvedValue(effect)+ expect(await pending.start(id(0), fingerprint, request, held)).toEqual(created)+ expect(effect).toHaveBeenCalledOnce()+})++it('bounds a large history per event-loop turn and does not keep retrying completed IDs', async () => {+ vi.spyOn(performance, 'now').mockReturnValue(0)+ let examined = 0+ const intent = { id: id(0), fingerprint, request, held }+ const receipts: IntentReceipts = {+ runIntent: vi.fn().mockRejectedValueOnce(new Error('storage unavailable')).mockResolvedValue({ state: 'pending', held }),+ cancelIntent: vi.fn(), pendingIntent: vi.fn(() => intent),+ pendingIntents: async function* () {+ for (let n = 0; n < 130; n++) { examined++; yield null }+ yield intent+ },+ }+ const { pending } = setup(vi.fn(), receipts)+ pending.open()+ await pending.recover()+ expect(examined).toBe(64)+ await vi.waitFor(() => expect(receipts.runIntent).toHaveBeenCalledOnce())+ expect(examined).toBe(130)+ vi.mocked(receipts.pendingIntent).mockReturnValue(null)+ // A later cancellation/completion is read from disk, then removed from the+ // retry set rather than retained as an ever-growing outcome cache.+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 3_000)+ await pending.recover(); await pending.recover()+ expect(receipts.runIntent).toHaveBeenCalledOnce()+})++it('contains a directory-close error on shutdown', async () => {+ const scan = (async function* () { for (;;) yield null })()+ vi.spyOn(scan, 'return').mockRejectedValueOnce(new Error('directory closed'))+ const receipts: IntentReceipts = { runIntent: vi.fn(), cancelIntent: vi.fn(), pendingIntent: vi.fn(), pendingIntents: () => scan }+ const { pending } = setup(vi.fn(), receipts)+ pending.open()+ await pending.recover()+ pending.stop()+ await Promise.resolve()+ expect(scan.return).toHaveBeenCalledOnce()+ expect(receipts.runIntent).not.toHaveBeenCalled()+})++it('bounds the retry window and visits the backlog beyond permanently held or damaged early IDs', async () => {+ vi.useFakeTimers()+ vi.spyOn(performance, 'now').mockReturnValue(0)+ const attempted = new Set<string>()+ let scanned = 0+ let largestBacklog = 0+ const receipts: IntentReceipts = {+ runIntent: vi.fn(async () => ({ state: 'pending' as const, held })), cancelIntent: vi.fn(),+ pendingIntent: vi.fn(key => {+ attempted.add(key)+ if (key === id(32)) throw new Error('damaged intent')+ return { id: key, fingerprint, request, held }+ }),+ pendingIntents: async function* () {+ for (let n = 0; n < 260; n++) {+ scanned+++ largestBacklog = Math.max(largestBacklog, scanned - attempted.size)+ yield { id: id(n), fingerprint, request, held }+ }+ },+ }+ const { pending } = setup(vi.fn(), receipts)+ pending.open()+ await vi.advanceTimersByTimeAsync(20_000)+ expect(largestBacklog).toBeLessThanOrEqual(128)+ expect(attempted.size).toBe(260)+ // An explicit new request while the window is full still receives its saved+ // hold; the window size never becomes a reason to reject durable admission.+ for (let n = 300; n < 450; n++) expect(await pending.start(id(n), fingerprint, request, held)).toEqual({ state: 'pending', held })+})++it('includes synchronous retry reads in the event-loop work budget', async () => {+ let work = 0+ vi.spyOn(performance, 'now').mockImplementation(() => work)+ const receipts: IntentReceipts = {+ runIntent: vi.fn(async () => ({ state: 'pending' as const, held })), cancelIntent: vi.fn(),+ pendingIntent: vi.fn(key => { work += 21; return { id: key, fingerprint, request, held } }),+ pendingIntents: async function* () { for (let n = 0; n < 5; n++) yield { id: id(n), fingerprint, request, held } },+ }+ const { pending } = setup(vi.fn(), receipts)+ pending.open(); await pending.recover()+ await pending.recover()+ expect(receipts.pendingIntent).toHaveBeenCalledOnce()+})diff --git a/cli/src/core/agents/pendingLaunches.ts b/cli/src/core/agents/pendingLaunches.tsnew file mode 100644index 000000000..b307be95b--- /dev/null+++ b/cli/src/core/agents/pendingLaunches.ts@@ -0,0 +1,130 @@+import type { AgentCreationOutcome, AgentCreationReceipts, CreationHold, PendingCreationIntent } from '../../lib/agentCreationReceipt.js'++export type PreparedCreation = (() => Promise<AgentCreationOutcome>) | null+export type IntentReceipts = Pick<AgentCreationReceipts, 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>++/** Core owns dependency retries. It opens after readiness, bounds stalled+ * service calls and never replays an effect whose durable claim already exists. */+export function createPendingLaunches({ receipts, prepare }: {+ receipts: IntentReceipts+ prepare: (request: Record<string, unknown>) => Promise<PreparedCreation>+}) {+ let stopped = false+ let opened = false+ let active = 0+ let timer: ReturnType<typeof setInterval> | undefined+ let continuation: ReturnType<typeof setImmediate> | undefined+ let recovering: Promise<void> | undefined+ let scan: AsyncGenerator<PendingCreationIntent | null> | undefined+ let scanAt = 0+ let crowded = false+ let startAfter = 0+ const windowSize = 128+ // Only IDs and retry times live here. Every attempt reads its private intent+ // afresh; resolved models, credentials and completed outcomes are not cached.+ const pending = new Map<string, number>()+ let turn = pending.entries()+ const preparing = new Map<string, Promise<PreparedCreation>>()+ const remember = (id: string, at: number) => {+ if (pending.has(id) || pending.size < windowSize) pending.set(id, at)+ else crowded = true // The complete request is already durable on disk.+ }++ const prepareOne = async (id: string, request: Record<string, unknown>): Promise<PreparedCreation> => {+ active+++ let deadline: ReturnType<typeof setTimeout> | undefined+ try {+ const ready = await Promise.race([+ // Retain a timed-out service's slot until its promise settles instead+ // of accumulating unlimited abandoned preparations during an outage.+ Promise.resolve().then(() => prepare(request)).catch(() => null).finally(() => { active--; preparing.delete(id) }),+ // launchTarget permits three minutes for credential preparation. The+ // receipt answers pending after five seconds without ending this work.+ new Promise<null>(resolve => { deadline = setTimeout(() => resolve(null), 185_000); deadline.unref?.() }),+ ])+ return stopped || !ready ? null : () => stopped ? Promise.resolve({ state: 'unconfirmed' }) : ready()+ } finally { clearTimeout(deadline) }+ }+ const bounded = (id: string, request: Record<string, unknown>): Promise<PreparedCreation> => {+ if (stopped) return Promise.resolve(null)+ const existing = preparing.get(id)+ if (existing) return existing+ if (active >= 4) return Promise.resolve(null)+ const result = prepareOne(id, request)+ preparing.set(id, result)+ return result+ }+ const start = (id: string, fingerprint: string, request: Record<string, unknown>, held: CreationHold) => {+ const result = receipts.runIntent(id, fingerprint, request, held, saved => bounded(id, saved))+ remember(id, Date.now() + 2_000)+ // Under backlog pressure, a settled hold gives its window slot to the next+ // disk entry. The cursor finishes that pass before revisiting earlier IDs;+ // permanently unavailable choices cannot starve the tail of the directory.+ const release = () => { if (crowded) pending.delete(id) }+ void result.then(status => { if (status.state !== 'pending') pending.delete(id); else release() }, release)+ return result+ }++ const recover = (): Promise<void> => {+ if (!opened || stopped) return Promise.resolve()+ if (recovering) return recovering+ recovering = (async () => {+ const began = performance.now()+ let started = 0+ // Include synchronous receipt reads in the SAME event-loop work budget+ // as the directory scan. Background dispatch is at most four per tick.+ if (Date.now() >= startAfter) {+ for (let inspected = 0; inspected < 64 && started < 4 && !stopped && performance.now() - began < 20; inspected++) {+ const next = turn.next()+ if (next.done) { turn = pending.entries(); break }+ const [id, at] = next.value+ if (Date.now() < at) continue+ pending.set(id, Date.now() + 2_000)+ started+++ try {+ const intent = receipts.pendingIntent(id)+ if (!intent) { pending.delete(id); continue }+ void start(id, intent.fingerprint, intent.request, intent.held).catch(() => {})+ } catch { if (crowded) pending.delete(id) /* Uncertain storage never blocks sibling IDs. */ }+ }+ if (started) startAfter = Date.now() + 250+ }+ // A cursor yields for EVERY directory entry, including old receipts and+ // corrupt records. Bound work per pass; a large history cannot monopolize+ // session control. A background rescan finds intents another core saved.+ try {+ if (!scan && Date.now() >= scanAt) scan = receipts.pendingIntents()+ if (scan) {+ for (let n = 0; n < 64 && !stopped && performance.now() - began < 20; n++) {+ if (pending.size >= windowSize) { crowded = true; break }+ const entry = await scan.next()+ if (entry.done) { scan = undefined; crowded = false; scanAt = Date.now() + 60_000; break }+ if (entry.value && !pending.has(entry.value.id)) remember(entry.value.id, 0)+ }+ }+ } catch { scan = undefined; scanAt = Date.now() + 2_000 }+ // Receipt replies have their own deadline. Neither they nor a stalled+ // dependency delay the next bounded scan or another session's retry.+ })().finally(() => {+ recovering = undefined+ if (scan && !stopped && pending.size < windowSize) continuation = setImmediate(() => { void recover() })+ })+ return recovering+ }++ return {+ start, recover,+ open: () => {+ if (opened || stopped) return+ opened = true+ timer = setInterval(() => { void recover() }, 250)+ timer.unref?.()+ void recover()+ },+ stop: () => {+ stopped = true+ clearInterval(timer); clearImmediate(continuation)+ void scan?.return(null).catch(() => {})+ },+ }+}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 5fbb3b310..de5475d8d 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -2432,6 +2432,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {})backend.createProvider = launches.createbackend.createStatusProvider = launches.createStatus+ backend.cancelCreateProvider = launches.cancelCreatebackend.restartProvider = launches.relaunchbackend.forkProvider = launches.fork@@ -2465,7 +2466,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// stops being `bootHandoff` HERE, and not a line earlier: everything the teardown releases exists by now.// A straight-line assignment, never a wait: if the body never reaches this line the handler stays// `bootHandoff`, and the fix still lands.- const updateTeardown = (): TeardownStep[] => { installedHooks?.close(); externalResumes?.stop(); return [+ const updateTeardown = (): TeardownStep[] => { installedHooks?.close(); externalResumes?.stop(); launches.stop(); return [['the registry', () => registry.flush({ exiting: true })], ['the updater', () => daemonBoot.updaterBeside?.()],['the reconciler', () => agentReconciler.stop()],['the timers', () => { clearInterval(logTrimTimer); clearInterval(runtimeReconcileTimer); clearInterval(paneTitleSyncTimer) }],@@ -2504,6 +2505,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const shutdown = async (signal: string): Promise<void> => {installedHooks?.close()externalResumes?.stop()+ launches.stop()console.log(`\n[cli] ${signal} — shutting down`)// A slow teardown may exhaust the master's grace. Persist already acknowledged bindings first.registry.flush({ exiting: true })@@ -2632,6 +2634,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Ready first, never after a service: the agents the boot held for one are launched now, in the background.void heldLaunches.restoreHeld()externalResumes.open()+ launches.open()}/**diff --git a/cli/src/core/transcripts/attach.control.spec.ts b/cli/src/core/transcripts/attach.control.spec.tsindex 25663ae68..4169ca121 100644--- a/cli/src/core/transcripts/attach.control.spec.ts+++ b/cli/src/core/transcripts/attach.control.spec.ts@@ -196,13 +196,23 @@ it.each(['inline', 'worker'] as const)('%s refuses a different replay descriptorconst other = t.file + '.other'; writeFileSync(other, prompt('T2'))const { open } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')const verifyFile = vi.spyOn(await import('../../lib/transcriptBoundary.js'), 'verifyTranscriptHandle')- vi.spyOn(nativeReads, 'open').mockImplementation((path, flags, access) => open(path === t.file ? other : path, flags, access))+ const redirected = new Set<Awaited<ReturnType<typeof open>>>()+ vi.spyOn(nativeReads, 'open').mockImplementation(async (path, flags, access) => {+ const handle = await open(path === t.file ? other : path, flags, access)+ if (path === t.file) redirected.add(handle)+ return handle+ })await t.attach.attachSession(t.row)expect(t.row.interpretationHold).toBeTruthy()expect(t.emit).not.toHaveBeenCalled()expect(t.settled).not.toHaveBeenCalled()expect(verifyFile).toHaveBeenCalled()- await expect(verifyFile.mock.results[0]?.value).rejects.toThrow('ENGINE_CONTROL_BOUNDARY_CHANGED')+ // A watcher read already in flight can verify its original descriptor first.+ // Check the handles redirected by this test, independent of that scheduling.+ const redirectedChecks = verifyFile.mock.calls.flatMap(([handle], index) =>+ redirected.has(handle) ? [verifyFile.mock.results[index]?.value] : [])+ expect(redirectedChecks.length).toBeGreaterThan(0)+ for (const check of redirectedChecks) await expect(check).rejects.toThrow('ENGINE_CONTROL_BOUNDARY_CHANGED')})it.each(['inline', 'worker'] as const)('%s retains a later ordinary Cancel without replacing its live parser', async mode => {diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.tsindex cbb9f94e9..962475c8e 100644--- a/cli/src/engines/otherIdentity.golden.spec.ts+++ b/cli/src/engines/otherIdentity.golden.spec.ts@@ -20,6 +20,7 @@import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { performance } from 'node:perf_hooks'import { fileURLToPath } from 'node:url'import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import type { AgentEngine } from './types.js'@@ -92,12 +93,17 @@ type Modules = {cursorDiscovery: typeof import('../core/engines/cursorDiscovery.js')}let m: Modules+let restoreClock = () => {}beforeAll(async () => {root = realpathSync(mkdtempSync(join(tmpdir(), 'other-identity-golden-')))for (const cwd of ['r', 'other']) mkdirSync(join(root, 'workspaces', cwd), { recursive: true })Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })vi.useFakeTimers({ toFake: ['Date'], now: NOW })+ // This records healthy identity wiring. Registry fsync under runner load must+ // not spend its proof deadline; nativeEvidence.spec.ts tests elapsed budgets.+ const monotonic = vi.spyOn(performance, 'now').mockReturnValue(0)+ restoreClock = () => monotonic.mockRestore()const home = join(root, 'home')const env: Record<string, string | undefined> = {HOME: home, XDG_CONFIG_HOME: undefined, XDG_DATA_HOME: undefined, ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'),@@ -128,6 +134,7 @@ beforeAll(async () => {})afterAll(() => {+ restoreClock()vi.useRealTimers()Object.defineProperty(process, 'platform', platform)for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = valuediff --git a/cli/src/lib/__fixtures__/initial-launch.golden.json b/cli/src/lib/__fixtures__/initial-launch.golden.jsonnew file mode 100644index 000000000..6b6ef00a2--- /dev/null+++ b/cli/src/lib/__fixtures__/initial-launch.golden.json@@ -0,0 +1,102 @@+{+ "linux": {+ "events": [+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "observed",+ 42+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "dormant",+ "engine process absent after 2 confirmed scans"+ ],+ [+ "terminal",+ false+ ],+ [+ "removed",+ "terminal runtime absent after 2 confirmed scans"+ ]+ ],+ "active": false,+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture/bin/codex",+ "startMarker": "fixture-start"+ }+ },+ "darwin": {+ "events": [+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "observed",+ 42+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "terminal",+ true+ ],+ [+ "dormant",+ "engine process absent after 2 confirmed scans"+ ],+ [+ "terminal",+ false+ ],+ [+ "removed",+ "terminal runtime absent after 2 confirmed scans"+ ]+ ],+ "active": false,+ "processIdentity": {+ "pid": 42,+ "executable": "/fixture/bin/codex",+ "startMarker": "fixture-start"+ }+ }+}diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.tsindex bcb7f43a8..aab1d5105 100644--- a/cli/src/lib/agentCreationReceipt.spec.ts+++ b/cli/src/lib/agentCreationReceipt.spec.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'+import * as fs from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from './agentCreationReceipt.js'@@ -15,6 +16,12 @@ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive:const id = 'creation-intent-0001'const fingerprint = creationFingerprint({ engine: 'claude', cwd: '/work', bypassPermission: false })+vi.mock('node:fs', async (original) => {+ const actual = await original<typeof import('node:fs')>()+ return { ...actual, fsyncSync: vi.fn(actual.fsyncSync), linkSync: vi.fn(actual.linkSync) }+})+afterEach(() => vi.restoreAllMocks())+describe('agent creation receipts', () => {it('shares an in-flight launch and recovers its result after a lost reply and daemon restart', async () => {const { directory, receipts } = fixture()@@ -77,6 +84,7 @@ describe('agent creation receipts', () => {const { directory, receipts } = fixture()const create = vi.fn(async () => ({ state: 'created' as const, agentId: 'agent-1' }))expect(receipts.status(id)).toEqual({ state: 'missing' })+ mkdirSync(directory, { mode: 0o700 })writeFileSync(join(directory, `${id}.json`), '{partial', { mode: 0o600 })expect(() => receipts.run(id, fingerprint, create)).toThrow('CREATION_STORAGE_FAILED')expect(() => receipts.run('../invalid-id', fingerprint, create)).toThrow('INVALID_CREATION_ID')@@ -119,3 +127,235 @@ it('retains a fresh restart outcome through a daemon restart', async () => {expect(await recovered.run(id, intent, restart)).toEqual(recovered.status(id))expect(restart).toHaveBeenCalledTimes(1)})++describe('recoverable undispatched creation intents', () => {+ const request = { kind: 'model-create', local: false, choices: { engine: 'claude', cwd: '/fixture/work', model: 'fixture-model' } }+ const held = { service: 'models', detail: 'Waiting for the selected model.' }+ const created = { state: 'created' as const, agentId: 'fixture-agent' }++ it('persists a held request, resumes it in another core and dispatches once across two cores', async () => {+ const { directory, receipts } = fixture()+ const offline = vi.fn(async () => null)+ expect(await receipts.runIntent(id, fingerprint, request, held, offline)).toEqual({ state: 'pending', held })+ const recovered = new AgentCreationReceipts(directory)+ expect(recovered.status(id)).toEqual({ state: 'pending', held })+ const found = []+ for await (const row of recovered.pendingIntents()) if (row) found.push(row)+ expect(found).toEqual([{ id, fingerprint, request, held }])+ let ready!: () => void+ const service = new Promise<void>(resolve => { ready = resolve })+ let finish!: (result: AgentCreationOutcome) => void+ const effect = vi.fn(() => new Promise<AgentCreationOutcome>(resolve => { finish = resolve }))+ const prepare = vi.fn(async (saved) => { expect(saved).toEqual(request); await service; return effect })+ const first = recovered.runIntent(id, fingerprint, request, held, prepare)+ const duplicate = recovered.runIntent(id, fingerprint, request, held, prepare)+ const competing = receipts.runIntent(id, fingerprint, request, held, prepare)+ expect(first).toBe(duplicate)+ ready()+ await vi.waitFor(() => expect(effect).toHaveBeenCalledOnce())+ expect(await competing).toEqual({ state: 'unconfirmed' })+ expect(recovered.status(id)).toEqual({ state: 'pending' })+ finish(created)+ expect(await first).toEqual(created)+ expect(new AgentCreationReceipts(directory).status(id)).toEqual(created)+ expect(await receipts.runIntent(id, fingerprint, request, held, prepare)).toEqual(created)+ expect(effect).toHaveBeenCalledOnce()+ })++ it('lets a durable cancellation beat an unresolved dependency without any effect', async () => {+ const { directory, receipts } = fixture()+ let ready!: () => void+ const service = new Promise<void>(resolve => { ready = resolve })+ const effect = vi.fn(async () => created)+ const running = receipts.runIntent(id, fingerprint, request, held, async () => { await service; return effect })+ expect(new AgentCreationReceipts(directory).cancelIntent(id)).toEqual({ state: 'cancelled' })+ ready()+ expect(await running).toEqual({ state: 'cancelled' })+ expect(effect).not.toHaveBeenCalled()+ expect(new AgentCreationReceipts(directory).status(id)).toEqual({ state: 'cancelled' })+ })++ it.each(['missing', 'corrupt', 'changed', 'directory', 'cancelled'])('revokes a deferred callback when its durable intent is %s', async change => {+ const { root, directory, receipts } = fixture()+ let ready!: () => void+ const service = new Promise<void>(resolve => { ready = resolve })+ const effect = vi.fn(async () => created)+ const running = receipts.runIntent(id, fingerprint, request, held, async () => { await service; return effect })+ const answer = running.catch(error => error)+ const file = join(directory, `${id}.json`)+ const bytes = readFileSync(file, 'utf8')+ if (change === 'directory') {+ renameSync(directory, join(root, 'old-receipts'))+ mkdirSync(directory, { mode: 0o700 })+ writeFileSync(file, bytes, { mode: 0o600 })+ } else if (change === 'corrupt') writeFileSync(file, '{')+ else if (change === 'changed') {+ const value = JSON.parse(bytes)+ value.request.changed = true+ value.checksum = creationFingerprint({ fingerprint: value.fingerprint, request: value.request, held: value.held })+ writeFileSync(file, JSON.stringify(value))+ } else {+ rmSync(file)+ if (change === 'cancelled') expect(new AgentCreationReceipts(directory).cancelIntent(id)).toEqual({ state: 'cancelled' })+ }+ ready()+ if (change === 'cancelled') expect(await answer).toEqual({ state: 'cancelled' })+ else expect(await answer).toMatchObject({ code: 'CREATION_STORAGE_FAILED' })+ expect(effect).not.toHaveBeenCalled()+ })++ it('keeps a cancel-before-create tombstone through restart and does not cancel a claimed effect', async () => {+ const { directory, receipts } = fixture()+ expect(receipts.cancelIntent(id)).toEqual({ state: 'cancelled' })+ const next = new AgentCreationReceipts(directory)+ const prepare = vi.fn()+ expect(await next.runIntent(id, fingerprint, request, held, prepare)).toEqual({ state: 'cancelled' })+ expect(await next.run(id, fingerprint, prepare)).toEqual({ state: 'cancelled' })+ expect(prepare).not.toHaveBeenCalled()+ let finish!: (result: AgentCreationOutcome) => void+ const effect = vi.fn(() => new Promise<AgentCreationOutcome>(resolve => { finish = resolve }))+ const running = next.runIntent(`${id}-next`, fingerprint, request, held, async () => effect)+ await vi.waitFor(() => expect(effect).toHaveBeenCalledOnce())+ expect(receipts.cancelIntent(`${id}-next`)).toEqual({ state: 'unconfirmed' })+ finish(created)+ expect(await running).toEqual(created)+ expect(receipts.cancelIntent(`${id}-next`)).toEqual(created)+ })++ it('never replays a claimed effect after an exception or a lost completion record', async () => {+ const { directory, receipts } = fixture()+ const effect = vi.fn(async () => { throw new Error('reply lost after project or terminal effect') })+ expect(await receipts.runIntent(id, fingerprint, request, held, async () => effect)).toEqual({ state: 'unconfirmed' })+ const restarted = new AgentCreationReceipts(directory)+ expect(await restarted.runIntent(id, fingerprint, request, held, async () => effect)).toEqual({ state: 'unconfirmed' })+ expect(effect).toHaveBeenCalledOnce()+ const other = `${id}-lost-result`+ await receipts.runIntent(other, fingerprint, request, held, async () => async () => {+ vi.mocked(fs.linkSync).mockImplementationOnce(() => { throw new Error('disk disconnected') })+ return created+ })+ expect(receipts.status(other)).toEqual(created)+ expect(new AgentCreationReceipts(directory).status(other)).toEqual({ state: 'unconfirmed' })+ })++ it('does not execute after a claim was linked but its directory sync failed', async () => {+ const { directory, receipts } = fixture()+ const effect = vi.fn(async () => created)+ const realSync = vi.mocked(fs.fsyncSync).getMockImplementation()+ const prepare = async () => {+ let calls = 0+ vi.mocked(fs.fsyncSync).mockImplementation(fd => {+ if (++calls === 3) throw new Error('directory sync failed after link')+ realSync!(fd)+ })+ return effect+ }+ await expect(receipts.runIntent(id, fingerprint, request, held, prepare)).rejects.toThrow('CREATION_STORAGE_FAILED')+ vi.mocked(fs.fsyncSync).mockImplementation(realSync!)+ expect(effect).not.toHaveBeenCalled()+ const other = new AgentCreationReceipts(directory)+ expect(await other.runIntent(id, fingerprint, request, held, prepare)).toEqual({ state: 'unconfirmed' })+ expect(effect).not.toHaveBeenCalled()+ })++ it.each(['claim-token', 'result-token', 'outcome', 'preexisting', 'missing-claim', 'cancel-kind', 'missing-all', 'missing-directory', 'tombstone', 'legacy'])('does not hide conflicting %s evidence beneath an unsaved local outcome', async conflict => {+ const { directory, receipts } = fixture()+ const effect = vi.fn(async () => {+ if (conflict === 'preexisting') {+ const claim = JSON.parse(readFileSync(join(directory, `${id}.json.claim`), 'utf8'))+ writeFileSync(join(directory, `${id}.json.result`), JSON.stringify({ ...claim, token: 'other-claim', outcome: created }), { mode: 0o600 })+ } else vi.mocked(fs.linkSync).mockImplementationOnce(() => { throw new Error('disk disconnected') })+ return created+ })+ if (conflict === 'preexisting') {+ await expect(receipts.runIntent(id, fingerprint, request, held, async () => effect)).rejects.toThrow('CREATION_STORAGE_FAILED')+ } else {+ expect(await receipts.runIntent(id, fingerprint, request, held, async () => effect)).toEqual(created)+ const claimFile = join(directory, `${id}.json.claim`)+ const claim = JSON.parse(readFileSync(claimFile, 'utf8'))+ if (conflict === 'claim-token') writeFileSync(claimFile, JSON.stringify({ ...claim, token: 'other-claim' }))+ else if (conflict === 'cancel-kind') writeFileSync(claimFile, JSON.stringify({ ...claim, kind: 'cancel' }))+ else if (['missing-claim', 'missing-all', 'tombstone', 'legacy'].includes(conflict)) {+ rmSync(claimFile)+ if (conflict === 'missing-all') rmSync(join(directory, `${id}.json`))+ if (conflict === 'tombstone') writeFileSync(join(directory, `${id}.json`), JSON.stringify({ version: 2, cancelled: true }))+ if (conflict === 'legacy') writeFileSync(join(directory, `${id}.json`), JSON.stringify({ version: 1, fingerprint, outcome: { state: 'pending' } }))+ }+ else if (conflict === 'missing-directory') rmSync(directory, { recursive: true })+ else writeFileSync(join(directory, `${id}.json.result`), JSON.stringify({ ...claim,+ token: conflict === 'result-token' ? 'other-claim' : claim.token,+ outcome: conflict === 'outcome' ? { state: 'created', agentId: 'different-agent' } : created }), { mode: 0o600 })+ }+ expect(() => receipts.status(id)).toThrow('CREATION_STORAGE_FAILED')+ await expect(async () => await receipts.runIntent(id, fingerprint, request, held, async () => effect)).rejects.toThrow('CREATION_STORAGE_FAILED')+ await expect(async () => await receipts.run(id, fingerprint, effect)).rejects.toThrow('CREATION_STORAGE_FAILED')+ expect(() => receipts.cancelIntent(id)).toThrow('CREATION_STORAGE_FAILED')+ expect(effect).toHaveBeenCalledOnce()+ })++ it('lets a slow successful dependency complete the original request after a prompt pending reply', async () => {+ vi.useFakeTimers()+ try {+ const { receipts } = fixture()+ const effect = vi.fn(async () => created)+ const prepare = vi.fn(async () => { await new Promise(resolve => setTimeout(resolve, 6_000)); return effect })+ const first = receipts.runIntent(id, fingerprint, request, held, prepare)+ await vi.advanceTimersByTimeAsync(5_000)+ expect(await first).toEqual({ state: 'pending', held })+ expect(receipts.status(id)).toEqual({ state: 'pending', held })+ expect(await receipts.runIntent(id, fingerprint, request, held, prepare)).toEqual({ state: 'pending', held })+ expect(prepare).toHaveBeenCalledOnce()+ await vi.advanceTimersByTimeAsync(1_000)+ expect(receipts.status(id)).toEqual(created)+ expect(effect).toHaveBeenCalledOnce()+ } finally { vi.useRealTimers() }+ })++ it('holds orphan results, missing intents and null records instead of repeating an effect', async () => {+ const { directory, receipts } = fixture()+ const effect = vi.fn(async () => created)+ const prepare = vi.fn(async () => effect)+ await receipts.runIntent(id, fingerprint, request, held, prepare)+ rmSync(join(directory, `${id}.json.claim`))+ const recovered = new AgentCreationReceipts(directory)+ expect(() => recovered.runIntent(id, fingerprint, request, held, prepare)).toThrow('CREATION_STORAGE_FAILED')+ expect(() => recovered.cancelIntent(id)).toThrow('CREATION_STORAGE_FAILED')+ rmSync(join(directory, `${id}.json`))+ expect(() => recovered.run(id, fingerprint, effect)).toThrow('CREATION_STORAGE_FAILED')+ expect(() => recovered.status(id)).toThrow('CREATION_STORAGE_FAILED')+ writeFileSync(join(directory, `${id}.json.result`), 'null', { mode: 0o600 })+ expect(() => recovered.runIntent(id, fingerprint, request, held, prepare)).toThrow('CREATION_STORAGE_FAILED')+ expect(effect).toHaveBeenCalledOnce()+ expect(prepare).toHaveBeenCalledOnce()+ })++ it('flushes new directory names before publishing and refuses an unavailable parent flush', async () => {+ const { directory, receipts } = fixture()+ const effect = vi.fn(async () => created)+ const prepare = vi.fn(async () => effect)+ vi.mocked(fs.fsyncSync).mockImplementationOnce(() => { throw new Error('parent not durable') })+ expect(() => receipts.runIntent(id, fingerprint, request, held, prepare)).toThrow('CREATION_STORAGE_FAILED')+ expect(prepare).not.toHaveBeenCalled()+ expect(effect).not.toHaveBeenCalled()+ expect(await new AgentCreationReceipts(directory).runIntent(id, fingerprint, request, held, prepare)).toEqual(created)+ })++ it('retains v1 exclusions and refuses changed, corrupt or oversized intent data', async () => {+ const { directory, receipts } = fixture()+ await receipts.run(id, fingerprint, async () => created)+ const prepare = vi.fn(async () => vi.fn())+ expect(await receipts.runIntent(id, fingerprint, request, held, prepare)).toEqual(created)+ expect(() => receipts.runIntent(id, creationFingerprint({ changed: true }), request, held, prepare)).toThrow('CREATION_CONFLICT')+ const other = `${id}-held`+ await receipts.runIntent(other, fingerprint, request, held, async () => null)+ expect(() => receipts.run(other, creationFingerprint({ changed: true }), vi.fn())).toThrow('CREATION_CONFLICT')+ expect(await receipts.run(other, fingerprint, vi.fn())).toEqual({ state: 'pending', held })+ writeFileSync(join(directory, `${other}.json.claim`), '{partial', { mode: 0o600 })+ expect(() => receipts.status(other)).toThrow('CREATION_STORAGE_FAILED')+ expect(() => receipts.runIntent(`${id}-huge`, fingerprint, { text: 'x'.repeat(262_144) }, held, prepare)).toThrow('CREATION_STORAGE_FAILED')+ const found = []+ for await (const item of receipts.pendingIntents()) if (item) found.push(item)+ expect(found).toEqual([])+ expect(prepare).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.tsindex f3dbbed11..9fb0ad9c6 100644--- a/cli/src/lib/agentCreationReceipt.ts+++ b/cli/src/lib/agentCreationReceipt.ts@@ -1,5 +1,6 @@import { createHash, randomUUID } from 'node:crypto'-import { closeSync, constants, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { opendir } from 'node:fs/promises'import { dirname, join } from 'node:path'import { readPrivateStateFile, secureStateDirectory } from './secureState.js'@@ -9,7 +10,23 @@ export type AgentCreationOutcome =| { state: 'unconfirmed' }export type AgentCreationStatus = AgentCreationOutcome- | { state: 'pending' | 'missing' }+ | { state: 'pending'; held?: CreationHold }+ | { state: 'missing' | 'cancelled' }++export interface CreationHold { service: string; detail: string }+export interface PendingCreationIntent { id: string; fingerprint: string; request: Record<string, unknown>; held: CreationHold }++/** An undispatched request can be recovered. A claimed request cannot: even a+ * dead owner may have left a live child, or changed a project before it died. */+type IntentReceipt = {+ version: 2+ fingerprint: string+ request: Record<string, unknown>+ held: CreationHold+ checksum: string+} | { version: 2; cancelled: true }+type IntentClaim = { fingerprint: string; token: string; kind: 'dispatch' | 'cancel' }+type IntentResult = { fingerprint: string; token: string; outcome: AgentCreationOutcome }type Receipt = {version: 1@@ -17,6 +34,14 @@ type Receipt = {outcome: AgentCreationOutcome | { state: 'pending' }}+function validOutcome(outcome: AgentCreationOutcome | undefined): outcome is AgentCreationOutcome {+ return !!outcome && (outcome.state === 'unconfirmed'+ || (outcome.state === 'failed' && typeof outcome.error === 'string')+ || (outcome.state === 'created' && typeof outcome.agentId === 'string' && !!outcome.agentId+ && (outcome.level === undefined || outcome.level === 'native' || outcome.level === 'handoff')+ && (outcome.resumed === undefined || typeof outcome.resumed === 'boolean')))+}+export class AgentCreationReceiptError extends Error {constructor(readonly code: 'INVALID_CREATION_ID' | 'CREATION_CONFLICT' | 'CREATION_STORAGE_FAILED') {super(code)@@ -27,8 +52,8 @@ export function validCreationId(value: unknown): value is string {return typeof value === 'string' && /^[a-zA-Z0-9_-]{16,96}$/.test(value)}-/** Only a hash is retained: launch credentials and folder/profile choices do not- * become a second copy of the launch configuration in the receipt directory. */+/** Stable semantic identity. Legacy receipts retain only this hash; recoverable+ * model intents also retain their private request, never a resolved credential. */export function creationFingerprint(value: unknown): string {const canonical = (item: unknown): unknown => Array.isArray(item)? item.map(canonical)@@ -52,12 +77,25 @@ export class AgentCreationReceipts {// A failed outcome write must not forget an agent we already know was created.// The on-disk reservation still prevents a duplicate after a later restart.private readonly unsaved = new Map<string, Receipt>()+ private readonly intentResults = new Map<string, IntentResult>()constructor(private readonly directory: string) {}+ /** An existing ID is consulted before mutable installation checks. A fresh+ * legacy request still gets its original, correctable validation refusal. */+ has(id: string, fingerprint: string): boolean {+ const receipt = this.read(id)+ if (!receipt) return false+ if (!(receipt.version === 2 && 'cancelled' in receipt) && receipt.fingerprint !== fingerprint) {+ throw new AgentCreationReceiptError('CREATION_CONFLICT')+ }+ return true+ }+status(id: string): AgentCreationStatus {const receipt = this.read(id)if (!receipt) return { state: 'missing' }+ if (receipt.version === 2) return this.intentStatus(id, receipt)return receipt.outcome.state === 'pending' && !this.inFlight.has(id)? { state: 'unconfirmed' }: receipt.outcome@@ -71,6 +109,7 @@ export class AgentCreationReceipts {}const receipt = this.read(id)if (receipt) {+ if (receipt.version === 2 && 'cancelled' in receipt) return Promise.resolve(this.intentStatus(id, receipt))if (receipt.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')return Promise.resolve(this.status(id))}@@ -81,6 +120,7 @@ export class AgentCreationReceipts {} catch (error) {if ((error as NodeJS.ErrnoException).code === 'EEXIST') {const existing = this.read(id)+ if (existing?.version === 2 && 'cancelled' in existing) return Promise.resolve(this.intentStatus(id, existing))if (existing?.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')return Promise.resolve(this.status(id))}@@ -99,20 +139,273 @@ export class AgentCreationReceipts {return result}+ /** Persist the complete private request before looking up its dependencies.+ * `prepare` may repeat service-owned credential refreshes, but MUST NOT prepare+ * projects, write launch configuration, signal or dispatch a process. It hands+ * back the effect callback only when its dependencies are ready. */+ runIntent(id: string, fingerprint: string, request: Record<string, unknown>, held: CreationHold,+ prepare: (request: Record<string, unknown>) => Promise<(() => Promise<AgentCreationOutcome>) | null>,+ ): Promise<AgentCreationStatus> {+ const running = this.inFlight.get(id)+ if (running) {+ if (running.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')+ return running.result+ }+ let receipt = this.read(id)+ if (!receipt) {+ const intended: IntentReceipt = { version: 2, fingerprint, request: structuredClone(request), held: { ...held },+ checksum: creationFingerprint({ fingerprint, request, held }) }+ this.publish(this.file(id), intended)+ receipt = this.read(id)+ }+ if (!receipt) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ if (receipt.version === 2 && 'cancelled' in receipt) return Promise.resolve(this.intentStatus(id, receipt))+ if (receipt.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')+ if (receipt.version === 1) return Promise.resolve(this.status(id))+ const before = this.intentStatus(id, receipt, false)+ if (before.state !== 'pending') return Promise.resolve(before)+ // Decode our own durable bytes, not a caller's later-mutated request object.+ const saved = receipt+ const directory = this.holdDirectory()+ const currentReceipt = (): IntentReceipt => {+ directory.verify()+ const current = this.read(id)+ if (current?.version !== 2 || (!('cancelled' in current) && current.checksum !== saved.checksum)) {+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ return current+ }+ const result = Promise.resolve().then(async (): Promise<AgentCreationStatus> => {+ let effect: (() => Promise<AgentCreationOutcome>) | null+ try { effect = await prepare(saved.request) }+ catch { effect = null }+ const current = this.intentStatus(id, currentReceipt(), false)+ if (!effect || current.state !== 'pending') return current+ const claim: IntentClaim = { fingerprint, token: randomUUID(), kind: 'dispatch' }+ // Exactly the successful publisher executes. In particular, seeing our+ // own claim after a failed directory fsync never grants a second attempt.+ if (!this.publish(this.intentFile(id, 'claim'), claim, true)) return this.intentStatus(id, saved, false)+ // A directory or primary intent replaced during service preparation must+ // not inherit this callback's authority, even if a later cancel created a+ // fresh tombstone at the same pathname. The open descriptor pins identity.+ if ('cancelled' in currentReceipt() || this.claim(id)?.token !== claim.token) {+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ let outcome: AgentCreationOutcome+ try { outcome = await effect() } catch { outcome = { state: 'unconfirmed' } }+ const completed: IntentResult = { fingerprint, token: claim.token, outcome }+ let published = false+ try { published = this.publish(this.intentFile(id, 'result'), completed, true) } catch { /* Retain the known outcome under its exact claim. */ }+ if (!published) {+ this.intentResults.set(id, completed)+ // EEXIST or a failed save is not permission to hide conflicting disk+ // evidence beneath a memory-only success.+ return this.intentStatus(id, currentReceipt(), false)+ }+ return outcome+ }).finally(() => { directory.close(); clearTimeout(replyTimer); this.inFlight.delete(id) })+ // The client gets its held receipt promptly while the SAME preparation+ // continues. A slow successful service answer can still win dispatch;+ // reconnects must not start several preparations for that one request.+ let replyTimer: ReturnType<typeof setTimeout>+ const answer = new Promise<AgentCreationStatus>((resolve, reject) => {+ replyTimer = setTimeout(() => {+ try { resolve(this.intentStatus(id, saved)) } catch (error) { reject(error) }+ }, 5_000)+ replyTimer.unref?.()+ void result.then(resolve, reject)+ })+ this.inFlight.set(id, { fingerprint, result: answer })+ return answer+ }++ /** Cancellation shares dispatch's exclusive slot. A missing ID gets a durable+ * tombstone too: a delayed create cannot undo an acknowledged cancellation. */+ cancelIntent(id: string): AgentCreationStatus {+ let receipt = this.read(id)+ if (!receipt) {+ this.publish(this.file(id), { version: 2, cancelled: true })+ receipt = this.read(id)+ }+ if (!receipt) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ if (receipt.version === 1) return this.status(id)+ if ('cancelled' in receipt) { this.ensureDirectory(); this.syncDirectory(); return this.intentStatus(id, receipt) }+ // Incomplete evidence cannot be repaired into an acknowledged cancellation.+ this.intentStatus(id, receipt, false)+ this.publish(this.intentFile(id, 'claim'), { fingerprint: receipt.fingerprint, token: randomUUID(), kind: 'cancel' }, true)+ const status = this.intentStatus(id, receipt, false)+ if (status.state === 'cancelled') this.syncDirectory()+ return status+ }++ /** Streaming recovery never loads an unbounded directory into the core. Old+ * receipts and terminal tombstones stay authoritative, but are not scheduled. */+ pendingIntent(id: string): PendingCreationIntent | null {+ const receipt = this.read(id)+ if (receipt?.version !== 2 || 'cancelled' in receipt || this.intentStatus(id, receipt, false).state !== 'pending') return null+ return { id, fingerprint: receipt.fingerprint, request: receipt.request, held: receipt.held }+ }++ async *pendingIntents(): AsyncGenerator<PendingCreationIntent | null> {+ this.ensureDirectory()+ const entries = await opendir(this.directory)+ for await (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith('.json')) { yield null; continue }+ const id = entry.name.slice(0, -5)+ if (!validCreationId(id)) { yield null; continue }+ try {+ yield this.pendingIntent(id)+ } catch { yield null /* Corrupt evidence remains held; one bad ID cannot block its siblings. */ }+ }+ }++ private intentFile(id: string, part: 'claim' | 'result'): string { return `${this.file(id)}.${part}` }++ private readIntentPart<T>(file: string): T | null {+ try {+ const value: unknown = JSON.parse(readPrivateStateFile(file, 262_144))+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid receipt part')+ return value as T+ }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ }++ private claim(id: string): IntentClaim | null {+ const claim = this.readIntentPart<IntentClaim>(this.intentFile(id, 'claim'))+ if (claim && (!/^[a-f0-9]{64}$/.test(claim.fingerprint) || typeof claim.token !== 'string' || !claim.token+ || (claim.kind !== 'dispatch' && claim.kind !== 'cancel'))) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ return claim+ }++ private intentStatus(id: string, receipt: IntentReceipt, live = this.inFlight.has(id)): AgentCreationStatus {+ const known = this.intentResults.get(id)+ if ('cancelled' in receipt) {+ if (known || this.claim(id) || this.readIntentPart(this.intentFile(id, 'result'))) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ return { state: 'cancelled' }+ }+ const claim = this.claim(id)+ const result = this.readIntentPart<IntentResult>(this.intentFile(id, 'result'))+ // A completed effect cannot become pending or cancelled when its disk+ // evidence disappears. Its retained result still requires the exact claim.+ if (known && (!claim || claim.kind !== 'dispatch' || known.fingerprint !== claim.fingerprint || known.token !== claim.token)) {+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ if (!claim) {+ if (result) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ return { state: 'pending', held: receipt.held }+ }+ if (claim.fingerprint !== receipt.fingerprint) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ if (claim.kind === 'cancel') {+ if (result) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ return { state: 'cancelled' }+ }+ if (result) {+ if (result.fingerprint !== claim.fingerprint || result.token !== claim.token || !validOutcome(result.outcome)+ || (known && creationFingerprint(known.outcome) !== creationFingerprint(result.outcome))) {+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ return result.outcome+ }+ if (known) return known.outcome+ return { state: live ? 'pending' : 'unconfirmed' }+ }++ private publish(file: string, value: unknown, existingDirectory = false): boolean {+ const bytes = JSON.stringify(value)+ if (Buffer.byteLength(bytes) > 262_144) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ const temporary = `${file}.${randomUUID()}.tmp`+ let opened = false+ try {+ if (existingDirectory) secureStateDirectory(this.directory, false)+ this.ensureDirectory()+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)+ opened = true+ try { writeFileSync(fd, bytes); fsyncSync(fd) } finally { closeSync(fd) }+ try { linkSync(temporary, file) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false+ throw error+ }+ this.syncDirectory()+ return true+ } catch { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }+ finally { if (opened) rmSync(temporary, { force: true }) }+ }++ private syncDirectory(path = this.directory, ancestor = false): void {+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | (ancestor ? 0 : constants.O_NOFOLLOW))+ try { fsyncSync(fd) } finally { closeSync(fd) }+ }++ private holdDirectory(): { verify(): void; close(): void } {+ let fd: number | undefined+ try {+ fd = openSync(this.directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)+ const identity = fstatSync(fd)+ return {+ verify: () => {+ try {+ const current = lstatSync(this.directory)+ if (!current.isDirectory() || current.dev !== identity.dev || current.ino !== identity.ino) throw new Error('Replaced receipt directory')+ } catch { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }+ },+ close: () => closeSync(fd!),+ }+ } catch {+ if (fd !== undefined) closeSync(fd)+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }+ }++ /** Publish every new directory name before using a child beneath it, in the+ * same order as engine-home adoption. Ancestors are flushed, never chmodded. */+ private ensureDirectory(path = this.directory, depth = 0): void {+ if (depth > 32) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ try {+ if (path === this.directory) secureStateDirectory(path, false)+ else if (!statSync(path).isDirectory()) throw new Error('Not a directory')+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ this.ensureDirectory(dirname(path), depth + 1)+ try { mkdirSync(path, { mode: 0o700 }) }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }+ if (path === this.directory) secureStateDirectory(path, false)+ }+ this.syncDirectory(dirname(path), true)+ }+private file(id: string): string {if (!validCreationId(id)) throw new AgentCreationReceiptError('INVALID_CREATION_ID')return join(this.directory, `${id}.json`)}- private read(id: string): Receipt | null {+ private read(id: string): Receipt | IntentReceipt | null {const file = this.file(id)const unsaved = this.unsaved.get(id)if (unsaved) return unsaved- try { secureStateDirectory(this.directory) }- catch { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }+ const completedIntent = this.intentResults.has(id)+ try { secureStateDirectory(this.directory, false) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !completedIntent) return null+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')+ }try {- const value = JSON.parse(readPrivateStateFile(file, 16_384)) as Partial<Receipt>- const outcome = value.outcome+ const value = JSON.parse(readPrivateStateFile(file, 262_144)) as Partial<Receipt> | Partial<IntentReceipt>+ if (value.version === 2) {+ if ('cancelled' in value && value.cancelled === true && Object.keys(value).sort().join(',') === 'cancelled,version') return { version: 2, cancelled: true }+ if ('request' in value && value.request && typeof value.request === 'object' && !Array.isArray(value.request)+ && /^[a-f0-9]{64}$/.test(value.fingerprint ?? '') && value.held && typeof value.held.service === 'string'+ && typeof value.held.detail === 'string'+ && value.checksum === creationFingerprint({ fingerprint: value.fingerprint, request: value.request, held: value.held })) return value as IntentReceipt+ throw new Error('Invalid creation intent')+ }+ const outcome = value.version === 1 ? value.outcome : undefined+ if (completedIntent || this.readIntentPart(this.intentFile(id, 'claim')) || this.readIntentPart(this.intentFile(id, 'result'))) {+ throw new Error('Legacy receipt has conflicting intent evidence')+ }if (value.version !== 1 || !/^[a-f0-9]{64}$/.test(value.fingerprint ?? '') || !outcome ||!['pending', 'unconfirmed', 'created', 'failed'].includes(outcome.state) ||(outcome.state === 'created' && (typeof outcome.agentId !== 'string' || !outcome.agentId ||@@ -123,12 +416,15 @@ export class AgentCreationReceipts {}return value as Receipt} catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' && !completedIntent+ && !this.readIntentPart(this.intentFile(id, 'claim')) && !this.readIntentPart(this.intentFile(id, 'result'))) return nullthrow new AgentCreationReceiptError('CREATION_STORAGE_FAILED')}}private write(id: string, receipt: Receipt, exclusive: boolean): void {+ if (exclusive) this.ensureDirectory()+ else secureStateDirectory(this.directory, false)const file = this.file(id)const writing = exclusive ? file : `${file}.${process.pid}.${randomUUID()}.tmp`let opened = falsediff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex b127c012a..c6dc8df2f 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -24,6 +24,8 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'grconst FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'scm_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'connectors', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'agent_handoff_prepare',+ // A held launch's cancellation and its receipt contain the client's private request identity.+ 'agent_create_cancel',// Memories (services/memory.ts): what this machine's agents remember, and About You and its on/off choice.'memory_snapshot', 'memory_about_put', 'memory_deliver', ...ROUTE_COMMAND_TYPES])const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex ec5af5f43..e0cb2de59 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -5,7 +5,7 @@ import { fileURLToPath } from 'url'import { dirname, join } from 'path'import * as C from './core.js'import type { Rng } from './core.js'-import { STRICT_DOWN_TYPES, encryptDownFrameFor } from './applicationFrames.js'+import { STRICT_DOWN_TYPES, encryptDownFrameFor, encryptRpcResult } from './applicationFrames.js'// Deterministic RNG for reproducible key material in tests.function seeded(seed: number): Rng {@@ -134,6 +134,8 @@ describe('e2ee core — codes + fingerprint + classification', () => {expect(C.isEncryptedDownType('agents_list')).toBe(true)expect(C.isEncryptedDownType('agent_update')).toBe(true)expect(C.isEncryptedDownType('agent_create_status')).toBe(true)+ expect(encryptDownFrameFor('agent_create_cancel', { strictDown: false })).toBe(true)+ expect(encryptRpcResult('agent_create_cancel_result')).toBe(true)expect(C.isEncryptedRpcResultType('agent_create_status_result')).toBe(true)// A machine's account usage names what the person spends and on whose subscription. Missing from// either list the request would not fail — it would time out, which is harder to find.diff --git a/cli/src/lib/initialLaunch.golden.spec.ts b/cli/src/lib/initialLaunch.golden.spec.tsnew file mode 100644index 000000000..7f8d33e11--- /dev/null+++ b/cli/src/lib/initialLaunch.golden.spec.ts@@ -0,0 +1,53 @@+/** Healthy discovery before changing initial-launch absence handling. No host process is probed. */+import { readFileSync, writeFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { afterAll, expect, it, vi } from 'vitest'+import type { RegisteredSession } from './registry.js'+import type { DiscoveredTerminalAgent, TerminalAgentProbe } from './terminalAgentDiscovery.js'+import { TerminalAgentReconciler } from './terminalAgentReconciler.js'++vi.mock('node:child_process', () => {+ const forbidden = () => { throw new Error('Golden cannot run a host binary') }+ return { exec: forbidden, execSync: forbidden, execFile: forbidden, execFileSync: forbidden, spawn: forbidden, spawnSync: forbidden }+})++const file = fileURLToPath(new URL('./__fixtures__/initial-launch.golden.json', import.meta.url))+const record = process.env.RECORD_INITIAL_LAUNCH_GOLDEN === '1'+const former = record ? {} : JSON.parse(readFileSync(file, 'utf8'))+const observations: Record<string, unknown> = {}++it.each(['linux', 'darwin'])('keeps healthy initial binding and later confirmed exits on %s', async platform => {+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })+ vi.stubEnv('TZ', 'UTC')+ const runtime = { backend: 'tmux' as const, paneId: '%fixture' }+ const processIdentity = { pid: 42, executable: '/fixture/bin/codex', startMarker: 'fixture-start' }+ const current = { agentId: 'fixture-agent', sessionId: '', engine: 'codex', active: true,+ cwd: '/fixture/project', runtimes: [runtime], primaryRuntimeKey: 'tmux\u0000%fixture',+ processIdentity: null, launch: { state: 'starting' } } as RegisteredSession+ const found: DiscoveredTerminalAgent = { engine: 'codex', cwd: '/fixture/project', processIdentity,+ args: '/fixture/bin/codex', resumeSessionId: null, runtimes: [runtime], primaryRuntimeKey: 'tmux\u0000%fixture' }+ let livePane = true, agents = [found]+ const events: unknown[] = []+ const reconciler = new TerminalAgentReconciler({+ current: () => [current], backends: [], backendOrder: ['tmux'],+ probe: async (): Promise<TerminalAgentProbe> => ({ processTableAvailable: true, agents, ambiguousPlacements: new Set(),+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: livePane ? [{ runtime, rootPid: 1, cwd: '/fixture/project' }] : [] } }] }),+ onDiscovered: () => { throw new Error('Existing pane cannot become another agent') },+ onObserved: observed => { events.push(['observed', observed.processIdentity.pid]); current.processIdentity = observed.processIdentity; current.launch = { state: 'ready' } },+ onDormant: (_row, reason) => { events.push(['dormant', reason]); current.active = false },+ onRemoved: (_row, reason) => { events.push(['removed', reason]) },+ onTerminalAvailability: (_row, available) => { events.push(['terminal', available]) },+ })+ try {+ await reconciler.trigger()+ agents = []+ await reconciler.trigger(); await reconciler.trigger()+ livePane = false+ await reconciler.trigger(); await reconciler.trigger()+ observations[platform] = { events, active: current.active, processIdentity: current.processIdentity }+ if (!record) expect(observations[platform]).toEqual(former[platform])+ } finally { reconciler.stop(); Object.defineProperty(process, 'platform', descriptor); vi.unstubAllEnvs() }+})++afterAll(() => { if (record) writeFileSync(file, JSON.stringify(observations, null, 2) + '\n') })diff --git a/cli/src/lib/remoteViewerProxy.ts b/cli/src/lib/remoteViewerProxy.tsindex ab6d53447..e54e157c9 100644--- a/cli/src/lib/remoteViewerProxy.ts+++ b/cli/src/lib/remoteViewerProxy.ts@@ -48,7 +48,7 @@ export class RemoteViewerProxy {else stream?.wire.handle(type, payload)return true}- const metadata = ['agents_list_result', 'agent_synced', 'agent_created', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result', 'agent_deleted'].includes(type)+ const metadata = ['agents_list_result', 'agent_synced', 'agent_created', 'agent_create_result', 'agent_create_status_result', 'agent_create_cancel_result', 'agent_restart_result', 'agent_deleted'].includes(type)if (!metadata) return falseconst generation = this.generationthis.metadata = this.metadata.then(async () => {diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.tsindex 03a953564..2e5845ead 100644--- a/cli/src/lib/terminalAgentReconciler.spec.ts+++ b/cli/src/lib/terminalAgentReconciler.spec.ts@@ -31,6 +31,70 @@ function probe(targets: TerminalAgentProbe['targets'], agents: DiscoveredTermina}describe('composite terminal reconciliation', () => {+ function initialLaunch() {+ const current: RegisteredSession = { ...session(), processIdentity: null, launch: { state: 'starting' } }+ const snapshot = probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } }])+ const read = vi.fn(async () => snapshot)+ const onDormant = vi.fn(() => { current.active = false })+ const onRemoved = vi.fn()+ const reconciler = new TerminalAgentReconciler({ current: () => [current], backends: [], backendOrder: ['tmux'],+ probe: read, onDiscovered: vi.fn(), onObserved: observed => { current.processIdentity = observed.processIdentity },+ onDormant, onRemoved })+ return { current, snapshot, read, onDormant, onRemoved, reconciler }+ }++ it('keeps an initial launch active until an engine is observed, then detects its later exit', async () => {+ const run = initialLaunch()+ for (let n = 0; n < 3; n++) await run.reconciler.trigger()+ expect(run.current.active).toBe(true)+ expect(run.onDormant).not.toHaveBeenCalled()+ expect(run.onRemoved).not.toHaveBeenCalled()+ run.snapshot.agents = [observed([tmux])]+ await run.reconciler.trigger()+ expect(run.current.processIdentity).toEqual(identity)+ // Even if startup's ready marker has not arrived, a known engine can exit.+ run.snapshot.agents = []+ await run.reconciler.trigger()+ expect(run.onDormant).not.toHaveBeenCalled()+ await run.reconciler.trigger()+ expect(run.onDormant).toHaveBeenCalledOnce()+ expect(run.current.active).toBe(false)+ })++ it('does not apply initial-start absence after readiness changes during the probe', async () => {+ const run = initialLaunch()+ run.read.mockImplementationOnce(async () => { run.current.launch = { state: 'ready' }; return run.snapshot })+ await run.reconciler.trigger()+ await run.reconciler.trigger()+ expect(run.current.active).toBe(true)+ expect(run.onDormant).not.toHaveBeenCalled()+ await run.reconciler.trigger()+ expect(run.onDormant).toHaveBeenCalledOnce()+ })++ it('discards earlier engine misses when a new initial start owns the pane', async () => {+ const run = initialLaunch()+ run.current.launch = { state: 'ready' }+ await run.reconciler.trigger()+ run.current.launch = { state: 'starting' }+ await run.reconciler.trigger()+ expect(run.onDormant).not.toHaveBeenCalled()+ run.current.launch = { state: 'ready' }+ await run.reconciler.trigger()+ expect(run.onDormant).not.toHaveBeenCalled()+ await run.reconciler.trigger()+ expect(run.onDormant).toHaveBeenCalledOnce()+ })++ it('still detects a genuinely missing pane during an initial start', async () => {+ const run = initialLaunch()+ run.read.mockResolvedValue(probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]))+ await run.reconciler.trigger()+ await run.reconciler.trigger()+ expect(run.onRemoved).toHaveBeenCalledOnce()+ expect(run.onDormant).not.toHaveBeenCalled()+ })+it('defers early startup hooks until restored panes have their original owners', async () => {const current = { ...session([tmux]), sessionId: 'saved-conversation', processIdentity: null }const onRemoved = vi.fn()diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.tsindex 2fded288c..072c06d88 100644--- a/cli/src/lib/terminalAgentReconciler.ts+++ b/cli/src/lib/terminalAgentReconciler.ts@@ -263,6 +263,7 @@ export class TerminalAgentReconciler {// (e2e/soak.e2e.ts, 2026-10-04).const probedAs = new Map(this.deps.current().map((agent) => [agent.agentId, {processKey: currentProcessKey(agent),+ starting: agent.launch?.state === 'starting',placements: new Set(agent.runtimes.map(terminalPlacementKey)),}]))// Routes that change hands from here on are this probe's blind spot. Reconciliation is serial, so@@ -398,7 +399,10 @@ export class TerminalAgentReconciler {if (terminalVerified) await this.deps.onTerminalAvailability?.(current, true)const probed = probedAs.get(current.agentId)- if (observed) {+ if (observed || (processKey === null && (current.launch?.state === 'starting' || probed?.starting))) {+ // Before the first engine exists, two quick scans prove no exit. The+ // startup watcher owns that decision; discovery still checks the pane.+ // A pre-start snapshot cannot count after readiness changes mid-probe.this.engineMisses.delete(current.agentId)} else if (probed && probed.processKey === processKey&& current.active && terminalVerified && !isTerminalEngine(current.engine) && !current.runtimes.some((runtime) =>diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex 710100801..0fa5fec47 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -250,10 +250,10 @@ describe('the core\'s request gate (core/main.ts)', () => {const ready = at('coreLink.ready()', opened)const logged = at("console.log('[cli] ready')", ready)const tail = source.slice(opened, from + text.length).split('\n').map((line) => line.trim()).filter(Boolean)- // Readiness never waits on a service: the agents the boot held for one are launched after it, in the background- // (core/agents/heldLaunches.ts).+ // Readiness never waits on a service: held agents and saved manual requests+ // start their dependency recovery only after the master knows core is ready.expect(tail).toEqual(['backend.openRequests()', 'daemonBoot.openRequests = null', 'coreLink.ready()', "console.log('[cli] ready')",- 'void heldLaunches.restoreHeld()', 'externalResumes.open()'])+ 'void heldLaunches.restoreHeld()', 'externalResumes.open()', 'launches.open()'])expect(logged).toBeGreaterThan(ready)})})diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.tsindex fb50d3dfc..31474a8df 100644--- a/cli/src/testing/socketCore.ts+++ b/cli/src/testing/socketCore.ts@@ -152,6 +152,7 @@ export function bindLaunchRequests(socket: BackendSocket, over: Partial<Launcher})socket.createProvider = launches.createsocket.createStatusProvider = launches.createStatus+ socket.cancelCreateProvider = launches.cancelCreatesocket.restartProvider = launches.relaunchsocket.forkProvider = launches.fork}diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dartindex 8b0a5db17..9f576e47b 100644--- a/desktop/lib/e2ee/envelope.dart+++ b/desktop/lib/e2ee/envelope.dart@@ -50,7 +50,7 @@ const Set<String> encryptedDownTypes = {'session_get','models_list','agent_create',- 'agent_create_status',+ 'agent_create_status', 'agent_create_cancel','agent_delete','agent_restart',// Reopens stopped work and forks a harness: the CLI has required both sealed since they werediff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 439165193..0f2c60587 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -266,6 +266,8 @@ class AgentCreationAttempt {HarnessPlacement? _placement;Future<String?>? _inFlight;bool _awaitingConfirmation = false, _finished = false;+ String? _holdReason;+ bool _cancelling = false;/// Prepare a session without adding a pane or changing the selected tab.final bool background;@@ -283,6 +285,7 @@ class AgentCreationAttempt {bool _codexHomeTrusted = false;bool get awaitingConfirmation => _awaitingConfirmation;+ bool get canCancelPending => _awaitingConfirmation && _holdReason != null;/// The machine's code for a request it refused before launching anything,/// such as `SESSION_BUSY_IN_TERMINAL`: what a caller can offer next.@@ -296,6 +299,7 @@ class AgentCreationAttempt {String? _complete(String? error) {_finished = true;_awaitingConfirmation = false;+ _holdReason = null;return _outcome = error;}}@@ -11708,6 +11712,39 @@ class AppNotifier extends ChangeNotifier {return _createAgentWithReceipt(creation);}+ /// Cancellation is confirmed by the machine's durable receipt. Losing this+ /// reply cannot turn the original request into a fresh creation attempt.+ Future<String?> cancelAgentCreation(AgentCreationAttempt creation) async {+ if (!creation.canCancelPending ||+ creation._cancelling ||+ creation._inFlight != null) {+ return 'Check the request status before cancelling.';+ }+ final machineId = creation._machineId;+ if (machineId == null || !machineStates.containsKey(machineId)) {+ return 'The original machine is unavailable. The request is still saved.';+ }+ creation._cancelling = true;+ try {+ final result = await _conn(machineId).request(+ 'agent_create_cancel',+ payload: {'creationId': creation._id},+ timeout: const Duration(seconds: 10),+ );+ if (result['creationId'] == creation._id &&+ result['state'] == 'cancelled') {+ creation._complete('Creation cancelled.');+ _activeAgentCreations.remove(creation);+ return null;+ }+ return 'The request may already be starting. Check status before starting another.';+ } catch (_) {+ return 'Cancellation is not confirmed. Check status before starting another.';+ } finally {+ creation._cancelling = false;+ }+ }+Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {final machineId = creation._machineId!;var targetId = creation._targetId!;@@ -11955,7 +11992,18 @@ class AppNotifier extends ChangeNotifier {return '$machineName has no record of this request. ''Use Open Harness to look for it before starting another.';case 'pending':+ final held = result['held'];+ if (held is Map) {+ final detail = held['detail'];+ if (detail is String && detail.isNotEmpty) {+ creation._holdReason = detail;+ return detail;+ }+ }+ creation._holdReason = null;return '$machineName is still starting your harness. Check again in a moment.';+ case 'cancelled':+ return creation._complete('Creation cancelled.');case 'unconfirmed':return '$machineName could not confirm whether this harness started. ''Use New Pane to look for it before starting another.';diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 9d39f6f40..575b80861 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -626,6 +626,7 @@ class NewHarnessController extends ChangeNotifier {? [for (final engine in allEngines) engine.id, kTerminalEngine]: selectedHarness?.supportedEngines ??[knownHarnessBase[canonicalHarnessId(_harnessId!)] ?? 'claude'];+/// The agent this person chose before, as stored, for the current harness;/// null when nothing is remembered.String? get _rememberedChoice => _desktopChoices@@ -3370,6 +3371,24 @@ class NewHarnessController extends ChangeNotifier {/// A reply was lost; Return now checks on it instead of creating again.bool get checking => _attempt?.awaitingConfirmation == true;+ bool get canCancelPending => _attempt?.canCancelPending == true;++ Future<void> cancelPending() async {+ if (busy || !canCancelPending) return;+ busy = true;+ notifyListeners();+ final problem = await app.cancelAgentCreation(_attempt!);+ if (_disposed) return;+ busy = false;+ if (problem == null) {+ _attempt = null;+ error = null;+ status = 'Creation cancelled.';+ } else {+ error = problem;+ }+ notifyListeners();+ }bool _warnedAboutClosing = false;@@ -3387,7 +3406,9 @@ class NewHarnessController extends ChangeNotifier {if (checking && !_warnedAboutClosing) {_warnedAboutClosing = true;warn(- _desktopChoices+ canCancelPending+ ? 'Your request is saved and will continue when the model is available. Cancel request to prevent that, or close again to leave it waiting.'+ : _desktopChoices? 'The harness may already exist. Check status to find it, or click Close again to leave this form.': 'The harness may already exist. Return checks on it; Escape again ''closes without knowing.',diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex 9c7d19661..58c74625f 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -225,6 +225,19 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {bool _checkingCreation = false;bool get _confirmationPending => _creation?.awaitingConfirmation == true;bool get _choicesLocked => _submitting || _confirmationPending;++ Future<void> _cancelPending() async {+ if (_submitting || _creation?.canCancelPending != true) return;+ setState(() => _submitting = true);+ final problem = await widget.notifier.cancelAgentCreation(_creation!);+ if (!mounted) return;+ setState(() {+ _submitting = false;+ _error = problem ?? 'Creation cancelled.';+ if (problem == null) _creation = null;+ });+ }+late String _engine = allEngines.first.id;String? _harnessId;final _harnessSearchFocus = FocusNode(debugLabel: 'Harness search');@@ -1067,6 +1080,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {icon: const Icon(AppIcons.search, size: 16),label: const Text('Find a harness'),),+ if (_creation?.canCancelPending == true)+ TextButton(+ key: const ValueKey('cancel-pending-creation'),+ onPressed: _submitting ? null : _cancelPending,+ child: const Text('Cancel request'),+ ),FilledButton(key: const ValueKey('create-agent-submit'),focusNode: _actionFocus,diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex f9ce71f95..5afbf474d 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -1834,7 +1834,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {if (attachments == null) {return Align(alignment: Alignment.centerRight,- child: _desktopStartButton(),+ child: _desktopLaunchActions(),);}return Row(@@ -1863,7 +1863,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {),),const SizedBox(width: 12),- _desktopStartButton(),+ _desktopLaunchActions(),],);}@@ -2071,6 +2071,21 @@ class NewHarnessFormState extends State<NewHarnessForm> {return '$action: ${_value(row)}';}+ Widget _cancelPendingButton() => TextButton(+ key: const ValueKey('cancel-pending-creation'),+ onPressed: box.busy ? null : box.cancelPending,+ child: const Text('Cancel request'),+ );++ Widget _desktopLaunchActions() => Wrap(+ spacing: 8,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [+ if (box.canCancelPending) _cancelPendingButton(),+ _desktopStartButton(),+ ],+ );+Widget _desktopStartButton() => ListenableBuilder(listenable: _desktopFocus[_Row.start]!,builder: (context, _) {@@ -2786,7 +2801,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {style: DesktopChrome.text(size: 12, color: DesktopChrome.muted),),),- _desktopStartButton(),+ _desktopLaunchActions(),],),],@@ -2835,6 +2850,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {),),_buildButton(),+ if (box.canCancelPending) _cancelPendingButton(),if (!_picking && box.requiredChoice != null) ...[SizedBox(height: _rowHeight),Padding(@@ -3071,6 +3087,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {),SizedBox(height: _rowHeight),_buildButton(),+ if (box.canCancelPending) _cancelPendingButton(),],),),diff --git a/desktop/test/agent_creation_recovery_test.dart b/desktop/test/agent_creation_recovery_test.dartindex 8c86cdc75..8fedb60ae 100644--- a/desktop/test/agent_creation_recovery_test.dart+++ b/desktop/test/agent_creation_recovery_test.dart@@ -43,6 +43,14 @@ class _Request {'created',agent: {'id': id, 'name': 'Recovered agent', 'engine': 'claude'},);+ void held() => reply.complete({+ 'creationId': creationId,+ 'state': 'pending',+ 'held': {+ 'service': 'models',+ 'detail': 'Waiting for the selected model. This request is saved.',+ },+ });}class _Connection extends WsConn {@@ -91,12 +99,7 @@ Future<void> _timeOut(}void main() {- for (final entry in [- 'new pane',- 'shortcut',- 'search shortcut',- 'new tab',- ]) {+ for (final entry in ['new pane', 'shortcut', 'search shortcut', 'new tab']) {for (final dismissal in ['outside', 'escape']) {testWidgets('$entry creation dismisses once on $dismissal', (tester,@@ -485,6 +488,182 @@ void main() {expect(await fresh, isNull);});+ test(+ 'held requests show their reason and cancel the original durable id',+ () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ final attempt = AgentCreationAttempt();+ final create = app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ );+ connection.calls.single.held();+ expect(+ await create,+ 'Waiting for the selected model. This request is saved.',+ );+ expect(attempt.canCancelPending, isTrue);+ final cancel = app.cancelAgentCreation(attempt);+ expect(connection.calls.last.type, 'agent_create_cancel');+ expect(+ connection.calls.last.creationId,+ connection.calls.first.creationId,+ );+ expect(+ await app.cancelAgentCreation(attempt),+ contains('Check the request status'),+ );+ connection.calls.last.status('cancelled');+ expect(await cancel, isNull);+ expect(attempt.awaitingConfirmation, isFalse);+ expect(attempt.canCancelPending, isFalse);+ expect(+ await app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ ),+ 'Creation cancelled.',+ );+ expect(connection.calls, hasLength(2));+ expect(app.panes, isEmpty);+ },+ );++ test('confirmed cancellation releases the original draft tab', () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ final origin = app.activeSwarmId;+ app.newSwarm(draft: true, newTabPage: true);+ final target = app.activeSwarmId;+ expect(app.isDraftSwarm(target), isTrue);+ final attempt = AgentCreationAttempt();+ final creating = app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ );+ connection.calls.single.held();+ await creating;+ expect(app.isDraftSwarm(target), isFalse);+ final cancelling = app.cancelAgentCreation(attempt);+ connection.calls.last.status('cancelled');+ expect(await cancelling, isNull);+ expect(app.isDraftSwarm(target), isTrue);+ expect(app.cancelSwarmDraft(target), isTrue);+ expect(app.activeSwarmId, origin);+ });++ for (final result in [+ 'disconnect',+ 'wrong receipt',+ 'unconfirmed',+ 'created',+ ]) {+ test(+ 'a $result cancellation keeps the original request recoverable',+ () async {+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ addTearDown(app.dispose);+ final attempt = AgentCreationAttempt();+ final create = app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ );+ connection.calls.single.held();+ await create;+ final cancel = app.cancelAgentCreation(attempt);+ switch (result) {+ case 'disconnect':+ connection.calls.last.reply.completeError(+ StateError('fixture disconnected'),+ );+ case 'wrong receipt':+ connection.calls.last.reply.complete({+ 'creationId': 'different-request',+ 'state': 'cancelled',+ });+ default:+ connection.calls.last.status(result);+ }+ expect(await cancel, contains('Check status'));+ expect(attempt.awaitingConfirmation, isTrue);+ final recover = app.createAgent(+ 'm',+ engine: 'claude',+ folder: '/work',+ attempt: attempt,+ );+ expect(connection.calls.last.type, 'agent_create_status');+ expect(+ connection.calls.last.creationId,+ connection.calls.first.creationId,+ );+ connection.calls.last.status('cancelled');+ expect(await recover, 'Creation cancelled.');+ expect(attempt.awaitingConfirmation, isFalse);+ expect(app.panes, isEmpty);+ },+ );+ }++ testWidgets(+ 'held creation offers cancellation without creating or sending terminal input',+ (tester) async {+ final files = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _FolderPicker();+ addTearDown(() => FileSelectorPlatform.instance = files);+ final connection = _Connection();+ final app = createApp(connectionForTest: (_) => connection);+ app.stateOf('m')!.localOnly = true;+ final input = <TerminalBinaryFrame>[];+ final pane = app.adoptSessionForTest(terminal('a0', input));+ await mount(tester, app);+ await openHarnessPicker(tester);+ await chord(tester, LogicalKeyboardKey.keyN);+ await tester.pumpAndSettle();+ await browseNewAgentProject(tester);+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('create-agent-submit')));+ await tester.pump();+ connection.calls.single.held();+ await tester.pumpAndSettle();+ expect(+ find.text('Waiting for the selected model. This request is saved.'),+ findsOneWidget,+ );+ await tester.tap(find.byKey(const ValueKey('cancel-pending-creation')));+ await tester.pump();+ expect(connection.calls.last.type, 'agent_create_cancel');+ connection.calls.last.status('cancelled');+ await tester.pumpAndSettle();+ expect(find.text('Creation cancelled.'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('cancel-pending-creation')),+ findsNothing,+ );+ expect(connection.calls.map((call) => call.type), [+ 'agent_create',+ 'agent_create_cancel',+ ]);+ expect(app.panes, [pane]);+ expect(input, isEmpty);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );+for (final result in ['unsupported','timeout',diff --git a/desktop/test/new_harness_start_failures_test.dart b/desktop/test/new_harness_start_failures_test.dartindex 295f0e22d..f280a5945 100644--- a/desktop/test/new_harness_start_failures_test.dart+++ b/desktop/test/new_harness_start_failures_test.dart@@ -20,6 +20,8 @@ class _Connection extends WsConn {);bool catalogUnavailable = false, installed = false;+ bool held = false, cancelLost = false;+ final cancels = <String>[];final install = Completer<Map<String, dynamic>>();int installs = 0;final starts = <Map<String, dynamic>>[];@@ -61,6 +63,16 @@ class _Connection extends WsConn {return reply;case 'agent_create':starts.add(Map.of(payload));+ if (held) {+ return {+ 'creationId': payload['creationId'],+ 'state': 'pending',+ 'held': {+ 'service': 'models',+ 'detail': 'Waiting for the selected model.',+ },+ };+ }return {'creationId': payload['creationId'],'state': 'created',@@ -70,6 +82,10 @@ class _Connection extends WsConn {'engine': payload['engine'],},};+ case 'agent_create_cancel':+ cancels.add(payload['creationId'] as String);+ if (cancelLost) throw StateError('fixture disconnected');+ return {'creationId': payload['creationId'], 'state': 'cancelled'};default:return {};}@@ -77,6 +93,47 @@ class _Connection extends WsConn {}void main() {+ test(+ 'held creation retains its choices until cancellation is confirmed',+ () async {+ final connection = _Connection()+ ..held = true+ ..cancelLost = true;+ final app = createApp(+ connectionForTest: (_) => connection,+ connected: true,+ );+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'claude',+ folder: '/work',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await box.create();+ expect(box.checking, isTrue);+ expect(box.canCancelPending, isTrue);+ expect(box.error, 'Waiting for the selected model.');+ expect(box.requestDismiss(), isFalse);+ expect(box.error, contains('will continue when the model is available'));+ await box.cancelPending();+ expect(box.checking, isTrue);+ expect(box.error, contains('Cancellation is not confirmed'));+ connection.cancelLost = false;+ await box.cancelPending();+ expect(box.checking, isFalse);+ expect(box.canCancelPending, isFalse);+ expect(box.status, 'Creation cancelled.');+ expect(box.requestDismiss(), isTrue);+ expect(connection.starts, hasLength(1));+ expect(connection.cancels, [+ connection.starts.single['creationId'],+ connection.starts.single['creationId'],+ ]);+ },+ );+for (final failure in [false, true]) {test('a missing Store harness waits for installation (failure=$failure)', () async {final connection = _Connection();diff --git a/docs/design/2026-10-10-durable-launch-intents.md b/docs/design/2026-10-10-durable-launch-intents.mdnew file mode 100644index 000000000..324d9523f--- /dev/null+++ b/docs/design/2026-10-10-durable-launch-intents.md@@ -0,0 +1,110 @@+# Durable manual launch intent++Manual model creation previously saved `GRID_UNAVAILABLE` as a completed failed+receipt. The same request could never recover when models returned, and the+receipt lacked the request needed after a core crash. This violates the daemon+bar: unavailable dependencies must hold dependent work with its reason.++## First implemented boundary++Fresh `agent_create` requests with a stable `creationId`, `gridModel` and+`gridName` now persist their complete semantic choices and original local/remote+authorization before model resolution. Only model identifiers are retained;+resolved endpoints and credentials are not cached. Resolution may renew+service-owned credentials, so it is repeatable preflight, not pure read-only work.++Unavailable, disconnected, stalled or temporarily unlisted models leave the+request pending with its reason. The same lookup continues after a five-second+pending reply; slow success is not discarded and reconnects do not start another+lookup for that ID. Core opens recovery after readiness through the ordinary+models port, including its existing on-demand startup. Optional interpreters do+not admit work. This complements `heldLaunches.ts`, which owns registered panes+waiting for dependencies; these intents precede those panes.++## Durable authority++The existing namespace supports v1 outcomes and v2 intents. An immutable private+v2 primary record contains the fingerprint, request, hold reason and checksum.+One canonical claim slot chooses dispatch or cancellation; only its successful+publisher executes. A result names the exact winning claim. Bounded owner-only+files are opened without following symlinks. Publication syncs a complete+temporary file, exclusively hard-links its final name, then syncs the directory.+New directory names are synced through their parents first.++Preflight retains an open receipt-directory descriptor. Before claiming and+again before an effect, it checks directory identity and rereads the complete+current intent. Missing, replaced, corrupt or conflicting evidence cannot+authorize an old callback. Failed claim publication or sync cannot authorize+another attempt merely because that claim can now be read.++Project preparation, configuration, native mutations and terminal dispatch stay+behind the claim. A claimed request without a conclusive result is unconfirmed+after restart, never blindly executed again. A locally known unsaved outcome+stays tied to its exact claim and cannot conceal contradictory disk evidence.+Orphan results, mismatched tokens and conflicting legacy/v2 parts hold work.++`agent_create_cancel` competes for the same claim slot and syncs a winning+cancellation before acknowledgment. An unknown ID gets a durable tombstone, so a+late create cannot undo it. Cancellation losing to dispatch reports the existing+outcome or uncertainty; it does not promise the effect stopped. No user data is+deleted. V1 outcomes remain authoritative. Fresh legacy installation refusals+remain correctable before reservation, while existing IDs are checked before+mutable refusals. Supported DSH former names retain canonical IDs/fingerprints.++## Resources and clients++Core keeps four model preparations and a retry window of 128 IDs. A stalled+promise retains its preparation slot until settlement; its wrapper deadline+allows the port's three-minute credential preparation allowance. Each recovery+pass examines at most 64 directory entries, with a shared 20 ms work budget that+includes retry reads. The cursor yields between passes and pauses at a full+window. Under pressure, settled holds make room for later entries before the+cursor rewinds. Broken or permanently unavailable early requests cannot starve+the tail. Explicit requests still persist when the window is full.++Ordinary holds retry after two seconds; background dispatch is at most four per+250 ms tick. A completed history scan repeats after one minute. Large backlogs+therefore trade recovery latency for bounded resources and responsive control.+No full intent or resolved-model cache lives in the retry window.++Desktop shows the reason and offers **Cancel request**. Lost cancellation replies+retain the original ID and Check status path. Confirmed cancellation releases+the attempt and its tab's pending ownership. All clients seal the new request.+TUI/mobile still have generic pending presentation and no cancellation control.+Desktop can also refuse an unavailable model before submitting a request; this+change covers durable admission of requests actually received by the daemon.++## Evidence and remaining work++The former healthy protocol was recorded from main `10c9e7420` in its own commit,+`ac32477c7`, before implementation. Its unchanged golden covers create, profiles,+model selection, project preparation, fork, resume and restart, duplicates and+reconstructed receipt readers. Linux/Darwin and UTC are pinned, paths are+placeholders and host binaries are forbidden. Mutants must fail assertions.++Fault regressions cover slow success, restart, two-core contention, cancellation+during awaits, changed intent/directory identity, conflicting outcomes, fsync+failure, bounded backlog fairness and client tab cleanup. The private daemon+lane kills models and core, verifies readiness and held reasons, cancels one+request, runs unrelated work and recovers the others exactly once.++This is one bounded part of the completion checklist. Required remaining work:++- Move later `buildGridLaunch` and Store dependency preparation before the effect+ boundary; either can still fail after the current claim.+- Preserve fork/resume/restart/retarget intent and original authorization, with+ target reservations across different IDs, restoration and held-pane recovery.+ Record retarget's former socket protocol before moving it.+- Journal project/clone/branch/Store effects and reserve the chosen path before+ changing it. Reserve agent, terminal and attempt identity before tmux, including+ internal retries. Never choose a second generated folder after a crash.+- Reconcile persistent native-write uncertainty read-only. Make Stop and Close+ durably revoke pending authority through a dispatch/settlement protocol; a dead+ owner can leave a live child, and PID absence never permits replay.+- Publish immutable generated configuration atomically from operation-owned+ paths, preserving foreign configuration and native user data. Retain ID+ tombstones and bound history work without permitting replay.++Final acceptance still requires the full dependency-failure matrix, coverage,+unchanged goldens, mutations, private e2e lanes, matched cost measurements,+independent review and green CI. No release is authorized.diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.mdindex 82f52a14f..aee1b5112 100644--- a/docs/research/2026-10-09-daemon-core-completion.md+++ b/docs/research/2026-10-09-daemon-core-completion.md@@ -29,7 +29,7 @@ This is the remaining completion scope as of October 9, after the six extraction1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [landed](2026-10-10-saved-binding-evidence.md). Atomic registration and live hook ownership are [landed](2026-10-10-native-hook-admission.md). Stop/Resume/Close transcript authority is [landed as #1139](2026-10-10-control-transcript-authority.md); reviewed history deletion is [landed as #1144](2026-10-10-native-history-consumers.md); [Change agent handoff authority](2026-10-10-native-handoff-authority.md) is landed as #1145 (`ea4e800b5`, October 10 15:13:53 UTC). Restart-persistent hook delivery, remaining saved-home consumers and legacy native-client acknowledgement/order still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.2. **Complete native launch preparation.** Probe executable/version facts asynchronously with a deadline and one confirmed executable snapshot per launch. The [asynchronous version-probe change](2026-10-10-native-version-probes.md) covers bounded subprocesses and concurrent observations/installers; the whole-launch snapshot, unknown-result policy and durable hook preparation remain open. Failed hook writes/removals hold launch, preserve foreign configuration and are checked consistently by create, fork, restart, retarget, restore and upgrades. Do not memoize an unavailable version as a permanent answer.-3. **Durable manual lifecycle intent and mutation authority.** Preserve create/fork/restart/retarget requests across unavailable services and daemon restart. Publish generated configuration atomically after dependencies are ready. Check immutable session ownership after every relevant await and before native writes, signals and publication. Reconcile unconfirmed OpenCode v2 mutations read-only; unreadable catalogs must not authorize mutation. Cover v1 missing-row/rollback cases and report a confirmed native change followed by failed respawn truthfully.+3. **Durable manual lifecycle intent and mutation authority.** The live-core mutation and ownership boundary is [landed as #1155](2026-10-10-native-mutation-authority.md), `71f42b852`, October 10 at 17:46:46 UTC: unconfirmed OpenCode v2 writes are reconciled read-only across requests; unavailable catalogs cannot authorize a mutation; immutable ownership fences native/tmux effects; partial effects are reported truthfully. The same change prevents an unbound fork from claiming its parent's conversation at discovery or Stop. Preserve create/fork/restart/retarget requests across unavailable services and daemon restart, including durable uncertain native receipts. Publish generated configuration atomically after dependencies are ready. Cover v1 missing-row/rollback cases. The [durable launch design](../design/2026-10-10-durable-launch-intents.md) records the implemented model-admission slice and the remaining lifecycle boundary.4. **Close, turns and input stay in core.** Audit OpenCode v2 Close checkpointing against its current conversation store; unavailable checkpoint/activity evidence keeps the live session with its reason. Finish per-engine Stop/turn facts, authority across asynchronous drains, Cursor pending-task persistence, agy backstop control, input verification declarations, and Pi header/argv and unwritten-conversation handling.5. **Final architecture acceptance.** Exercise startup, discovery, binding, launch, resume, Stop, hook admission, turn closing and Close with required services absent, stalled, disconnected and recovered. Verify readiness remains independent, pending work survives without partial writes or archival, and stale completions cannot affect a replacement session. Run the relevant coverage gates, unchanged goldens and assertion-failing wiring mutations, affected private e2e/chaos lanes, and matched runtime-cost measurements. Obtain independent review and merge every completed change.diff --git a/docs/research/2026-10-10-durable-model-requests-cost.json b/docs/research/2026-10-10-durable-model-requests-cost.jsonnew file mode 100644index 000000000..c3235610a--- /dev/null+++ b/docs/research/2026-10-10-durable-model-requests-cost.json@@ -0,0 +1,62 @@+[+ {+ "mode": "legacy",+ "count": 60,+ "medianMs": 76.92431600000009,+ "p95Ms": 96.907463,+ "totalMs": 4531.940067999998,+ "cpuMs": 111.741,+ "rssDeltaMiB": 0.6015625,+ "iteration": 0+ },+ {+ "mode": "intent",+ "count": 60,+ "medianMs": 183.29277000000002,+ "p95Ms": 305.06287900000007,+ "totalMs": 12037.063724,+ "cpuMs": 416.391,+ "rssDeltaMiB": -0.38671875,+ "iteration": 0+ },+ {+ "mode": "legacy",+ "count": 60,+ "medianMs": 78.92271800000071,+ "p95Ms": 97.60997899999984,+ "totalMs": 4756.671986000001,+ "cpuMs": 120.582,+ "rssDeltaMiB": 0.46484375,+ "iteration": 1+ },+ {+ "mode": "intent",+ "count": 60,+ "medianMs": 189.75338699999884,+ "p95Ms": 244.87026799999967,+ "totalMs": 11460.335184000003,+ "cpuMs": 431.72,+ "rssDeltaMiB": 1.0546875,+ "iteration": 1+ },+ {+ "mode": "legacy",+ "count": 60,+ "medianMs": 78.28556500000013,+ "p95Ms": 113.59663099999943,+ "totalMs": 5017.650269,+ "cpuMs": 121.699,+ "rssDeltaMiB": 0.3203125,+ "iteration": 2+ },+ {+ "mode": "intent",+ "count": 60,+ "medianMs": 182.31383199999993,+ "p95Ms": 333.90176299999985,+ "totalMs": 12637.719837999992,+ "cpuMs": 397.07,+ "rssDeltaMiB": 1.95703125,+ "iteration": 2+ }+]diff --git a/docs/research/2026-10-10-durable-model-requests.md b/docs/research/2026-10-10-durable-model-requests.mdnew file mode 100644index 000000000..778007095--- /dev/null+++ b/docs/research/2026-10-10-durable-model-requests.md@@ -0,0 +1,114 @@+# Recover manual model requests after an outage++Previously a model service outage completed an identified create as+`failed/GRID_UNAVAILABLE`. The same creation ID could never recover. Core now+persists the semantic model request before lookup, returns a visible hold,+recovers it after restart, and lets cancellation win a durable exclusive slot+against dispatch. A claimed but uncertain effect is not replayed.++The [design](../design/2026-10-10-durable-launch-intents.md) records the exact+boundary and remaining lifecycle work. This covers identified manual model+selection, not every create/fork/restart/retarget dependency. Later Store and+grid-launch preparation still need the same boundary.++## Evidence++The healthy Linux/Darwin request golden was recorded from main `10c9e7420` in+commit `ac32477c7`, before implementation. It passes unchanged. It pins platform,+UTC and placeholder paths and forbids host subprocesses. The mutation script is+`cli/scripts/handoff-2026-10-08/mutate-launch-intents.py`; it checks healthy+wiring, original authorization, receipt/directory identity, cancellation,+conflicting disk evidence and bounded scheduling through assertion failures.++The new private `serviceProcesses.e2e.ts` case kills models, saves three requests,+kills core, verifies readiness and held reasons, cancels one, exercises an+unrelated session, then recovers the two remaining IDs exactly once. It passes+for both fake Claude Code and Codex. All daemons, homes, ports and tmux servers+belong to the fixture. The five-second reply deadline does not abandon a slow+lookup; a six-second successful lookup has its own regression.++Independent review found and prompted fixes for a discarded slow lookup,+unbounded historical/retry work, incomplete receipt evidence, ancestor sync,+changed legacy validation, missing early hold reasons, stale preflight authority,+canonical DSH aliases, contradictory memory/disk results, and retained tab+ownership after cancellation. Each has an executable regression. Final review+attestation and exact-head CI/local receipts belong in the PR body; this record+does not substitute for those gates.++The full Linux e2e run also exposed a pre-existing initial-launch race in+`stall.e2e.ts`: two process scans marked a new Codex row dormant 163 ms before its+ready marker, clearing its control and input state. This happened before the+fixture's first injected stall. Discovery now leaves initial engine absence to+the startup watcher while the row is starting without a process identity. It+still detects a missing pane, and two later absences of an observed engine still+count. A scan begun before readiness cannot count after readiness changes.++Commit `4cb11bec4` recorded the healthy discovery golden from the unchanged main+implementation before this correction. Linux/Darwin are pinned and host binaries+are forbidden. Three fault regressions failed before the correction and pass+afterward; the healthy golden and original e2e assertion remain unchanged.++Three paired runs of 10,000 in-memory initial-launch reconciliation passes on+Node 22.23.2 measured 77.4–81.3 ms before and 74.3–78.2 ms after; parent CPU was+140.7–147.8 ms and 135.2–141.2 ms, with noisy RSS deltas of 14.2–17.8 MiB and+12.2–16.0 MiB. This narrow workload supplies private synthetic process/pane+snapshots and no-op lifecycle callbacks; it measures the recurring decision,+not tmux/process probing or a user-visible speedup. The+[six results](2026-10-10-initial-launch-cost.json) and+[`initial-launch-cost.mjs`](../../cli/scripts/handoff-2026-10-08/initial-launch-cost.mjs)+retain the measurement. Bundle main `71f42b852` and the candidate reconciler with+the same CLI esbuild, using `cli/src/lib` as the baseline's import directory and+Node ESM with a `createRequire` banner; pass each bundle path to that script,+alternating before/after three times under `TZ=UTC TMPDIR=/tmp` on a quiet host.++## Matched cost++On the same macOS host and Node 22.23.2, three alternating runs measured 60 healthy+receipt creations plus reconstructed status readers each. The former source is+main `71f42b852`; fixtures use private temporary directories. These are journal+microbenchmarks, not total agent startup or end-to-end responsiveness measurements.++| Metric per run | Former v1 receipt | Recoverable v2 intent |+| --- | --- | --- |+| Median operation latency | 76.9–78.9 ms | 182.3–189.8 ms |+| p95 operation latency | 96.9–113.6 ms | 244.9–333.9 ms |+| Process CPU for 60 operations | 111.7–121.7 ms | 397.1–431.7 ms |+| RSS change during run | 0.3–0.6 MiB | −0.4–2.0 MiB |++The extra immutable intent/claim/result and directory syncs add measurable local+I/O latency. RSS changes are noisy deltas, not peak-memory bounds. This change+makes no speedup claim. Recovery keeps four preparations, 128 retry IDs and a+shared 20 ms per-pass work budget, checked between operations; a single synchronous+filesystem operation can exceed it. The private crash test separately checks+readiness within 15 seconds and working unrelated sessions during the outage.++The [anonymous results](2026-10-10-durable-model-requests-cost.json) retain all six+runs. For 60 sorted samples, the reported median is the upper middle sample at+index 30 and p95 is the sample at index 57. The measurement script is+[`receipt-cost.mjs`](../../cli/scripts/handoff-2026-10-08/receipt-cost.mjs).+From the repository root, prepare both implementations with the same installed+CLI dependencies, then alternate these commands three times on an otherwise+quiet host (Node 22.23.2 for the recorded measurement):++```sh+mkdir -p .harness/receipt-cost-before+git show 71f42b852:cli/src/lib/agentCreationReceipt.ts > .harness/receipt-cost-before/agentCreationReceipt.ts+git show 71f42b852:cli/src/lib/secureState.ts > .harness/receipt-cost-before/secureState.ts+cli/node_modules/.bin/esbuild .harness/receipt-cost-before/agentCreationReceipt.ts --bundle --platform=node --format=esm --outfile=.harness/receipt-before.mjs+cli/node_modules/.bin/esbuild cli/src/lib/agentCreationReceipt.ts --bundle --platform=node --format=esm --outfile=.harness/receipt-after.mjs+TZ=UTC TMPDIR=/tmp node cli/scripts/handoff-2026-10-08/receipt-cost.mjs .harness/receipt-before.mjs legacy+TZ=UTC TMPDIR=/tmp node cli/scripts/handoff-2026-10-08/receipt-cost.mjs .harness/receipt-after.mjs intent+```++The recorded v2 source was `3f960b4db`; the subsequent receipt-evidence correction+does not change the healthy benchmark path. Each invocation owns and removes only+its newly created temporary fixture directory.++## Accounting++This slice began October 10 around 17:24 UTC; the first golden commit preceded+implementation. Implementation, test development, validation, review/CI waiting+and merge are recorded separately in the PR's validation receipts. At this+write-up the change is under validation and not yet landed. No publication or+release occurred. The full daemon refactor remains governed by the+[completion checklist](2026-10-09-daemon-core-completion.md).diff --git a/docs/research/2026-10-10-initial-launch-cost.json b/docs/research/2026-10-10-initial-launch-cost.jsonnew file mode 100644index 000000000..8c8bc1f04--- /dev/null+++ b/docs/research/2026-10-10-initial-launch-cost.json@@ -0,0 +1,50 @@+[+ {+ "pair": 0,+ "mode": "before",+ "count": 10000,+ "elapsedMs": 81.304879,+ "cpuMs": 145.579,+ "rssDeltaMiB": 17.83984375+ },+ {+ "pair": 0,+ "mode": "after",+ "count": 10000,+ "elapsedMs": 74.26582400000001,+ "cpuMs": 135.199,+ "rssDeltaMiB": 15.6953125+ },+ {+ "pair": 1,+ "mode": "before",+ "count": 10000,+ "elapsedMs": 77.363237,+ "cpuMs": 140.724,+ "rssDeltaMiB": 17.76171875+ },+ {+ "pair": 1,+ "mode": "after",+ "count": 10000,+ "elapsedMs": 78.21921900000001,+ "cpuMs": 141.177,+ "rssDeltaMiB": 12.2265625+ },+ {+ "pair": 2,+ "mode": "before",+ "count": 10000,+ "elapsedMs": 81.15286400000001,+ "cpuMs": 147.805,+ "rssDeltaMiB": 14.1640625+ },+ {+ "pair": 2,+ "mode": "after",+ "count": 10000,+ "elapsedMs": 74.90714700000001,+ "cpuMs": 135.301,+ "rssDeltaMiB": 16.02734375+ }+]diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dartindex 1ba1017b0..dec9e889d 100644--- a/mobile/lib/e2ee/envelope.dart+++ b/mobile/lib/e2ee/envelope.dart@@ -26,6 +26,7 @@ const Set<String> encryptedDownTypes = {'models_list','agent_create','agent_create_status',+ 'agent_create_cancel','agent_delete','agent_restart',// Reopens stopped work (`AppNotifier.resumeAgent`). Missing here, every tap on a Stopped row came