The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep idle Close pending through native recovery (#1251)
Deeca7741da55f6
diff --git a/cli/e2e/ends.e2e.ts b/cli/e2e/ends.e2e.tsindex ab8b6c2e4..3a65109c5 100644--- a/cli/e2e/ends.e2e.ts+++ b/cli/e2e/ends.e2e.ts@@ -144,6 +144,32 @@ describe('how an agent\'s life ends', () => {client.close()})+ it.each(engines)('%s: a queued Close keeps its intent while native history is held, then recovers', async engine => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `close-held-${engine}`)+ await turn(client, agent.id, 'Keep this conversation through recovery')+ expect(await close(client, agent, 'after_task')).toMatchObject({ deferred: true })+ const paths = transcriptsOf(d, agent.sessionId)+ expect(paths).toHaveLength(1)+ const file = paths[0], original = readFileSync(file, 'utf8')+ const lines = original.split('\n'), first = JSON.parse(lines[0])+ if (engine === 'codex') first.payload.id = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'+ else first.sessionId = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'+ lines[0] = JSON.stringify(first)+ writeFileSync(file, lines.join('\n'))+ // More than two idle checks: the same durable request must keep waiting.+ await new Promise(resolve => setTimeout(resolve, 12_000))+ expect(await row(client, agent.id)).toMatchObject({ status: 'active', sessionId: agent.sessionId,+ closePlan: { state: 'waiting' } })+ expect(client.frames.filter(frame => frame.type === 'agent_deleted' && frame.payload?.agentId === agent.id)).toHaveLength(0)+ expect((await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}')).trim().split('\n')).toContain(agent.tmuxPane)+ writeFileSync(file, original)+ await stopped(client, agent.id, 60_000)+ expect(readFileSync(file, 'utf8')).toContain('Keep this conversation through recovery')+ client.close()+ })+it.each(engines)('%s: closed after its task, it finishes the turn, then closes on its own', async (engine) => {const d = await fresh()const client = await LocalClient.connect(d)diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-close.py b/cli/scripts/handoff-2026-10-08/mutate-native-close.pynew file mode 100644index 000000000..f8e6fac8d--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-native-close.py@@ -0,0 +1,71 @@+"""Native recovery holds must survive automatic cleanup and physical Stop."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+close = 'src/core/agents/close.ts'+service = 'src/lib/closeAgentService.ts'+spec = 'src/core/agents/closeCleanup.spec.ts'+mutations = [+ ('pending admission mistaken for idle', close, '!s.identityHold && !s.admissionHold && !s.interpretationHold',+ '!s.identityHold && !s.interpretationHold', 'automatic cleanup keeps old idle work while admissionHold'),+ ('unrecovered native process mistaken for idle', close, '&& nativeRecoveryReady(s)', '',+ 'automatic cleanup keeps old idle work while recovery'),+ ('old screen adopts new native evidence', close, '&& paneReadIdentity(latest) === identity', '',+ 'an idle screen from before native evidence'),+ ('hold during final screen read ignored', close,+ "const reading = await readScreen(s, screen)\n if (!current()) return 'unknown'", 'const reading = await readScreen(s, screen)',+ 'native admission starting during screen'),+ ('idle Stop discards physical revocation', service, 'if (this.deps.idleCurrent?.(latest) === false) idleRevoked = true', '',+ 'automatic Stop remains revocable at dispatch'),+ ('recovery hold prevents explicit now closure', service, "if (request.mode === 'now') return true", '', 'explicit now still closes'),+ ('pane close ignores revocation while queued', 'src/lib/tmuxBackend.ts',+ ' if (current && !current()) { resolve(undefined); return }', '',+ 'the real Stop path cannot remove a pane'),+ ('pane close result silently retires held work', 'src/lib/stopAgentService.ts',+ " verifyTranscript()\n if (!sameTarget() || options.current?.() === false) {\n throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')\n }\n stoppedAgents.finishResume",+ " verifyTranscript()\n if (!sameTarget()) {\n throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')\n }\n stoppedAgents.finishResume",+ 'the real Stop path retains its row'),+ ('pane proof failure loses retryable identity hold', 'src/lib/stopAgentService.ts',+ ' if (nativeIdentityError) throw nativeIdentityError\n if (panes.some',+ ' if (panes.some', 'the real Stop path cannot remove a pane after transcript'),+ ('late recovery hold permanently fails deferred close', service,+ " if (code === 'STOP_UNCONFIRMED' && idleRevoked && current()) return { error: 'SESSION_NOT_IDLE', activity: 'unknown' }", '',+ 'keeps the same after-task intent waiting'),+]+environment = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+for key in list(environment):+ if key in ['TMUX', 'TMUX_PANE'] or key.startswith('RECORD_'):+ environment.pop(key)+assert Path(environment.get('TMUX_TMPDIR', '/missing')).is_dir(), 'Private TMUX_TMPDIR is required'+++def run(pattern='.'):+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', spec, '--maxWorkers=1', '-t', pattern],+ cwd=cli, env=environment, text=True, capture_output=True, timeout=45)+++baseline = run()+if baseline.returncode:+ raise SystemExit('Baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr)+print('Automatic cleanup and real Close composition baseline passed', flush=True)+failures = []+for label, name, before, after, pattern in mutations:+ path = cli / name+ original = path.read_text()+ assert original.count(before) == 1, (label, original.count(before))+ try:+ path.write_text(original.replace(before, after))+ result = run(pattern)+ output = result.stdout + result.stderr+ if result.returncode == 0 or 'AssertionError' not in output:+ failures.append(label)+ print(label + ': not caught by an assertion\n' + output, flush=True)+ else:+ print(label + ': caught by assertion', flush=True)+ finally:+ path.write_text(original)+if failures:+ raise SystemExit('Mutations without assertion proof: ' + ', '.join(failures))diff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.tsindex f89c2c45e..eef5e537f 100644--- a/cli/src/core/agents/close.spec.ts+++ b/cli/src/core/agents/close.spec.ts@@ -17,14 +17,15 @@ vi.mock('../../lib/closeAgentService.js', async (real) => {const row = (over: Partial<RegisteredSession> = {}) =>({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', registeredAt: 0, ...over }) as RegisteredSession-function setup(over: Partial<ClosingDeps> = {}, advertised: RegisteredSession[] = []) {+function setup(over: Partial<ClosingDeps> = {}, advertised: RegisteredSession[] = [], current = row()) {const deps: ClosingDeps = {readScreen: readInlineScreen,- registry: { advertised: vi.fn(() => advertised) } as unknown as ClosingDeps['registry'],+ registry: { advertised: vi.fn(() => advertised), byAgent: vi.fn(() => current) } as unknown as ClosingDeps['registry'],cleanupTabs: { refresh: vi.fn(async () => {}), isHidden: vi.fn(() => true), assertHidden: vi.fn(async () => {}) },watcher: { pollSession: vi.fn(async () => {}) } as unknown as ClosingDeps['watcher'],captureTerminal: vi.fn(async () => 'screen'),sessionTurnState: vi.fn(() => false),+ nativeRecoveryReady: vi.fn(() => true),openQuestions: { has: vi.fn(() => false) },terminals: { captureRetained: vi.fn(async () => ({ state: 'succeeded', value: 'scrollback' })) } as unknown as ClosingDeps['terminals'],sessionCheckpoints: { save: vi.fn(async () => {}) } as unknown as ClosingDeps['sessionCheckpoints'],@@ -74,6 +75,10 @@ describe('closing agents no window shows', () => {})describe('what an agent is doing', () => {+ it('uses the registry and turn holds when the core has no separate native recovery gate', async () => {+ expect(await setup({ nativeRecoveryReady: undefined }).close.activity(row())).toBe('idle')+ })+it('reads its newest lines first, then its screen, its turn and whether it is asking', async () => {const { deps, close } = setup()expect(await close.activity(row())).toBe('idle')@@ -85,16 +90,18 @@ describe('closing agents no window shows', () => {})it('with no session yet, has no lines to read', async () => {- const { deps, close } = setup()- await close.activity(row({ sessionId: '' }))+ const session = row({ sessionId: '' })+ const { deps, close } = setup({}, [], session)+ await close.activity(session)expect(deps.watcher.pollSession).not.toHaveBeenCalled()})it.each(['ENGINE_STALE_REPLY', 'ENGINE_UNAVAILABLE'])('reads once more after %s, once the restarted worker is linked again', async code => {vi.spyOn(console, 'log').mockImplementation(() => {})const pollSession = vi.fn().mockRejectedValueOnce(Object.assign(new Error(code), { code })).mockResolvedValue(undefined)- const { deps, close } = setup({ watcher: { pollSession } as unknown as ClosingDeps['watcher'] })- expect(await close.activity(row({ engine: 'codex' }))).toBe('idle')+ const session = row({ engine: 'codex' })+ const { deps, close } = setup({ watcher: { pollSession } as unknown as ClosingDeps['watcher'] }, [], session)+ expect(await close.activity(session)).toBe('idle')expect(deps.engineReady).toHaveBeenCalledWith('codex', CLOSE_READ_RECONNECT_MS)expect(pollSession).toHaveBeenCalledTimes(2)})diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.tsindex 814e3cbdb..d2c38e5d4 100644--- a/cli/src/core/agents/close.ts+++ b/cli/src/core/agents/close.ts@@ -9,11 +9,12 @@ import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'import { CloseAgentService, inspectCloseActivity, type CloseAgentServiceDeps, type CloseMode } from '../../lib/closeAgentService.js'import type { OpenTabProtection } from '../../lib/openTabProtection.js'import { sid } from '../../lib/log.js'-import { projectDisplayName, type registry } from '../../lib/registry.js'+import { projectDisplayName, type RegisteredSession, type registry } from '../../lib/registry.js'import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'import type { Watcher } from '../../watcher/watcher.js'+import { paneReadIdentity } from '../transcripts/readIdentity.js'export interface ClosingDeps {readScreen: ScreenReader@@ -22,6 +23,8 @@ export interface ClosingDeps {watcher: Pick<Watcher, 'pollSession'>captureTerminal: (target: string, historyLines?: number) => Promise<string | null>sessionTurnState: (sessionId: string) => boolean | undefined+ /** Synchronous core recovery authority, never a transcript or service answer. */+ nativeRecoveryReady?: (session: RegisteredSession) => boolean/** What is still being asked, by session. */openQuestions: { has(sessionId: string): boolean }terminals: Pick<TerminalBackendCoordinator, 'captureRetained'>@@ -39,8 +42,10 @@ export const CLOSE_READ_RECONNECT_MS = 10_000export function createAgentClosing({readScreen, registry, cleanupTabs, watcher, captureTerminal, sessionTurnState, openQuestions, terminals, sessionCheckpoints,- stopAgent, announceSession, engineReady, stoppedAgents,+ stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true,}: ClosingDeps) {+ const ready = (s: RegisteredSession): boolean =>+ !s.identityHold && !s.admissionHold && !s.interpretationHold && nativeRecoveryReady(s)/*** Read what the transcript has that the tail has not delivered yet. A close sent just as the engine's worker* restarted found its live read refused as stale (seen end to end: ENGINE_STALE_REPLY, the close failed).@@ -67,10 +72,24 @@ export function createAgentClosing({registry,openTabs: cleanupTabs,activity: async s => {+ // Automatic cleanup can see an old idle parser while native admission or+ // recovery deliberately holds its reader. Keep that work through every+ // await; a fresh empty composer alone does not make it safe to close.+ const identity = paneReadIdentity(s)+ const current = () => {+ const latest = registry.byAgent(s.agentId)+ return !!latest && paneReadIdentity(latest) === identity && ready(latest)+ }+ if (!current()) return 'unknown'if (s.sessionId) await drain(s)+ if (!current()) return 'unknown'const screen = await captureTerminal(s.agentId, 80)- return inspectCloseActivity(s, await readScreen(s, screen), sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))+ if (!current()) return 'unknown'+ const reading = await readScreen(s, screen)+ if (!current()) return 'unknown'+ return inspectCloseActivity(s, reading, sessionTurnState(s.sessionId), openQuestions.has(s.sessionId))},+ idleCurrent: s => ready(s) && (!s.sessionId || sessionTurnState(s.sessionId) === false) && !openQuestions.has(s.sessionId),checkpoint: async (s, phase) => {const captured = phase === 'before' ? await terminals.captureRetained(s, { historyLines: 2000 }) : nullawait sessionCheckpoints.save(s, { screen: captured?.state === 'succeeded' ? captured.value : null })diff --git a/cli/src/core/agents/closeCleanup.spec.ts b/cli/src/core/agents/closeCleanup.spec.tsnew file mode 100644index 000000000..e9e916915--- /dev/null+++ b/cli/src/core/agents/closeCleanup.spec.ts@@ -0,0 +1,246 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { ScreenReading } from '../../engines/facets/screen.js'+import { controlTranscriptEvidence } from '../../engines/transcriptBindings.js'+import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'+import { createStopAgentService, type StopAgentServiceDeps } from '../../lib/stopAgentService.js'+import { AgentRestartCoordinator } from '../../lib/restartAgent.js'+import { TmuxBackend } from '../../lib/tmuxBackend.js'+import { tmuxControlGate } from '../../lib/tmuxControlGate.js'+import { assumeTmuxVersion, resetTmuxVersionCache } from '../../lib/tmuxVersion.js'+import { createAgentCleanup, IDLE_CLOSE_MS } from '../../services/agentCleanup.js'+import { fakeCore } from '../../testing/fakeCore.js'+import { createAgentClosing, type ClosingDeps } from './close.js'++// Native identity readings and OS process I/O are fixtures. The actual close,+// Stop service, tmux backend and notification queue compose below unchanged.+const native = vi.hoisted(() => ({ execFile: vi.fn(), spawn: vi.fn() }))+vi.mock('node:child_process', async original => ({ ...await original<object>(), ...native }))+vi.mock('child_process', async original => ({ ...await original<object>(), ...native }))+vi.mock('../../lib/captureResumeIdentity.js', () => ({ captureResumeIdentity: async (s: RegisteredSession) => structuredClone(s) }))+vi.mock('../../lib/deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: async () => 'gone' }))+vi.mock('../../engines/transcriptBindings.js', async original => ({ ...await original<object>(),+ controlTranscriptEvidence: vi.fn(),+}))+const dispose: Array<() => void> = []+afterEach(() => { for (const stop of dispose.splice(0)) stop(); vi.restoreAllMocks(); resetTmuxVersionCache() })+const idleScreen = (): ScreenReading => ({ busy: false, activity: null, stoppedGoal: false,+ pane: { idle: true, plan: false, dialog: false, draft: false }, question: null, messageHold: null, teamHold: null })++// The first group exercises each close await; the physical group additionally+// installs the real Stop service and tmux queue before reaching the OS stub.+function setup(physical = false) {+ const dir = mkdtempSync(join(tmpdir(), 'native-cleanup-'))+ dispose.push(() => rmSync(dir, { recursive: true, force: true }))+ let now = Date.parse('2026-10-12T12:00:00Z'), ready = true+ let transcriptReady = true+ vi.mocked(controlTranscriptEvidence).mockReset().mockImplementation((_engine, _id, path) => ({ path,+ verify: () => { if (!transcriptReady) throw new IdentityReadUnavailable('the original transcript proof changed') },+ }))+ let session: RegisteredSession | undefined = {+ schemaVersion: 2, active: true, agentId: 'child', sessionId: 'conversation', engine: 'cursor', cwd: '/work/app',+ registeredAt: 0, boundAt: 0, runtimes: [{ backend: 'tmux', paneId: '%1' }], startedBy: 'agent', parentAgentId: 'parent',+ transcriptPath: '/work/app/transcript.jsonl', projectDir: '/work/app', primaryRuntimeKey: 'tmux:%1', tmuxPane: '%1',+ source: null, title: null, model: null, cliVersion: null, processIdentity: { pid: 42, executable: 'cursor', startMarker: 'fixture-birth' },+ touchedAt: 0, lastHookAt: 0, lastTranscriptAt: 0,+ }+ const registry = {+ byAgent: (id: string) => id === session?.agentId ? session : undefined,+ advertised: () => session ? [session] : [], list: () => session ? [session] : [],+ setClosePlan: vi.fn((_id: string, plan: RegisteredSession['closePlan'] | null) => { session!.closePlan = plan ?? undefined; return session }),+ } as unknown as ClosingDeps['registry']+ const stopped = vi.fn()+ const beforeSignal = vi.fn(async () => {})+ native.execFile.mockReset().mockImplementation((file: string, args: string[], _options: unknown, done: (error: null, out: string, err: string) => void) => {+ expect(file).toBe('tmux')+ expect(args).toEqual(['kill-pane', '-t', '%1'])+ queueMicrotask(() => done(null, '', ''))+ return { kill: vi.fn() }+ })+ native.spawn.mockReset().mockImplementation(() => { throw Error('No fixture may spawn a host process') })+ const stopDeps: StopAgentServiceDeps = {+ registry: { resolve: () => session },+ stoppedAgents: { save: vi.fn(), finishResume: vi.fn() } as unknown as StopAgentServiceDeps['stoppedAgents'],+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: new TmuxBackend(),+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },+ forgetSession: vi.fn(() => { stopped(); session = undefined }), markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: vi.fn(async () => {}),+ }+ const deps = {+ registry,+ cleanupTabs: { refresh: vi.fn(async () => {}), isHidden: () => true, assertHidden: vi.fn(async () => {}) },+ watcher: { pollSession: vi.fn(async () => {}) }, captureTerminal: vi.fn(async () => 'empty composer'),+ readScreen: vi.fn(async () => idleScreen()), sessionTurnState: vi.fn((): boolean | undefined => false),+ nativeRecoveryReady: () => ready,+ openQuestions: { has: vi.fn(() => false) }, engineReady: vi.fn(async () => {}),+ terminals: { captureRetained: vi.fn(async () => ({ state: 'succeeded' as const, value: 'empty composer' })) },+ sessionCheckpoints: { save: vi.fn(async () => {}) }, announceSession: vi.fn(),+ stopAgent: physical ? createStopAgentService(stopDeps) : vi.fn(async (_id, options) => {+ await options.checkpoint!(session!, 'before')+ await options.beforeStop!(session!)+ await beforeSignal()+ if (!options.current!()) throw Object.assign(new Error('The idle close was revoked.'), { code: 'STOP_UNCONFIRMED' })+ stopped()+ }),+ } satisfies ClosingDeps+ const closing = createAgentClosing(deps)+ dispose.push(() => closing.closeAgentService.dispose())+ const closeStarted = vi.fn(async (_id: string, mode: 'idle' | 'now') => closing.closeAgentService.request({+ agentId: 'child', sessionId: 'conversation', createdAt: new Date(0).toISOString(), mode,+ }))+ const cleanup = createAgentCleanup(fakeCore({+ dataDir: dir, agents: { live: registry.list, resolve: registry.byAgent, closeStarted, lastActivity: async () => 0 },+ }), { now: () => now, log: vi.fn(), every: () => () => {} })+ dispose.push(() => cleanup.port.stop())+ return { deps, stopDeps, closing, cleanup, closeStarted, stopped, beforeSignal, row: () => session!,+ replace: (value: RegisteredSession | undefined) => { session = value },+ ready: (value: boolean) => { ready = value },+ transcriptReady: (value: boolean) => { transcriptReady = value },+ clean: async () => { await cleanup.look(); now += IDLE_CLOSE_MS; await cleanup.look() },+ }+}++it.each(['admissionHold', 'interpretationHold', 'identityHold', 'recovery'] as const)(+ 'automatic cleanup keeps old idle work while %s is unresolved; explicit now still closes', async hold => {+ const t = setup()+ if (hold === 'recovery') t.ready(false)+ else t.row()[hold] = 'Waiting for original native evidence.'+ await t.clean()+ expect(t.closeStarted).toHaveBeenCalledWith('child', 'idle')+ expect(t.stopped).not.toHaveBeenCalled()+ expect(t.deps.sessionCheckpoints.save).not.toHaveBeenCalled()+ expect(t.deps.watcher.pollSession).not.toHaveBeenCalled()+ expect(await t.closeStarted('child', 'now')).toEqual({ closed: true })+ expect(t.stopped).toHaveBeenCalledOnce()+ })++it.each(['admission', 'recovery', 'working', 'evidence', 'transcript'] as const)(+ 'the real Stop path cannot remove a pane after %s changes in the tmux queue', async change => {+ const t = setup(true)+ assumeTmuxVersion({ major: 3, minor: 4 })+ const release = await tmuxControlGate.enter('attach')+ const closing = t.closeStarted('child', 'idle')+ try {+ await vi.waitFor(() => expect(tmuxControlGate.state.waiting).toBe(1))+ expect(native.execFile).not.toHaveBeenCalled()+ if (change === 'admission') t.row().admissionHold = 'Waiting for original native admission.'+ if (change === 'recovery') t.ready(false)+ if (change === 'working') t.deps.sessionTurnState.mockReturnValue(true)+ if (change === 'evidence') t.row().evidenceRevision = 1+ if (change === 'transcript') t.transcriptReady(false)+ } finally { release() }+ expect(await closing).toMatchObject({ error: change === 'transcript' ? 'IDENTITY_UNAVAILABLE'+ : change === 'evidence' ? 'STOP_UNCONFIRMED' : 'SESSION_NOT_IDLE' })+ expect(native.execFile).not.toHaveBeenCalled()+ expect(t.stopped).not.toHaveBeenCalled()+ expect(t.stopDeps.stoppedAgents.finishResume).not.toHaveBeenCalled()+ expect(t.row()).toMatchObject({ agentId: 'child', sessionId: 'conversation' })+ })++it('the real Stop path retains its row when native recovery becomes unknown after pane dispatch', async () => {+ const t = setup(true)+ assumeTmuxVersion({ major: 3, minor: 7 })+ native.execFile.mockImplementationOnce((_file, _args, _options, done) => {+ t.ready(false)+ queueMicrotask(() => done(null, '', ''))+ return { kill: vi.fn() }+ })+ expect(await t.closeStarted('child', 'idle')).toMatchObject({ error: 'SESSION_NOT_IDLE' })+ expect(native.execFile).toHaveBeenCalledOnce()+ expect(t.stopped).not.toHaveBeenCalled()+ expect(t.stopDeps.stoppedAgents.finishResume).not.toHaveBeenCalled()+ expect(t.row()).toMatchObject({ agentId: 'child' })+})++it('the real Stop path honors explicit now despite pending admission', async () => {+ const t = setup(true)+ assumeTmuxVersion({ major: 3, minor: 7 })+ t.row().admissionHold = 'Waiting for original native admission.'+ expect(await t.closeStarted('child', 'now')).toEqual({ closed: true })+ expect(native.execFile).toHaveBeenCalledOnce()+ expect(t.stopped).toHaveBeenCalledOnce()+})++it.each(['drain', 'capture', 'screen', 'checkpoint'] as const)(+ 'native admission starting during %s prevents automatic Stop', async phase => {+ const t = setup()+ const held = async () => { t.row().admissionHold = 'Waiting for native admission.' }+ if (phase === 'drain') t.deps.watcher.pollSession.mockImplementationOnce(held)+ if (phase === 'capture') t.deps.captureTerminal.mockImplementationOnce(async () => { await held(); return 'empty composer' })+ if (phase === 'screen') t.deps.readScreen.mockImplementationOnce(async () => { await held(); return idleScreen() })+ if (phase === 'checkpoint') t.deps.sessionCheckpoints.save.mockImplementationOnce(held)+ await t.clean()+ expect(t.stopped).not.toHaveBeenCalled()+ if (phase !== 'checkpoint') expect(t.deps.sessionCheckpoints.save).not.toHaveBeenCalled()+ expect(await t.closeStarted.mock.results[0].value).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'unknown' })+ })++it('requires known turn state after recovery, and closes once current work is confirmed idle', async () => {+ const t = setup()+ t.deps.sessionTurnState.mockReturnValueOnce(undefined)+ await t.clean()+ expect(t.stopped).not.toHaveBeenCalled()+ expect(await t.closeStarted('child', 'idle')).toEqual({ closed: true })+ expect(t.stopped).toHaveBeenCalledOnce()+})++it.each(['replaced', 'gone', 'evidence', 'recovery'] as const)(+ 'an idle screen from before native %s cannot authorize close', async change => {+ const t = setup()+ t.deps.readScreen.mockImplementationOnce(async () => {+ if (change === 'replaced') t.replace({ ...t.row(), boundAt: 1 })+ if (change === 'gone') t.replace(undefined)+ if (change === 'evidence') t.row().evidenceRevision = 1+ if (change === 'recovery') t.ready(false)+ return idleScreen()+ })+ await t.clean()+ expect(t.stopped).not.toHaveBeenCalled()+ expect(t.deps.sessionCheckpoints.save).not.toHaveBeenCalled()+ })++it.each(['admissionHold', 'interpretationHold', 'identityHold', 'recovery', 'running', 'unknown', 'question'] as const)(+ 'automatic Stop remains revocable at dispatch after %s changes', async change => {+ const t = setup()+ t.beforeSignal.mockImplementationOnce(async () => {+ if (change === 'recovery') t.ready(false)+ else if (change === 'running') t.deps.sessionTurnState.mockReturnValue(true)+ else if (change === 'unknown') t.deps.sessionTurnState.mockReturnValue(undefined)+ else if (change === 'question') t.deps.openQuestions.has.mockReturnValue(true)+ else t.row()[change] = 'Waiting for original native evidence.'+ })+ await t.clean()+ expect(t.stopped).not.toHaveBeenCalled()+ expect(await t.closeStarted.mock.results[0].value).toMatchObject({ error: 'SESSION_NOT_IDLE' })+ expect(await t.closeStarted('child', 'now')).toEqual({ closed: true })+ expect(t.stopped).toHaveBeenCalledOnce()+ })++it('keeps the same after-task intent waiting when a late recovery hold revokes Stop, then completes it', async () => {+ let now = Date.parse('2026-10-12T12:00:00Z')+ vi.spyOn(Date, 'now').mockImplementation(() => now)+ const t = setup(true)+ assumeTmuxVersion({ major: 3, minor: 4 })+ expect(await t.closing.closeAgentService.request({ agentId: 'child', sessionId: 'conversation',+ createdAt: new Date(0).toISOString(), mode: 'after_task' })).toEqual({ deferred: true })+ const plan = t.row().closePlan!+ await t.closing.closeAgentService.tick()+ now += 5_000+ const release = await tmuxControlGate.enter('attach')+ const tick = t.closing.closeAgentService.tick()+ try {+ await vi.waitFor(() => expect(tmuxControlGate.state.waiting).toBe(1))+ t.ready(false)+ } finally { release() }+ await tick+ expect(native.execFile).not.toHaveBeenCalled()+ expect(t.row().closePlan).toEqual(plan)+ expect(t.row().closePlan?.state).toBe('waiting')+ t.ready(true)+ now += 5_000+ await t.closing.closeAgentService.tick()+ expect(native.execFile).toHaveBeenCalledOnce()+ expect(t.stopped).toHaveBeenCalledOnce()+})diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex 302679f21..9565843d8 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -103,6 +103,8 @@ function matches(s: RegisteredSession | undefined, request: AgentCloseRequest, aexport interface CloseAgentServiceDeps {registry: Pick<typeof liveRegistry, 'byAgent' | 'list' | 'setClosePlan'>activity(s: RegisteredSession): Promise<CloseActivity>+ /** Cheap revocation after the final activity read, at each physical Stop boundary. */+ idleCurrent?(s: RegisteredSession): booleancheckpoint(s: RegisteredSession, phase: 'before' | 'after'): Promise<void>stop(agentId: string, options: StopAgentOptions): Promise<void>changed(s: RegisteredSession): void@@ -235,6 +237,7 @@ export class CloseAgentService {private async attempt(request: AgentCloseRequest, target: string, revision: number, withoutConversation = false): Promise<AgentCloseResult> {let unkept = false+ let idleRevoked = falseconst current = () => {const s = this.deps.registry.byAgent(request.agentId)return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision@@ -268,7 +271,15 @@ export class CloseAgentService {if (request.mode === 'idle' && activity !== 'idle') return { error: 'SESSION_NOT_IDLE', activity }await this.deps.stop(s.agentId, {...(withoutConversation ? { withoutConversation: () => { unkept = true } } : {}),- current: () => !!current(),+ current: () => {+ const latest = current()+ if (!latest) return false+ if (request.mode === 'now') return true+ // A hold after beforeStop also revokes this attempt. Remember it so+ // clearing the hold cannot revive an old command waiting in a queue.+ if (this.deps.idleCurrent?.(latest) === false) idleRevoked = true+ return !idleRevoked+ },checkpoint: (s, phase) => this.deps.checkpoint(s, phase),confirmUnusedConversation: async captured => {// A missing ID alone could be failed discovery of active work. Only@@ -296,6 +307,10 @@ export class CloseAgentService {} catch (error) {if (error instanceof CloseRefused) return { error: 'SESSION_NOT_IDLE', activity: error.activity }const code = (error as { code?: unknown })?.code+ // Stop keeps an uncertain physical outcome as STOP_UNCONFIRMED. When its+ // own guard specifically refused an idle close, retain the queued intent+ // exactly as beforeStop does; a service hold must never make it failed.+ if (code === 'STOP_UNCONFIRMED' && idleRevoked && current()) return { error: 'SESSION_NOT_IDLE', activity: 'unknown' }return { error: typeof code === 'string' ? code : 'CLOSE_FAILED',detail: error instanceof Error ? error.message : 'Could not close this session safely. Please try again.' }}diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.tsindex fd32ded79..ed6d6123d 100644--- a/cli/src/lib/stopAgentService.spec.ts+++ b/cli/src/lib/stopAgentService.spec.ts@@ -81,7 +81,7 @@ it('cancels immediately, then joins the core pane commit before capturing the rurow.runtimes = [{ backend: 'tmux', paneId: '%90' }]committed()await stopping- expect(deps.tmuxBackend!.kill).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%90' })+ expect(deps.tmuxBackend!.kill).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%90' }, expect.any(Function))})it('storage failure leaves the live process and registry untouched', async () => {vi.spyOn(stoppedAgents, 'save').mockImplementation(() => { throw new Error('disk full') })@@ -248,7 +248,7 @@ it('only signals through the validated process deleter and does not erase a newerow.runtimes.push({ backend: 'unknown', endpointId: 'fixture', paneId: '2' } as any)await createStopAgentService(deps)(row.agentId)expect(signal).toHaveBeenCalledExactlyOnceWith(77, 'SIGTERM'); expect(deps.stopJobs.has(row.agentId)).toBe(true)- expect(deps.tmuxBackend!.kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%44' })+ expect(deps.tmuxBackend!.kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%44' }, expect.any(Function))})it.each(['claude', 'codex'] as const)('captures an unbound %s conversation before deleting its process', async engine => {diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.tsindex 4a80907e3..a9a9563e7 100644--- a/cli/src/lib/stopAgentService.ts+++ b/cli/src/lib/stopAgentService.ts@@ -173,15 +173,21 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {}const panes = await Promise.allSettled(tmuxBackend? s.runtimes.filter((runtime): runtime is TmuxRuntimeRef => runtime.backend === 'tmux')- .map(runtime => tmuxBackend.kill(runtime)) : [])+ .map(runtime => tmuxBackend.kill(runtime, () => {+ // tmux's notification gate can wait after the preceding check.+ // Carry the original Close permission to the actual kill command.+ verifyTranscript()+ return sameTarget() && options.current?.() !== false+ })) : [])+ if (nativeIdentityError) throw nativeIdentityErrorif (panes.some(result => result.status !== 'fulfilled' || result.value.state !== 'succeeded')|| (isTerminalEngine(s.engine) && !panes.length)) {throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try stopping again.')}- if (!sameTarget()) {+ verifyTranscript()+ if (!sameTarget() || options.current?.() === false) {throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')}- verifyTranscript()stoppedAgents.finishResume(sessionId)if (s.processIdentity) agentReconciler.suppress(s)// This publishes agent_deleted. It must follow confirmed termination, or adiff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex 0dad5ea1c..45a698fd8 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -23,7 +23,8 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimreadonly instanceId: stringcreate(request: TerminalCreateRequest): Promise<TerminalCreateResult<Ref>>- kill(runtime: Ref): Promise<TerminalActionResult>+ /** Recheck the original Stop permission after backend waits, at command dispatch. */+ kill(runtime: Ref, current?: () => boolean): Promise<TerminalActionResult>inventory(): Promise<TerminalInventoryResult>/** Current user-visible titles keyed by backend-scoped terminal route key. */titles(): Promise<TerminalReadResult<Map<string, string>>>diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex b494d3ee6..895e79b0c 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -323,15 +323,17 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return terminalActionNotStarted('The waiting pane no longer has this adoption identity')}- async kill(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {+ async kill(runtime: TmuxRuntimeRef, current?: () => boolean): Promise<TerminalActionResult> {if (!/^%\d+$/.test(runtime.paneId)) return terminalActionNotStarted('invalid tmux pane identity')// Discovered harnesses can share a tmux session with unrelated work. The// canonical pane id is the entire target; never widen this to kill-session.// The last pane gone closes its session, a notification to every control client: on a tmux before// 3.7, not while one attaches (tmuxControlGate.ts).- const ok = await inTmuxRoom('notify', () => new Promise<boolean>((resolve) => {+ const ok = await inTmuxRoom('notify', () => new Promise<boolean | undefined>((resolve) => {+ if (current && !current()) { resolve(undefined); return }run('tmux', ['kill-pane', '-t', runtime.paneId], { timeout: 5_000 }, (error) => resolve(!error))}))+ if (ok === undefined) return terminalActionNotStarted('The harness changed before pane close')if (ok) return TERMINAL_ACTION_SUCCEEDED// The engine may have exited and removed its pane before the parallel PID// check completed. Only authoritative inventory makes that an idempotent success.diff --git a/cli/src/lib/unusedCodexClose.spec.ts b/cli/src/lib/unusedCodexClose.spec.tsindex aec292b9b..1010b7345 100644--- a/cli/src/lib/unusedCodexClose.spec.ts+++ b/cli/src/lib/unusedCodexClose.spec.ts@@ -76,7 +76,7 @@ it.each(['idle', 'now'] as const)('closes an unused companion with a shared Codeexpect(await service.request({ ...request, mode })).toEqual({ closed: true })expect(terminateDeletedAgent).toHaveBeenCalledOnce()expect(vi.mocked(terminateDeletedAgent).mock.calls[0][0].processIdentity?.pid).toBe(99)- expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' })+ expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' }, expect.any(Function))expect(registry.byAgent(row.agentId)).toBeUndefined()const manifest = JSON.parse(readFileSync(join(checkpointDirectory, readdirSync(checkpointDirectory).find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))expect(JSON.parse(readFileSync(join(checkpointDirectory, manifest.file), 'utf8')).screen).toBe(emptyComposer)@@ -109,7 +109,7 @@ it('closes the saved shell when an unbound Codex client exits before discovery cexpect(await service.request({ ...request, mode: 'inspect' })).toEqual({ activity: 'unknown' })expect(await service.request({ ...request, mode: 'idle' })).toMatchObject({ error: 'SESSION_NOT_IDLE' })expect(await service.request({ ...request, mode: 'now' })).toEqual({ closed: true })- expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' })+ expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' }, expect.any(Function))expect(registry.byAgent(row.agentId)).toBeUndefined()const manifest = JSON.parse(readFileSync(join(checkpointDirectory, readdirSync(checkpointDirectory).find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))expect(JSON.parse(readFileSync(join(checkpointDirectory, manifest.file), 'utf8')).screen).toBe(screen)@@ -125,7 +125,7 @@ it.runIf(process.env.RUN_REAL_TMUX_DISCOVERY === '1')('closes only the exited clvi.mocked(processRows).mockImplementation(actualTmux.processRows)vi.mocked(checkPidRuntime).mockImplementation(actualStop.checkPidRuntime)vi.mocked(terminateDeletedAgent).mockImplementation(actualStop.terminateDeletedAgent)- killPane.mockImplementation(runtime => new TmuxBackend().kill(runtime))+ killPane.mockImplementation((runtime, current) => new TmuxBackend().kill(runtime, current))try {const sibling = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'close-fixture', 'sleep 600')const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`diff --git a/docs/research/2026-10-12-idle-close-recovery.md b/docs/research/2026-10-12-idle-close-recovery.mdnew file mode 100644index 000000000..90c6d38dc--- /dev/null+++ b/docs/research/2026-10-12-idle-close-recovery.md@@ -0,0 +1,32 @@+# Idle Close during native recovery++Automatic cleanup could read an old idle parser and an empty composer while+native admission or interpretation was held. Close now checks the live original+pane and evidence before and after each asynchronous read. Identity, admission+and interpretation holds mean unknown activity. Explicit Close now remains an+explicit request; it still must retain the original conversation safely.++The permission also reaches the actual Stop boundaries. A tmux notification+queue cannot outlive it, and an unconfirmed pane result cannot retire the row.+A lost transcript proof keeps its retryable identity error. A late idle-only+revocation retains the same Close-after-task request as waiting, so recovery can+complete it without a new request. Once revoked, an old attempt cannot resume+just because the hold clears.++The regression composes automatic cleanup, Close, the real Stop service, tmux+backend and notification gate with fixture native readings and mocked OS I/O.+Eleven initial activity assertions and five physical-boundary assertions failed+before their fixes. Ten deliberate mutations cover the guards and retry behavior.+Private daemon cases cover Claude Code and Codex queued Close through unavailable+history, recovery, and ordinary Close/resume and agent cleanup. Exact validation+receipts and the independent review belong in the PR body.++This fix is isolated from draft #1172. It does not activate its unfinished native+turn controller or durable Cancel/rearm path. The optional recovery gate allows+that integration to supply its own authority later; current main uses its registry+holds. The owner requested this finished fix be merged and further daemon work+paused afterward. No release is authorized.++Work on this correction began October 12 at approximately 08:06 UTC. Implementation,+validation, independent review/CI waiting and merge are accounted for separately+in the PR. Publication is zero.