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
fix(cli): defer launch writes until dependencies answer (#1113)
Dee62cc1cc4343b
diff --git a/cli/e2e/storeProcess.e2e.ts b/cli/e2e/storeProcess.e2e.tsindex 11abe5a08..4bdf67c97 100644--- a/cli/e2e/storeProcess.e2e.ts+++ b/cli/e2e/storeProcess.e2e.ts@@ -49,10 +49,10 @@ const connected = (d: IsolatedDaemon) => d.log().split('[services] store connectconst row = async (client: LocalClient, agentId: string) =>((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents).find((agent) => agent.id === agentId)-async function create(d: IsolatedDaemon, client: LocalClient, folder: string, dsh?: string, engine: 'claude' | 'codex' = 'claude'): Promise<Record<string, any>> {+async function create(d: IsolatedDaemon, client: LocalClient, folder: string, dsh?: string, engine: 'claude' | 'codex' = 'claude', codexHome?: string): Promise<Record<string, any>> {const cwd = join(d.projectsDir, folder)mkdirSync(cwd, { recursive: true })- const created = await client.request('agent_create', { engine, cwd, bypassPermission: true, ...(dsh ? { dsh } : {}) }, 90_000)+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true, ...(dsh ? { dsh } : {}), ...(codexHome ? { codexHome } : {}) }, 90_000)expect(created.error, JSON.stringify(created)).toBeUndefined()return until(`${folder} to bind`, async () => {const found = await row(client, created.agent.id)@@ -142,7 +142,9 @@ describe('the Store in its own process, beside the viewers', () => {const d = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '3000', HARNESSD_SERVICE_STOP_GRACE_MS: '100' })let client = await LocalClient.connect(d)expect(await client.request('dsh_install', { url: repository(d) }, 180_000)).toMatchObject({ ok: true })- const agents = [await create(d, client, 'held-claude', HARNESS), await create(d, client, 'held-codex', HARNESS, 'codex')]+ const profile = join(d.root, 'held-codex-profile')+ mkdirSync(profile)+ const agents = [await create(d, client, 'held-claude', HARNESS), await create(d, client, 'held-codex', HARNESS, 'codex', profile)]const stopped = await create(d, client, 'stop-while-store-is-held', HARNESS)for (const agent of [...agents, stopped]) await turn(client, agent.id, 'before the reboot')const hold = join(d.root, 'hold-store')@@ -151,6 +153,19 @@ describe('the Store in its own process, beside the viewers', () => {client.close()await d.stop()await d.tmux.run('kill-server')+ // Make pending instruction/profile work observable. Neither a Store outage nor a held retry+ // may perform it before the package preparation succeeds. Every path is private to this daemon.+ const instructionFiles = [join(d.projectsDir, 'held-claude', 'CLAUDE.md'), join(d.projectsDir, 'held-codex', 'AGENTS.md')]+ const instructionsBefore = instructionFiles.map(file => readFileSync(file, 'utf8'))+ const profileHooks = join(profile, 'hooks.json')+ const profileBefore = JSON.stringify({ fixtureOwner: 'preserve' })+ writeFileSync(profileHooks, profileBefore)+ const apiDir = join(d.dataDir, 'api-connections')+ mkdirSync(apiDir, { recursive: true })+ writeFileSync(join(apiDir, 'connections.json'), JSON.stringify({ version: 1, connections: [{+ id: 'fixture', provider: 'fixture', name: 'Fixture API', baseUrl: 'http://127.0.0.1:9/v1',+ keyEnv: 'FIXTURE_API_KEY', authHeader: 'Authorization', authPrefix: 'Bearer', apiKey: 'fixture-key',+ }] }), { mode: 0o600 })const started = Date.now()await d.start()expect(Date.now() - started).toBeLessThan(15_000)@@ -173,6 +188,8 @@ describe('the Store in its own process, beside the viewers', () => {expect(refused).toMatchObject({ error: 'DSH_UNAVAILABLE' })expect(readdirSync(cwd)).toEqual([])for (const agent of agents) expect(await row(client, agent.id)).toMatchObject({ launch: { state: 'held' } })+ expect(instructionFiles.map(file => readFileSync(file, 'utf8'))).toEqual(instructionsBefore)+ expect(readFileSync(profileHooks, 'utf8')).toBe(profileBefore)rmSync(hold)for (const agent of agents) {await until('the prepared package resumes its conversation', async () => {@@ -181,6 +198,8 @@ describe('the Store in its own process, beside the viewers', () => {}, 90_000, 250)await turn(client, agent.id, 'after Store recovery')}+ for (const file of instructionFiles) expect(readFileSync(file, 'utf8')).toContain('<!-- harness:apis -->')+ expect(readFileSync(profileHooks, 'utf8')).toContain('SessionStart')expect(await row(client, stopped.id)).toMatchObject({ status: 'stopped', sessionId: stopped.sessionId })expect(d.log()).not.toContain('could not build its launch')expect(d.coresStarted()).toBe(2)diff --git a/cli/scripts/handoff-2026-10-08/mutate-launch-preparation.py b/cli/scripts/handoff-2026-10-08/mutate-launch-preparation.pynew file mode 100644index 000000000..5c83e399b--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-launch-preparation.py@@ -0,0 +1,57 @@+"""Break preparation wiring or authority; only an assertion failure counts as a kill."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+golden = 'src/engines/dshLaunchShapes.golden.spec.ts'+launch = 'src/core/agents/launch.spec.ts'+overrides = 'src/lib/launchOverrides.spec.ts'+authority = 'src/core/agents/launchAuthority.spec.ts'+restore = 'src/core/agents/restoreLaunch.spec.ts'+mutations = [+ ('drop harness account', 'src/services/storeLaunch.ts', 'prepareHarnessLaunch(installed, workspace, engine, key, account, sourceKey)', 'prepareHarnessLaunch(installed, workspace, engine, key, {}, sourceKey)', golden),+ ('drop harness argv', 'src/lib/launchOverrides.ts', '...overrides.extraArgs, ...dsh.args', '...overrides.extraArgs, ...[]', golden),+ ('write before Store answers', 'src/lib/launchOverrides.ts', " let dsh: Extract<DshLaunchAnswer", " await base.commit()\n let dsh: Extract<DshLaunchAnswer", overrides),+ ('write notes during outage', 'src/core/agents/launch.ts', "if (!result.ok && (result.unavailable || result.error === 'AGENT_CHANGED')) return result", "if (!result.ok && result.error === 'AGENT_CHANGED') return result", launch),+ ('ignore dispatch authority', 'src/core/agents/launch.ts', 'const dispatchCurrent = authority(session.agentId)', 'const dispatchCurrent = () => true', launch),+ ('ignore caller authority', 'src/core/agents/launch.ts', 'operationCurrent() && dispatchCurrent()', 'dispatchCurrent()', launch),+ ('ignore Stop revision', 'src/core/agents/launchAuthority.ts', 'deps.revision(id) === revision', 'true', authority),+ ('compare projection to live row', 'src/core/agents/launch.ts', 'session = structuredClone(session)', "session = structuredClone(session)\n if (session.engine === 'terminal') return { ok: false, error: 'AGENT_CHANGED', detail: 'wrong projection fence' }", restore),+ ('fail cancelled restore', 'src/core/agents/restoreLaunch.ts', "if (!built.ok && built.error === 'AGENT_CHANGED') return { cancelled: true }", '// cancellation incorrectly becomes a launch error', restore),+ ('reuse committed preparation', 'src/lib/launchOverrides.ts', 'if (committed) return', 'if (false) return', overrides),+ ('restore old write order without duplicate writes', 'src/lib/launchOverrides.ts',+ 'const base = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine }, engine, source, configKey)',+ 'const originalBase = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine }, engine, source, configKey)\n'+ ' const early = originalBase.ok ? await originalBase.commit() : originalBase\n'+ ' const base = early.ok ? { ok: true as const, commit: async () => early } : early',+ 'src/engines/launchArgv.golden.spec.ts'),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+for key in ['TMUX', 'TMUX_PANE', 'RECORD_DSH_LAUNCH_SHAPES_GOLDEN']:+ env.pop(key, 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(list(dict.fromkeys(item[4] for item in mutations)))+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[int(os.environ.get('MUTATION_START', '0')):]:+ 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/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 5e866d608..3c1aa25a0 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -18,6 +18,9 @@ import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/extimport { clearPaneRemainOnExit } from '../../lib/tmux.js'import { tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'import { createAgentCreator, type CreateAgentDeps } from './create.js'+import { prepareInstructionWrites } from '../../scm/scmProjects.js'++vi.mock('../../scm/scmProjects.js', async real => ({ ...await real<object>(), prepareInstructionWrites: vi.fn(async () => {}) }))vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))vi.mock('../../dsh/manifest.js', async (real) => ({ ...await real<object>(), dshPinnedPermissionMode: vi.fn(() => null) }))@@ -184,6 +187,7 @@ describe('creating an agent', () => {expect(await create(request({ dsh: 'blender', grid }))).toEqual({ ok: false, error: 'GRID_UNAVAILABLE', detail: 'models is down' })expect(materializeWorkspace).not.toHaveBeenCalled()expect(preTrustClaudeProject).not.toHaveBeenCalled()+ expect(prepareInstructionWrites).not.toHaveBeenCalled()vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)})diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 89ac15373..cb3413a98 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -125,7 +125,6 @@ export function createAgentCreator({// `TmuxBackend.inventory()`): the panes this daemon creates carry its tag, which goes with them into// any session the person moves them to.const label = buildHarnessSessionLabel(engine)- await prepareInstructionWrites(cwd)// Prepare the harness workspace, then bind its session context to the selected engine.// Missing packages or invalid runtimes refuse the launch before the agent is started.let dshEnv: Record<string, string> | undefined@@ -272,6 +271,7 @@ export function createAgentCreator({// answered and refused (`SPAWN_FAILED`) — see createAgentPane.ts. Registration itself is retried// there: a stale registry entry from a previous tmux-server generation occasionally collides with// a freshly-minted pane id, and that collision clears on its own on the very next pane.+ await prepareInstructionWrites(cwd)prepareApiTools(cwd, engine)// Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex// profile becomes the new session's CODEX_HOME (its session store's variable, lib/engineHomes.tsdiff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.tsindex 7e3503a07..d52d84c17 100644--- a/cli/src/core/agents/fork.spec.ts+++ b/cli/src/core/agents/fork.spec.ts@@ -82,6 +82,16 @@ describe('forking an agent', () => {})afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('does not open instruction files or install API notes while its harness waits for the Store', async () => {+ vi.mocked(installedDsh).mockReturnValueOnce({ manifest: { name: 'Fixture' } } as never)+ launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Waiting for the Store.', unavailable: 'store' })+ const { fork, deps } = setup(source({ dsh: 'fixture/tools' }))+ expect(await fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ ok: false, error: 'DSH_UNAVAILABLE' })+ expect(prepareInstructionWrites).not.toHaveBeenCalled()+ expect(deps.prepareApiTools).not.toHaveBeenCalled()+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ })+it('refuses without tmux, an agent, a folder, or with a grid or a turn in progress', async () => {expect(await setup(source(), { tmuxBackend: null }).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })expect(await setup(null).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.tsindex 268d12cf9..ed688eaa0 100644--- a/cli/src/core/agents/fork.ts+++ b/cli/src/core/agents/fork.ts@@ -78,7 +78,6 @@ export function createAgentForker({const opencode = engine === 'opencode' ? opencodeLaunch : nullconst label = buildHarnessSessionLabel(engine)- await prepareInstructionWrites(source.cwd)// Fork the source's saved harness context. Workspace templates and init are not run again.let dshEnv: Record<string, string> | undefinedlet dshArgs: string[] = []@@ -127,6 +126,7 @@ export function createAgentForker({console.warn(`[agent] fork refused · ${engine} · ${forkRefusal.detail}`)return { ok: false, ...forkRefusal }}+ await prepareInstructionWrites(source.cwd)prepareApiTools(source.cwd, engine)const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.tsindex 66d423819..37b220f2d 100644--- a/cli/src/core/agents/launch.spec.ts+++ b/cli/src/core/agents/launch.spec.ts@@ -26,6 +26,7 @@ const session = (over: Partial<RegisteredSession> = {}): RegisteredSession =>function setup() {const deps: LaunchHelperDeps = {+ authority: () => () => true,prepareApiTools: vi.fn(),launchOverridesDeps: { marker: 'deps' } as unknown as LaunchOverridesDeps,setGridLaunch: vi.fn(() => true),@@ -37,6 +38,53 @@ function setup() {describe('relaunch helpers', () => {afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('rejects preparation that was already revoked before dispatch', async () => {+ const { deps } = setup()+ deps.authority = () => () => false+ expect(await createLaunchHelpers(deps).relaunchOverrides(session())).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(buildLaunchOverrides).not.toHaveBeenCalled()+ expect(prepareInstructionWrites).not.toHaveBeenCalled()+ })++ it('keeps the caller authority separate and does not write after a cancelled preparation reply', async () => {+ const { deps, helpers } = setup()+ expect(await helpers.relaunchOverrides(session(), session(), () => false)).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(buildLaunchOverrides).not.toHaveBeenCalled()+ vi.mocked(buildLaunchOverrides).mockResolvedValueOnce({ ok: false, error: 'AGENT_CHANGED', detail: 'revoked' })+ expect(await helpers.relaunchOverrides(session())).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(prepareInstructionWrites).not.toHaveBeenCalled()+ expect(deps.prepareApiTools).not.toHaveBeenCalled()+ })++ it.each(['service', 'SCM'] as const)('a Stop or rebind during %s cannot redirect deferred instructions', async stage => {+ const { deps } = setup()+ let allowed = true+ deps.authority = () => () => allowed+ const row = session()+ let release!: () => void+ const gate = new Promise<void>(resolve => { release = resolve })+ if (stage === 'service') vi.mocked(buildLaunchOverrides).mockImplementationOnce(async () => { await gate; return { ok: true } as never })+ else vi.mocked(prepareInstructionWrites).mockImplementationOnce(async () => { await gate })+ const result = createLaunchHelpers(deps).relaunchOverrides(row)+ await vi.waitFor(() => expect(stage === 'service' ? buildLaunchOverrides : prepareInstructionWrites).toHaveBeenCalled())+ row.cwd = '/replacement'; row.engine = 'codex'+ allowed = false+ release()+ expect(await result).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(deps.prepareApiTools).not.toHaveBeenCalled()+ if (stage === 'service') expect(prepareInstructionWrites).not.toHaveBeenCalled()+ else expect(prepareInstructionWrites).toHaveBeenCalledExactlyOnceWith('/work')+ })++ it.each(['store', 'models'])('leaves instruction files alone while %s is unavailable', async unavailable => {+ const { deps, helpers } = setup()+ const refused = { ok: false as const, error: 'SERVICE_UNAVAILABLE', detail: 'Waiting for preparation.', unavailable }+ vi.mocked(buildLaunchOverrides).mockResolvedValueOnce(refused)+ expect(await helpers.relaunchOverrides(session())).toEqual(refused)+ expect(prepareInstructionWrites).not.toHaveBeenCalled()+ expect(deps.prepareApiTools).not.toHaveBeenCalled()+ })+it('relaunches with eager control when optional OpenCode code cannot load', async () => {const { deps, helpers } = setup()vi.mocked(loadEngine).mockImplementation(() => new Promise(() => {}))@@ -53,10 +101,10 @@ describe('relaunch helpers', () => {expect(deps.prepareApiTools).toHaveBeenCalledWith('/work', 'claude')expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({dsh: 'blender', dshRuntime: null, cwd: '/work', agent: 'reviewer', gridLaunch: null,- }), 'a1')+ }), 'a1', expect.any(Function))const grid = { networkId: 'grid-1', networkName: 'Home grid' }await helpers.relaunchOverrides(session({ dsh: undefined, dshRuntime: undefined, agent: undefined } as Partial<RegisteredSession>), { gridLaunch: grid } as never)- expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, gridLaunch: grid }), 'a1')+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, gridLaunch: grid }), 'a1', expect.any(Function))})it('records the web-search decision a relaunch made, when it made one', () => {diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.tsindex dd294f9eb..e84c9ff40 100644--- a/cli/src/core/agents/launch.ts+++ b/cli/src/core/agents/launch.ts@@ -30,6 +30,8 @@ export function gridLaunchThrough(models: () => Pick<ModelsPort, 'gridLaunch'>)}export interface LaunchHelperDeps {+ /** Capture dispatch authority before a service can yield to Stop or a replacement binding. */+ authority: (agentId: string) => () => boolean/** Writes the saved APIs' tool instructions into the agent's folder before it launches. */prepareApiTools: (cwd: string | null | undefined, engine: string) => voidlaunchOverridesDeps: LaunchOverridesDeps@@ -38,17 +40,27 @@ export interface LaunchHelperDeps {setTail: (sessionId: string, offset: number) => void}-export function createLaunchHelpers({ prepareApiTools, launchOverridesDeps, setGridLaunch, setTail }: LaunchHelperDeps) {+export function createLaunchHelpers({ authority, prepareApiTools, launchOverridesDeps, setGridLaunch, setTail }: LaunchHelperDeps) {// Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,// workspace and named agent come from the row: a retarget must not silently drop the harness the// agent is, or bring a pane opened as `harness-compute` back as a general session.// An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key// pasted since takes effect, and a removed API is refused rather than kept on its old key: the models// service reads them as it builds the launch (`buildLaunchOverrides`, `refresh`).- const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {+ const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session, operationCurrent: () => boolean = () => true): Promise<LaunchOverridesResult> => {+ const dispatchCurrent = authority(session.agentId)+ const current = () => operationCurrent() && dispatchCurrent()+ session = structuredClone(session)+ const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const+ if (!current()) return changed+ const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, session.agentId, current)+ if (!current()) return changed+ if (!result.ok && (result.unavailable || result.error === 'AGENT_CHANGED')) return result+ // Saved-API instructions remain available after an ordinary semantic refusal, as before.+ // A missing dependency or revoked operation must leave these files untouched.await prepareInstructionWrites(session.cwd)+ if (!current()) return changedprepareApiTools(session.cwd, session.engine)- const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, session.agentId)if (result.ok && session.externalResume?.request.engine === session.engine) {result.overrides.extraArgs.push(...session.externalResume.session?.launchArgs ?? [])}diff --git a/cli/src/core/agents/launchAuthority.spec.ts b/cli/src/core/agents/launchAuthority.spec.tsnew file mode 100644index 000000000..b4c88f203--- /dev/null+++ b/cli/src/core/agents/launchAuthority.spec.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import { createLaunchAuthority } from './launchAuthority.js'++const agent = () => ({ agentId: 'fixture-agent', engine: 'claude', sessionId: 'conversation', registeredAt: 1,+ boundAt: 2, cwd: '/workspace', active: true, processIdentity: { pid: 42, startMarker: 'old' },+ runtimes: [{ backend: 'tmux', paneId: '%7' }], gridLaunch: { model: 'original' },+}) as unknown as RegisteredSession++describe('launch preparation authority', () => {+ it('captures binding and operation revision, independently of the mutable registry object', () => {+ let row: RegisteredSession | undefined = agent(), revision = 1, cancelled = false+ const authority = createLaunchAuthority({ byAgent: () => row, revision: () => revision, cancelled: () => cancelled })+ const current = authority(row.agentId)+ expect(current()).toBe(true)+ cancelled = true; expect(current()).toBe(false)+ cancelled = false; revision++; expect(current()).toBe(false)+ const next = authority(row.agentId)+ row = undefined; expect(next()).toBe(false)+ })++ it.each([+ { cwd: '/replacement' }, { engine: 'codex' }, { sessionId: 'replacement' }, { registeredAt: 3 },+ { boundAt: 3 }, { processIdentity: { pid: 42, startMarker: 'replacement' } },+ { runtimes: [{ backend: 'tmux', paneId: '%8' }] }, { codexHome: '/profile' },+ { dsh: 'fixture/other' }, { dshRuntime: 'other' }, { agent: 'other' },+ { gridLaunch: { model: 'replacement' } }, { scmLaunch: { kind: 'fixture' } },+ { subscriptionModel: 'replacement' }, { permissionMode: 'auto' }, { bypassPermission: true },+ { active: false }, { launch: { state: 'held', service: 'store' } }, { externalResume: { token: 'other' } },+ ])('revokes after changed launch facts: %j', change => {+ const row = agent()+ const current = createLaunchAuthority({ byAgent: () => row, revision: () => 1, cancelled: () => false })(row.agentId)+ Object.assign(row, change)+ expect(current()).toBe(false)+ })++ it('allows display-only updates and route ordering without losing the original target', () => {+ const row = agent()+ row.runtimes.push({ backend: 'tmux', paneId: '%9' })+ const current = createLaunchAuthority({ byAgent: () => row, revision: () => 1, cancelled: () => false })(row.agentId)+ row.runtimes.reverse()+ row.defaultName = 'Display name'+ expect(current()).toBe(true)+ row.gridLaunch!.model = 'changed in place'+ expect(current()).toBe(false)+ })++ it('can prepare an absent stopped row until another live binding appears', () => {+ let row: RegisteredSession | undefined+ const current = createLaunchAuthority({ byAgent: () => row, revision: () => 1, cancelled: () => false })('fixture-agent')+ expect(current()).toBe(true)+ row = agent()+ expect(current()).toBe(false)+ })+})diff --git a/cli/src/core/agents/launchAuthority.ts b/cli/src/core/agents/launchAuthority.tsnew file mode 100644index 000000000..7f1fc2ff0--- /dev/null+++ b/cli/src/core/agents/launchAuthority.ts@@ -0,0 +1,23 @@+/** Local launch writes belong to one binding and lifecycle revision, never just to a pane id. */+import type { RegisteredSession } from '../../lib/registry.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'++const identity = (row: RegisteredSession | undefined) => row && JSON.stringify([+ row.registeredAt, row.boundAt, row.sessionId, row.engine, row.cwd, row.processIdentity,+ row.codexHome, row.dsh, row.dshRuntime, row.agent, row.gridLaunch, row.scmLaunch,+ row.subscriptionModel, row.permissionMode, row.bypassPermission, row.active,+ row.runtimes.map(terminalRouteKey).sort(), row.launch, row.externalResume,+])++export function createLaunchAuthority(deps: {+ byAgent(id: string): RegisteredSession | undefined+ revision(id: string): number+ cancelled(id: string): boolean+}) {+ return (id: string): (() => boolean) => {+ // The requested launch may be a stopped row or a projected terminal fallback. Its owner's+ // predicate grants that operation; this extra fence watches the live table as dispatch found it.+ const target = identity(deps.byAgent(id)), revision = deps.revision(id)+ return () => !deps.cancelled(id) && deps.revision(id) === revision && identity(deps.byAgent(id)) === target+ }+}diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex 5e62a3a8b..699905368 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -161,7 +161,7 @@ export function createAgentRestarter({// half, and an agent moved here by a retarget has nothing in the session env at all), or its// Codex profile. Refused before anything is killed, so a restart that cannot honour the grid// leaves the running process alone.- const built = await relaunchOverrides(session)+ const built = await relaunchOverrides(session, session, current)if (!current()) return changedif (!built.ok) return { ok: false, error: built.error, detail: built.detail }diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.tsindex 448ccceee..84d99791f 100644--- a/cli/src/core/agents/restoreLaunch.spec.ts+++ b/cli/src/core/agents/restoreLaunch.spec.ts@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../../lib/registry.js'import type { LaunchOverridesResult } from '../../lib/launchOverrides.js'import { createRestoreLaunch } from './restoreLaunch.js'+import { createLaunchHelpers } from './launch.js'+import { createLaunchAuthority } from './launchAuthority.js'const entry = { agentId: 'agent', sessionId: 'conversation', cwd: '/workspace' } as RegisteredSessionconst built: Extract<LaunchOverridesResult, { ok: true }> = { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } }@@ -17,6 +19,50 @@ const setup = () => {}describe('restore preparation keeps session authority in core', () => {+ it.each(['dead process', 'terminal fallback', 'fresh fallback'] as const)('composes preparation for a legitimate %s projection', async projection => {+ const live = { ...entry, engine: 'claude', active: true, launch: { state: 'ready' },+ processIdentity: { pid: 42, startMarker: 'old' }, runtimes: [{ backend: 'tmux', paneId: '%7' }],+ } as RegisteredSession+ const requested = structuredClone(live)+ if (projection === 'dead process') live.processIdentity = null+ if (projection === 'terminal fallback') { requested.engine = 'terminal'; requested.sessionId = '' }+ if (projection === 'fresh fallback') live.launch = { state: 'starting' }+ const apiNotes = vi.fn()+ const helpers = createLaunchHelpers({+ authority: createLaunchAuthority({ byAgent: () => live, revision: () => 1, cancelled: () => false }),+ prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),+ launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null },+ })+ const { deps } = setup()+ const build = createRestoreLaunch({ ...deps, relaunchOverrides: helpers.relaunchOverrides })+ expect(await build(requested, { current: () => true })).toEqual({ argv: ['engine'] })+ expect(apiNotes).toHaveBeenCalledWith('/workspace', requested.engine)+ expect(deps.launch).toHaveBeenCalledWith(requested, {}, expect.any(Object), expect.any(Object))+ })++ it('a richer dispatch fence cancels restore without failing or publishing the replacement', async () => {+ const live = { ...entry, engine: 'claude', dsh: 'fixture/tools', active: true, processIdentity: null,+ runtimes: [{ backend: 'tmux', paneId: '%7' }],+ } as RegisteredSession+ const apiNotes = vi.fn()+ const helpers = createLaunchHelpers({+ authority: createLaunchAuthority({ byAgent: () => live, revision: () => 1, cancelled: () => false }),+ prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),+ launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null,+ dshLaunch: async () => { live.permissionMode = 'ask'; return { ok: true, launch: { env: {}, args: [] } } } },+ })+ const { deps } = setup()+ const build = createRestoreLaunch({ ...deps, relaunchOverrides: helpers.relaunchOverrides })+ expect(await build(structuredClone(live), { current: () => true })).toEqual({ cancelled: true })+ expect(live.permissionMode).toBe('ask')+ expect(apiNotes).not.toHaveBeenCalled()+ expect(deps.prepareSessionResume).not.toHaveBeenCalled()+ expect(deps.refreshGridWebSearch).not.toHaveBeenCalled()+ expect(deps.launch).not.toHaveBeenCalled()+ })+it.each([undefined, 'conversation'])('applies confirmed preparation only to the current owner: resume %s', async resumeSessionId => {const { deps, build } = setup()expect(await build(entry, { resumeSessionId, current: () => true })).toEqual({ argv: ['engine'] })diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.tsindex 37f127f75..8f8809af8 100644--- a/cli/src/core/agents/restoreLaunch.ts+++ b/cli/src/core/agents/restoreLaunch.ts@@ -6,7 +6,7 @@ import type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.jinterface RestoreLaunchDeps {workspaceMissing(cwd: string | null | undefined): { error: string; detail: string } | null- relaunchOverrides(entry: RegisteredSession): Promise<LaunchOverridesResult>+ relaunchOverrides(entry: RegisteredSession, source: RegisteredSession, current: () => boolean): Promise<LaunchOverridesResult>downgradedPermission(entry: RegisteredSession): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }>prepareSessionResume(entry: RegisteredSession): voidrefreshGridWebSearch(agentId: string, overrides: LaunchOverrides): void@@ -20,8 +20,9 @@ export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps[detail: entry.launch?.state === 'held' ? entry.launch.detail : 'Waiting to verify this external conversation.' }const missing = deps.workspaceMissing(entry.cwd)if (missing) return missing- const built = await deps.relaunchOverrides(entry)+ const built = await deps.relaunchOverrides(entry, entry, current)if (!current()) return { cancelled: true }+ if (!built.ok && built.error === 'AGENT_CHANGED') return { cancelled: true }if (!built.ok) return built.unavailable? { held: built.unavailable, detail: built.detail, holdScope: built.holdScope }: { error: built.error, detail: built.detail }diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex cbfe67703..24657730a 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -125,6 +125,7 @@ import { createForgetSession } from './agents/forget.js'import { createBinding } from './agents/bind.js'import { createDiscoveryHandlers } from './agents/discovery.js'import { createLaunchHelpers, gridLaunchThrough } from './agents/launch.js'+import { createLaunchAuthority } from './agents/launchAuthority.js'import { AgentRestartCoordinator } from '../lib/restartAgent.js'import { createPaneOperations } from './agents/paneOperations.js'import { createRestoreLaunch } from './agents/restoreLaunch.js'@@ -425,6 +426,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {let externalResumes: ReturnType<typeof createExternalResumes> | null = nulllet searchGeneration = 0let restoreCancelled = (_agentId: string): boolean => false+ let launchCancelled = (_agentId: string): boolean => falselet restoreOnly: ((only: ReadonlySet<string>) => Promise<RestoreSummary>) | null = nullconst heldLaunches = createHeldLaunches({registry,@@ -1972,6 +1974,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restore// pass below, which calls these for every pane it rebuilds.const launchHelpers = createLaunchHelpers({+ authority: createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: restoreRevision, cancelled: id => launchCancelled(id) }),prepareApiTools,launchOverridesDeps,setGridLaunch: (agentId, launch) => registry.setGridLaunch(agentId, launch),@@ -2353,6 +2356,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {relaunchMarks,})const stopJobs = lifecycle.stopJobs+ launchCancelled = id => stopJobs.has(id)restoreCancelled = (agentId) => stopJobs.has(agentId) || pinnedControls.has(agentId) || (restartJobs.operation(agentId) !== undefined && restartJobs.operation(agentId) !== 'restart')binding.whileChanging((agentId) => restorePanes.busy(agentId) || restartJobs.busy(agentId) || stopJobs.has(agentId))const stopAgent = lifecycle.stopAgentdiff --git a/cli/src/engines/launchArgv.golden.spec.ts b/cli/src/engines/launchArgv.golden.spec.tsindex 050abd024..16ff39923 100644--- a/cli/src/engines/launchArgv.golden.spec.ts+++ b/cli/src/engines/launchArgv.golden.spec.ts@@ -502,7 +502,29 @@ describe('every launch hands tmux what it did before Claude Code and Codex declaexpect({ ...mine, script: mine.script && actual.scripts[mine.script] }, `${platform} · ${name}`).toEqual({ ...value, script: value.script && golden.scripts[value.script] })}- for (const [name, value] of Object.entries(want.overrides)) expect(got.overrides[name], `${platform} · ${name}`).toEqual(value)+ for (const [name, value] of Object.entries(want.overrides)) {+ // Launch preparation intentionally asks the Store before publishing grid files. Keep the+ // former artifact intact and pin this one ordering change explicitly, including its old+ // trace. Every result field, call argument and other case still compares byte-for-byte.+ const changedOrder: Record<string, readonly [string, string]> = {+ 'opencode · harness on a grid, as git, as a named agent': [+ 'writeGridConfigDir agent-0001 opencode.json',+ 'dshLaunch acme/studio /work/studio opencode agent-0001',+ ],+ 'pi · harness on a grid, as git, as a named agent': [+ 'writeGridConfigDir agent-0001 models.json,settings.json',+ 'dshLaunch acme/studio /work/studio pi agent-0001',+ ],+ }+ const order = changedOrder[name]+ let expected = value+ if (order) {+ const former = value as { calls: string[] }+ expect(former.calls, `${platform} · ${name} · former order`).toEqual(order)+ expected = { ...former, calls: [order[1], order[0]] }+ }+ expect(got.overrides[name], `${platform} · ${name}`).toEqual(expected)+ }expect(Object.keys(got.overrides).sort(), platform).toEqual(Object.keys(want.overrides).sort())expect(got.adapters, platform).toEqual(want.adapters)}diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex d4617cbe2..72a5b732b 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { loadEngine } from '../engines/inProcess.js'-import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'+import { buildLaunchOverrides, prepareLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'import { DSH_SESSION_ENV } from '../dsh/launch.js'import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'@@ -35,6 +35,68 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {}describe('buildLaunchOverrides — a relaunch comes back where the agent was', () => {+ it.each(['before', 'models', 'Store', 'commit', 'write'] as const)('revocation at %s cannot apply a stale preparation', async stage => {+ let allowed = stage !== 'before'+ const { d, calls } = deps({+ gridLaunch: async request => {+ if (stage === 'models') allowed = false+ return gridLaunchInProcess()(request)+ },+ dshLaunch: async () => {+ if (stage === 'Store') allowed = false+ return { ok: true, launch: { env: {}, args: [] } }+ },+ writeGridConfigDir: async () => { calls.push('write'); if (stage === 'write') allowed = false; return '/fixture/config' },+ })+ const prepared = await prepareLaunchOverrides(d, 'pi', { gridLaunch: GRID, dsh: 'fixture/tools', cwd: '/workspace' }, 'agent-1', () => allowed)+ if (stage === 'commit') allowed = false+ const result = prepared.ok ? await prepared.commit() : prepared+ expect(result).toMatchObject({ error: 'AGENT_CHANGED' })+ expect(calls).toEqual(stage === 'write' ? ['write'] : [])+ })++ it.each(['pi', 'codex'] as const)('does not alter %s configuration when the Store cannot prepare its harness', async engine => {+ const refusal = { ok: false as const, error: 'DSH_UNAVAILABLE', detail: 'Preparation is unconfirmed.', unavailable: 'store' as const, holdScope: 'workspace' as const }+ const { d, calls } = deps({ dshLaunch: async () => refusal })+ const source = { dsh: 'fixture/tools', cwd: '/workspace', ...(engine === 'pi' ? { gridLaunch: GRID } : { codexHome: '/profiles/work' }) }+ expect(await buildLaunchOverrides(d, engine, source, 'agent-1')).toEqual(refusal)+ expect(calls).toEqual([])+ })++ it('does not ask the Store or write configuration when models is unavailable', async () => {+ const dshLaunch = vi.fn()+ const refusal = { ok: false as const, error: 'GRID_UNAVAILABLE', detail: 'Waiting for models.', unavailable: 'models' }+ const { d, calls } = deps({ gridLaunch: async () => refusal, dshLaunch })+ expect(await buildLaunchOverrides(d, 'pi', { gridLaunch: GRID, dsh: 'fixture/tools', cwd: '/workspace' }, 'agent-1')).toEqual(refusal)+ expect(dshLaunch).not.toHaveBeenCalled()+ expect(calls).toEqual([])+ })++ it('keeps one request and machine snapshot while services answer, and writes only on commit', async () => {+ const machine = vi.fn(() => ({ hermesSystemManaged: false, opencodeMajor: 1 }))+ const source = { gridLaunch: { ...GRID }, dsh: 'fixture/tools', cwd: '/workspace', agent: 'reviewer' }+ const { d, calls } = deps({ machine, dshLaunch: async () => {+ source.agent = 'changed'+ source.gridLaunch.apiKey = 'changed'+ machine.mockReturnValue({ hermesSystemManaged: false, opencodeMajor: 2 })+ return { ok: true, launch: { env: { HARNESS_DSH: 'fixture/tools' }, args: ['--context', 'fixture'] } }+ } })+ const prepared = await prepareLaunchOverrides(d, 'opencode', source, 'agent-1')+ expect(prepared.ok).toBe(true)+ expect(calls).toEqual([])+ if (!prepared.ok) throw new Error('Fixture preparation failed')+ const result = await prepared.commit()+ expect(result).toMatchObject({ ok: true, overrides: {+ env: { HARNESS_DSH: 'fixture/tools' },+ extraArgs: expect.arrayContaining(['-m', '--agent', 'reviewer', '--context', 'fixture']),+ gridLaunchRecord: { override: { apiKey: GRID.apiKey } },+ } })+ expect(calls).toEqual(['writeConfig:agent-1'])+ expect(machine).toHaveBeenCalledExactlyOnceWith('opencode')+ expect(await prepared.commit()).toMatchObject({ error: 'LAUNCH_PREPARATION_USED' })+ expect(calls).toHaveLength(1)+ })+it('rebuilds a grid launch from the persisted override: env with the key, argv, and the vendor variables to clear', async () => {const { d, calls } = deps()const result = await buildLaunchOverrides(d, 'claude', { gridLaunch: GRID }, 'agent-1')diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 1050eb9c0..bfc6b199c 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -60,6 +60,12 @@ export type LaunchOverridesResult =| { ok: true; overrides: LaunchOverrides }| { ok: false; error: string; detail: string; unavailable?: string; holdScope?: 'workspace' }+/** A preparation has consulted every required service; committing performs only local writes.+ * Keep the closure private to this attempt: it contains the current credentials, never a cache. */+export type LaunchPreparationResult =+ | { ok: true; commit: () => Promise<LaunchOverridesResult> }+ | Extract<LaunchOverridesResult, { ok: false }>+export interface LaunchOverridesDeps {/** The facts about THIS machine a contract needs and cannot read for itself — see `GridLaunchMachine`. */machine: (engine: AgentEngine) => GridLaunchMachine@@ -166,11 +172,30 @@ export async function buildLaunchOverrides(engine: AgentEngine,source: LaunchSource,configKey: string,+ current: () => boolean = () => true,): Promise<LaunchOverridesResult> {- const base = await buildBaseLaunchOverrides(deps, engine, source, configKey)+ const prepared = await prepareLaunchOverrides(deps, engine, source, configKey, current)+ return prepared.ok ? prepared.commit() : prepared+}++/** Ask dependencies before writing a live pane's configuration or installing profile hooks.+ * A models answer followed by an unavailable Store used to overwrite the old grid files first. */+export async function prepareLaunchOverrides(+ deps: LaunchOverridesDeps,+ engine: AgentEngine,+ source: LaunchSource,+ configKey: string,+ current: () => boolean = () => true,+): Promise<LaunchPreparationResult> {+ const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const+ if (!current()) return changed+ source = structuredClone(source)+ const machine = { ...deps.machine(engine) }+ const base = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine }, engine, source, configKey)+ if (!current()) return changedif (!base.ok) return base- let overrides = base.overridesif (source.dsh && !source.cwd) return { ok: false, error: 'DSH_WORKSPACE_MISSING', detail: `${source.dsh} has no saved workspace` }+ let dsh: Extract<DshLaunchAnswer, { ok: true }>['launch'] | undefinedif (source.dsh && source.cwd) {let prepared: DshLaunchAnswer | nulltry {@@ -178,43 +203,51 @@ export async function buildLaunchOverrides(} catch (error) {return { ok: false, error: 'DSH_RUNTIME_FAILED', detail: String(error) }}+ if (!current()) return changedif (!prepared) return { ok: false, error: 'DSH_NOT_INSTALLED', detail: `${source.dsh} is not installed on this machine` }if (!prepared.ok) return { ok: false, error: prepared.error, detail: prepared.detail,...(prepared.unavailable ? { unavailable: prepared.unavailable } : {}),...(prepared.holdScope ? { holdScope: prepared.holdScope } : {}) }- const dsh = prepared.launch- // The DSH's variables layer over the grid's or the profile's; `HARNESS_*` are the daemon's own- // and a manifest cannot set them (see `dshLaunch`), so nothing here can shadow a grid credential.- overrides = {- ...overrides,- env: { ...overrides.env, ...dsh.env },- extraArgs: [...overrides.extraArgs, ...dsh.args],- }- }- // The workspace's own SCM binding layers last: it is the daemon's, like `HARNESS_*`, and neither a- // grid nor a DSH has a say in which workspace the pane is bound to. Nothing for git, so a git row's- // overrides are exactly what they were.- const scmEnv = scmLaunchEnv(source.scmLaunch)- if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }- // The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an- // engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),- // so the guard is for a row edited by hand — it relaunches as a general session rather than- // handing the engine a flag it does not know. The same guard covers an opencode agent created on- // v1 and relaunched on v2, whose TUI has no `--agent`: a resumed v2 session keeps the agent it- // stored (`session_v2.agent`), so nothing is lost by not naming it.- const opencodeMajor = deps.machine(engine).opencodeMajor ?? null- if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {- overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }+ dsh = prepared.launch}- return { ok: true, overrides: { ...overrides, clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }+ let committed = false+ return { ok: true, commit: async () => {+ if (!current()) return changed+ if (committed) return { ok: false, error: 'LAUNCH_PREPARATION_USED', detail: 'Launch preparation must be requested again before another attempt.' }+ committed = true+ const written = await base.commit()+ if (!current()) return changed+ if (!written.ok) return written+ let overrides = written.overrides+ if (dsh) {+ // The service's harness environment layers over the base exactly as in a fresh create.+ overrides = { ...overrides, env: { ...overrides.env, ...dsh.env }, extraArgs: [...overrides.extraArgs, ...dsh.args] }+ }+ // The workspace's own SCM binding layers last: it is the daemon's, like `HARNESS_*`, and neither a+ // grid nor a DSH has a say in which workspace the pane is bound to. Nothing for git, so a git row's+ // overrides are exactly what they were.+ const scmEnv = scmLaunchEnv(source.scmLaunch)+ if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }+ // The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an+ // engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),+ // so the guard is for a row edited by hand — it relaunches as a general session rather than+ // handing the engine a flag it does not know. The same guard covers an opencode agent created on+ // v1 and relaunched on v2, whose TUI has no `--agent`: a resumed v2 session keeps the agent it+ // stored (`session_v2.agent`), so nothing is lost by not naming it.+ const opencodeMajor = machine.opencodeMajor ?? null+ if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {+ overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }+ }+ return { ok: true, overrides: { ...overrides, clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }+ } }}-async function buildBaseLaunchOverrides(+async function prepareBaseLaunchOverrides(deps: LaunchOverridesDeps,engine: AgentEngine,source: LaunchSource,configKey: string,-): Promise<LaunchOverridesResult> {+): Promise<LaunchPreparationResult> {// Coming back to the engine's own login undoes TWO things the grid launch set, and they are// undone separately because the engine remembers them differently.//@@ -250,44 +283,48 @@ async function buildBaseLaunchOverrides(if (!built.ok) return { ok: false, error: built.error, detail: built.detail, ...(built.unavailable ? { unavailable: built.unavailable } : {}) }const tmux = await tmuxRefusal(deps, engine, built.override)if (!tmux.ok) return tmux- const env: Record<string, string> = { ...built.launch.env }- if (built.launch.configDir) {- const { envVar, files, pointAt, links } = built.launch.configDir- try {- const dir = await deps.writeGridConfigDir(configKey, files, links ?? [])- // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.- env[envVar] = pointAt ? join(dir, pointAt) : dir- } catch (error) {- const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`- return { ok: false, error: 'GRID_CONFIG_FAILED', detail }+ return { ok: true, commit: async () => {+ const env: Record<string, string> = { ...built.launch.env }+ if (built.launch.configDir) {+ const { envVar, files, pointAt, links } = built.launch.configDir+ try {+ const dir = await deps.writeGridConfigDir(configKey, files, links ?? [])+ // Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.+ env[envVar] = pointAt ? join(dir, pointAt) : dir+ } catch (error) {+ const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail }+ }}- }- // Derived from what this launch actually provides (the config-dir variable included), so an- // inherited vendor key never outranks the grid the engine was handed.- return {- ok: true,- overrides: {- env,- extraArgs: [...built.launch.args],- clearEnv: gridConflictingEnvToClear({ env }),- gridLaunchRecord: { override: built.override, webSearch: built.launch.webSearch },- ...(built.launch.sessionModel ? { sessionModel: built.launch.sessionModel } : {}),- },- }+ // Derived from what this launch actually provides (the config-dir variable included), so an+ // inherited vendor key never outranks the grid the engine was handed.+ return {+ ok: true,+ overrides: {+ env,+ extraArgs: [...built.launch.args],+ clearEnv: gridConflictingEnvToClear({ env }),+ gridLaunchRecord: { override: built.override, webSearch: built.launch.webSearch },+ ...(built.launch.sessionModel ? { sessionModel: built.launch.sessionModel } : {}),+ },+ }+ } }}if (source.codexHome) {// A Codex agent on a profile OTHER than this machine's default reads hooks.json from THAT folder,// not the one `harness login` installed into — without this it fires no hook at all. Idempotent.- deps.installCodexHooks(source.codexHome)- return {- ok: true,- overrides: {- env: { ...profileEnvironment(engine, source.codexHome), ...(ownLogin?.env ?? {}) },- extraArgs: [...(ownLogin?.extraArgs ?? [])],- clearEnv: [],- },- }+ const home = source.codexHome+ return { ok: true, commit: async () => {+ deps.installCodexHooks(home)+ return {+ ok: true,+ overrides: {+ env: { ...profileEnvironment(engine, home), ...(ownLogin?.env ?? {}) },+ extraArgs: [...(ownLogin?.extraArgs ?? [])],+ clearEnv: [],+ },+ }+ } }}- if (ownLogin) return { ok: true, overrides: ownLogin }- return { ok: true, overrides: noOverrides() }+ return { ok: true, commit: async () => ({ ok: true, overrides: ownLogin ?? noOverrides() }) }}diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex 27eceb82d..748276712 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -14,6 +14,8 @@ import { checkSessionRuntime, clearPaneRemainOnExit, resolvePaneEngineProcess, timport { buildEngineLaunchArgv, dropPermissionFlagIfUnsupported, refusePermissionFlagIfUnsupported } from './engineLaunch.js'import { enginePathOverride } from './engineBin.js'import { installedDsh } from '../dsh/installed.js'+import { createLaunchHelpers } from '../core/agents/launch.js'+import { createLaunchAuthority } from '../core/agents/launchAuthority.js'vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn() }))vi.mock('./tmuxAgentDiscovery.js', () => ({ listTmuxPanes: vi.fn() }))@@ -85,6 +87,21 @@ beforeEach(() => {afterEach(() => { vi.useRealTimers(); for (const row of registry.list()) registry.removeAgent(row.agentId); rmSync(dir, { recursive: true, force: true }) })describe('production resume handler', () => {+ it('composes stopped resume with real launch preparation before any live row exists', async () => {+ const apiNotes = vi.fn()+ const helpers = createLaunchHelpers({+ authority: createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: id => deps.restartJobs.revision(id), cancelled: id => deps.stopJobs.has(id) }),+ prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),+ launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null },+ })+ deps.relaunchOverrides = helpers.relaunchOverrides+ expect(registry.byAgent(saved.agentId)).toBeUndefined()+ expect(await start()).toMatchObject({ ok: true, resumed: true, session: { agentId: saved.agentId, sessionId: saved.sessionId } })+ expect(apiNotes).toHaveBeenCalledWith(dir, 'codex')+ expect(create).toHaveBeenCalledOnce()+ })+it.each(['auto', 'ask'])('resumes the same conversation with an explicit %s permission choice', async permissionMode => {rewrite({ engine: 'opencode', permissionMode: permissionMode === 'auto' ? 'ask' : 'auto' })vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true, overrides: {diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.tsindex fac74e53c..da4567d2e 100644--- a/cli/src/lib/resumeAgentService.ts+++ b/cli/src/lib/resumeAgentService.ts@@ -27,7 +27,7 @@ export interface ResumeAgentServiceDeps {pinnedControls: { has(agentId: string): boolean }retainExitedSession(session: RegisteredSession, paneAlive: boolean): voidannounceSession(session: RegisteredSession): void- relaunchOverrides(session: RegisteredSession): Promise<LaunchOverridesResult>+ relaunchOverrides(session: RegisteredSession, source: RegisteredSession, current: () => boolean): Promise<LaunchOverridesResult>prepareSessionResume(session: RegisteredSession): voidrefreshGridWebSearch(agentId: string, overrides: LaunchOverrides): voidclearDeleted(agentId: string): void@@ -211,7 +211,7 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {token = stoppedAgents.beginResume(agentId)if (!token) token = retakeStaleReservation(agentId)if (!token) return resumeUnconfirmed- const built = await relaunchOverrides(saved)+ const built = await relaunchOverrides(saved, saved, current)if (!built.ok) return { ok: false, error: built.error, detail: built.detail }if (!current()) return resumeChangedif (resumeSessionId) {diff --git a/cli/src/services/storeLaunch.spec.ts b/cli/src/services/storeLaunch.spec.tsindex 536f5b6f1..74103ee2e 100644--- a/cli/src/services/storeLaunch.spec.ts+++ b/cli/src/services/storeLaunch.spec.ts@@ -3,8 +3,10 @@ import { installedDsh } from '../dsh/installed.js'import { materializeWorkspace } from '../dsh/materialize.js'import { forkRuntimeKey, prepareHarnessLaunch } from '../dsh/runtime.js'import type { PrepareDsh } from '../dsh/preparation.js'+import { prepareInstructionWrites } from '../scm/scmProjects.js'import { storeLaunchPort } from './storeLaunch.js'+vi.mock('../scm/scmProjects.js', () => ({ prepareInstructionWrites: vi.fn(async () => {}) }))vi.mock('../dsh/installed.js', () => ({ installedDsh: vi.fn(), dshRootDir: () => '/unused' }))vi.mock('../dsh/materialize.js', () => ({ materializeWorkspace: vi.fn() }))vi.mock('../dsh/runtime.js', () => ({ forkRuntimeKey: vi.fn(() => 'source-runtime'), prepareHarnessLaunch: vi.fn() }))@@ -19,6 +21,7 @@ describe('the Store owns package preparation', () => {const refused = { ok: false, error: 'DSH_NOT_INSTALLED', detail: 'test/draw is not installed on this machine' }expect(await port.dshMaterialize(request)).toEqual(refused)expect(await port.dshLaunch(request)).toEqual(refused)+ expect(prepareInstructionWrites).not.toHaveBeenCalled()expect(materializeWorkspace).not.toHaveBeenCalled()expect(prepareHarnessLaunch).not.toHaveBeenCalled()})@@ -36,6 +39,9 @@ describe('the Store owns package preparation', () => {expect(forkRuntimeKey).toHaveBeenCalledWith({ cwd: request.workspace, agentId: 'source', dshRuntime: null })expect(prepareHarnessLaunch).toHaveBeenLastCalledWith(pkg, request.workspace, request.engine, request.key, request.account, 'source-runtime')expect(materializeWorkspace).toHaveBeenCalledOnce()+ expect(prepareInstructionWrites).toHaveBeenCalledTimes(3)+ expect(prepareInstructionWrites).toHaveBeenCalledWith(request.workspace)+ expect(vi.mocked(prepareInstructionWrites).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(materializeWorkspace).mock.invocationCallOrder[0])})it('returns package errors without bringing down the service, with both historical error forms', async () => {const port = storeLaunchPort(() => pkg, run)@@ -53,6 +59,7 @@ describe('the Store owns package preparation', () => {for (const answer of [await port.dshMaterialize(request), await port.dshLaunch(request)]) {expect(answer).toEqual({ ok: false, error: 'DSH_UNAVAILABLE', unavailable: 'store', holdScope: 'workspace', detail: 'Previous workspace preparation is unconfirmed' })}+ expect(prepareInstructionWrites).not.toHaveBeenCalled()expect(materializeWorkspace).not.toHaveBeenCalled()expect(prepareHarnessLaunch).not.toHaveBeenCalled()})diff --git a/cli/src/services/storeLaunch.ts b/cli/src/services/storeLaunch.tsindex bbc7b4327..ac8b3a6ab 100644--- a/cli/src/services/storeLaunch.ts+++ b/cli/src/services/storeLaunch.ts@@ -5,6 +5,7 @@ import { dshRootDir, installedDsh as lookup } from '../dsh/installed.js'import { materializeWorkspace } from '../dsh/materialize.js'import { forkRuntimeKey, prepareHarnessLaunch } from '../dsh/runtime.js'import { dshPreparations, type PrepareDsh } from '../dsh/preparation.js'+import { prepareInstructionWrites } from '../scm/scmProjects.js'const detail = (error: unknown) => error instanceof Error ? error.message : String(error)@@ -19,6 +20,9 @@ export function storeLaunchPort(installedDsh: typeof lookup = lookup,try {return await prepare(workspace, { kind: 'materialize', ...request, package: installed }, async () => {try {+ // Admission to the durable preparation precedes SCM edits too. Core must not open+ // tracked instruction files for writing while this service is unavailable.+ await prepareInstructionWrites(workspace)const { created, kept, warnings } = await materializeWorkspace(installed, workspace, account, engine)return { ok: true as const, created, kept, warnings }}@@ -35,6 +39,9 @@ export function storeLaunchPort(installedDsh: typeof lookup = lookup,try {return await prepare(workspace, { kind: 'launch', ...request, package: installed }, async () => {try {+ // Admission to the durable preparation precedes SCM edits too. Core must not open+ // tracked instruction files for writing while this service is unavailable.+ await prepareInstructionWrites(workspace)const sourceKey = forkOf ? forkRuntimeKey({ cwd: workspace, ...forkOf }) : nullreturn { ok: true as const, launch: prepareHarnessLaunch(installed, workspace, engine, key, account, sourceKey) }} catch (error) { return { ok: false as const, error: 'DSH_RUNTIME_FAILED', detail: detail(error), thrown: String(error) } }diff --git a/cli/src/testing/launchShapes.ts b/cli/src/testing/launchShapes.tsindex ad72392f8..e45f7a51a 100644--- a/cli/src/testing/launchShapes.ts+++ b/cli/src/testing/launchShapes.ts@@ -91,6 +91,7 @@ export function launchShapes(world: LaunchWorld) {dshLaunch: dshLaunch.relaunch,}const helpers = createLaunchHelpers({+ authority: () => () => true,prepareApiTools, launchOverridesDeps,setGridLaunch: world.setGridLaunch as never, setTail: () => {},})diff --git a/docs/research/2026-10-09-launch-preparation-cost.json b/docs/research/2026-10-09-launch-preparation-cost.jsonnew file mode 100644index 000000000..15bb387cc--- /dev/null+++ b/docs/research/2026-10-09-launch-preparation-cost.json@@ -0,0 +1,102 @@+{+ "nativeHooks": true,+ "node": "v22.23.2",+ "platform": "darwin",+ "tmux": "tmux 3.5a",+ "samples": [+ {+ "bundle": "baseline",+ "readyMs": 1960.940514,+ "atReady": {+ "cpuMs": 300,+ "rssMiB": 78.38671875+ },+ "launches": [+ {+ "phase": "cold",+ "requestMs": 188.8492299999998,+ "coreCpuMs": 20,+ "rssMiB": 79.06640625+ },+ {+ "phase": "warm",+ "requestMs": 91.55305899999985,+ "coreCpuMs": 20,+ "rssMiB": 80.05859375+ }+ ]+ },+ {+ "bundle": "candidate",+ "readyMs": 1555.316334,+ "atReady": {+ "cpuMs": 340,+ "rssMiB": 78.43359375+ },+ "launches": [+ {+ "phase": "cold",+ "requestMs": 195.31679599999916,+ "coreCpuMs": 30,+ "rssMiB": 79.17578125+ },+ {+ "phase": "warm",+ "requestMs": 97.33563400000003,+ "coreCpuMs": 20,+ "rssMiB": 80.02734375+ }+ ]+ },+ {+ "bundle": "candidate",+ "readyMs": 1631.636294,+ "atReady": {+ "cpuMs": 350,+ "rssMiB": 78.36328125+ },+ "launches": [+ {+ "phase": "cold",+ "requestMs": 191.81856700000026,+ "coreCpuMs": 20,+ "rssMiB": 79.109375+ },+ {+ "phase": "warm",+ "requestMs": 100.44675599999937,+ "coreCpuMs": 20,+ "rssMiB": 80.42578125+ }+ ]+ },+ {+ "bundle": "baseline",+ "readyMs": 1581.9255520000006,+ "atReady": {+ "cpuMs": 310,+ "rssMiB": 78.43359375+ },+ "launches": [+ {+ "phase": "cold",+ "requestMs": 186.56023300000015,+ "coreCpuMs": 30,+ "rssMiB": 79.16015625+ },+ {+ "phase": "warm",+ "requestMs": 89.49597899999935,+ "coreCpuMs": 10,+ "rssMiB": 80.26171875+ }+ ]+ }+ ],+ "baseline": "b6e15e10c7dee075b8db098647bb5b4ffca56d83",+ "candidateProduction": "90f51bc76930b78f3865f69c15cbec612d378827",+ "bundleSha256": {+ "baseline": "a5f3452c8634ea92bbe80c59f5c74da05969266c970dcaf58cb8d9261ecf28b3",+ "candidate": "436f1a6206ac57bd4029d3dbf7bf0b0b700c89d3ff95647b315b2919dea2d514"+ }+}diff --git a/docs/research/2026-10-09-launch-preparation.md b/docs/research/2026-10-09-launch-preparation.mdnew file mode 100644index 000000000..472eac33c--- /dev/null+++ b/docs/research/2026-10-09-launch-preparation.md@@ -0,0 +1,27 @@+# Launch preparation and durable holds++Former-code baseline, recorded before implementation: main `ee33093971d27e9dcda7f2ae8c35f54b61cec0bb`. The native OpenCode, grid/saved API and DSH launch goldens were re-recorded under UTC and `/tmp`, with the existing pinned Linux platform, private homes and binary placeholders. All three artifacts are byte-for-byte identical to main. Recording passed in 28.7 seconds, followed by verification with recording disabled in 28.7 seconds (six tests across three files).++Artifact SHA-256:++- `opencode-launch.golden.json`: `f5985028ccaa7c363389a482471d0ad6d97c27b9140e537a0698e380a86779b1`+- `launch-shapes.golden.json`: `ba6f25ebdf3cb56bb930d603d938830d93ef09939208aa59b7ffb29d2d8be9de`+- `dsh-launch-shapes.golden.json`: `d523f9b50b9ed6b5f33aee2222035aeda085bdd7a4d74c7afeb4c05c1710e9bd`++The launch-port design's older refusal policy for manual operations is superseded by the current requirement: an unavailable dependency must hold the intent with a visible reason, without failing or half-writing it. Session control and readiness stay independent. Preparation must use confirmed executable facts, preserve operation authority across awaits, and publish only confirmed effects. A durable journal must distinguish safe retries from unconfirmed mutations. These are safety changes following the compatibility extractions, not line-count targets.++Validation will preserve the former golden artifacts, add regressions for the new guarantees, deliberately break wiring, run the affected private-daemon lanes and enforce TypeScript, architecture and per-file core/master coverage. Independent exact-head review and automatic CI precede each merge. No release is authorized.++The first implementation introduces a preparation/commit boundary for relaunch overrides. Models answers before the Store is asked; profile hooks and grid configuration wait until both answers succeed. One deep request snapshot and one machine-fact snapshot supply the attempt. Core instruction-file preparation and saved-API notes wait for an available dependency answer. Ordinary semantic refusals retain the established saved-API notes; the former grid golden caught this distinction. The Store opens SCM instruction files only inside its durable workspace reservation, immediately before the package writes them; an unavailable or uncertain Store causes no earlier core SCM edit. Fresh create and fork likewise defer their own saved-API instruction work.++This step does not yet journal a manual create/fork/restart/retarget intent, make grid writes atomic, or solve retarget authority and native-write uncertainty. Those remain required. In particular, callers still need a durable held outcome instead of converting unavailable-service answers into ordinary failure receipts. Successful former golden observations must remain unchanged through this staging change.++Independent review found that moving instruction writes after a service await could reread a changed registry row. Relaunch now captures immutable requested data separately from core-owned lifecycle authority. Stopped resume and restore’s terminal/fresh projections are legitimate requests that differ from the live row. Their owning current predicate grants the operation; a separate snapshot of the actual live row at dispatch detects later changes. Binding, process, route, launch facts, Stop state and coordinator revision fence local commits and deferred instructions; authority is checked again after SCM preparation. Prepared closures are ephemeral and accept one commit only. This does not claim atomic rollback of an already-dispatched write or fencing of an in-flight Store operation.++Private Store-outage acceptance preserves custom-profile hook bytes and both workspaces’ instruction bytes while launches are held, then verifies required hooks and saved-API notes appear only after recovery. The broader authority and durable-intent work remains separate.++Review also caught that equating a requested projection with the live registry would reject stopped resume and terminal fallback. The first bundled fork lane reproduced that regression for both engines. The corrected composition explicitly passes restart/restore/resume authority, accepts an absent stopped row, and treats preparation revocation as cancellation in restore rather than failing or retiring the newer row. Composed regressions exercise those paths with the real launch helper. A matrix fixture exceeded its existing five-second case budget while broad checks ran; its isolated serial pass is required separately. No failed suite is counted as passing.++Linux CI also caught the older launch-argv golden's precise call trace: OpenCode and Pi on a DSH plus grid formerly wrote configuration before asking the Store. That order is the safety behavior intentionally changed here. The former JSON stays byte-for-byte intact. Only those two named expectations, on both platforms, assert the exact former trace and then require the reversed trace; their complete results and every other case retain exact equality. A mutation restores the old order without adding duplicate writes and must fail this golden assertion. This is an explicit behavior change, not a claim that the entire former call order is unchanged.++[Runtime observations](2026-10-09-launch-preparation-cost.json) compare frozen main and candidate bundles in baseline/candidate/candidate/baseline order, with all thirteen native installers and two fresh OpenCode launches per private daemon. Ready time was 1,582–1,961 ms on main and 1,555–1,632 ms on the candidate; core CPU at ready was 300–310 versus 340–350 ms; RSS rounded to 78.4 MiB in all four runs. Cold launch requests were 187–189 versus 192–195 ms and warm requests 89–92 versus 97–100 ms. These two samples per bundle and the 10 ms CPU observation resolution are reference measurements, not a speed claim or threshold. This workload measures startup and fresh launch, not all retarget or Store-outage latency. Reproduce with `OPENCODE_COST_ROOT` containing frozen `baseline/cli.js` and `candidate/cli.js`, `OPENCODE_COST_NATIVE_HOOKS=1`, and `e2e/opencodeLaunchCost.e2e.ts` alone under the recorded Node/tmux, UTC and private tmux environment.