Skip to content

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.

Preserve native mutation and Stop authority across retarget retries (#1155)

Dee71f42b852ab7
diff --git a/cli/e2e/eagerOpenCode.e2e.ts b/cli/e2e/eagerOpenCode.e2e.ts
index b8b2a392b..1c97aa083 100644
--- a/cli/e2e/eagerOpenCode.e2e.ts
+++ b/cli/e2e/eagerOpenCode.e2e.ts
@@ -1,6 +1,6 @@
/** Real launch dispatch keeps working without OpenCode's optional interpretation chunk. */
import { execFileSync } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'
@@ -33,6 +33,8 @@ it.each([['missing', 1], ['stalled', 1], ['missing', 2], ['stalled', 2]] as cons
const d = daemon = await IsolatedDaemon.create({ scriptPath: script, env: { HARNESS_CONNECTIONS_PORT: '0' } })
onTestFailed(() => console.log(d.log()))
const binary = join(d.root, 'bin', 'opencode'), launches = join(d.root, 'launches.jsonl')
+ const apiCalls = join(d.root, 'api.jsonl'), nativeModel = join(d.root, 'model.json')
+ const fault = join(d.root, 'api-fault'), readEntered = join(d.root, 'read-entered'), readRelease = join(d.root, 'read-release')
d.env.OPENCODE_PATH = binary
d.env.OPENCODE_DATA_DIR = join(d.root, 'opencode', 'data')
d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')
@@ -42,11 +44,32 @@ const args = process.argv.slice(2);
if (args.includes('--version')) { console.log('opencode v${major}.0.18'); process.exit(0) }
if (args.includes('--help')) { console.log('--auto --session --prompt --agent'); process.exit(0) }
if (args[0] === 'models') { console.log('fixture/model'); process.exit(0) }
+if (args[0] === 'api') {
+ fs.appendFileSync(${JSON.stringify(apiCalls)}, JSON.stringify(args) + '\\n');
+ const fault = fs.existsSync(${JSON.stringify(fault)}) ? fs.readFileSync(${JSON.stringify(fault)}, 'utf8') : '';
+ const id = args[args.indexOf('--param') + 1]?.split('=')[1];
+ if (args[1] === 'session.switchModel') {
+ fs.writeFileSync(${JSON.stringify(nativeModel)}, args[args.indexOf('-d') + 1]);
+ process.exit(fault === 'lost-reply' ? 1 : 0);
+ }
+ if (args[1] !== 'session.get') process.exit(2);
+ if (fault === 'unavailable') process.exit(1);
+ const answer = () => {
+ const data = JSON.parse(fs.readFileSync(${JSON.stringify(nativeModel)}, 'utf8'));
+ if (fault === 'native-choice') data.model.id = 'chosen-in-terminal';
+ console.log(JSON.stringify({data:{id,...data}})); process.exit(0);
+ };
+ if (fault === 'stalled') {
+ fs.writeFileSync(${JSON.stringify(readEntered)}, '');
+ setInterval(() => { if (fs.existsSync(${JSON.stringify(readRelease)})) answer(); }, 10);
+ } else answer();
+} else {
const id = args.includes('--session') ? args[args.indexOf('--session') + 1] : 'ses_' + process.pid;
process.title = ('opencode --session ' + id).padEnd(160);
fs.appendFileSync(${JSON.stringify(launches)}, JSON.stringify({id,args,pid:process.pid}) + '\\n');
console.log('fixture-opencode-ready'); console.log('┃');
setInterval(() => {}, 1000);
+}
`, { mode: 0o755 })
await d.start()
const c = client = await LocalClient.connect(d)
@@ -90,7 +113,44 @@ setInterval(() => {}, 1000);
// its checkpoint; Stop can still preserve that ID and resume the same native process contract.
expect(closed, JSON.stringify(closed)).toMatchObject({ error: 'HISTORY_NOT_SAVED' })
expect((await active(source.id)).sessionId).toBe(source.sessionId)
- expect((await c.request('agent_delete', { agentId: source.id }, 45_000)).error).toBeUndefined()
+ let pendingRetarget: Promise<Record<string, any>> | undefined, retargetClient: LocalClient | undefined
+ const nativeWrites = () => readFileSync(apiCalls, 'utf8').split('\n').filter(Boolean)
+ .map(line => JSON.parse(line) as string[]).filter(args => args[1] === 'session.switchModel')
+ let beforeStop = records().length
+ try {
+ if (major === 2) {
+ const grid = { networkId: 'net-fixture', networkName: 'fixture-grid', baseUrl: 'https://fixture.invalid/g/net-fixture/relay', apiKey: 'fixture-key', model: 'Small-Q4' }
+ writeFileSync(fault, 'lost-reply')
+ const switched = await c.request('agent_retarget', { agentId: source.id, grid }, 45_000)
+ expect(switched.error, JSON.stringify(switched)).toBeUndefined()
+ await active(source.id)
+ expect(nativeWrites()).toHaveLength(1)
+ const count = records().length
+ const next = { ...grid, model: 'Large-Q4' }
+ writeFileSync(fault, 'unavailable')
+ expect(await c.request('agent_retarget', { agentId: source.id, grid: next }, 30_000))
+ .toMatchObject({ error: 'OPENCODE_MODEL_SWITCH_FAILED', detail: expect.stringContaining('may already have applied') })
+ expect(nativeWrites()).toHaveLength(2)
+ writeFileSync(fault, 'native-choice')
+ expect(await c.request('agent_retarget', { agentId: source.id, grid: next }, 30_000))
+ .toMatchObject({ error: 'OPENCODE_MODEL_SWITCH_FAILED' })
+ expect(nativeWrites()).toHaveLength(2)
+ expect(records()).toHaveLength(count)
+ expect((await active(source.id)).sessionId).toBe(source.sessionId)
+ writeFileSync(fault, 'stalled')
+ retargetClient = await LocalClient.connect(d)
+ pendingRetarget = retargetClient.request('agent_retarget', { agentId: source.id, grid: next }, 30_000)
+ await until('native confirmation read to wait', () => existsSync(readEntered), 10_000, 20)
+ beforeStop = records().length
+ }
+ expect((await c.request('agent_delete', { agentId: source.id }, 10_000)).error).toBeUndefined()
+ } finally {
+ writeFileSync(readRelease, '')
+ const result = await pendingRetarget?.finally(() => retargetClient?.close())
+ if (result) expect(result).toMatchObject({ error: 'AGENT_CHANGED', detail: expect.stringContaining('may already have applied') })
+ }
+ expect(records()).toHaveLength(beforeStop)
+ if (major === 2) expect(nativeWrites()).toHaveLength(2)
await until('Stop preserves the conversation', async () => {
const row = (await rows()).find(row => row.id === source.id)
return row?.status === 'stopped' && row.sessionId === source.sessionId ? row : null
diff --git a/cli/e2e/handoff.e2e.ts b/cli/e2e/handoff.e2e.ts
index be5b56576..1bfe0aec8 100644
--- a/cli/e2e/handoff.e2e.ts
+++ b/cli/e2e/handoff.e2e.ts
@@ -117,11 +117,15 @@ describe('change agent in the edge host', () => {
expect((await client.request('agent_delete', { agentId: forkId }, 30_000)).error).toBeUndefined()
client.close()
await d.stop()
- // Exercise the handoff reader against the exact pending row observed above. Stop's separate
- // resume-identity capture can find the source named on a fork's argv; it is not the state this
- // case covers. With the daemon off, seed the retained unbound record as the store would save it.
+ // Stop must preserve the actual unbound fork and its parent. A recent-file
+ // guess used to give the fork its parent's identity, then ownership settlement
+ // set the parent aside. Verify the saved records before restarting the daemon.
const savedPath = join(d.dataDir, 'stopped-agents', `${forkId}.json`)
- writeFileSync(savedPath, JSON.stringify({ version: 1, session: { ...pending, active: false, launch: { state: 'ready' } } }))
+ expect(JSON.parse(readFileSync(savedPath, 'utf8')).session).toMatchObject({
+ agentId: forkId, sessionId: '', forkedFrom: pending.forkedFrom,
+ })
+ expect(JSON.parse(readFileSync(join(d.dataDir, 'stopped-agents', `${agentId}.json`), 'utf8')).session)
+ .toMatchObject({ agentId, sessionId: pending.forkedFrom.sessionId })
await d.start()
await until('handoff to reconnect after the restart', () => d.log().split('[services] handoff connected').length >= 3 || null, 30_000, 200)
const restarted = await LocalClient.connect(d)
diff --git a/cli/package.json b/cli/package.json
index bcb21a9d9..caf7d0cfc 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -24,7 +24,7 @@
"test:remote-viewers": "vitest run --config vitest.viewer.config.ts",
"test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
"test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/codexUpdateRestart.real.spec.ts src/lib/restartDiscovery.real.spec.ts src/lib/terminalClose.real.spec.ts src/lib/engineStop.real.spec.ts --reporter=verbose",
- "test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
+ "test:resume": "vitest run src/lib/controlTranscript.spec.ts src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
"test:resume-native": "tsc -p tsconfig.resume-native.json && tsx scripts/resume-native-e2e.ts",
"test:portability": "vitest run --config vitest.portability.config.ts"
},
diff --git a/cli/scripts/handoff-2026-10-08/mutate-fork-source.py b/cli/scripts/handoff-2026-10-08/mutate-fork-source.py
new file mode 100644
index 000000000..b0008aed6
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-fork-source.py
@@ -0,0 +1,64 @@
+"""Break fork-source ownership only in an explicitly owned disposable worktree."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+assert (cli.parent / '.git').is_file(), 'An owned disposable worktree is required'
+assert os.environ.get('HARNESS_NATIVE_MUTATIONS_OWNED') == '1'
+assert subprocess.check_output(['git', 'status', '--porcelain'], cwd=cli, text=True) == ''
+repair = 'src/lib/sessionRepair.ts'
+descriptors = 'src/lib/nativeConversation.ts'
+repair_spec = 'src/lib/sessionRepair.spec.ts'
+descriptor_spec = 'src/lib/nativeConversation.spec.ts'
+stop_spec = 'src/lib/captureResumeIdentity.spec.ts'
+bind_spec = 'src/core/agents/bind.spec.ts'
+mutations = [
+ ('recent-file source retained', repair, 'if (found.sessionId === opts?.excludedSessionId) continue', '', repair_spec, 'excludes a known fork parent', 1),
+ ('Stop omits fork source', 'src/lib/captureResumeIdentity.ts', '...(session.forkedFrom?.sessionId ? { excludedSessionId: session.forkedFrom.sessionId } : {}),', '', stop_spec, 'does not give an unbound', 1),
+ ('binding omits fork source', 'src/core/agents/bind.ts', '...(agent.forkedFrom?.sessionId ? { excludedSessionId: agent.forkedFrom.sessionId } : {}),', '', bind_spec, 'keeps a stopped parent', 1),
+ ('open source accepted', descriptors, 'if (meta.id === options.excludedSessionId) continue', '', descriptor_spec, 'excludes a fork source', 1),
+ ('descriptor inference omits fork source', repair, ', excludedSessionId: opts.excludedSessionId', '', repair_spec, 'reads a live process', 1),
+ ('excluded header not rechecked', descriptors, 'headers.push({ key, verify: header.verify })', 'if (header.meta.id !== options.excludedSessionId) headers.push({ key, verify: header.verify })', descriptor_spec, 'retains changed evidence', 1),
+ ('database source accepted', repair, '&& id !== excludedSessionId', '', repair_spec, 'from a limited pool', 1),
+ ('database lookup omits fork source', repair, ' opts?.excludedSessionId,', '', repair_spec, 'from a limited pool', 3),
+ ('truncated pool treated as complete', repair, 'const rows = result.rows', 'const rows = result.rows.filter(row => row.id !== excludedSessionId)', repair_spec, 'from a limited pool', 1),
+ ('Hermes source retained', repair, 'if (row.id === opts?.excludedSessionId) continue', '', repair_spec, 'complete Hermes pool', 1),
+]
+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')
+for key in ('TMUX', 'TMUX_PANE'):
+ environment.pop(key, None)
+tmux = cli.parent / '.harness/tmux'
+tmux.mkdir(parents=True, exist_ok=True)
+environment['TMUX_TMPDIR'] = str(tmux)
+
+
+def run(files, pattern=''):
+ command = ['node', 'node_modules/vitest/vitest.mjs', 'run', *files, '--maxWorkers=1']
+ if pattern:
+ command += ['-t', pattern]
+ return subprocess.run(command, cwd=cli, env=environment, text=True, capture_output=True, timeout=180)
+
+
+baseline = run([repair_spec, descriptor_spec, stop_spec, bind_spec])
+assert baseline.returncode == 0, 'Unchanged baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr
+print('Unchanged baselines passed', flush=True)
+failures = []
+for label, relative, before, after, spec, pattern, expected in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == expected, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([spec], pattern)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ failures.append(label)
+ print(label + ': NOT caught by assertion\n' + output, flush=True)
+ else:
+ print(label + ': caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
+if failures:
+ raise SystemExit('Uncaught mutations: ' + ', '.join(failures))
diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-mutation.py b/cli/scripts/handoff-2026-10-08/mutate-native-mutation.py
new file mode 100644
index 000000000..21201383e
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-native-mutation.py
@@ -0,0 +1,67 @@
+"""Owned disposable worktree only: mutation safety and healthy protocol must be asserted."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+assert (cli.parent / '.git').is_file(), 'An owned disposable worktree is required'
+assert os.environ.get('HARNESS_NATIVE_MUTATIONS_OWNED') == '1'
+golden = 'src/engines/nativeMutation.golden.spec.ts'
+faults = 'src/engines/nativeMutation.spec.ts'
+dispatch = 'src/engines/kit/nativeMutationDispatch.spec.ts'
+retarget = 'src/core/agents/retarget.spec.ts'
+native = 'src/engines/kit/nativeSessionModel.ts'
+control = 'src/core/agents/retarget.ts'
+mutations = [
+ ('native provider protocol', 'src/engines/opencode/contract.ts', "provider: 'providerID'", "provider: 'provider'", golden, ''),
+ ('unreadable catalog admits write', native, 'const known = await listsModel(run, requested, receipt.cwd)', 'const known = (await listsModel(run, requested, receipt.cwd)) ?? true', faults, 'required catalog'),
+ ('uncertain receipt forgotten', native, 'const previous = pending.get(sessionId)', 'const previous = undefined', faults, 'across later requests'),
+ ('wrong conversation accepted', native, "|| data[fields.id] !== sessionId", '', faults, 'matching model data'),
+ ('legacy fallback ignores pending write', native, 'if (pending.has(sessionId)) return', 'if (false) return', dispatch, 'does not bypass'),
+ ('stdin kept open', native, 'child.stdin?.end()', "child.stdin?.write('')", dispatch, 'bounds children'),
+ ('retarget follows mutable row', control, 'const session = structuredClone(live)', 'const session = live', retarget, 'mutable row'),
+ ('retarget loses revocable authority', control, 'return () => !!registry.byAgent(session.agentId) && owns()', 'return () => true', retarget, 'owner changes during'),
+ ('route expires during swap', control, 'holdRoute(routeKey, null)', 'holdRoute(routeKey)', retarget, 'past the default hold timer'),
+ ('old retarget releases newer Stop', control, 'releaseRoute?.()', ";(agentReconciler as TerminalAgentReconciler).releaseRoute(routeKey)", retarget, 'newer Stop route hold'),
+ ('confirmed native effect hidden', control, "nativeEffect = written.ok ? 'applied' : (written.effect ?? 'none')", "nativeEffect = 'none'", retarget, 'discloses an applied model'),
+ ('environment dispatch not fenced', 'src/lib/tmuxBackend.ts', "if (current?.() === false) return terminalActionNotStarted('The harness changed before clearing its environment')", '', 'src/lib/tmuxBackend.spec.ts', 'revoked during session lookup'),
+ ('signal escalation not fenced', 'src/lib/deleteAgentFallback.ts', "if (deps.current?.() === false) return 'not-ours'", '', 'src/lib/deleteAgentFallback.spec.ts', 'ownership is revoked'),
+]
+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')
+for key in ('TMUX', 'TMUX_PANE', 'RECORD_NATIVE_MUTATION_GOLDEN', 'RECORD_OPENCODE_LAUNCH_GOLDEN'):
+ environment.pop(key, None)
+tmux = cli.parent / '.harness/tmux'
+tmux.mkdir(parents=True, exist_ok=True)
+environment['TMUX_TMPDIR'] = str(tmux)
+
+
+def run(files, pattern=''):
+ command = ['node', 'node_modules/vitest/vitest.mjs', 'run', *files, '--maxWorkers=1']
+ if pattern:
+ command += ['-t', pattern]
+ return subprocess.run(command, cwd=cli, env=environment, text=True, capture_output=True, timeout=180)
+
+
+baseline = run([golden, faults, dispatch, retarget, 'src/lib/tmuxBackend.spec.ts', 'src/lib/deleteAgentFallback.spec.ts'])
+assert baseline.returncode == 0, 'Unchanged baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr
+print('Unchanged baselines passed', flush=True)
+failures = []
+for label, relative, before, after, spec, pattern in mutations:
+ path = cli / relative
+ original = path.read_text()
+ expected = 4 if label == 'signal escalation not fenced' else 1
+ assert original.count(before) == expected, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([spec], pattern)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ failures.append(label)
+ print(label + ': NOT caught by assertion\n' + output, flush=True)
+ else:
+ print(label + ': caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
+if failures:
+ raise SystemExit('Uncaught mutations: ' + ', '.join(failures))
diff --git a/cli/scripts/handoff-2026-10-08/native-mutation-cost.ts b/cli/scripts/handoff-2026-10-08/native-mutation-cost.ts
new file mode 100644
index 000000000..3cca7dc8a
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/native-mutation-cost.ts
@@ -0,0 +1,43 @@
+/** Matched native model control workload; synthetic native latency, no host binaries or files. */
+import { performance } from 'node:perf_hooks'
+import { resolve, join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import childProcess from 'node:child_process'
+import { syncBuiltinESMExports } from 'node:module'
+
+const root = process.env.NATIVE_MUTATION_COST_CLI ?? resolve(import.meta.dirname, '../..')
+const workload = process.argv[2]
+if (!['healthy', 'lost-reply'].includes(workload)) throw Error('Unknown workload')
+const hostPlatform = process.platform
+Object.defineProperty(process, 'platform', { value: 'linux' })
+const forbidden = () => { throw Error('Host binaries are forbidden in this measurement') }
+Object.assign(childProcess, { exec: forbidden, execSync: forbidden, execFile: forbidden, execFileSync: forbidden, spawn: forbidden, spawnSync: forbidden, fork: forbidden })
+syncBuiltinESMExports()
+const { createSessionModelControl } = await import(pathToFileURL(join(root, 'src/engines/kit/nativeSessionModel.ts')).href)
+const { OPENCODE_SESSION_MODEL } = await import(pathToFileURL(join(root, 'src/engines/opencode/contract.ts')).href)
+console.log = () => {}; console.warn = () => {}
+const control = createSessionModelControl(OPENCODE_SESSION_MODEL, () => '/fixture/opencode')
+const iterations = 40, latenciesMs: number[] = []
+let writes = 0, reads = 0, confirmed = 0
+const cpu = process.cpuUsage()
+for (let index = 0; index < iterations; index++) {
+ const sessionId = `ses_fixture${index}`, started = performance.now()
+ const result = await control.switchSessionModel(sessionId, { providerID: 'fixture', modelID: 'model' }, {
+ retryDelayMs: 0, run: async (args: string[]) => {
+ await new Promise(done => setTimeout(done, 2))
+ if (args[1] === 'session.switchModel') {
+ writes++
+ if (workload === 'lost-reply') throw Error('committed, reply lost')
+ return { stdout: '' }
+ }
+ reads++
+ return { stdout: JSON.stringify({ data: { id: sessionId, model: { providerID: 'fixture', id: 'model' } } }) }
+ },
+ })
+ if (result.ok) confirmed++
+ latenciesMs.push(performance.now() - started)
+}
+const used = process.cpuUsage(cpu)
+process.stdout.write(JSON.stringify({ workload, iterations, latenciesMs, cpuMs: (used.user + used.system) / 1000,
+ peakRssMiB: process.resourceUsage().maxRSS / 1024, writes, reads, confirmed,
+ node: process.version, hostPlatform, evidencePlatform: process.platform, arch: process.arch }) + '\n')
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index 9c420cac6..bc4935210 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -748,6 +748,21 @@ describe('binding a running process to its session', () => {
})
describe('a repair', () => {
+ it('keeps a stopped parent out of an unbound fork\'s fallback discovery', async () => {
+ const owners = { settle: vi.fn(() => []) }, run = setup({ owners })
+ const parent = agent({ agentId: 'parent-agent', sessionId: 'parent', active: false })
+ const fork = agent({ sessionId: '', forkedFrom: { agentId: parent.agentId, name: 'Parent', sessionId: parent.sessionId } })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(fork)
+ vi.mocked(run.deps.stoppedAgents.get).mockReturnValue(parent)
+ vi.mocked(findLiveSession).mockImplementation(async (_engine, _cwd, _start, options) =>
+ options?.excludedSessionId === parent.sessionId ? null : { sessionId: parent.sessionId, transcriptPath: '/parent' })
+ await run.binding.bindObservedAgent(observed())
+ expect(run.deps.registry.register).not.toHaveBeenCalled()
+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()
+ expect(owners.settle).not.toHaveBeenCalled()
+ expect(fork.sessionId).toBe('')
+ })
+
it.each(['rebound', 'stopped'] as const)('does not publish native Codex evidence after its owner was %s', async change => {
const run = setup(), entry = agent({ engine: 'codex', sessionId: '' }), seen = observed({ engine: 'codex' })
vi.mocked(run.deps.registry.byProcess).mockReturnValue(entry)
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index af179e7cd..3e30feeea 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -378,6 +378,7 @@ export function createBinding({
//
const located = await read(() => findLiveSession(observed.engine, observed.cwd, startedAtMs, {
bornOnly: true,
+ ...(agent.forkedFrom?.sessionId ? { excludedSessionId: agent.forkedFrom.sessionId } : {}),
pid: observed.processIdentity.pid,
expectedProcess: observed.processIdentity,
codexHome: agent.codexHome ?? undefined,
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index 18cce6e67..f5dc81530 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -253,7 +253,7 @@ describe('restarting an agent', () => {
expect(bypassPermissionFor).toHaveBeenCalledWith(agent(), expect.any(Function))
expect(run.deps.liveBypassPermission).toHaveBeenCalledWith(agent())
expect(run.deps.downgradedPermission).toHaveBeenCalledWith(agent(), true, 'restart')
- expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(agent(), runtime, { env: { GRID_KEY: 'k' } }, 'auto')
+ expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(agent(), runtime, { env: { GRID_KEY: 'k' } }, 'auto', expect.any(Function))
const [target, bypass, swapDeps] = vi.mocked(restartAgent).mock.calls[0]
expect(target).toEqual({ engine: 'claude', sessionId: 's1' })
expect(bypass).toBe(true)
@@ -277,7 +277,7 @@ describe('restarting an agent', () => {
const run = setup(grid, { downgradedPermission: vi.fn(async () => ({ bypassPermission: false })) as never })
vi.mocked(restartAgent).mockResolvedValueOnce({ ok: true, resumed: false, processIdentity: newProcess } as never)
expect(await run.restart('a1')).toEqual({ ok: true, session: grid, resumed: false })
- expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(grid, runtime, { env: { GRID_KEY: 'k' } }, null)
+ expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(grid, runtime, { env: { GRID_KEY: 'k' } }, null, expect.any(Function))
expect(vi.mocked(restartAgent).mock.calls[0][1]).toBe(false)
expect(console.log).toHaveBeenCalledWith('[restart] a1 claude · fresh session · grid Home')
})
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index 699905368..5e46ea43d 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -172,7 +172,7 @@ export function createAgentRestarter({
const outcome = await restartAgent(
{ engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },
restartPermission.bypassPermission === true,
- { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null), isCurrent: current },
+ { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null, current), isCurrent: current },
)
if (!current()) return changed
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index 99218a02c..ff9acdd15 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -1,14 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { applyOpencodeSessionModel, parseOpencodeModelId } from '../../engines/launchControl.js'
+import { applyOpencodeSessionModel, parseOpencodeModelId, opencodeMajorVersion } from '../../engines/launchControl.js'
import { isOpencodeV2 } from '../../engines/launchControl.js'
import { binaryOnPath } from '../../lib/binaryOnPath.js'
import { validateLaunchOverrides } from '../../lib/launchOverrides.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
+import { AgentRestartCoordinator, bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
+import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
+import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
+import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import { createAgentRetargeter, type RetargetDeps } from './retarget.js'
vi.mock('../../engines/launchControl.js', async (real) => ({
@@ -39,14 +42,14 @@ vi.mock('../../lib/tmux.js', async (real) => ({
}))
vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))
-const pane = { backend: 'tmux', paneId: '%4' }
+const pane = { backend: 'tmux' as const, paneId: '%4' }
const grid = { networkId: 'g1', networkName: 'Home', baseUrl: 'http://g', model: 'big', apiKey: 'k' }
const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({
agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work', runtimes: [pane], processIdentity: { pid: 1, startMarker: 'old' }, ...over,
}) as unknown as RegisteredSession
function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDeps> = {}) {
- const release = vi.fn()
+ const release = vi.fn(), releaseRoute = vi.fn()
const deps: RetargetDeps = {
readScreen: async (session, capture) => ({ pane: inspectRuntimePane(session.engine, capture ?? ''), question: null, messageHold: null, teamHold: null, activity: null, busy: false, stoppedGoal: false }),
purgeBusy: vi.fn(() => false),
@@ -65,8 +68,8 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDe
acquireTerminalControl: vi.fn(() => release),
relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { gridLaunchRecord: { override: grid, webSearch: 'off' } } })) as never,
downgradedPermission: vi.fn(async (_s, bypass: boolean) => ({ bypassPermission: bypass, permissionMode: null })) as never,
- agentReconciler: { holdRoute: vi.fn(), releaseRoute: vi.fn() },
- restartJobs: { busy: vi.fn(() => false), cancel: vi.fn() } as never,
+ agentReconciler: { holdRoute: vi.fn(() => releaseRoute) },
+ restartJobs: { busy: vi.fn(() => false), cancel: vi.fn(), revision: () => 0 } as never,
paneSwapDeps: vi.fn(() => ({})) as never,
liveBypassPermission: vi.fn(async () => true),
announceSession: vi.fn(),
@@ -74,7 +77,7 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDe
opencodeDb: '/db/opencode.db',
...over,
}
- return { deps, release, retarget: createAgentRetargeter(deps) }
+ return { deps, release, releaseRoute, retarget: createAgentRetargeter(deps) }
}
describe('retargeting an agent', () => {
@@ -100,6 +103,82 @@ describe('retargeting an agent', () => {
})
describe('refusals before anything is touched', () => {
+ it('keeps the admitted conversation in an asynchronous reader while a mutable row changes', async () => {
+ const row = agent()
+ let release!: () => void, entered = false, observed: string | undefined
+ const ready = new Promise<void>(done => { release = done })
+ const run = setup(row, { readScreen: async snapshot => {
+ entered = true
+ await ready
+ observed = snapshot.sessionId
+ return { pane: { idle: true } } as never
+ } })
+ const pending = run.retarget({ agentId: 'a1', grid })
+ await vi.waitFor(() => expect(entered).toBe(true))
+ row.sessionId = 'replacement'
+ release()
+ expect(await pending).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(observed).toBe('s1')
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it('cannot follow a mutable row to a replacement conversation while capture waits', async () => {
+ const row = agent()
+ let finish!: (value: string) => void
+ const run = setup(row, { captureTerminal: () => new Promise(done => { finish = done }) })
+ const pending = run.retarget({ agentId: 'a1', grid })
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ row.sessionId = 'replacement'
+ row.processIdentity = { pid: 77, startMarker: 'replacement', executable: 'claude' }
+ finish('idle pane')
+ expect(await pending).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+ it.each(['validation', 'version', 'screen', 'preparation', 'native-write', 'environment', 'bypass', 'permission', 'replacement', 'gateway', 'pane-option'] as const)(
+ 'cannot publish or continue a retarget whose owner changes during %s', async phase => {
+ const row = agent({ engine: 'opencode', subscriptionModel: 'fixture/model' })
+ const run = setup(row, { relaunchOverrides: vi.fn(async () => ({ ok: true as const,
+ overrides: { sessionModel: 'fixture/model', env: {}, extraArgs: [], clearEnv: [] } })) })
+ const replace = () => { row.sessionId = 'replacement' }
+ switch (phase) {
+ case 'validation': vi.mocked(validateLaunchOverrides).mockImplementationOnce(async () => { replace(); return { ok: true } }); break
+ case 'version': vi.mocked(opencodeMajorVersion).mockImplementationOnce(async () => { replace(); return 2 }); break
+ case 'screen': run.deps.readScreen = vi.fn(async () => { replace(); return { pane: { idle: true } } as never }); break
+ case 'preparation': vi.mocked(run.deps.relaunchOverrides).mockImplementationOnce(async () => { replace(); return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } } }); break
+ case 'native-write': vi.mocked(applyOpencodeSessionModel).mockImplementationOnce(async () => { replace(); return { ok: true } }); break
+ case 'environment': vi.mocked(run.deps.tmuxBackend!.clearEnv).mockImplementationOnce(async () => { replace(); return { state: 'succeeded', dispatch: 'executed' } }); break
+ case 'bypass': vi.mocked(bypassPermissionFor).mockImplementationOnce(async () => { replace(); return true }); break
+ case 'permission': vi.mocked(run.deps.downgradedPermission).mockImplementationOnce(async () => { replace(); return {} }); break
+ case 'replacement': vi.mocked(restartAgent).mockImplementationOnce(async () => { replace(); return { ok: true, resumed: true, processIdentity: { pid: 2, executable: 'opencode', startMarker: 'new' } } }); break
+ case 'gateway': vi.mocked(probeGatewayRuntime).mockImplementationOnce(async () => { replace(); return { kind: 'none' } as never }); break
+ case 'pane-option': vi.mocked(clearPaneRemainOnExit).mockImplementationOnce(async () => { replace() }); break
+ }
+ const result = await createAgentRetargeter(run.deps)({ agentId: 'a1', grid: phase === 'environment' ? null : grid })
+ expect(result).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ expect(run.deps.registry.setGridLaunch).not.toHaveBeenCalled()
+ expect(run.deps.announceSession).not.toHaveBeenCalled()
+ })
+
+ it('honors Stop cancellation while service preparation waits, even if the row is unchanged', async () => {
+ const restartJobs = new AgentRestartCoordinator()
+ const run = setup(agent(), { restartJobs })
+ vi.mocked(run.deps.relaunchOverrides).mockImplementationOnce(async () => {
+ restartJobs.cancel('a1')
+ return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } }
+ })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(restartAgent).not.toHaveBeenCalled()
+ expect(run.release).toHaveBeenCalledOnce()
+ })
+
+ it('releases terminal control if preparation throws', async () => {
+ const run = setup(agent(), { relaunchOverrides: vi.fn(async () => { throw Error('preparation failed') }) })
+ await expect(run.retarget({ agentId: 'a1', grid })).rejects.toThrow('preparation failed')
+ expect(run.release).toHaveBeenCalledOnce()
+ expect(run.releaseRoute).not.toHaveBeenCalled()
+ })
it('invalidates an older restore as soon as retarget takes control', async () => {
const { deps, retarget, release } = setup()
await retarget({ agentId: 'a1', grid })
@@ -135,7 +214,7 @@ describe('retargeting an agent', () => {
expect(await setup(agent(), { captureTerminal: vi.fn(async () => null) }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'TMUX_FAILED' })
vi.mocked(inspectRuntimePane).mockReturnValueOnce({ idle: false } as never)
expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
- expect(await setup(agent(), { restartJobs: { busy: () => true } as never }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
+ expect(await setup(agent(), { restartJobs: { busy: () => true, revision: () => 0 } as never }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
expect(await setup(agent(), { acquireTerminalControl: () => null }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
})
@@ -148,22 +227,121 @@ describe('retargeting an agent', () => {
})
describe('a move that goes ahead', () => {
+ it('keeps its route until a slow replacement is confirmed, even past the default hold timer', async () => {
+ vi.useFakeTimers()
+ const onDiscovered = vi.fn()
+ const reconciler = new TerminalAgentReconciler({ current: () => [], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => ({ processTableAvailable: true, ambiguousPlacements: new Set(),
+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: pane, rootPid: 1, cwd: '/work' }] } }],
+ agents: [{ engine: 'claude', cwd: '/work', processIdentity: { pid: 4, executable: 'claude', startMarker: 'replacement' },
+ args: 'claude', resumeSessionId: null, runtimes: [pane], primaryRuntimeKey: terminalRouteKey(pane) }],
+ }),
+ })
+ let finish!: () => void
+ vi.mocked(restartAgent).mockImplementationOnce(() => new Promise(done => { finish = () => done({ ok: false, detail: 'fixture complete' }) }))
+ const run = setup(agent(), { agentReconciler: reconciler })
+ const pending = run.retarget({ agentId: 'a1', grid })
+ try {
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ await vi.advanceTimersByTimeAsync(30_001)
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ finish()
+ await pending
+ await reconciler.trigger()
+ expect(onDiscovered).toHaveBeenCalledOnce()
+ } finally { finish?.(); await pending; vi.useRealTimers() }
+ })
+
+ it('cannot release a newer Stop route hold when an older retarget completes', async () => {
+ const onDiscovered = vi.fn()
+ const reconciler = new TerminalAgentReconciler({ current: () => [], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved: vi.fn(), onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => ({ processTableAvailable: true, ambiguousPlacements: new Set(),
+ targets: [{ instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: pane, rootPid: 1, cwd: '/work' }] } }],
+ agents: [{ engine: 'claude', cwd: '/work', processIdentity: { pid: 4, executable: 'claude', startMarker: 'replacement' },
+ args: 'claude', resumeSessionId: null, runtimes: [pane], primaryRuntimeKey: terminalRouteKey(pane) }],
+ }),
+ })
+ const restartJobs = new AgentRestartCoordinator()
+ const run = setup(agent(), { agentReconciler: reconciler, restartJobs })
+ let releaseStop!: () => void
+ vi.mocked(restartAgent).mockImplementationOnce(async () => {
+ restartJobs.cancel('a1')
+ releaseStop = reconciler.holdRoute(terminalRouteKey(pane))
+ return { ok: false, detail: 'cancelled' }
+ })
+ try {
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ await reconciler.trigger()
+ expect(onDiscovered).not.toHaveBeenCalled()
+ releaseStop()
+ await reconciler.trigger()
+ expect(onDiscovered).toHaveBeenCalledOnce()
+ } finally { releaseStop?.() }
+ })
+
+ it.each(['environment', 'permission', 'cancelled'] as const)('discloses an applied model change when later %s preparation fails', async phase => {
+ const row = agent({ engine: 'opencode', subscriptionModel: 'fixture/model' })
+ const run = setup(row, { relaunchOverrides: vi.fn(async () => ({ ok: true as const,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], sessionModel: 'fixture/model' } })) })
+ if (phase === 'environment') vi.mocked(run.deps.tmuxBackend!.clearEnv).mockResolvedValueOnce({ state: 'failed', dispatch: 'rejected', reason: 'fixture failure' })
+ if (phase === 'permission') vi.mocked(run.deps.downgradedPermission).mockRejectedValueOnce(Error('fixture failure'))
+ if (phase === 'cancelled') vi.mocked(applyOpencodeSessionModel).mockImplementationOnce(async () => {
+ row.sessionId = 'replacement'
+ return { ok: true }
+ })
+ await expect(run.retarget({ agentId: 'a1', grid: null })).resolves.toMatchObject({ ok: false,
+ detail: expect.stringContaining('native model change was applied') })
+ expect(restartAgent).not.toHaveBeenCalled()
+ expect(run.release).toHaveBeenCalledOnce()
+ })
+
+ it('retains uncertainty when Stop revokes a write whose reply was lost', async () => {
+ const row = agent({ engine: 'opencode' })
+ const run = setup(row, { relaunchOverrides: vi.fn(async () => ({ ok: true as const,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], sessionModel: 'fixture/model' } })) })
+ vi.mocked(applyOpencodeSessionModel).mockImplementationOnce(async () => {
+ row.sessionId = 'replacement'
+ return { ok: false, code: 'AGENT_CHANGED', effect: 'uncertain', detail: 'reply lost' }
+ })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED',
+ detail: expect.stringContaining('may already have applied') })
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it('reports a replacement that started before a later non-Error exception', async () => {
+ const run = setup()
+ vi.mocked(probeGatewayRuntime).mockRejectedValueOnce('fixture probe unavailable')
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'RETARGET_FAILED',
+ detail: 'The replacement process started, but retarget did not complete. fixture probe unavailable' })
+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ })
+
+ it('does not announce a row removed by a publication observer', async () => {
+ const run = setup()
+ vi.mocked(run.deps.registry.setActive).mockImplementationOnce(() => { vi.mocked(run.deps.registry.byAgent).mockReturnValue(undefined); return true })
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(run.deps.announceSession).not.toHaveBeenCalled()
+ })
+
it('onto a grid: the pane respawned, the new process adopted, the launch and the model it left kept', async () => {
const log = vi.mocked(console.log)
const run = setup()
expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
expect(run.deps.agentReconciler.holdRoute).toHaveBeenCalled()
- expect(restartAgent).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1' }, true, {})
+ expect(restartAgent).toHaveBeenCalledWith({ engine: 'claude', sessionId: 's1' }, true, { isCurrent: expect.any(Function) })
// The grid is read off the new process's command line, never its executable alone.
expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', expect.objectContaining({ pid: 2 }), 'none')
expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', { override: grid, webSearch: 'off' })
expect(run.deps.registry.setSubscriptionModel).toHaveBeenCalledWith('a1', 'opus')
expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', true)
expect(run.deps.refreshGridAssignment).toHaveBeenCalledWith(agent())
- expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4')
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%4', expect.any(Function))
expect(run.deps.announceSession).toHaveBeenCalled()
expect(run.release).toHaveBeenCalled()
- expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalled()
+ expect(run.releaseRoute).toHaveBeenCalled()
expect(log.mock.calls.map(([line]) => String(line))).toContain('claude on Home · retargeted a1 · resumed')
})
@@ -193,7 +371,7 @@ describe('retargeting an agent', () => {
vi.mocked(restartAgent).mockResolvedValueOnce({ ok: true, resumed: false, processIdentity: { pid: 2, startMarker: 'n' } } as never)
expect(await run.retarget({ agentId: 'a1', grid: null })).toEqual({ ok: true })
expect(vi.mocked(validateLaunchOverrides).mock.lastCall?.[2]).toEqual({ gridLaunch: null, codexHome: undefined, subscriptionModel: 'opus' })
- expect(run.deps.tmuxBackend!.clearEnv).toHaveBeenCalledWith(pane, ['ANTHROPIC_BASE_URL'])
+ expect(run.deps.tmuxBackend!.clearEnv).toHaveBeenCalledWith(pane, ['ANTHROPIC_BASE_URL'], expect.any(Function))
expect(run.deps.registry.setGridLaunch).toHaveBeenCalledWith('a1', null)
expect(run.deps.registry.setSubscriptionModel).not.toHaveBeenCalled()
expect(log.mock.calls.map(([line]) => String(line))).toContain('claude on its own login · retargeted a1 · fresh session')
@@ -211,7 +389,7 @@ describe('retargeting an agent', () => {
vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, detail: 'no process' } as never)
expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'RESPAWN_FAILED', detail: 'no process' })
expect(run.release).toHaveBeenCalledTimes(3)
- expect(run.deps.agentReconciler.releaseRoute).toHaveBeenCalledTimes(3)
+ expect(run.releaseRoute).toHaveBeenCalledTimes(3)
})
it('rewrites a resumed OpenCode session\'s model before the respawn, and refuses if it cannot', async () => {
@@ -219,7 +397,7 @@ describe('retargeting an agent', () => {
const withModel = { relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { sessionModel: 'grid/big', gridLaunchRecord: null } })) as never }
const run = setup(opencode, withModel)
await run.retarget({ agentId: 'a1', grid })
- expect(applyOpencodeSessionModel).toHaveBeenCalledWith({ opencodeMajor: 1, dbPath: '/db/opencode.db', sessionId: 's1', model: { providerID: 'grid', modelID: 'big' }, cwd: '/work', checkCatalog: false })
+ expect(applyOpencodeSessionModel).toHaveBeenCalledWith({ opencodeMajor: 1, dbPath: '/db/opencode.db', sessionId: 's1', model: { providerID: 'grid', modelID: 'big' }, cwd: '/work', checkCatalog: false }, { current: expect.any(Function) })
vi.mocked(applyOpencodeSessionModel).mockResolvedValueOnce({ ok: false, code: 'SESSION_NOT_FOUND', detail: 'no rows' } as never)
expect(await setup(agent({ engine: 'opencode', cwd: undefined } as Partial<RegisteredSession>), withModel).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'no rows' })
// v2 needs no sqlite3; a model the overrides do not name, or one that does not parse, writes nothing.
@@ -257,13 +435,22 @@ describe('retargeting an agent', () => {
} finally { clearTimeout(timer) }
})
- it('reads the live bypass flag only when the row recorded none, and announces nothing for a row gone meanwhile', async () => {
+ it('does not act on a row removed before retarget can establish ownership', async () => {
const run = setup()
vi.mocked(run.deps.registry.byAgent).mockReturnValue(undefined)
- await run.retarget({ agentId: 'a1', grid })
- expect(bypassPermissionFor).toHaveBeenCalled()
- expect(run.deps.liveBypassPermission).toHaveBeenCalled()
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(bypassPermissionFor).not.toHaveBeenCalled()
+ expect(run.deps.liveBypassPermission).not.toHaveBeenCalled()
expect(run.deps.announceSession).not.toHaveBeenCalled()
})
+
+ it('reports a confirmed native model change if the subsequent respawn fails', async () => {
+ const run = setup(agent({ engine: 'opencode' }), { relaunchOverrides: vi.fn(async () => ({ ok: true as const,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], sessionModel: 'fixture/model' } })) })
+ vi.mocked(restartAgent).mockResolvedValueOnce({ ok: false, detail: 'spawn failed' })
+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'RESPAWN_FAILED',
+ detail: expect.stringContaining('native model change was applied') })
+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ })
})
})
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 884d22649..5e56b5a2e 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -31,6 +31,7 @@ import type { TmuxBackend } from '../../lib/tmuxBackend.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
import type { PaneSwap } from './swap.js'
+import { createLaunchAuthority } from './launchAuthority.js'
type LaunchHelpers = ReturnType<typeof createLaunchHelpers>
@@ -48,7 +49,7 @@ export interface RetargetDeps {
acquireTerminalControl: (id: string, opts?: { forAnswer?: boolean }) => (() => void) | null
relaunchOverrides: LaunchHelpers['relaunchOverrides']
downgradedPermission: LaunchHelpers['downgradedPermission']
- agentReconciler: Pick<TerminalAgentReconciler, 'holdRoute' | 'releaseRoute'>
+ agentReconciler: Pick<TerminalAgentReconciler, 'holdRoute'>
restartJobs: PaneSwap['restartJobs']
paneSwapDeps: PaneSwap['paneSwapDeps']
liveBypassPermission: PaneSwap['liveBypassPermission']
@@ -63,11 +64,31 @@ export function createAgentRetargeter({
relaunchOverrides, downgradedPermission, agentReconciler, restartJobs, paneSwapDeps, liveBypassPermission,
announceSession, refreshGridAssignment, opencodeDb,
}: RetargetDeps) {
+ const authority = createLaunchAuthority({ byAgent: id => registry.byAgent(id),
+ revision: id => restartJobs.revision(id), cancelled: () => false })
const retargetAgent: RetargetAgent = async ({ agentId, grid }) => {
if (purgeBusy(agentId)) return { ok: false, error: 'AGENT_BUSY' }
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- const session = registry.resolve(agentId)
- if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ const live = registry.resolve(agentId)
+ if (!live) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ // Registry observations can update a row in place while a service or pane
+ // read waits. The request keeps its original conversation and exact process.
+ const session = structuredClone(live)
+ grid = grid && structuredClone(grid)
+ const captureAuthority = () => {
+ const owns = authority(session.agentId)
+ return () => !!registry.byAgent(session.agentId) && owns()
+ }
+ let current = captureAuthority()
+ let nativeEffect: 'none' | 'uncertain' | 'applied' = 'none'
+ let replacementStarted = false
+ const failed = (error: string, detail: string) => ({ ok: false as const, error, detail: [
+ nativeEffect === 'applied' ? 'The native model change was applied.'
+ : nativeEffect === 'uncertain' ? 'The native model change may already have applied.' : '',
+ replacementStarted ? 'The replacement process started, but retarget did not complete.' : '',
+ detail,
+ ].filter(Boolean).join(' ') })
+ const changed = () => failed('AGENT_CHANGED', 'The harness changed or stopped during retarget.')
const pane = session.runtimes.find((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')
// Only tmux panes can be respawned. Saying so is better than a generic failure the user cannot act on.
if (!pane) return { ok: false, error: 'RETARGET_UNSUPPORTED_BACKEND', detail: `${session.engine} is not running in a tmux pane` }
@@ -115,6 +136,7 @@ export function createAgentRetargeter({
...(grid ? {} : { subscriptionModel: remembered }),
}
const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)
+ if (!current()) return changed()
if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }
// A resumed opencode session takes its model from its own rows in opencode.db, not from `-m`
// (see below), and those rows are written through the `sqlite3` CLI. Without it the respawn
@@ -128,6 +150,7 @@ export function createAgentRetargeter({
&& (!!grid || !!remembered?.includes('/'))
const opencode = session.engine === 'opencode' ? opencodeLaunch : null
const opencodeMajor = opencode ? await opencode.opencodeMajorVersion() : null
+ if (!current()) return changed()
if (rewritesOpencodeSession && opencode && !opencode.isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {
return {
ok: false,
@@ -144,37 +167,40 @@ export function createAgentRetargeter({
// move them once they are done, rather than being asked to choose between losing a turn and losing
// the grid.
const capture = await captureTerminal(session.agentId, 100)
+ if (!current()) return changed()
if (!capture) return { ok: false, error: 'TMUX_FAILED' }
- if (!(await readScreen(session, capture))?.pane.idle) return { ok: false, error: 'AGENT_BUSY' }
+ const screen = await readScreen(session, capture)
+ if (!current()) return changed()
+ if (!screen?.pane.idle) return { ok: false, error: 'AGENT_BUSY' }
// Nothing may type into the pane while it is being replaced.
if (purgeBusy(session.agentId) || restartJobs.busy(session.agentId)) return { ok: false, error: 'AGENT_BUSY' }
const release = acquireTerminalControl(session.agentId)
if (!release) return { ok: false, error: 'AGENT_BUSY' }
// The old restore watcher stays cancelled after this control pin is released.
restartJobs.cancel(session.agentId)
- // The grid's env and argv, config directory written (keyed on the agent, so moving it between
- // grids rewrites one directory) — or nothing at all for a move back to the engine's own login
- // (clearing uses set-environment, which every supported tmux has). Built from the override the
- // desktop just sent, never from the row: the row is what this call REPLACES. After the refusal
- // guards, so a refused move leaves the live process's own configuration untouched.
- const built = await relaunchOverrides(session, target)
- if (!built.ok) {
- release()
- return { ok: false, error: built.error, detail: built.detail }
- }
-
- // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.
- //
- // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an existing
- // record to an observation by pid + start marker (`currentProcessKey`), and its same-pane fallback
- // only applies to an agent with no bound engine session. A respawn changes the pid, so left to
- // discovery the new process is an unmatched observation — `onDiscovered` mints a NEW agent id, and
- // the record the user was looking at becomes a ghost that the app still lists, still counts as "on
- // an older target", and still offers to move. Moving it respawns the same pane again. Holding the
- // route shuts the reconciler out for the duration; rebinding below is what ends the swap.
+ current = captureAuthority()
const routeKey = terminalRouteKey(pane)
- agentReconciler.holdRoute(routeKey)
+ let releaseRoute: (() => void) | undefined
try {
+ // The grid's env and argv, config directory written (keyed on the agent, so moving it between
+ // grids rewrites one directory) — or nothing at all for a move back to the engine's own login
+ // (clearing uses set-environment, which every supported tmux has). Built from the override the
+ // desktop just sent, never from the row: the row is what this call REPLACES. After the refusal
+ // guards, so a refused move leaves the live process's own configuration untouched.
+ const built = await relaunchOverrides(session, target, current)
+ if (!current()) return changed()
+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+
+ // ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.
+ //
+ // Identity in this daemon is keyed on the PROCESS, not the pane: the reconciler matches an existing
+ // record to an observation by pid + start marker (`currentProcessKey`), and its same-pane fallback
+ // only applies to an agent with no bound engine session. A respawn changes the pid, so left to
+ // discovery the new process is an unmatched observation — `onDiscovered` mints a NEW agent id, and
+ // the record the user was looking at becomes a ghost that the app still lists, still counts as "on
+ // an older target", and still offers to move. Moving it respawns the same pane again. Holding the
+ // route shuts the reconciler out for the duration; rebinding below is what ends the swap.
+ releaseRoute = agentReconciler.holdRoute(routeKey, null)
// Back to the engine's own login. Nothing is built, because there is no launch to build. If this
// agent was launched onto a grid at creation, `new-session -e` wrote the grid's variables into
// the pane's SESSION environment, which a bare respawn-pane would inherit — clearing them first
@@ -205,12 +231,15 @@ export function createAgentRetargeter({
if (rewritesOpencodeSession && opencode) {
const model = built.overrides.sessionModel ? opencode.parseOpencodeModelId(built.overrides.sessionModel) : null
if (model) {
+ nativeEffect = 'uncertain'
const written = await opencode.applyOpencodeSessionModel({
opencodeMajor, dbPath: opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,
// (A model of opencode's own is looked for in its catalogue; a grid's provider lives in
// the pane's own config, which the service never reads.)
checkCatalog: !grid,
- })
+ }, { current })
+ nativeEffect = written.ok ? 'applied' : (written.effect ?? 'none')
+ if (!current()) return changed()
if (!written.ok) {
console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)
return { ok: false, error: written.code, detail: written.detail }
@@ -218,24 +247,32 @@ export function createAgentRetargeter({
}
}
if (!grid) {
- const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine))
+ const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine), current)
+ if (!current()) return changed()
if (cleared.state !== 'succeeded') {
- return { ok: false, error: 'GRID_CLEAR_FAILED', detail: 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment' }
+ return failed('GRID_CLEAR_FAILED', 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment')
}
}
- const retargetPermission = await downgradedPermission(session,
- await bypassPermissionFor(session, () => liveBypassPermission(session)), 'retarget')
+ const bypassPermission = await bypassPermissionFor(session, () => liveBypassPermission(session))
+ if (!current()) return changed()
+ const retargetPermission = await downgradedPermission(session, bypassPermission, 'retarget')
+ if (!current()) return changed()
const outcome = await restartAgent(
{ engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },
retargetPermission.bypassPermission === true,
- paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null),
+ { ...paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null, current), isCurrent: current },
)
+ replacementStarted = outcome.ok
+ if (!current()) return changed()
if (!outcome.ok) {
console.warn(`[grid] retarget ${sid(session.agentId)} failed · ${outcome.detail}`)
- return { ok: false, error: 'RESPAWN_FAILED', detail: outcome.detail }
+ return failed('RESPAWN_FAILED', outcome.detail)
}
// Commit the new process now. Optional grid metadata follows outside the route hold.
const gateway = await probeGatewayRuntime(outcome.processIdentity)
+ if (!current()) return changed()
+ await clearPaneRemainOnExit(pane.paneId, current)
+ if (!current()) return changed()
registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind)
// The launch that just worked is the one a restart or a post-reboot restore must repeat — and
// what it decided about web search is what the app shows for this agent from now on. Null for
@@ -246,7 +283,6 @@ export function createAgentRetargeter({
// agent left on a grid for a week still knows where it came from.
if (grid && remembered) registry.setSubscriptionModel(session.agentId, remembered)
registry.setActive(session.agentId, true)
- await clearPaneRemainOnExit(pane.paneId)
const refreshed = registry.byAgent(session.agentId)
// The app decides whether to still offer a move from what it is told here, so a silent success
// would leave the banner up over an agent that had already been moved.
@@ -261,9 +297,12 @@ export function createAgentRetargeter({
// on its model through the `/models` picker here (MODEL_SELECT_FAILED); its store is rewritten
// before the respawn instead, see above.
return { ok: true }
+ } catch (error) {
+ if (nativeEffect !== 'none' || replacementStarted) return failed('RETARGET_FAILED', error instanceof Error ? error.message : String(error))
+ throw error
} finally {
release()
- agentReconciler.releaseRoute(routeKey)
+ releaseRoute?.()
}
}
return retargetAgent
diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index ff6c0817d..fe3d36258 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -38,6 +38,7 @@ function setup(row: RegisteredSession | null = session()) {
describe('the pane-process swap', () => {
beforeEach(() => {
+ vi.mocked(terminateDeletedAgent).mockClear()
vi.mocked(resolvePaneEngineProcess).mockReset().mockResolvedValue(null)
vi.mocked(buildEngineLaunchArgv).mockClear()
})
@@ -51,6 +52,19 @@ describe('the pane-process swap', () => {
expect(swap.restartJobs.revision('a1')).toBe(boot)
})
+ it('passes revocable ownership into the final signal and tmux dispatch boundaries', async () => {
+ const { swap, tmuxBackend } = setup()
+ const current = () => false
+ const prepared = swap.paneSwapDeps(session(), runtime, {}, null, current)
+ expect(prepared.isCurrent?.()).toBe(false)
+ await prepared.holdOpen()
+ expect(tmuxBackend.holdOpen).toHaveBeenCalledWith(runtime, current)
+ await prepared.terminate()
+ expect(vi.mocked(terminateDeletedAgent).mock.lastCall?.[1].current).toBe(current)
+ await prepared.respawn(['fixture-engine'])
+ expect(tmuxBackend.respawn).toHaveBeenCalledWith(runtime, expect.objectContaining({ current }))
+ })
+
it('restarts only the agent it was asked about: same registration, same pane, same engine', () => {
expect(setup().swap.sameRestartTarget(session())).toBe(true)
expect(setup(null).swap.sameRestartTarget(session())).toBe(false)
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index b2980c99b..fff191ddf 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -52,13 +52,15 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
/** The mode this swap may actually ask for — the row's own, unless the engine on disk has since
* stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */
permissionMode: string | null = session.permissionMode ?? null,
+ current?: () => boolean,
): RestartAgentDeps => ({
+ ...(current ? { isCurrent: current } : {}),
prepareResume: () => prepareSessionResume(session),
// The row as the swap found it: the conversation a fallback to a fresh start leaves behind.
keepAbandoned: () => keepAbandonedConversation(session),
respawnRefusal: () => tmuxBackend!.respawnRefusal(launch.env ? { env: launch.env } : {}),
holdOpen: async () => {
- const result = await tmuxBackend!.holdOpen(runtime)
+ const result = await tmuxBackend!.holdOpen(runtime, current)
return result.state === 'succeeded'
? { ok: true }
: { ok: false, reason: 'reason' in result ? result.reason : 'could not re-arm remain-on-exit' }
@@ -68,10 +70,12 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
kill: (pid, signal) => process.kill(pid, signal),
sleep: (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() }),
log: (message) => console.log(message),
+ ...(current ? { current } : {}),
}, checkAfterMs),
respawn: async (argv) => {
const result = await tmuxBackend!.respawn(runtime, {
command: argv,
+ ...(current ? { current } : {}),
cwd: homedir(),
...(launch.env ? { env: launch.env } : {}),
})
diff --git a/cli/src/engines/__fixtures__/native-mutation.golden.json b/cli/src/engines/__fixtures__/native-mutation.golden.json
new file mode 100644
index 000000000..e4ac12241
--- /dev/null
+++ b/cli/src/engines/__fixtures__/native-mutation.golden.json
@@ -0,0 +1,286 @@
+{
+ "linux:catalog=false:variant=false": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "linux:catalog=false:variant=true": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\",\"variant\":\"high\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "linux:catalog=true:variant=false": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "model.list"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "linux:catalog=true:variant=true": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "model.list"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\",\"variant\":\"high\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "darwin:catalog=false:variant=false": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "darwin:catalog=false:variant=true": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\",\"variant\":\"high\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "darwin:catalog=true:variant=false": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "model.list"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ },
+ "darwin:catalog=true:variant=true": {
+ "result": {
+ "ok": true
+ },
+ "calls": [
+ {
+ "args": [
+ "api",
+ "model.list"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.switchModel",
+ "--param",
+ "sessionID=ses_fixture",
+ "-d",
+ "{\"model\":{\"id\":\"model\",\"providerID\":\"fixture\",\"variant\":\"high\"}}"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ },
+ {
+ "args": [
+ "api",
+ "session.get",
+ "--param",
+ "sessionID=ses_fixture"
+ ],
+ "options": {
+ "cwd": "/fixture/work"
+ }
+ }
+ ]
+ }
+}
diff --git a/cli/src/engines/kit/nativeMutationDispatch.spec.ts b/cli/src/engines/kit/nativeMutationDispatch.spec.ts
new file mode 100644
index 000000000..0afc58332
--- /dev/null
+++ b/cli/src/engines/kit/nativeMutationDispatch.spec.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createSessionModelControl } from './nativeSessionModel.js'
+import { OPENCODE_SESSION_MODEL } from '../opencode/contract.js'
+
+const exec = vi.hoisted(() => vi.fn())
+vi.mock('node:child_process', () => ({ execFile: exec }))
+afterEach(() => vi.clearAllMocks())
+const model = { providerID: 'fixture', modelID: 'model' }
+
+describe('native mutation process dispatch', () => {
+ it.each([null, 1])('does not bypass an unresolved API write when a later version probe says %s', async major => {
+ const control = createSessionModelControl(OPENCODE_SESSION_MODEL, () => '/fixture/bin/opencode')
+ const run = vi.fn(async () => { throw Error('native service unavailable after write') })
+ const input = { dbPath: '/fixture/opencode.db', sessionId: 'ses_fixture', model }
+ expect(await control.applySessionModel({ ...input, major: 2 }, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ // An assertion, rather than an executable, records any attempted SQL fallback.
+ exec.mockImplementation((_file, _args, _options, done) => { queueMicrotask(() => done(null, '5000\n1\n1\n', '')); return {} })
+ const fallback = control.applySessionModel({ ...input, major }, { run, retryDelayMs: 0 }).catch(error => ({ error }))
+ const result = await fallback
+ expect(exec).not.toHaveBeenCalled()
+ expect(result).toMatchObject({ ok: false, effect: 'uncertain' })
+ expect(run.mock.calls).toHaveLength(3)
+ })
+
+ it('does not dispatch after ownership is revoked during asynchronous binary resolution', async () => {
+ let release!: (binary: string) => void, current = true
+ const binary = vi.fn(() => new Promise<string>(done => { release = done }))
+ const control = createSessionModelControl(OPENCODE_SESSION_MODEL, binary)
+ const pending = control.switchSessionModel('ses_fixture', model, { current: () => current })
+ await vi.waitFor(() => expect(binary).toHaveBeenCalledOnce())
+ current = false
+ release('/fixture/bin/opencode')
+ expect(await pending).toMatchObject({ ok: false, code: 'AGENT_CHANGED' })
+ expect(exec).not.toHaveBeenCalled()
+ })
+
+ it('keeps one executable through uncertain-write retries, bounds children and closes stdin', async () => {
+ const end = vi.fn(), binary = vi.fn(async () => '/fixture/bin/opencode')
+ let unavailable = true
+ exec.mockImplementation((_file, args: string[], _options, done) => {
+ queueMicrotask(() => {
+ if (unavailable) done(Error('reply lost'), '', 'fixture transport unavailable')
+ else done(null, JSON.stringify({ data: { id: 'ses_fixture', model: { providerID: 'fixture', id: 'model' } } }), '')
+ })
+ return { stdin: { end } }
+ })
+ const control = createSessionModelControl(OPENCODE_SESSION_MODEL, binary)
+ expect(await control.switchSessionModel('ses_fixture', model, { retryDelayMs: 0 }))
+ .toMatchObject({ ok: false, effect: 'uncertain', detail: expect.stringContaining('fixture transport unavailable') })
+ binary.mockResolvedValue('/fixture/replaced/opencode')
+ unavailable = false
+ expect(await control.switchSessionModel('ses_fixture', model, { retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(binary).toHaveBeenCalledOnce()
+ expect(exec.mock.calls.map(call => call[0])).toEqual(Array(4).fill('/fixture/bin/opencode'))
+ expect(exec.mock.calls.map(call => call[1][1])).toEqual(['session.switchModel', 'session.get', 'session.get', 'session.get'])
+ for (const [, , options] of exec.mock.calls) expect(options).toMatchObject({ timeout: 15_000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 })
+ expect(end).toHaveBeenCalledTimes(4)
+ })
+})
diff --git a/cli/src/engines/kit/nativeSessionModel.ts b/cli/src/engines/kit/nativeSessionModel.ts
index 134e3d763..d045834c6 100644
--- a/cli/src/engines/kit/nativeSessionModel.ts
+++ b/cli/src/engines/kit/nativeSessionModel.ts
@@ -5,8 +5,9 @@ import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
export interface NativeSessionModel { providerID: string; modelID: string }
-export type NativeModelResult = { ok: true } | { ok: false; code: string; detail: string }
+export type NativeModelResult = { ok: true } | { ok: false; code: string; detail: string; effect?: 'uncertain' }
export type NativeApiRun = (args: string[], options: { cwd?: string }) => Promise<{ stdout: string }>
+export interface NativeModelAuthority { current?: () => boolean }
export interface NativeModelRule {
label: string; serviceMajor: number; id: RegExp; modelFlags: readonly string[]; modelEquals: string; variantSeparator: string
errors: { sqliteMissing: string; sessionMissing: string; writeFailed: string; binaryMissing: string; switchFailed: string; unknownModel: string }
@@ -16,9 +17,19 @@ export interface NativeModelRule {
fields: { data: string; model: string; id: string; alternativeId: string; provider: string; variant: string } }
}
const execFileAsync = promisify(execFile)
+class NativeDispatchCancelled extends Error {}
-export function createSessionModelControl(rule: NativeModelRule, binary: () => string) {
+export function createSessionModelControl(rule: NativeModelRule, binary: () => string | Promise<string>) {
const ID_RE = rule.id
+ const changed = (dispatched = false): NativeModelResult => ({ ok: false, code: 'AGENT_CHANGED',
+ detail: `The harness changed or stopped during native model preparation.${dispatched ? ' The native model change may already have applied.' : ''}`,
+ ...(dispatched ? { effect: 'uncertain' as const } : {}) })
+ // An uncertain write cannot be forgotten just because its request returned. Keep
+ // one receipt per conversation until a later read confirms it. At capacity, hold
+ // new work instead of evicting a receipt and making a blind retry possible.
+ type Pending = { model: NativeSessionModel; cwd?: string; store?: string; busy: boolean; dispatched: boolean; executable?: Promise<string> }
+ const pending = new Map<string, Pending>()
+ const capacity = 256
/** A SQL string literal — the only way a value reaches the statement. */
function lit(value: string): string {
return `'${value.replace(/'/g, "''")}'`
@@ -57,7 +68,11 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
dbPath: string,
sessionId: string,
model: NativeSessionModel,
+ authority: NativeModelAuthority = {},
): Promise<NativeModelResult> {
+ if (authority.current?.() === false) return changed()
+ if (pending.has(sessionId)) return { ok: false, code: rule.errors.switchFailed, effect: 'uncertain',
+ detail: 'Waiting to confirm the earlier native API model change. A changed or unavailable version cannot authorize a SQLite fallback.' }
if (!ID_RE.test(sessionId)) {
return { ok: false, code: rule.errors.sessionMissing, detail: `not an ${rule.label} session id: ${sessionId}` }
}
@@ -103,12 +118,20 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
return { ok: true }
}
- const runNative: NativeApiRun = async (args, options) => {
- // Bounded like the sqlite3 write: the service answers in well under a second (77ms measured).
- const { stdout } = await execFileAsync(binary(), args, {
- ...(options.cwd ? { cwd: options.cwd } : {}), timeout: rule.api.timeoutMs, killSignal: 'SIGKILL',
- })
- return { stdout }
+ const nativeRun = (authority: NativeModelAuthority, selection: { executable?: Promise<string> }): NativeApiRun => {
+ // Resolve once for this operation, before its first native command. Resolving
+ // through a login shell can yield; cancellation must be checked afterwards.
+ return async (args, options) => {
+ selection.executable ??= Promise.resolve().then(binary)
+ const executable = await selection.executable
+ if (authority.current?.() === false) throw new NativeDispatchCancelled('Native model operation was cancelled before dispatch')
+ return new Promise((done, failed) => {
+ const child = execFile(executable, args, { ...(options.cwd ? { cwd: options.cwd } : {}),
+ timeout: rule.api.timeoutMs, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024, encoding: 'utf8',
+ }, (error, stdout, stderr) => { if (error) failed(Object.assign(error, { stdout, stderr })); else done({ stdout }) })
+ child.stdin?.end()
+ })
+ }
}
/** What a failed `opencode api` call said: the body is on stdout, the HTTP status on stderr. */
@@ -129,31 +152,77 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
* Measured on 2.0.18 that the service stores any id (`opencode/does-not-exist` reads back as set),
* so with `checkCatalog` the model is looked for in `model.list` first — for a model of opencode's
* own; a grid's provider is declared in its pane's own config, which the service never reads. A
- * switch that did not land is tried once more, after `retryDelayMs`; one that cannot (no such
- * session, no opencode, an unknown model) is not.
+ * lost reply does not prove the switch was not applied. Reconciliation retries
+ * only the read: another write could overwrite a later choice made in the TUI.
*/
async function switchSessionModel(
sessionId: string,
model: NativeSessionModel,
- options: { cwd?: string; run?: NativeApiRun; checkCatalog?: boolean; retryDelayMs?: number } = {},
+ options: { cwd?: string; store?: string; run?: NativeApiRun; checkCatalog?: boolean; retryDelayMs?: number } & NativeModelAuthority = {},
): Promise<NativeModelResult> {
+ options = { ...options }
+ const current = () => options.current?.() !== false
+ if (!current()) return changed()
if (!ID_RE.test(sessionId)) {
return { ok: false, code: rule.errors.sessionMissing, detail: `not an ${rule.label} session id: ${sessionId}` }
}
- const run = options.run ?? runNative
- if (options.checkCatalog) {
- const known = await listsModel(run, model, options.cwd)
- if (known === false) {
- return { ok: false, code: rule.errors.unknownModel, detail: `${rule.label} has no ${model.providerID}/${model.modelID} — \`${rule.label} models\` lists the ones it has` }
- }
+ const requested = { ...model }
+ const previous = pending.get(sessionId)
+ const held = (detail: string): NativeModelResult => ({ ok: false, code: rule.errors.switchFailed, detail,
+ ...(previous?.dispatched ? { effect: 'uncertain' as const } : {}) })
+ if (previous?.busy) return held('Waiting for the native model operation already running for this conversation. No additional change was sent.')
+ if (previous && (previous.cwd !== options.cwd || previous.store !== options.store)) {
+ return held('Waiting to confirm the earlier native model change in its original store and folder. No additional change was sent.')
}
- let result = await switchOnce(run, sessionId, model, options.cwd)
- if (!result.ok && result.code === rule.errors.switchFailed) {
- console.warn(`[${rule.label}] switch to ${model.providerID}/${model.modelID} did not land (${result.detail}) · trying once more`)
- await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? rule.api.retryDelayMs))
- result = await switchOnce(run, sessionId, model, options.cwd)
+ if (!previous && pending.size >= capacity) return held('Waiting for outstanding native model changes to be confirmed. No model change was sent.')
+ const receipt: Pending = previous ?? { model: requested, cwd: options.cwd, store: options.store, busy: false, dispatched: false }
+ receipt.busy = true
+ pending.set(sessionId, receipt)
+ const run = options.run ?? nativeRun(options, receipt)
+ let confirmed = false
+ try {
+ if (!previous) {
+ if (options.checkCatalog) {
+ const known = await listsModel(run, requested, receipt.cwd)
+ if (!current()) return changed()
+ if (known === null) return held(`Waiting for ${rule.label}'s model catalog before changing the session. No model change was sent.`)
+ if (!known) return { ok: false, code: rule.errors.unknownModel, detail: `${rule.label} has no ${requested.providerID}/${requested.modelID} — \`${rule.label} models\` lists the ones it has` }
+ }
+ const param = `${rule.api.sessionParam}=${sessionId}`
+ const { id, variant } = splitVariant(requested.modelID)
+ const fields = rule.api.fields
+ const body = JSON.stringify({ [fields.model]: { [fields.id]: id, [fields.provider]: requested.providerID, ...(variant ? { [fields.variant]: variant } : {}) } })
+ receipt.dispatched = true
+ try {
+ await run([...rule.api.switch, rule.api.paramFlag, param, rule.api.bodyFlag, body], { cwd: receipt.cwd })
+ } catch (err) {
+ if (err instanceof NativeDispatchCancelled) { receipt.dispatched = false; return changed() }
+ const failure = apiFailure(err)
+ if (failure.missing || rule.api.missingSession.test(failure.text)) {
+ receipt.dispatched = false
+ return { ok: false, code: failure.missing ? rule.errors.binaryMissing : rule.errors.sessionMissing, detail: failure.text }
+ }
+ // Transport failure does not prove that the write failed. Only read next.
+ }
+ }
+ if (!current()) return changed(receipt.dispatched)
+ let result = await confirmModel(run, sessionId, receipt.model, receipt.cwd)
+ if (!current()) return changed(receipt.dispatched)
+ if (!result.ok) {
+ await new Promise((resolve) => setTimeout(resolve, options.retryDelayMs ?? rule.api.retryDelayMs))
+ if (!current()) return changed(receipt.dispatched)
+ result = await confirmModel(run, sessionId, receipt.model, receipt.cwd)
+ }
+ if (!current()) return changed(receipt.dispatched)
+ confirmed = result.ok
+ if (confirmed && (requested.modelID !== receipt.model.modelID || requested.providerID !== receipt.model.providerID)) {
+ return held('The earlier native model change is now confirmed. Retry the new choice to start a separate change; no additional change was sent.')
+ }
+ return result.ok ? result : { ...result, effect: 'uncertain' }
+ } finally {
+ receipt.busy = false
+ if (!receipt.dispatched || confirmed) pending.delete(sessionId)
}
- return result
}
/**
@@ -173,6 +242,8 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
const fields = rule.api.fields
const rows = (Array.isArray(parsed) ? parsed : parsed[fields.data]) as Array<Record<string, unknown>> | undefined
if (!Array.isArray(rows)) return null
+ if (rows.some(row => !row || typeof row !== 'object' || typeof row[fields.provider] !== 'string'
+ || typeof (row[fields.id] ?? row[fields.alternativeId]) !== 'string')) return null
const { id } = splitVariant(model.modelID)
return rows.some((m) => m[fields.provider] === model.providerID && (m[fields.id] === id || m[fields.alternativeId] === id))
} catch {
@@ -180,32 +251,28 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
}
}
- /** One switch through the service, read back. */
- async function switchOnce(run: NativeApiRun, sessionId: string, model: NativeSessionModel, cwd?: string): Promise<NativeModelResult> {
+ /** Confirmation never repeats a mutation, including after an uncertain reply. */
+ async function confirmModel(run: NativeApiRun, sessionId: string, model: NativeSessionModel, cwd?: string): Promise<NativeModelResult> {
const options = { cwd }
const param = `${rule.api.sessionParam}=${sessionId}`
const { id, variant } = splitVariant(model.modelID)
const fields = rule.api.fields
- const body = JSON.stringify({ [fields.model]: { [fields.id]: id, [fields.provider]: model.providerID, ...(variant ? { [fields.variant]: variant } : {}) } })
- try {
- await run([...rule.api.switch, rule.api.paramFlag, param, rule.api.bodyFlag, body], { cwd: options.cwd })
- } catch (err) {
- const failure = apiFailure(err)
- if (failure.missing) return { ok: false, code: rule.errors.binaryMissing, detail: `${rule.label} not found: ${failure.text}` }
- const code = rule.api.missingSession.test(failure.text) ? rule.errors.sessionMissing : rule.errors.switchFailed
- return { ok: false, code, detail: failure.text }
- }
// Read back: the service answers 204 for any model, known or not, so only the session itself can
// say the switch landed.
let stdout: string
try {
({ stdout } = await run([...rule.api.get, rule.api.paramFlag, param], { cwd: options.cwd }))
} catch (err) {
- return { ok: false, code: rule.errors.switchFailed, detail: `could not read the session back · ${apiFailure(err).text}` }
+ return { ok: false, code: rule.errors.switchFailed, detail: `Waiting to confirm the native model change; it may already have applied. ${apiFailure(err).text}` }
}
let now: Record<string, unknown> | undefined
try {
- now = (JSON.parse(stdout) as Record<string, Record<string, Record<string, unknown>>>)[fields.data]?.[fields.model]
+ const data = (JSON.parse(stdout) as Record<string, Record<string, unknown>>)[fields.data]
+ if (!data || typeof data !== 'object' || Array.isArray(data) || data[fields.id] !== sessionId) {
+ return { ok: false, code: rule.errors.switchFailed, detail: `Waiting for confirmation of session ${sessionId}; the native response did not identify that conversation.` }
+ }
+ const model = data[fields.model]
+ now = model && typeof model === 'object' && !Array.isArray(model) ? model as Record<string, unknown> : undefined
} catch {
now = undefined
}
@@ -229,12 +296,13 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
*/
async function applySessionModel(
input: { major: number | null | undefined; dbPath: string; sessionId: string; model: NativeSessionModel; cwd?: string; checkCatalog?: boolean },
- deps: { run?: NativeApiRun; retryDelayMs?: number } = {},
+ deps: { run?: NativeApiRun; retryDelayMs?: number } & NativeModelAuthority = {},
): Promise<NativeModelResult> {
+ if (deps.current?.() === false) return changed()
if ((input.major ?? 0) >= rule.serviceMajor) {
- return switchSessionModel(input.sessionId, input.model, { cwd: input.cwd, run: deps.run, checkCatalog: input.checkCatalog, retryDelayMs: deps.retryDelayMs })
+ return switchSessionModel(input.sessionId, input.model, { cwd: input.cwd, store: input.dbPath, run: deps.run, checkCatalog: input.checkCatalog, retryDelayMs: deps.retryDelayMs, current: deps.current })
}
- const written = await setSessionModel(input.dbPath, input.sessionId, input.model)
+ const written = await setSessionModel(input.dbPath, input.sessionId, input.model, deps)
return !written.ok && written.code === rule.errors.sessionMissing ? { ok: true } : written
}
diff --git a/cli/src/engines/launchControl.eager.spec.ts b/cli/src/engines/launchControl.eager.spec.ts
index f27483e18..47ac71ac6 100644
--- a/cli/src/engines/launchControl.eager.spec.ts
+++ b/cli/src/engines/launchControl.eager.spec.ts
@@ -1,7 +1,10 @@
import { expect, it, vi } from 'vitest'
-import { opencodeBin } from '../lib/engineBin.js'
+import { opencodeBin, opencodeBinAsync } from '../lib/engineBin.js'
-vi.mock('../lib/engineBin.js', () => ({ opencodeBin: vi.fn(() => { throw new Error('a native command was resolved during import') }) }))
+vi.mock('../lib/engineBin.js', () => ({
+ opencodeBin: vi.fn(() => { throw new Error('a native command was resolved during import') }),
+ opencodeBinAsync: vi.fn(() => { throw new Error('a native command was resolved during import') }),
+}))
vi.mock('./inProcess.js', () => ({ loadEngine: vi.fn(() => { throw new Error('optional code was loaded during import') }) }))
it('imports native control without probing an executable, reading a store or loading interpretation', async () => {
@@ -9,5 +12,6 @@ it('imports native control without probing an executable, reading a store or loa
expect(control.parseOpencodeMajor('opencode v2.0.18')).toBe(2)
expect(control.parseOpencodeModelId('fixture/model')).toEqual({ providerID: 'fixture', modelID: 'model' })
expect(opencodeBin).not.toHaveBeenCalled()
+ expect(opencodeBinAsync).not.toHaveBeenCalled()
expect((await import('./inProcess.js')).loadEngine).not.toHaveBeenCalled()
})
diff --git a/cli/src/engines/launchControl.ts b/cli/src/engines/launchControl.ts
index 0a87b33c4..235566222 100644
--- a/cli/src/engines/launchControl.ts
+++ b/cli/src/engines/launchControl.ts
@@ -1,8 +1,8 @@
/** Eager native launch control. Importing it neither probes a binary nor reads or writes a store. */
-import { opencodeBin, opencodeBinAsync } from '../lib/engineBin.js'
+import { opencodeBinAsync } from '../lib/engineBin.js'
import { OPENCODE_SESSION_MODEL, OPENCODE_VERSION } from './opencode/contract.js'
import { majorVersion, nativeVersionProbe, parseMajor, type VersionProbe } from './kit/nativeVersion.js'
-import { createSessionModelControl, type NativeApiRun, type NativeModelResult, type NativeSessionModel } from './kit/nativeSessionModel.js'
+import { createSessionModelControl, type NativeApiRun, type NativeModelResult, type NativeSessionModel, type NativeModelAuthority } from './kit/nativeSessionModel.js'
export { isOpencodeV2 } from './opencode/contract.js'
export type OpencodeVersionProbe = VersionProbe
@@ -19,12 +19,12 @@ export async function opencodeMajorVersion(probe?: VersionProbe, memo = versionM
export type OpencodeSessionModel = NativeSessionModel
export type SetOpencodeSessionModelResult = NativeModelResult
export type OpencodeApiRun = NativeApiRun
-const model = createSessionModelControl(OPENCODE_SESSION_MODEL, opencodeBin)
+const model = createSessionModelControl(OPENCODE_SESSION_MODEL, opencodeBinAsync)
export const opencodeModelFromArgv = model.modelFromArgv
export const parseOpencodeModelId = model.parseModelId
export const setOpencodeSessionModel = model.setSessionModel
export const switchOpencodeSessionModel = model.switchSessionModel
export function applyOpencodeSessionModel(
input: { opencodeMajor: number | null | undefined; dbPath: string; sessionId: string; model: NativeSessionModel; cwd?: string; checkCatalog?: boolean },
- deps: { run?: NativeApiRun; retryDelayMs?: number } = {},
+ deps: { run?: NativeApiRun; retryDelayMs?: number } & NativeModelAuthority = {},
): Promise<NativeModelResult> { return model.applySessionModel({ ...input, major: input.opencodeMajor }, deps) }
diff --git a/cli/src/engines/nativeHooks.eager.spec.ts b/cli/src/engines/nativeHooks.eager.spec.ts
index 541f90368..e8746d939 100644
--- a/cli/src/engines/nativeHooks.eager.spec.ts
+++ b/cli/src/engines/nativeHooks.eager.spec.ts
@@ -1,6 +1,6 @@
import { expect, it, vi } from 'vitest'
import { mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
-import { opencodeBin } from '../lib/engineBin.js'
+import { opencodeBin, opencodeBinAsync } from '../lib/engineBin.js'
import { loadEngine } from './inProcess.js'
vi.mock('node:fs', async real => ({ ...await real<object>(),
@@ -9,11 +9,14 @@ vi.mock('node:fs', async real => ({ ...await real<object>(),
unlinkSync: vi.fn(() => { throw new Error('file removed while importing native hooks') }),
writeFileSync: vi.fn(() => { throw new Error('file written while importing native hooks') }),
}))
-vi.mock('../lib/engineBin.js', () => ({ opencodeBin: vi.fn(() => { throw new Error('native executable resolved during import') }) }))
+vi.mock('../lib/engineBin.js', () => ({
+ opencodeBin: vi.fn(() => { throw new Error('native executable resolved during import') }),
+ opencodeBinAsync: vi.fn(() => { throw new Error('native executable resolved during import') }),
+}))
vi.mock('./inProcess.js', () => ({ loadEngine: vi.fn(() => { throw new Error('optional code requested during import') }) }))
it('composes hook declarations without probing, installing or requesting optional code', async () => {
const hooks = await import('./nativeHooks.js')
expect(Object.keys(hooks)).toHaveLength(11)
- for (const operation of [opencodeBin, loadEngine, mkdirSync, renameSync, unlinkSync, writeFileSync]) expect(operation).not.toHaveBeenCalled()
+ for (const operation of [opencodeBin, opencodeBinAsync, loadEngine, mkdirSync, renameSync, unlinkSync, writeFileSync]) expect(operation).not.toHaveBeenCalled()
})
diff --git a/cli/src/engines/nativeMutation.golden.spec.ts b/cli/src/engines/nativeMutation.golden.spec.ts
new file mode 100644
index 000000000..feb57e9c6
--- /dev/null
+++ b/cli/src/engines/nativeMutation.golden.spec.ts
@@ -0,0 +1,58 @@
+/** Healthy native model protocol, recorded from main before changing mutation recovery. */
+import { mkdirSync, mkdtempSync, readFileSync, 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'
+
+vi.mock('node:child_process', async original => ({
+ ...await original<object>(),
+ execFile: () => { throw Error('Host executables are forbidden in this golden') },
+ execFileSync: () => { throw Error('Host executables are forbidden in this golden') },
+ spawn: () => { throw Error('Host executables are forbidden in this golden') },
+}))
+
+const artifact = fileURLToPath(new URL('./__fixtures__/native-mutation.golden.json', import.meta.url))
+const record = process.env.RECORD_NATIVE_MUTATION_GOLDEN === '1'
+const observations: Record<string, unknown> = {}
+const expected = record ? {} : JSON.parse(readFileSync(artifact, 'utf8'))
+
+it.each(['linux', 'darwin'])('preserves the confirmed native model protocol on %s', async platform => {
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = mkdtempSync(join(tmpdir(), 'native-mutation-golden-'))
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })
+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T16:15:00Z') })
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'OPENCODE_CONFIG_DIR', 'OPENCODE_DATA_DIR']) {
+ const path = join(root, name); mkdirSync(path); vi.stubEnv(name, path)
+ }
+ vi.stubEnv('OPENCODE_PATH', '/fixture/bin/opencode'); vi.stubEnv('TZ', 'UTC'); vi.resetModules()
+ const { applyOpencodeSessionModel } = await import('./launchControl.js')
+ for (const checkCatalog of [false, true]) for (const variant of [false, true]) {
+ const calls: unknown[] = []
+ let model: unknown
+ const result = await applyOpencodeSessionModel({ opencodeMajor: 2, dbPath: '/fixture/unused.db',
+ sessionId: 'ses_fixture', model: { providerID: 'fixture', modelID: variant ? 'model#high' : 'model' },
+ cwd: '/fixture/work', checkCatalog }, { run: async (args, options) => {
+ calls.push({ args, options })
+ if (args[1] === 'model.list') return { stdout: JSON.stringify({ data: [{ providerID: 'fixture', id: 'model' }] }) }
+ if (args[1] === 'session.switchModel') { model = JSON.parse(args[args.indexOf('-d') + 1]!).model; return { stdout: '' } }
+ if (args[1] === 'session.get') return { stdout: JSON.stringify({ data: { id: 'ses_fixture', model } }) }
+ throw Error('Unexpected native command')
+ } })
+ const key = `${platform}:catalog=${checkCatalog}:variant=${variant}`
+ observations[key] = { result, calls }
+ if (!record) expect({ key, value: observations[key] }).toEqual({ key, value: expected[key] })
+ }
+ } finally {
+ log.mockRestore(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.resetModules()
+ Object.defineProperty(process, 'platform', descriptor)
+ rmSync(root, { recursive: true, force: true })
+ }
+})
+
+afterAll(() => {
+ if (record) writeFileSync(artifact, JSON.stringify(observations, null, 2) + '\n')
+ else expect(Object.keys(observations).sort()).toEqual(Object.keys(expected).sort())
+})
diff --git a/cli/src/engines/nativeMutation.spec.ts b/cli/src/engines/nativeMutation.spec.ts
new file mode 100644
index 000000000..55487ee60
--- /dev/null
+++ b/cli/src/engines/nativeMutation.spec.ts
@@ -0,0 +1,147 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createSessionModelControl, type NativeApiRun } from './kit/nativeSessionModel.js'
+import { OPENCODE_SESSION_MODEL } from './opencode/contract.js'
+
+const requested = { providerID: 'fixture', modelID: 'new' }
+const answer = (id = 'new') => ({ stdout: JSON.stringify({ data: { id: 'ses_fixture', model: { providerID: 'fixture', id } } }) })
+const control = () => createSessionModelControl(OPENCODE_SESSION_MODEL, () => '/fixture/bin/opencode')
+
+describe('native mutation recovery', () => {
+ it('does not write when the required catalog is unavailable', async () => {
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'model.list') throw Error('catalog unavailable')
+ return answer()
+ })
+ expect(await control().switchSessionModel('ses_fixture', requested, { run, checkCatalog: true, retryDelayMs: 0 }))
+ .toMatchObject({ ok: false })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['model.list'])
+ })
+
+ it('reads back a lost write reply without sending the mutation again', async () => {
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'session.switchModel') throw Error('reply lost after commit')
+ return answer()
+ })
+ expect(await control().switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['session.switchModel', 'session.get'])
+ })
+
+ it('retries only reads when the first confirmation is unavailable', async () => {
+ let reads = 0
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'session.get' && ++reads === 1) throw Error('read unavailable')
+ return answer()
+ })
+ expect(await control().switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['session.switchModel', 'session.get', 'session.get'])
+ })
+
+ it('does not overwrite a different native choice while reconciling', async () => {
+ const run = vi.fn<NativeApiRun>(async () => answer('chosen-in-terminal'))
+ expect(await control().switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ expect(run.mock.calls.filter(([args]) => args[1] === 'session.switchModel')).toHaveLength(1)
+ })
+
+ it('keeps an uncertain write read-only across later requests, even for a different requested model', async () => {
+ const session = control()
+ let unavailable = true
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'session.get' && unavailable) throw Error('read unavailable after commit')
+ return answer('chosen-in-terminal')
+ })
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ unavailable = false
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ expect(await session.switchSessionModel('ses_fixture', { ...requested, modelID: 'another' }, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ expect(run.mock.calls.filter(([args]) => args[1] === 'session.switchModel')).toHaveLength(1)
+ run.mockImplementation(async () => answer())
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(run.mock.calls.filter(([args]) => args[1] === 'session.switchModel')).toHaveLength(1)
+ })
+
+ it.each(['ses_stranger', undefined])('does not accept matching model data for session %s', async id => {
+ const run = vi.fn<NativeApiRun>(async () => ({ stdout: JSON.stringify({ data: { id, model: { providerID: 'fixture', id: 'new' } } }) }))
+ expect(await control().switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toMatchObject({ ok: false })
+ expect(run.mock.calls.filter(([args]) => args[1] === 'session.switchModel')).toHaveLength(1)
+ })
+
+ it('serializes the first catalog read, retaining a snapshot of the requested model and folder', async () => {
+ const session = control()
+ let release!: () => void
+ const ready = new Promise<void>(done => { release = done })
+ const model = { ...requested }, options = { cwd: '/fixture/original', checkCatalog: true }
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'model.list') { await ready; return { stdout: JSON.stringify({ data: [{ providerID: 'fixture', id: 'new' }] }) } }
+ return answer()
+ })
+ const first = session.switchSessionModel('ses_fixture', model, { ...options, run, retryDelayMs: 0 })
+ model.modelID = 'later'
+ const second = await session.switchSessionModel('ses_fixture', requested, { ...options, run, retryDelayMs: 0 })
+ expect(second).toMatchObject({ ok: false, detail: expect.stringContaining('already running') })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['model.list'])
+ release()
+ expect(await first).toEqual({ ok: true })
+ const [args, passed] = run.mock.calls.find(([args]) => args[1] === 'session.switchModel')!
+ expect(JSON.parse(args.at(-1)!)).toEqual({ model: { providerID: 'fixture', id: 'new' } })
+ expect(passed.cwd).toBe('/fixture/original')
+ })
+
+ it('keeps unresolved receipts at capacity and holds new conversations', async () => {
+ const session = control()
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === 'session.get') throw Error('unavailable')
+ return { stdout: '' }
+ })
+ for (let n = 0; n < 256; n++) {
+ await session.switchSessionModel(`ses_fixture${n}`, requested, { run, retryDelayMs: 0 })
+ }
+ run.mockClear()
+ expect(await session.switchSessionModel('ses_overflow', requested, { run, retryDelayMs: 0 }))
+ .toMatchObject({ ok: false, detail: expect.stringContaining('outstanding') })
+ expect(run).not.toHaveBeenCalled()
+ await session.switchSessionModel('ses_fixture0', requested, { run, retryDelayMs: 0 })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['session.get', 'session.get'])
+ })
+
+ it('does not carry an unresolved write to another native store or folder', async () => {
+ const session = control()
+ const run = vi.fn<NativeApiRun>(async () => { throw Error('unavailable') })
+ await session.switchSessionModel('ses_fixture', requested, { run, store: '/fixture/store', cwd: '/fixture/work', retryDelayMs: 0 })
+ run.mockClear()
+ for (const options of [{ store: '/fixture/other', cwd: '/fixture/work' }, { store: '/fixture/store', cwd: '/fixture/other' }]) {
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, ...options, retryDelayMs: 0 }))
+ .toMatchObject({ ok: false, detail: expect.stringContaining('original store and folder') })
+ }
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ it('confirms a previous choice without silently starting a different one', async () => {
+ const session = control()
+ const run = vi.fn<NativeApiRun>(async () => { throw Error('unavailable') })
+ await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })
+ run.mockClear().mockImplementation(async () => answer())
+ expect(await session.switchSessionModel('ses_fixture', { ...requested, modelID: 'other' }, { run, retryDelayMs: 0 }))
+ .toMatchObject({ ok: false, detail: expect.stringContaining('earlier native model change is now confirmed') })
+ expect(run.mock.calls.map(([args]) => args[1])).toEqual(['session.get'])
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toEqual({ ok: true })
+ })
+
+ it.each(['catalog', 'write', 'read'] as const)('stops after ownership is revoked during %s', async phase => {
+ let current = true
+ const run = vi.fn<NativeApiRun>(async args => {
+ if (args[1] === ({ catalog: 'model.list', write: 'session.switchModel', read: 'session.get' })[phase]) current = false
+ return args[1] === 'model.list' ? { stdout: JSON.stringify([{ providerID: 'fixture', id: 'new' }]) } : answer()
+ })
+ const session = control()
+ const result = await session.switchSessionModel('ses_fixture', requested, { run, current: () => current, checkCatalog: true, retryDelayMs: 0 })
+ expect(result).toMatchObject({ ok: false, code: 'AGENT_CHANGED' })
+ const writes = () => run.mock.calls.filter(([args]) => args[1] === 'session.switchModel')
+ expect(writes()).toHaveLength(phase === 'catalog' ? 0 : 1)
+ // A cancelled operation after dispatch still leaves its receipt for a later read.
+ if (phase !== 'catalog') {
+ run.mockImplementation(async () => answer())
+ expect(await session.switchSessionModel('ses_fixture', requested, { run, retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(writes()).toHaveLength(1)
+ }
+ })
+})
diff --git a/cli/src/engines/opencode/sessionModel.spec.ts b/cli/src/engines/opencode/sessionModel.spec.ts
index 3705af8a7..7f336c217 100644
--- a/cli/src/engines/opencode/sessionModel.spec.ts
+++ b/cli/src/engines/opencode/sessionModel.spec.ts
@@ -17,7 +17,9 @@ const hasSqlite = (() => {
})()
const d = hasSqlite ? describe : describe.skip
-const SID = 'ses_testABC123'
+let sessionNumber = 0
+let SID = 'ses_testABC123'
+beforeEach(() => { SID = `ses_testABC${++sessionNumber}` })
const OTHER = 'ses_otherXYZ789'
const OLD = { providerID: 'opencode', modelID: 'big-pickle' }
const NEW = { providerID: 'minhduccm90-cecb9724', modelID: 'Qwen3.6-35B-A3B' }
@@ -233,11 +235,12 @@ describe('switchOpencodeSessionModel (opencode v2, `opencode api`)', () => {
.resolves.toMatchObject({ ok: false, code: 'OPENCODE_SESSION_NOT_FOUND', detail: expect.stringContaining('Session not found') })
})
- it('refuses when the session still reads back on another model after a second try', async () => {
+ it('holds when the session still reads back on another model after a second read', async () => {
const { run, calls } = fakeApi({ get: () => JSON.stringify({ data: { id: SID, model: { id: OLD.modelID, providerID: OLD.providerID } } }) })
await expect(switchOpencodeSessionModel(SID, NEW, { run, retryDelayMs: 0 }))
.resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED', detail: expect.stringContaining('opencode/big-pickle') })
- expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(2)
+ expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(1)
+ expect(calls.filter((c) => c[1] === 'session.get')).toHaveLength(2)
})
// `provider/model#variant` is opencode's own way to name an effort (`opencode run -m`): on v2 the
@@ -251,7 +254,7 @@ describe('switchOpencodeSessionModel (opencode v2, `opencode api`)', () => {
.resolves.toMatchObject({ ok: false, code: 'OPENCODE_MODEL_SWITCH_FAILED' })
})
- it('tries once more when the first switch did not land, and is done when the second does', async () => {
+ it('reads once more when the first observation lags behind the switch', async () => {
let reads = 0
const { run, calls } = fakeApi({ get: () => {
reads += 1
@@ -259,7 +262,8 @@ describe('switchOpencodeSessionModel (opencode v2, `opencode api`)', () => {
return JSON.stringify({ data: { id: SID, model: { id: m.modelID, providerID: m.providerID } } })
} })
await expect(switchOpencodeSessionModel(SID, NEW, { run, retryDelayMs: 0 })).resolves.toEqual({ ok: true })
- expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(2)
+ expect(calls.filter((c) => c[1] === 'session.switchModel')).toHaveLength(1)
+ expect(calls.filter((c) => c[1] === 'session.get')).toHaveLength(2)
})
it('does not try again where a second try cannot help (no such session)', async () => {
@@ -277,13 +281,13 @@ describe('switchOpencodeSessionModel (opencode v2, `opencode api`)', () => {
expect(calls.map((c) => c[1])).toEqual(['model.list'])
})
- it('switches without the check when the catalogue cannot be read, or was not asked for (a grid declared per pane)', async () => {
+ it('holds for an unreadable required catalog; a grid declared per pane does not ask for the catalog', async () => {
const { run, calls } = fakeApi({ list: () => { throw exitError('', 'HTTP 500') } })
- await expect(switchOpencodeSessionModel(SID, NEW, { run, checkCatalog: true })).resolves.toEqual({ ok: true })
+ await expect(switchOpencodeSessionModel(SID, NEW, { run, checkCatalog: true })).resolves.toMatchObject({ ok: false })
const plain = fakeApi({ list: () => JSON.stringify({ data: [] }) })
await expect(switchOpencodeSessionModel(SID, NEW, { run: plain.run })).resolves.toEqual({ ok: true })
expect(plain.calls.map((c) => c[1])).not.toContain('model.list')
- expect(calls.map((c) => c[1])).toContain('session.switchModel')
+ expect(calls.map((c) => c[1])).toEqual(['model.list'])
})
it('refuses when opencode is not installed, or the id is not a session id', async () => {
diff --git a/cli/src/engines/opencodeLaunch.golden.spec.ts b/cli/src/engines/opencodeLaunch.golden.spec.ts
index 1368ea91f..f05894c58 100644
--- a/cli/src/engines/opencodeLaunch.golden.spec.ts
+++ b/cli/src/engines/opencodeLaunch.golden.spec.ts
@@ -73,7 +73,7 @@ fs.appendFileSync(${JSON.stringify(calls)}, JSON.stringify({binary:'opencode',ar
if(args[0]==='--version') console.log(${JSON.stringify(version)});
else if(args[1]==='model.list') console.log(JSON.stringify({data:[{providerID:'fixture',id:'model'}]}));
else if(args[1]==='session.switchModel') { fs.writeFileSync(${JSON.stringify(join(root, 'model.json'))}, args[args.indexOf('-d')+1]); console.log('{}'); }
-else if(args[1]==='session.get') console.log(JSON.stringify({data:JSON.parse(fs.readFileSync(${JSON.stringify(join(root, 'model.json'))},'utf8'))}));
+else if(args[1]==='session.get') console.log(JSON.stringify({data:{id:'ses_fixture',...JSON.parse(fs.readFileSync(${JSON.stringify(join(root, 'model.json'))},'utf8'))}}));
else { console.error('Unexpected fixture command'); process.exitCode=1; }
`, { mode: 0o755 })
}
@@ -141,8 +141,8 @@ it('records create, fork, relaunch and actual retarget dispatch before the extra
captureTerminal: async () => 'fixture idle', readScreen: async () => ({ pane: { idle: true } }),
acquireTerminalControl: () => () => event(['release']), relaunchOverrides: shapes.relaunch,
downgradedPermission: async () => ({ bypassPermission: false, permissionMode: null }),
- agentReconciler: { holdRoute: () => event(['holdRoute']), releaseRoute: () => event(['releaseRoute']) },
- restartJobs: { busy: () => false, cancel: () => event(['cancel']) },
+ agentReconciler: { holdRoute: () => { event(['holdRoute']); return () => event(['releaseRoute']) } },
+ restartJobs: { busy: () => false, cancel: () => event(['cancel']), revision: () => 0 },
paneSwapDeps: (s: RegisteredSession, _pane: unknown, overrides: { extraArgs: string[]; env: unknown; clearEnv: string[] }) => ({
holdOpen: async () => { event(['holdOpen']); return { ok: true } },
terminate: async () => { event(['terminate']); return 'gone' },
diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.ts
index 071bc9748..b24b0ec99 100644
--- a/cli/src/lib/captureResumeIdentity.spec.ts
+++ b/cli/src/lib/captureResumeIdentity.spec.ts
@@ -130,6 +130,26 @@ it('captures a unique fresh session before its first hook arrives', async () =>
expect(row.sessionId).toBe('')
expect(findLiveSession).toHaveBeenCalledWith('claude', '/work', Date.parse(row.processIdentity!.startMarker), expect.objectContaining({ pid: 77, bornOnly: true, codexHome: undefined, expectedProcess: row.processIdentity }))
})
+it.each(['claude', 'codex'] as const)('does not give an unbound %s fork its parent from the recent-file pool', async engine => {
+ Object.assign(row, { engine, forkedFrom: { agentId: 'parent-agent', name: 'Parent', sessionId: 'parent', transcriptPath: '/parent' } })
+ // A parent created in the same process-clock interval is a unique "born" candidate,
+ // even though its newer turns and conversation still belong to the parent.
+ vi.mocked(findLiveSession).mockImplementation(async (_engine, _cwd, _start, options) =>
+ options?.excludedSessionId === 'parent' ? null : { sessionId: 'parent', transcriptPath: '/parent' })
+ expect(await captureResumeIdentity(row)).toBe(row)
+ expect(savedTranscriptEvidence).not.toHaveBeenCalled()
+ expect(findLiveSession).toHaveBeenCalledWith(engine, '/work', expect.any(Number), expect.objectContaining({ excludedSessionId: 'parent' }))
+})
+it.each(['native record', 'explicit resume', 'new conversation'] as const)('preserves an unbound fork\'s %s evidence', async mode => {
+ row.forkedFrom = { agentId: 'parent-agent', name: 'Parent', sessionId: 'parent', transcriptPath: '/parent' }
+ if (mode === 'native record') vi.mocked(processSessionEvidence).mockResolvedValue({ session: { sessionId: 'parent', transcriptPath: '/parent' }, verify: vi.fn() })
+ if (mode === 'explicit resume') {
+ vi.mocked(resumeSessionId).mockReturnValue('parent')
+ vi.mocked(findResumedTranscript).mockResolvedValue('/parent')
+ }
+ if (mode === 'new conversation') vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'child', transcriptPath: '/child' })
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: mode === 'new conversation' ? 'child' : 'parent', source: 'stop-repair' })
+})
it.each([null, { sessionId: 'missing' }, { sessionId: 'unsafe', transcriptPath: '/unsafe' }])('does not bind ambiguous or unsafe history: %s', async found => {
vi.mocked(findLiveSession).mockResolvedValue(found)
vi.mocked(savedTranscriptEvidence).mockReturnValue({ path: null, fileKey: null, verify: vi.fn() })
diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.ts
index 8aa1191a4..c33781758 100644
--- a/cli/src/lib/captureResumeIdentity.ts
+++ b/cli/src/lib/captureResumeIdentity.ts
@@ -54,6 +54,7 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) ?? undefined }
: await findLiveSession(session.engine, session.cwd, Date.parse(expected.startMarker), {
...options, hermesHome: session.hermesHome ?? undefined, pid: expected.pid, bornOnly: true,
+ ...(session.forkedFrom?.sessionId ? { excludedSessionId: session.forkedFrom.sessionId } : {}),
expectedProcess: expected, nativeBudget: budget,
}))
// Codex's open-file finder verifies this owner, all candidate headers and its descriptor
diff --git a/cli/src/lib/deleteAgentFallback.spec.ts b/cli/src/lib/deleteAgentFallback.spec.ts
index 34a326c74..22e55c08a 100644
--- a/cli/src/lib/deleteAgentFallback.spec.ts
+++ b/cli/src/lib/deleteAgentFallback.spec.ts
@@ -42,6 +42,21 @@ function deps(over: Partial<TerminateDeps> = {}): TerminateDeps & { kills: Array
}
describe('delete-agent process termination', () => {
+ it.each(['initial wait', 'identity read', 'grace read', 'escalation read'] as const)('does not signal after ownership is revoked during %s', async phase => {
+ let current = true, reads = 0
+ const d = deps({ current: () => current,
+ sleep: async () => { if (phase === 'initial wait') current = false },
+ checkRuntime: async () => {
+ reads++
+ if ((phase === 'identity read' && reads === 1) || (phase === 'grace read' && reads === 2)
+ || (phase === 'escalation read' && reads === 3)) current = false
+ return runtime(true)
+ },
+ })
+ expect(await terminateDeletedAgent(SESSION, d, 0, 250)).toBe('not-ours')
+ expect(d.kills).toEqual(phase === 'initial wait' || phase === 'identity read' ? [] : [[4242, 'SIGTERM']])
+ })
+
it('does nothing when the engine already left', async () => {
const d = deps({ checkRuntime: async () => runtime(false) })
await expect(terminateDeletedAgent(SESSION, d)).resolves.toBe('gone')
diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.ts
index 20e1e205d..735aef13a 100644
--- a/cli/src/lib/deleteAgentFallback.ts
+++ b/cli/src/lib/deleteAgentFallback.ts
@@ -43,6 +43,8 @@ export type TerminateOutcome =
| 'failed'
export interface TerminateDeps {
+ /** Stop or a newer binding can revoke this operation while native identity is being read. */
+ current?: () => boolean
/** Three-valued exact identity check. Probe failure is not evidence that the process is gone. */
checkRuntime: (session: RegisteredSession) => Promise<RuntimeCheck>
/** `process.kill`. Throws on EPERM/ESRCH like the real one. */
@@ -64,6 +66,7 @@ export async function terminateDeletedAgent(
killGraceMs = FALLBACK_KILL_GRACE_MS,
): Promise<TerminateOutcome> {
await deps.sleep(checkAfterMs)
+ if (deps.current?.() === false) return 'not-ours'
const check = async (): Promise<RuntimeCheck> => {
try { return await deps.checkRuntime(session) }
@@ -72,6 +75,7 @@ export async function terminateDeletedAgent(
// PID + start marker validation is what prevents a recycled PID from receiving our signal. Unknown
// means we cannot prove the target and must leave the runtime suppressed rather than call it gone.
const initial = await check()
+ if (deps.current?.() === false) return 'not-ours'
if (initial.state === 'gone') return 'gone'
if (initial.state === 'unknown') {
deps.log(`[delete] could not validate ${session.engine} runtime: ${initial.reason}`)
@@ -82,6 +86,7 @@ export async function terminateDeletedAgent(
if (!pid) return 'not-ours'
const signal = (sig: NodeJS.Signals): boolean => {
+ if (deps.current?.() === false) return false
try { deps.kill(pid, sig); return true } catch (err) {
const code = (err as NodeJS.ErrnoException)?.code
// ESRCH = it exited between the check and the signal. Anything else (EPERM…) is a real failure to
@@ -99,12 +104,14 @@ export async function terminateDeletedAgent(
for (let waited = 0; waited < killGraceMs; waited += POLL_MS) {
await deps.sleep(POLL_MS)
const current = await check()
+ if (deps.current?.() === false) return 'not-ours'
if (current.state === 'gone') return 'terminated'
}
// Revalidate at the escalation boundary. A process-table timeout or PID replacement after SIGTERM is
// not permission to send SIGKILL to the saved number.
const beforeKill = await check()
+ if (deps.current?.() === false) return 'not-ours'
if (beforeKill.state === 'gone') return 'terminated'
if (beforeKill.state === 'unknown') {
deps.log(`[delete] could not revalidate ${session.engine} before SIGKILL: ${beforeKill.reason}`)
diff --git a/cli/src/lib/nativeConversation.spec.ts b/cli/src/lib/nativeConversation.spec.ts
index 6dec377ab..ea774d1eb 100644
--- a/cli/src/lib/nativeConversation.spec.ts
+++ b/cli/src/lib/nativeConversation.spec.ts
@@ -24,7 +24,7 @@ function rollout(n = 1, folder = cwd, base = home): string {
const file = join(base, 'day', `rollout-${id(n)}.jsonl`)
mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, header(id(n), folder)); return file
}
-const find = (options: Pick<NativeConversationOptions, 'expected' | 'budget'> = {}) =>
+const find = (options: Pick<NativeConversationOptions, 'expected' | 'budget' | 'excludedSessionId'> = {}) =>
nativeOpenFileSession('codex', 42, [home], cwd, { sources, ...options })
beforeEach(async () => {
Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
@@ -50,6 +50,25 @@ it('holds two eligible files rather than letting Stop accept an empty identity',
held = [rollout(1), rollout(2)]
await expect(find()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
})
+it('excludes a fork source opened for copying before choosing the child rollout', async () => {
+ const parent = rollout(1), child = rollout(2)
+ held = [parent]
+ await expect(find({ excludedSessionId: id(1) })).resolves.toBeNull()
+ held = [parent, child]
+ await expect(find({ excludedSessionId: id(1) })).resolves.toEqual({ sessionId: id(2), transcriptPath: child })
+})
+it.each(['invalid', 'changed'] as const)('retains %s evidence for an excluded fork source', async mode => {
+ const parent = rollout(1), child = rollout(2); held = [parent, child]
+ if (mode === 'invalid') writeFileSync(parent, JSON.stringify({ type: 'session_meta', payload: { id: id(1), cwd, source: false } }) + '\n')
+ else {
+ const read = sources.descriptors
+ sources.descriptors = async (...args) => {
+ const proof = await read(...args)
+ return { ...proof, verify: async () => { await proof.verify(); writeFileSync(parent, header(id(3))) } }
+ }
+ }
+ await expect(find({ excludedSessionId: id(1) })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+})
it.each(['missing', 'invalid', 'empty', 'wrong-id', 'unknown-folder'] as const)('cannot exclude a %s competitor to make a healthy file unique', async mode => {
const own = rollout(1), other = rollout(2)
held = [own, other]
diff --git a/cli/src/lib/nativeConversation.ts b/cli/src/lib/nativeConversation.ts
index cd5fe9e2d..265b5270e 100644
--- a/cli/src/lib/nativeConversation.ts
+++ b/cli/src/lib/nativeConversation.ts
@@ -18,6 +18,7 @@ export interface NativeConversationSources {
}
export interface NativeConversationOptions {
expected?: ProcessIdentity
+ excludedSessionId?: string
budget?: NativeEvidenceBudget
sources?: NativeConversationSources
}
@@ -110,6 +111,10 @@ export async function nativeOpenFileSession(engine: AgentEngine, pid: number, ro
if ((declared && !declared.info.isDirectory()) || (requested && !requested.info.isDirectory())) return nativeUnavailable('a native conversation folder is not a directory')
const same = meta.cwd === cwd || (declared && requested && nativeFileKey(declared.info) === nativeFileKey(requested.info))
if (!same) continue
+ // A fork opens its source while copying it. A descriptor proves that read,
+ // not that the new process owns the source conversation. Keep its proof in
+ // the final checks even though it cannot be selected as the child.
+ if (meta.id === options.excludedSessionId) continue
found.set(key, { sessionId: meta.id, transcriptPath: location.path })
}
await evidence.verify()
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index 3a6458e6d..abfe7bb7a 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -19,6 +19,7 @@ const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
delete process.env.GROK_HOME
+ vi.unstubAllEnvs()
vi.unstubAllGlobals()
vi.resetModules()
})
@@ -46,8 +47,21 @@ async function load(claudeProjectsDir: string) {
const STARTED_AT = Date.parse('2026-08-03T09:00:00Z')
const CWD = '/Users/demo/work/project'
+const hasSqlite = (() => {
+ try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
+})()
describe('session repair', () => {
+ it('excludes a known fork parent before deciding whether a recent-file pool is unique', async () => {
+ const root = tempRoot()
+ writeTranscript(root, 'proj', 'parent', CWD, STARTED_AT + 5_000)
+ const { findLiveSession } = await load(root)
+ await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true, excludedSessionId: 'parent' })).resolves.toBeNull()
+ writeTranscript(root, 'proj', 'child', CWD, STARTED_AT + 6_000)
+ await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true, excludedSessionId: 'parent' }))
+ .resolves.toMatchObject({ sessionId: 'child' })
+ })
+
it('finds the session the running engine started in this directory', async () => {
const root = tempRoot()
writeTranscript(root, 'proj', 'sess-live', CWD, STARTED_AT + 5_000)
@@ -596,6 +610,10 @@ describe('session repair — a Codex process names its own rollout', () => {
await vi.waitFor(async () => expect(await openFiles(holder.pid!)).toContain(realpathSync(forkFile)), { timeout: 10_000, interval: 100 })
await expect(findLiveSession('codex', CWD, STARTED_AT, { codexHome: profile, bornOnly: true, pid: holder.pid! }))
.resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })
+ // A fork can read the source while copying it. The descriptor alone cannot
+ // turn that known parent into the new process's current conversation.
+ await expect(findLiveSession('codex', CWD, STARTED_AT,
+ { codexHome: profile, bornOnly: true, pid: holder.pid!, excludedSessionId: fork })).resolves.toBeNull()
expect(await openFiles(-1)).toEqual([])
vi.unstubAllGlobals()
} finally {
@@ -634,6 +652,9 @@ describe('session repair — homes the person moved', () => {
const { processSessionOf, findLiveSession } = await moved(claudeHome, tempRoot())
const transcriptPath = join(claudeHome, 'projects', 'project', `${id}.jsonl`)
await expect(processSessionOf('claude', 77, CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath })
+ // An exact native process claim can resume that parent despite a fallback exclusion.
+ await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true, pid: 77, excludedSessionId: id }))
+ .resolves.toEqual({ sessionId: id, transcriptPath })
// And by the folder scan, when there is no process record to read.
await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true })).resolves.toEqual({ sessionId: id, transcriptPath })
})
@@ -867,10 +888,35 @@ it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'd
* `<HERMES_HOME>/state.db` could never rebind a profile agent after a restart — its row is in a
* database that store has never heard of (openharness#191).
*/
+describe('database session repair', () => {
+ const t = hasSqlite ? it : it.skip
+ t.each(['opencode', 'kilo', 'devin'] as const)('never gives an unbound %s fork its known parent from a limited pool', async engine => {
+ const data = tempRoot()
+ vi.stubEnv('XDG_DATA_HOME', data)
+ const home = join(data, engine, ...(engine === 'devin' ? ['cli'] : []))
+ mkdirSync(home, { recursive: true })
+ const db = join(home, engine === 'devin' ? 'sessions.db' : `${engine}.db`)
+ const table = engine === 'devin' ? 'sessions' : 'session'
+ const directory = engine === 'devin' ? 'working_directory' : 'directory'
+ const created = engine === 'devin' ? 'created_at' : 'time_created'
+ const updated = engine === 'devin' ? 'last_activity_at' : 'time_updated'
+ const time = Math.trunc(STARTED_AT / (engine === 'devin' ? 1000 : 1)) + 5
+ execFileSync('sqlite3', [db,
+ `CREATE TABLE ${table} (id TEXT, ${directory} TEXT, parent_id TEXT, ${created} INTEGER, ${updated} INTEGER);`
+ + `INSERT INTO ${table} VALUES ('parent','${CWD}',NULL,${time},${time});`])
+ const { findLiveSession } = await load(tempRoot())
+ const find = () => findLiveSession(engine, CWD, STARTED_AT, { bornOnly: true, excludedSessionId: 'parent' })
+ await expect(find()).resolves.toBeNull()
+ // LIMIT 2 can hide a third candidate. Filtering its two returned rows must
+ // never make the remaining child look unique.
+ execFileSync('sqlite3', [db,
+ `INSERT INTO ${table} VALUES ('child','${CWD}',NULL,${time},${time - 1});`
+ + `INSERT INTO ${table} VALUES ('sibling','${CWD}',NULL,${time},${time - 2});`])
+ await expect(find()).resolves.toBeNull()
+ })
+})
+
describe('hermes repair across profile homes', () => {
- const hasSqlite = (() => {
- try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false }
- })()
const t = hasSqlite ? it : it.skip
const SID_DEFAULT = '20260727_162325_e25264'
const SID_PROFILE = '20260921_152236_a1b2c3'
@@ -923,6 +969,16 @@ describe('hermes repair across profile homes', () => {
expect(await findLiveSession('hermes', CWD, STARTED_AT, { bornOnly: true })).toBeNull()
})
+ t('excludes a known parent from the complete Hermes pool while retaining its evidence', async () => {
+ const home = hermesHome(tempRoot(), SID_DEFAULT)
+ const { findLiveSession } = await loadWithHome(home)
+ const find = () => findLiveSession('hermes', CWD, STARTED_AT, { bornOnly: true, excludedSessionId: SID_DEFAULT })
+ await expect(find()).resolves.toBeNull()
+ const childHome = hermesHome(join(home, 'profiles', 'demo'), SID_PROFILE)
+ expect(await find()).toMatchObject({ sessionId: SID_PROFILE, hermesHome: childHome })
+ execFileSync('sqlite3', [join(home, 'state.db'), "UPDATE sessions SET started_at = 'invalid';"])
+ await expect(find()).rejects.toThrow('invalid discovery evidence')
+ })
})
// Filesystem durability deadlines are exercised separately from these deterministic fixture reads.
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index 1f274487b..25702dfdc 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -222,7 +222,7 @@ async function fileEngineSession(
cwd: string,
startedAtMs: number,
readMeta: (path: string) => Promise<TranscriptMeta | null>,
- opts?: { bornOnly?: boolean; excludedDirectory?: string },
+ opts?: { bornOnly?: boolean; excludedDirectory?: string; excludedSessionId?: string },
): Promise<RepairedSession | null> {
const since = startedAtMs - START_SLACK_MS
const born: RepairedSession[] = []
@@ -239,6 +239,9 @@ async function fileEngineSession(
const meta = await readMeta(file.path)
if (!meta?.cwd || !await sameDir(meta.cwd, cwd)) continue
const found = { sessionId: meta.sessionId || idFromFile(file.path), transcriptPath: file.path }
+ // A fork's source can still be within the process start-time slack. Removing
+ // it before uniqueness is decided also lets the fork's own new file be found.
+ if (found.sessionId === opts?.excludedSessionId) continue
;(file.birthMs >= since ? born : wrote).push(found)
}
// "Unique or nothing" at each tier: two candidates means two agents in one directory, and a wrong guess
@@ -264,7 +267,7 @@ async function reportMissingSqliteOnce(): Promise<void> {
}
/** Read-only, through the same helper the readers use, so a repair can never write to the user's store. */
-async function dbEngineSession(dbPath: string, sql: string, params: SqliteParam[]): Promise<RepairedSession | null> {
+async function dbEngineSession(dbPath: string, sql: string, params: SqliteParam[], excludedSessionId?: string): Promise<RepairedSession | null> {
const result = await sqliteReadAll(dbPath, sql, params, { maxBuffer: 1024 * 1024 })
if (!result.ok) {
// No reader at all is not a transient DB lock, and repair returning null forever with no signal is
@@ -273,9 +276,11 @@ async function dbEngineSession(dbPath: string, sql: string, params: SqliteParam[
return null
}
const rows = result.rows
+ // These queries return at most two rows. Removing the source from that
+ // truncated result cannot establish that the remaining row is unique.
if (rows.length !== 1) return null // 0 = nothing to adopt, >1 = ambiguous
const id = rows[0].id
- return typeof id === 'string' && id ? { sessionId: id } : null
+ return typeof id === 'string' && id && id !== excludedSessionId ? { sessionId: id } : null
}
/** One `?` per directory, for an `IN (…)` over both spellings of the cwd. */
@@ -326,7 +331,7 @@ async function storeSession(
store: SessionStoreContract,
cwd: string,
startedAtMs: number,
- opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },
+ opts?: { bornOnly?: boolean; excludedSessionId?: string; pid?: number; codexHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },
): Promise<RepairedSession | null> {
const scan = scanMeta(engine, store.scan, cwd)
if ('record' in store.live) {
@@ -335,7 +340,8 @@ async function storeSession(
}
const sessions = repairRoots(engine, opts?.codexHome)
const found = opts?.pid && 'open' in store.live
- ? await openFileSessionOf(engine, opts.pid, sessions, cwd, { expected: opts.expectedProcess, budget: opts.nativeBudget })
+ ? await openFileSessionOf(engine, opts.pid, sessions, cwd,
+ { expected: opts.expectedProcess, budget: opts.nativeBudget, excludedSessionId: opts.excludedSessionId })
: await fileEngineSession(sessions, cwd, startedAtMs, scan,
{ ...opts, ...(store.scan.from === 'head' ? { excludedDirectory: store.scan.childFolder } : {}) })
// The login shell may adopt another home during any native read. Its unseen candidates
@@ -352,7 +358,9 @@ export async function findLiveSession(
startedAtMs: number,
// codexHome: the specific agent's own profile (its CODEX_HOME), when it isn't this machine's default —
// see RegisteredSession.codexHome. Read only for an engine whose sessions follow one (`sessions.profile`).
- opts?: { bornOnly?: boolean; pid?: number; codexHome?: string; hermesHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },
+ // A known fork source cannot identify the child through a file/DB pool or a
+ // descriptor opened for copying. Exact native current-session records still can.
+ opts?: { bornOnly?: boolean; excludedSessionId?: string; pid?: number; codexHome?: string; hermesHome?: string; expectedProcess?: ProcessIdentity; nativeBudget?: NativeEvidenceBudget },
): Promise<RepairedSession | null> {
const store = sessionStoreOf(engine)
if (store) return storeSession(engine, store, cwd, startedAtMs, opts)
@@ -418,6 +426,7 @@ export async function findLiveSession(
+ ' AND (time_created >= ? OR time_updated >= ?)'
+ ' ORDER BY time_updated DESC LIMIT 2;',
[...dirs, Math.trunc(sinceMs), Math.trunc(sinceMs)],
+ opts?.excludedSessionId,
)
case 'kilo':
// Same store shape as opencode (measured: `session` is byte-identical between the two DBs), and
@@ -428,6 +437,7 @@ export async function findLiveSession(
+ ' AND (time_created >= ? OR time_updated >= ?)'
+ ' ORDER BY time_updated DESC LIMIT 2;',
[...dirs, Math.trunc(sinceMs), Math.trunc(sinceMs)],
+ opts?.excludedSessionId,
)
case 'hermes': {
// started_at is epoch SECONDS (fractional).
@@ -462,6 +472,7 @@ export async function findLiveSession(
throw new IdentityReadUnavailable('a Hermes store contains an invalid conversation id')
}
if (opts?.hermesHome && !aliases.includes(opts.hermesHome)) continue
+ if (row.id === opts?.excludedSessionId) continue
candidates.push({ sessionId: row.id, hermesHome: opts?.hermesHome ?? home })
}
return candidates.length === 1 ? candidates[0] : null
@@ -476,6 +487,7 @@ export async function findLiveSession(
+ ' AND (created_at >= ? OR last_activity_at >= ?)'
+ ' ORDER BY last_activity_at DESC LIMIT 2;',
[...dirs, Math.trunc(sinceMs / 1000), Math.trunc(sinceMs / 1000)],
+ opts?.excludedSessionId,
)
case 'copilot': {
// The lock the process holds is the only thing a `/resume` leaves behind, and it is exact.
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index 3670eee74..878d39876 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -448,6 +448,17 @@ it('an unbound observation of the same process keeps its confirmed conversation'
store.save({ ...saved, sessionId: '', transcriptPath: null, title: 'Renamed', boundAt: null, source: null })
expect(store.get(saved.agentId)).toMatchObject({ sessionId: saved.sessionId, transcriptPath: '/history.jsonl', title: 'Renamed', boundAt: 1, source: 'hook' })
})
+it.each(['same', 'missing', 'different'] as const)('preserves an unbound Hermes conversation only with a compatible home: %s', async mode => {
+ const { saved, store } = await fixture()
+ Object.assign(saved, { engine: 'hermes', hermesHome: '/fixture/hermes' })
+ store.save(saved)
+ const hermesHome = mode === 'missing' ? undefined : mode === 'same' ? saved.hermesHome : '/fixture/other-hermes'
+ store.save({ ...saved, sessionId: '', transcriptPath: null, hermesHome })
+ expect(store.get(saved.agentId)).toMatchObject({
+ sessionId: mode === 'different' ? '' : saved.sessionId,
+ hermesHome: mode === 'different' ? hermesHome : saved.hermesHome,
+ })
+})
it('a pathless observation of the same conversation keeps its captured native path', async () => {
const { saved, store } = await fixture()
saved.hermesHome = '/fixture/hermes'
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index 8a48614c7..03a953564 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -404,7 +404,7 @@ describe('restart route hold', () => {
expect(onObserved).not.toHaveBeenCalled()
})
- it('resumes normal reconciliation once the route is released', async () => {
+ it.each([30_000, null])('resumes normal reconciliation only when the current %s hold is released', async timeout => {
const current = session([tmux])
const onDormant = vi.fn()
const validate = vi.fn(async () => ({ state: 'alive' as const }))
@@ -415,8 +415,8 @@ describe('restart route hold', () => {
probe: async () => probe([{ instanceId: 'tmux:default', result: { state: 'available', roots: [] } }]),
})
const routeKey = terminalRouteKey(tmux)
- const releaseOld = reconciler.holdRoute(routeKey)
- const releaseCurrent = reconciler.holdRoute(routeKey)
+ const releaseOld = reconciler.holdRoute(routeKey, timeout)
+ const releaseCurrent = reconciler.holdRoute(routeKey, timeout)
releaseOld()
await reconciler.trigger()
expect(onDormant).not.toHaveBeenCalled()
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index f675b0c9a..2fded288c 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -127,7 +127,7 @@ export class TerminalAgentReconciler {
* identity like `suppressed` — the replacement process's identity is not known until the swap
* finishes, so there is nothing to key a process-identity suppression on yet. */
private readonly heldRoutes = new Set<string>()
- private readonly heldRouteTimers = new Map<string, NodeJS.Timeout>()
+ private readonly heldRouteOwners = new Map<string, { timer?: NodeJS.Timeout }>()
/** When each route was last held or released, as a sequence number, so a probe can tell a route
* that changed hands while it ran (see `reconcileOnce`). */
private routeSeq = 0
@@ -181,30 +181,32 @@ export class TerminalAgentReconciler {
* process appearing in the same pane before the restart handler rebinds it would otherwise be opened
* as a brand-new agent (`onDiscovered` mints a fresh `agentId`).
*
- * `autoReleaseMs` is a belt-and-suspenders bound: the caller is expected to `releaseRoute` in a
- * `finally`, but a future refactor that drops that `finally` must not leave a route permanently
- * invisible to reconciliation.
+ * A timed hold is useful when there is no operation to await. Pass null for a bounded operation
+ * that owns the route through publication and releases it in finally: a timer expiring while its
+ * replacement is still being confirmed would let discovery create a second agent for that process.
*/
- holdRoute(routeKey: string, autoReleaseMs = 30_000): () => void {
+ holdRoute(routeKey: string, autoReleaseMs: number | null = 30_000): () => void {
this.heldRoutes.add(routeKey)
this.routeTouched.set(routeKey, ++this.routeSeq)
- const existing = this.heldRouteTimers.get(routeKey)
- if (existing) clearTimeout(existing)
- const timer = setTimeout(() => this.releaseRoute(routeKey), autoReleaseMs)
- timer.unref?.()
- this.heldRouteTimers.set(routeKey, timer)
+ const existing = this.heldRouteOwners.get(routeKey)
+ if (existing?.timer) clearTimeout(existing.timer)
+ const owner: { timer?: NodeJS.Timeout } = {}
+ this.heldRouteOwners.set(routeKey, owner)
// A cancelled restore cannot release the newer Stop/restart that took this route over.
- return () => { if (this.heldRouteTimers.get(routeKey) === timer) this.releaseRoute(routeKey) }
+ const release = () => { if (this.heldRouteOwners.get(routeKey) === owner) this.releaseRoute(routeKey) }
+ if (autoReleaseMs !== null) {
+ owner.timer = setTimeout(release, autoReleaseMs)
+ owner.timer.unref?.()
+ }
+ return release
}
/** Resume normal reconciliation for a route held by `holdRoute`. Idempotent. */
releaseRoute(routeKey: string): void {
if (this.heldRoutes.delete(routeKey)) this.routeTouched.set(routeKey, ++this.routeSeq)
- const timer = this.heldRouteTimers.get(routeKey)
- if (timer) {
- clearTimeout(timer)
- this.heldRouteTimers.delete(routeKey)
- }
+ const owner = this.heldRouteOwners.get(routeKey)
+ if (owner?.timer) clearTimeout(owner.timer)
+ this.heldRouteOwners.delete(routeKey)
}
/** Held now, or held or released since the probe numbered `probeSeq` began: that probe cannot speak
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 84e2a747c..d7c370f71 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -1350,10 +1350,11 @@ export function tmuxPaneInfo(pane: string, socket?: string): Promise<TmuxPaneInf
* Called as soon as a created pane becomes a real agent: from then on it must vanish when its engine
* exits, exactly like a pane the user started themselves, rather than lingering as a dead pane.
*/
-export async function clearPaneRemainOnExit(pane: string): Promise<void> {
+export async function clearPaneRemainOnExit(pane: string, current?: () => boolean): Promise<void> {
// The pane's own option where tmux has one (`paneOptionScope`): restarting an agent the person had
// moved into a window of their own must not switch remain-on-exit off for their panes there.
const scope = paneOptionScope(await tmuxFeatures())
+ if (current?.() === false) return
return new Promise((resolve) => {
run('tmux', ['set-option', scope, '-t', pane, 'remain-on-exit', 'off'], { timeout: 2_000 }, () => resolve())
})
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index fb06a241f..6eba170ef 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -69,6 +69,29 @@ afterEach(async () => {
})
describe('TmuxBackend lifecycle', () => {
+ it('keeps environment writes out of a pane revoked during session lookup', async () => {
+ const calls = recordingTmux('', '$4')
+ let current = true
+ const pending = new TmuxBackend().clearEnv({ backend: 'tmux', paneId: '%4' }, ['FIXTURE_MODEL'], () => current)
+ current = false
+ expect(await pending).toMatchObject({ state: 'failed', dispatch: 'not_started' })
+ expect(calls()).toEqual(['display-message -p -t %4 #{session_id}'])
+ })
+
+ it('does not retain a pane after ownership changes during feature discovery', async () => {
+ const calls = recordingTmux()
+ let release!: () => void, current = true
+ const ready = new Promise<void>(done => { release = done })
+ const features = vi.fn(async () => { await ready; return { paneOptions: true } })
+ const pending = new TmuxBackend(undefined, undefined, undefined, features as never)
+ .holdOpen({ backend: 'tmux', paneId: '%4' }, () => current)
+ await vi.waitFor(() => expect(features).toHaveBeenCalled())
+ current = false
+ release()
+ expect(await pending).toMatchObject({ state: 'failed', dispatch: 'not_started' })
+ expect(calls()).toEqual([])
+ })
+
it.each(['create', 'respawn'] as const)('rechecks core ownership after the feature wait before %s dispatch', async operation => {
let release!: () => void
let current = true
@@ -557,7 +580,7 @@ exit 1
})
/** A fake tmux on PATH that records every call, prints [listing] for `list-panes` and `%42` otherwise. */
-function recordingTmux(listing = ''): () => string[] {
+function recordingTmux(listing = '', sessionId = '%42'): () => string[] {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-old-'))
dirs.push(dir)
const calls = join(dir, 'calls')
@@ -565,6 +588,7 @@ function recordingTmux(listing = ''): () => string[] {
printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
case "$1" in
list-panes) printf '${listing.replace(/%/g, '%%')}' ;;
+ display-message) printf '${sessionId.replace(/%/g, '%%')}\\n' ;;
*) printf '%%42\\n' ;;
esac
`, { mode: 0o700 })
@@ -637,6 +661,14 @@ describe('TmuxBackend on a tmux before 3.0', () => {
})
describe('handing a pane back to tmux\'s disposal', () => {
+ it('cannot turn off a newer owner\'s remain-on-exit after the feature await', async () => {
+ const calls = recordingTmux()
+ let current = true
+ const pending = clearPaneRemainOnExit('%4', () => current)
+ current = false
+ await pending
+ expect(calls()).toEqual([])
+ })
// A window option on an agent the person had moved into a window of their own switched
// remain-on-exit off for their panes there too.
it('switches remain-on-exit off on the pane alone where tmux has pane options', async () => {
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 04f345644..505f378f6 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -345,9 +345,10 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
* `respawn-pane` inherits it — so respawning with no `-e` flags would leave the old grid in place
* while reporting a clean swap. This is what makes "back to your own login" actually true.
*/
- async clearEnv(runtime: TmuxRuntimeRef, names: readonly string[]): Promise<TerminalActionResult> {
+ async clearEnv(runtime: TmuxRuntimeRef, names: readonly string[], current?: () => boolean): Promise<TerminalActionResult> {
if (!names.length) return legacyActionResult(true, 'tmux clear environment')
const sessionId = await this.resolveSessionId(runtime.paneId)
+ if (current?.() === false) return terminalActionNotStarted('The harness changed before clearing its environment')
if (!sessionId) return terminalActionNotStarted('tmux session could not be resolved from pane')
const ok = await new Promise<boolean>((resolve) => {
run('tmux', clearEnvArgs(sessionId, names), { timeout: 5_000 }, (error) => resolve(!error))
@@ -373,8 +374,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
* re-arming it here tmux destroys the pane — and, being its only pane, the whole session — the
* instant the old process exits.
*/
- async holdOpen(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {
+ async holdOpen(runtime: TmuxRuntimeRef, current?: () => boolean): Promise<TerminalActionResult> {
const scope = paneOptionScope(await this.features())
+ if (current?.() === false) return terminalActionNotStarted('The harness changed before retaining its pane')
const ok = await new Promise<boolean>((resolve) => {
run('tmux', ['set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {
resolve(!error)
diff --git a/docs/research/2026-10-10-native-mutation-authority.md b/docs/research/2026-10-10-native-mutation-authority.md
new file mode 100644
index 000000000..964bcae17
--- /dev/null
+++ b/docs/research/2026-10-10-native-mutation-authority.md
@@ -0,0 +1,105 @@
+# Native mutation authority
+
+The next part of the daemon completion checklist addresses a concrete native
+mutation failure: OpenCode v2's model switch may have committed even when its
+reply or subsequent read is unavailable. Repeating the write can overwrite a
+later native choice. An unreadable model catalog also currently permits a write.
+Retarget retains a mutable registry row across asynchronous reads, so an old
+request can act after its conversation or process changes.
+
+The healthy protocol is recorded from main `f0875b08a` in
+`cli/src/engines/nativeMutation.golden.spec.ts`, before implementation changes.
+It exercises the eager launch-control entry and the declared native protocol on
+pinned Linux and Darwin platforms, with private homes, UTC, fixture paths and no
+host executable. The existing OpenCode launch/retarget golden remains an
+additional production-wiring check.
+
+The intended correction is to retain uncertain writes for read-only
+reconciliation, refuse mutation without complete required catalog evidence,
+and check immutable operation ownership before native effects and publication.
+Failure tests must show the old violation first. This does not claim that manual
+lifecycle requests or hook delivery are already durable across a daemon crash.
+
+## Prior phase
+
+The asynchronous version probe and concurrent hook-installation fix landed as
+[#1149](https://github.com/autonomous-ai/openharness/pull/1149),
+`f0875b08a75e8b1895e2c2fea50b32fed05cadbe`, October 10 at 16:14:29 UTC.
+Independent exact-head review, 25 assertion-failing wiring mutations, all local
+coverage gates, automatic CI and the full private end-to-end workflow passed.
+The final main integration also passed 82 Memories tests and five rebuilt daemon
+tests. The merge helper verified the complete tested tree. No release occurred.
+
+This phase began October 10 at 16:15 UTC. Implementation, validation, review/CI
+waiting and merge durations will be recorded separately in its PR.
+
+## Implemented boundary
+
+The eager native model controller keeps at most 256 live pending conversation
+receipts. Catalog failure prevents dispatch. A lost write reply is followed only
+by reads, including on later requests; an unresolved receipt is never evicted to
+make room for another write. Store/folder changes and legacy version fallback
+cannot bypass it. Confirmation must name the exact session and requested model.
+Native command resolution is asynchronous, children have time/output bounds and
+closed stdin, and a retry retains its selected executable path.
+
+Retarget snapshots the registry row and restart revision, rechecks ownership
+after asynchronous preparation, and passes that authority into the final signal
+and tmux write boundaries. Its discovery hold belongs to the operation through
+publication. A slow confirmation cannot expire it, and an older finally cannot
+release a newer Stop's hold. Replies distinguish a confirmed or uncertain native
+change from a later replacement failure.
+
+The initial five fault tests failed on the former implementation. Independent
+review then found across-request replay, wrong-session confirmation, release of a
+newer Stop hold, hidden partial effects, version-fallback bypass, and expiry of a
+still-owned route. Each has an assertion-based reproduction and a regression.
+The first complete private daemon run passed all eight tests in the eager
+OpenCode/hooks lanes, including lost replies, unavailable confirmations, another
+native choice, and Stop during a pending read. It exercises a private native API
+fixture and the actual daemon, not a new claim about vendor API semantics.
+
+The healthy native-mutation and existing launch golden artifacts remain
+unchanged. Mutation tests deliberately break protocol fields, admission, live
+receipt retention, response identity, version fallback, stream closure, session
+ownership, route lifetime, failure reporting and final tmux/signal fences.
+
+The full end-to-end run also exposed an ownership error at Stop: an unbound fork
+could claim its recently created parent's conversation through discovery's
+start-time slack. The stopped-conversation index then superseded the parent,
+breaking handoff. Known fork sources are now excluded from fallback file and
+database pools and from descriptors opened while copying the source. Complete
+native process records and explicit resumes retain their authority. Excluded
+descriptor headers still participate in final evidence verification; removing a
+row from a truncated database pool cannot establish uniqueness. The handoff test
+checks the actual saved parent and fork after Stop instead of reseeding the fork.
+
+## Still unfinished
+
+These receipts survive requests in one live core, not a daemon crash. Manual
+lifecycle intent still needs its durable journal. Retaining an executable path
+does not provide the whole-launch inode snapshot. Unknown-version retry policy,
+v1 SQLite uncertainty/missing-row handling, durable hook preparation, and atomic
+generated-configuration publication remain on the completion checklist. This
+change must not be described as completing those boundaries or the whole refactor.
+
+## Matched cost observation
+
+`cli/scripts/handoff-2026-10-08/native-mutation-cost.ts` ran on former main
+`f0875b08a` and the changed controller at `542e60748`, using Node 22.23.2 on the
+same Darwin x64 host, pinned Linux evidence and UTC. Seven fresh processes per
+revision/workload ran 40 calls each, alternating revisions. Native API latency
+was a synthetic 2 ms per command; host binaries were forbidden. These are helper
+costs, not vendor-service performance or a full-daemon benchmark.
+
+| Workload | Revision | Median / p95 latency | CPU per 40 calls | Peak RSS | Writes / reads / confirmed |
+| --- | --- | --- | --- | --- | --- |
+| Healthy | Former | 4.84 / 5.28 ms | 22.05 ms | 84.71 MiB | 40 / 40 / 40 |
+| Healthy | Changed | 4.75 / 5.22 ms | 22.72 ms | 83.92 MiB | 40 / 40 / 40 |
+| Lost reply after commit | Former | 6.03 / 6.60 ms | 27.18 ms | 84.21 MiB | 80 / 0 / 0 |
+| Lost reply after commit | Changed | 4.89 / 5.34 ms | 23.77 ms | 85.54 MiB | 40 / 40 / 40 |
+
+CPU and peak RSS are medians across the seven processes; latency pools their
+calls. The useful result is the removed duplicate mutation and successful
+read-back recovery. Small healthy-path timing differences are noise, not a speed
+claim. No new numerical performance gate is proposed.