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
Close a harness that is still starting; wait says "closed (you closed it)" (#1229)
Dee0696e0fc2bcd
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.tsindex 3b8b0becf..b63f4b122 100644--- a/cli/e2e/agentClient.e2e.ts+++ b/cli/e2e/agentClient.e2e.ts@@ -11,6 +11,7 @@ import { execFileSync, spawn } from 'node:child_process'import { createInterface } from 'node:readline'import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { join } from 'node:path'+import { pathToFileURL } from 'node:url'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'@@ -247,6 +248,46 @@ describe('Harness for agents, end to end', () => {client.close()})+ // Codex 0.162.1 in a clean macOS VM (2026-10-12): `harness close <it> --now` a second after `harness new` answered+ // "Conversation identity is held: the native control descriptor type is unavailable." and the harness kept working,+ // because for its first seconds every read of the Codex process was refused. The fake Codex holds such a descriptor+ // for as long, and its first hook is as late: until then nothing could bind its conversation, as there.+ it.each([+ ['binds its conversation a few seconds in', 6_000, 'Closed pong. Its conversation is kept.'],+ ['never binds while the close waits', 120_000, 'Closed pong. It was still starting, so no conversation was kept.'],+ ] as const)('an agent closes a Codex it started a second ago, which %s', async (_, unboundMs, said) => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).href+ const config = { ...d.engineConfig, unreadableDescriptorMs: unboundMs, firstHookDelayMs: unboundMs }+ writeFileSync(join(d.root, 'bin', 'codex'), `#!${process.execPath}\nimport(${JSON.stringify(module)}).then((m) => m.run('codex', ${JSON.stringify(config)}))\n`, { mode: 0o755 })+ await d.start()+ const client = await LocalClient.connect(d)+ const run = (...args: string[]) => harness(d, '', args, { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'outside-session' })++ const started = await run('new', 'codex', 'pong', '--name', 'pong', '--', 'Reply with pong')+ expect(started.code, started.out + started.err).toBe(0)+ // The same start asked again is the same harness, started "just now", not "1 min ago".+ const again = await run('new', 'codex', 'pong', '--name', 'pong', '--', 'Reply with pong')+ expect(again.out + again.err).toContain('you started it just now')+ const row = async () => ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents).find((a) => a.name === 'pong')+ const live = await until('pong running', async () => { const r = await row(); return r?.status === 'active' && r.tmuxPane ? r : null }, 60_000, 250)+ await new Promise((resolve) => setTimeout(resolve, 1_000))+ const closed = await run('close', 'pong', '--now')+ expect(closed.err).not.toMatch(/descriptor|identity is held/)+ expect(closed.code, closed.out + closed.err).toBe(0)+ expect(closed.out.trim()).toBe(said)+ const stopped = await until('pong stopped', async () => { const r = await row(); return !r || r.status === 'stopped' ? r ?? {} : null }, 30_000, 250)+ if (unboundMs < 10_000) expect(stopped.sessionId).toBeTruthy()+ expect(await enginesIn(d, String(live.tmuxPane))).toBe('')+ // It closed it itself: `wait` says so, and is not a failure.+ const waited = await run('wait', 'pong', '--timeout', '30s')+ expect(waited.out.trim()).toBe('pong: closed (you closed it)')+ expect(waited.code, waited.out + waited.err).toBe(0)+ client.close()+ }, 180_000)+it('an agent that uses MCP does the same through harness mcp', async () => {const d = await IsolatedDaemon.create()daemon = d@@ -432,6 +473,13 @@ describe('Harness for agents, end to end', () => {})})+/** The fake engines still running in [pane]'s process tree, or '' once none is: a pane closed with them has no tree. */+async function enginesIn(d: IsolatedDaemon, pane: string): Promise<string> {+ const panes = await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}').catch(() => '')+ if (!panes.split('\n').includes(pane)) return ''+ return (await commandsIn(d, pane)).split('\n').filter((line) => /^(?:codex|claude)\s/.test(line)).join('\n')+}+/** [text] as a pattern that matches it whatever `ps` prints for a character outside ASCII. */const ascii = (text: string): string => [...text].map((ch) => /[ -~]/.test(ch) ? ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '.+?').join('')diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex 71270a82b..f5a32819d 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -47,6 +47,8 @@ export interface EngineConfig {version?: stringwithout?: string[]startDelayMs?: number+ /** Hold a descriptor the daemon's process reader cannot classify for this long once started (Codex 0.162.1's first seconds). */+ unreadableDescriptorMs?: number/** Hold startup before the transcript opens until this disposable path's .release file exists. */startupGate?: stringfirstHookDelayMs?: numberdiff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 2fa78b960..7f73dcdac 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -45,7 +45,10 @@// rewriting its wrapper: `version` is what it reports and writes, `without` lists the flags and// subcommands that release no longer has, `updateAvailable` (Codex) names a newer release it asks to update// to before it starts, and `startDelayMs` is how long it takes, once started, before-// it draws or announces anything (an engine's first run after an update). `firstHookDelayMs` is how long+// it draws or announces anything (an engine's first run after an update). `unreadableDescriptorMs` is how long,+// once started, it holds a descriptor the daemon's process reader has no name for, as Codex 0.162.1 did for its+// first seconds in a clean macOS VM (2026-10-12): every read of its process was refused until then ("the native+// control descriptor type is unavailable"). `firstHookDelayMs` is how long// its first SessionStart takes to reach the daemon once the engine is up: the hook command starting on a// loaded machine, while the daemon has already found the engine and its conversation. `root` is the// test's throwaway root, the only place whose hooks it will run, and `hookLog` where it notes every hook@@ -61,7 +64,7 @@// child in the same process group and terminal (`codexWrapper`).import { execFileSync, spawn } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, symlinkSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'import { dirname, isAbsolute, join, relative, resolve } from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'@@ -114,6 +117,23 @@ async function codexWrapper(config) {else process.exit(ended.code ?? 1)}+/**+ * A descriptor the daemon's process reader cannot classify, held for [ms] (`unreadableDescriptorMs`). Which one the real+ * Codex held is not known; what the daemon met is: a descriptor of a kind its reader refuses. On macOS that is a+ * symbolic link opened as itself (O_SYMLINK: a vnode of a type the reader has no name for, the same refusal); on Linux a+ * network namespace, whose target (`net:[…]`) is no path, socket, pipe or anonymous inode.+ */+function holdUnreadableDescriptor(config, ms) {+ let fd+ if (process.platform === 'darwin') {+ const link = join(config.root, `unreadable-descriptor-${process.pid}`)+ if (!within(config.root, link)) throw new Error('unreadable descriptor outside its throwaway home')+ symlinkSync('nothing', link)+ fd = openSync(link, constants.O_RDONLY | constants.O_SYMLINK)+ } else fd = openSync('/proc/self/ns/net', 'r')+ setTimeout(() => closeSync(fd), ms).unref()+}+export async function run(engine, config = {}, { native = false } = {}) {if (engine === 'codex' && !native) return codexWrapper(config)const args = process.argv.slice(2)@@ -177,6 +197,7 @@ export async function run(engine, config = {}, { native = false } = {}) {// terminal still in line mode keeps at most 1 KiB of a line, so a paste that arrived before the// engine was ready lost the rest of itself (measured: 1,018 of 2,406 characters).process.stdin.setRawMode?.(true)+ if (config.unreadableDescriptorMs) holdUnreadableDescriptor(config, config.unreadableDescriptorMs)// Slow to start, as an engine is on its first run after an update: the process is there and holds// the terminal, and nothing is drawn, announced or read until it is ready.// October 6 sibling-conversation incident: hold startup before this process has a transcript, whilediff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.tsindex 550b38c87..b8e0231b6 100644--- a/cli/src/agentClient/commands.spec.ts+++ b/cli/src/agentClient/commands.spec.ts@@ -381,6 +381,40 @@ describe('harness wait', () => {expect(g.out[0]).toBe('x: gone · it is gone')})+ // A Codex lead closed its harness, then waited on it as it had queued: "Failed (exit 4) … stopped · it was stopped".+ it('says a harness the caller closed was closed by it, and is no failure; another\'s close still is', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead'), frame('kid', { status: 'stopped' }), frame('gone')]+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ started(h.ledger, 'lead', 'gone')+ h.ledger.append({ at: NOW, by: { machineId: 'm', agentId: 'lead' }, closed: { machineId: 'm', agentId: 'kid' } })+ expect(await waitCommand(['kid'], h.deps)).toBe(EXIT.ok)+ expect(h.out).toEqual(['kid: closed (you closed it)'])+ expect(await waitCommand(['kid', '--json'], h.deps)).toBe(EXIT.ok)+ expect(JSON.parse(h.out[1])).toEqual({ harnesses: [{ name: 'kid', id: 'kid', state: 'closed' }] })+ // Gone from the list after it closed it: still its close.+ h.ledger.append({ at: NOW, by: { machineId: 'm', agentId: 'lead' }, closed: { machineId: 'm', agentId: 'gone' } })+ let n = 0+ d.extra.agents_list = () => ({ agents: n++ < 1 ? d.frames : [] })+ const g = harness(d)+ expect(await waitCommand(['gone'], g.deps)).toBe(EXIT.ok)+ expect(g.out).toEqual(['gone: closed (you closed it)'])+ // Closed by another agent, or by the person: stopped, as before.+ delete d.extra.agents_list+ const other = harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 'T1' } })+ other.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'codex:T1', name: 'Codex', engine: 'codex' }, child: { machineId: 'm', agentId: 'kid', name: 'kid' } })+ expect(await waitCommand(['kid'], other.deps)).toBe(EXIT.stopped)+ expect(other.out).toEqual(['kid: stopped · it was stopped'])+ const person = harness(d, { pane: undefined })+ expect(await waitCommand(['kid'], person.deps)).toBe(EXIT.stopped)+ // Reopened after it closed it, worked on and stopped again: not its close any more.+ d.frames = [frame('lead'), frame('kid', { status: 'stopped', updatedAt: '2026-10-11T12:05:00Z' })]+ const reopened = harness(d)+ expect(await waitCommand(['kid'], reopened.deps)).toBe(EXIT.stopped)+ expect(reopened.out).toEqual(['kid: stopped · it was stopped'])+ })+it('waits for all of several, listing once a round, or the first with --any; a name twice is one harness', async () => {const d = new FakeDaemon()d.frames = [frame('a'), frame('b')]@@ -535,6 +569,43 @@ describe('harness close', () => {])})+ // Codex 0.162.1, closed a second after its start (2026-10-12): the machine's own reason came through as it was,+ // "Conversation identity is held: the native control descriptor type is unavailable."+ it('says plainly when it closed a harness still starting without a conversation, or could not close one', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead'), frame('kid')]+ const replies: Array<Record<string, unknown>> = [+ { closed: true, withoutConversation: true }, { closed: true, withoutConversation: true },+ { error: 'IDENTITY_UNAVAILABLE', detail: 'Conversation identity is held: the native control descriptor type is unavailable.' },+ ]+ d.extra.agent_close = () => replies.shift()!+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ expect(await closeCommand(['kid', '--now'], h.deps)).toBe(EXIT.ok)+ expect(h.out).toEqual(['Closed kid. It was still starting, so no conversation was kept.'])+ expect(await closeCommand(['kid', '--now', '--json'], h.deps)).toBe(EXIT.ok)+ expect(JSON.parse(h.out[1])).toEqual({ name: 'kid', id: 'kid', closed: true, conversationKept: false })+ expect(await closeCommand(['kid', '--now'], h.deps)).toBe(EXIT.failed)+ expect(h.err).toEqual(['kid was not closed: Harness cannot tell which conversation it is in right now, and closing it would lose that conversation. Try again in a moment.'])+ })++ it('records what an agent closed, for its wait; the person\'s closes and a record that cannot be written change nothing', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead'), frame('kid'), frame('theirs')]+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ expect(await closeCommand(['kid'], h.deps)).toBe(EXIT.ok)+ expect(h.ledger.closedBy({ machineId: 'm', agentId: 'lead' }, { machineId: 'm', agentId: 'kid' })).toBe(NOW)+ // Older lines and readers: the closed line is no start, and asks for nothing.+ expect(h.ledger.childrenOf({ machineId: 'm', agentId: 'lead' }).map((row) => row.child.agentId)).toEqual(['kid'])+ expect(h.ledger.pendingOf(null, NOW)).toEqual([])+ expect(await closeCommand(['theirs'], harness(d, { pane: undefined }).deps)).toBe(EXIT.ok)+ expect(readFileSync(ledgerPath(dir), 'utf8').trim().split('\n')).toHaveLength(2)+ const unwritable = harness(d, { ledger: (data) => Object.assign(new Ledger(ledgerPath(data)), { append: () => { throw new Error('read-only') } }) })+ expect(await closeCommand(['kid'], unwritable.deps)).toBe(EXIT.ok)+ expect(unwritable.out).toEqual(['Closed kid. Its conversation is kept.'])+ })+it('closes one harness at a time, by name', async () => {const h = harness(new FakeDaemon())expect(await closeCommand([], h.deps)).toBe(EXIT.usage)@@ -948,6 +1019,19 @@ describe('an agent asking again for a harness it already has', () => {expect(await (await agentOrigin(later.deps))!.existing!('reviewer', codexHere)).toBeNull()})+ // Asked again two seconds later, an agent was told it had started it "1 min ago".+ it('says a harness started under a minute ago was started just now', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('k1', { name: 'pong' })]+ const h = harness(d)+ h.ledger.append({ at: NOW - 2_000, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, child: { machineId: 'm', agentId: 'k1', name: 'pong' } })+ expect((await (await agentOrigin(h.deps))!.existing!('pong', { machineId: 'm', engine: 'codex' }))?.note)+ .toMatch(/^"pong" is already running: you started it just now\. /)+ const minute = harness(d, { now: () => NOW + 58_000 })+ expect((await (await agentOrigin(minute.deps))!.existing!('pong', { machineId: 'm', engine: 'codex' }))?.note)+ .toMatch(/you started it 1 min ago\. /)+ })+it('records a harness asked for before it starts, and its creation once it has', async () => {const d = new FakeDaemon()d.frames = [frame('lead', { engine: 'claude' })]diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.tsindex 1d785452d..349a0f9bf 100644--- a/cli/src/agentClient/commands.ts+++ b/cli/src/agentClient/commands.ts@@ -52,7 +52,8 @@ A harness's state and its last turn: what it was asked and what it answered (theexport const WAIT_USAGE = `Usage: harness wait <name>[,<name>…] [--any] [--timeout 30m] [--json]Waits until each harness has stopped working, then prints its state. --any returns when the first one does.-Exit status: 0 idle, 3 one needs the person (a question or a permission), 4 one stopped or is gone, 124 timed out.+Exit status: 0 idle or closed by you, 3 one needs the person (a question or a permission), 4 one stopped or is gone,+124 timed out.--timeout takes 90s, 30m, 2h; 0 waits as long as it takes.`export const CLOSE_USAGE = `Usage: harness close <name> [--now] [--json]@@ -467,7 +468,11 @@ export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Pro// ── wait ───────────────────────────────────────────────────────────────────────────────────────────-type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'timeout' | 'failed'+/** How far another machine's clock may be off from this one's, for what happened before or after a close. */+const CLOCK_SLACK_MS = 60_000++/** `closed`: stopped or gone because the caller closed it (`harness close`, the ledger's `Closed` line). */+type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'closed' | 'timeout' | 'failed'export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {return run(WAIT_USAGE, deps, wantsJson, argv, async (s) => {@@ -519,12 +524,20 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Proconst sawWorking = new Set<Target>()/** Idle looks in a row, on the same turn. */const idle = new Map<Target, { turn: string; looks: number }>()+ // Ended because the caller closed it: what it asked for, not a failure. A real Codex lead closed its harness and+ // then waited on it, as it had queued, and was answered "Failed (exit 4) · stopped · it was stopped". Not when its+ // conversation went on after that close (the person reopened it), or a minute past it on another machine's clock.+ const ended = (t: Target, state: 'stopped' | 'gone'): Settled => {+ const closedAt = o.caller ? o.ledger.closedBy(o.caller, { machineId: t.machineId, agentId: t.frame.id }) : null+ const active = Date.parse(t.frame.updatedAt ?? '')+ return closedAt !== null && !(active > closedAt + CLOCK_SLACK_MS) ? 'closed' : state+ }const look = async (t: Target, frames: Frame[]): Promise<Settled | null> => {const frame = frames.find((f) => f.id === t.frame.id)// Not live: stopped, or gone. Asked of the full list only then.- if (!frame) return (await list(t.daemon, true)).some((f) => f.id === t.frame.id) ? 'stopped' : 'gone'+ if (!frame) return ended(t, (await list(t.daemon, true)).some((f) => f.id === t.frame.id) ? 'stopped' : 'gone')t.frame = frame- if (frame.status === 'stopped') return 'stopped'+ if (frame.status === 'stopped') return ended(t, 'stopped')// The daemon says it is working: no need to read its screen.const screen = frame.activity?.state === 'working' ? 'working' : await inspect(t)if (screen === 'working') { sawWorking.add(t); idle.delete(t); return null }@@ -587,6 +600,7 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro]if (flags.has('--json')) s.out(JSON.stringify({ harnesses: results }, null, 1))else for (const r of results) {+ if (r.state === 'closed') { s.out(`${r.name}: closed (you closed it)`); continue }const next = r.state === 'idle' ? `read it: ${step(s.env, 'show', r.name)}`: r.state === 'needs-input' ? 'it waits for the person (a question or a permission); only the person answers it': r.state === 'timeout' ? `still working; wait again or read it: ${step(s.env, 'show', r.name)}`@@ -649,8 +663,21 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Prthrow new AgentClientError('WORKING', `${name} is ${reply.activity === 'needs_input' ? 'waiting for the person' : 'working'}. Wait for it (${step(s.env, 'wait', name)}), or close it anyway with ${s.env[VIA_MCP_ENV] === '1' ? 'now: true' : '--now'}.`)}if (reply.error === 'AGENT_CHANGED') throw new AgentClientError('AGENT_CHANGED', `${name} changed while closing. Check it with ${step(s.env, 'show', name)}, then try again.`)+ // Its machine cannot read which conversation it is in just now, and closing it would lose that conversation. The+ // machine's own reason ("the native control descriptor type is unavailable") means nothing to the agent asking.+ if (reply.error === 'IDENTITY_UNAVAILABLE') {+ throw new AgentClientError('IDENTITY_UNAVAILABLE', `${name} was not closed: Harness cannot tell which conversation it is in right now, and closing it would lose that conversation. Try again in a moment.`)+ }if (reply.error) throw new AgentClientError(String(reply.error), typeof reply.detail === 'string' && reply.detail ? reply.detail : `Could not close ${name}.`)- s.out(flags.has('--json') ? JSON.stringify({ name, id: t.frame.id, closed: true }) : `Closed ${name}. Its conversation is kept.`)+ // Recorded for `wait`, which then says the caller closed it rather than that it stopped. The close is done either way.+ if (o.caller) {+ try { o.ledger.append({ at: s.now(), by: { machineId: o.caller.machineId, agentId: o.caller.agentId }, closed: { machineId: t.machineId, agentId: t.frame.id } }) }+ catch { /* `wait` then says it stopped */ }+ }+ // Closed while still starting, before its machine could read its conversation: there is none to keep.+ const kept = reply.withoutConversation !== true+ s.out(flags.has('--json') ? JSON.stringify({ name, id: t.frame.id, closed: true, ...(kept ? {} : { conversationKept: false }) })+ : kept ? `Closed ${name}. Its conversation is kept.` : `Closed ${name}. It was still starting, so no conversation was kept.`)return EXIT.ok} finally { if (t?.remote) t.daemon.close(); o.daemon.close() }})@@ -789,9 +816,11 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesRconst live = await liveFor(s, o, caller)const running = recent.findLast((row) => live.has(memberKey(row.child.machineId, row.child.agentId)))if (!running) return null- const called = running.child.name, minutes = Math.max(1, Math.round((s.now() - running.at) / 60_000))+ // Under a minute is "just now": rounded up to a minute, a harness started two seconds earlier was "1 min ago".+ const called = running.child.name, age = s.now() - running.at+ const when = age < 60_000 ? 'just now' : `${Math.round(age / 60_000)} min ago`return { name: called, machineId: running.child.machineId, agentId: running.child.agentId, state: 'running',- note: `"${called}" is already running: you started it ${minutes} min ago. Wait for it with ${step(s.env, 'wait', called)} `+ note: `"${called}" is already running: you started it ${when}. Wait for it with ${step(s.env, 'wait', called)} `+ `or read it with ${step(s.env, 'show', called)}. Do not start it again; to start a new one by that name, close it first (${step(s.env, 'close', called)}).` }},pending: (machineId, creation) => {diff --git a/cli/src/agentClient/ledger.ts b/cli/src/agentClient/ledger.tsindex 1876f7ee3..1685ff63a 100644--- a/cli/src/agentClient/ledger.ts+++ b/cli/src/agentClient/ledger.ts@@ -10,6 +10,9 @@* A harness asked for and not started yet (its engine still installing) has a line of its own, `Pending`, with the* machine's creation id: it starts by itself later, after `harness new` has answered, and is then recorded as started* by whichever verb of the agent's first sees it made (agentClient/commands.ts `opened`). Older readers skip the line.+ *+ * A harness an agent closed with `harness close` has a line too, `Closed`: its `harness wait` then says the harness+ * was closed, by the agent itself, rather than reporting it stopped as a failure. Older readers skip that line as well.*/import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs'import { dirname, join } from 'node:path'@@ -33,6 +36,13 @@ export interface Pending {depth: number}+/** [by] closed [closed] with `harness close`. */+export interface Closed {+ at: number+ by: LedgerMember+ closed: LedgerMember+}+/** How long a pending line is asked after. An install ends within twenty minutes (engines/kit/nativeInstall.ts). */export const PENDING_WITHIN_MS = 30 * 60_000@@ -77,10 +87,18 @@ export function parsePending(line: string): Pending | null {}}+export function parseClosed(line: string): Closed | null {+ let v: Record<string, unknown>+ try { v = JSON.parse(line) } catch { return null }+ if (!v || typeof v !== 'object' || typeof v.at !== 'number' || !member(v.by) || !member(v.closed)) return null+ const by = v.by as unknown as LedgerMember, closed = v.closed as unknown as LedgerMember+ return { at: v.at, by: { machineId: by.machineId, agentId: by.agentId }, closed: { machineId: closed.machineId, agentId: closed.agentId } }+}+const same = (a: LedgerMember, b: LedgerMember): boolean => a.machineId === b.machineId && a.agentId === b.agentIdexport class Ledger {- private cache: { key: string; rows: Started[]; pending: Pending[] } | null = null+ private cache: { key: string; rows: Started[]; pending: Pending[]; closed: Closed[] } | null = nullconstructor(readonly path: string) {}/** Where the older lines went when the file passed its size. */@@ -90,11 +108,11 @@ export class Ledger {* only when either changed. */all(): Started[] { return this.read().rows }- private read(): { rows: Started[]; pending: Pending[] } {+ private read(): { rows: Started[]; pending: Pending[]; closed: Closed[] } {const files = [this.previous, this.path].map((path) => { try { const st = statSync(path); return { path, key: `${st.mtimeMs}:${st.size}` } } catch { return null } })const key = files.map((f) => f?.key ?? '-').join('|')if (this.cache?.key === key) return this.cache- const rows: Started[] = [], pending: Pending[] = []+ const rows: Started[] = [], pending: Pending[] = [], closed: Closed[] = []for (const file of files) {if (!file) continuelet text = ''@@ -104,14 +122,16 @@ export class Ledger {const row = parseStarted(line)if (row) { rows.push(row); continue }const asked = parsePending(line)- if (asked) pending.push(asked)+ if (asked) { pending.push(asked); continue }+ const close = parseClosed(line)+ if (close) closed.push(close)}}- this.cache = { key, rows, pending }+ this.cache = { key, rows, pending, closed }return this.cache}- append(row: Started | Pending): void {+ append(row: Started | Pending | Closed): void {mkdirSync(dirname(this.path), { recursive: true })// One short line with O_APPEND: two agents starting harnesses at once never interleave.appendFileSync(this.path, `${JSON.stringify(row)}\n`, { mode: 0o600 })@@ -139,6 +159,11 @@ export class Ledger {return [...children.values()].sort((a, b) => a.at - b.at)}+ /** When [by] last closed [m] with `harness close`, or null when it did not. */+ closedBy(by: LedgerMember, m: LedgerMember): number | null {+ return this.read().closed.findLast((row) => same(row.by, by) && same(row.closed, m))?.at ?? null+ }+/** 0 for a harness the person started. */depthOf(m: LedgerMember): number {return this.parentOf(m)?.depth ?? 0diff --git a/cli/src/engines/kit/identityScan.ts b/cli/src/engines/kit/identityScan.tsindex c3a5ca41e..2cdf07713 100644--- a/cli/src/engines/kit/identityScan.ts+++ b/cli/src/engines/kit/identityScan.ts@@ -6,6 +6,11 @@ export class IdentityReadUnavailable extends Error {readonly code = 'IDENTITY_UNAVAILABLE'constructor(reason: string, message = `Conversation identity is held: ${reason}.`) { super(message) }}+/** A conversation was seen and then could not be read: never a reason to stop its process without it+ * (lib/stopAgentService.ts `withoutConversation`). */+export class ObservedConversationUnavailable extends IdentityReadUnavailable {+ constructor(message: string) { super('', message) }+}export type IdentityVersion = Pick<Stats, 'dev' | 'ino' | 'size' | 'mtimeMs' | 'ctimeMs'> & {/** Descriptor numbers can exceed Number's exact range; never round kernel ownership evidence. */diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.tsindex b24b0ec99..b4c174541 100644--- a/cli/src/lib/captureResumeIdentity.spec.ts+++ b/cli/src/lib/captureResumeIdentity.spec.ts@@ -4,6 +4,7 @@ import { engineKeepsTranscriptFile, type RegisteredSession } from './registry.jsimport { controlTranscriptEvidence, savedTranscriptEvidence } from '../engines/transcriptBindings.js'import { findLiveSession, findResumedTranscript, processSessionEvidence } from './sessionRepair.js'import { processRows, resumeSessionId } from './tmux.js'+import { IdentityReadUnavailable, ObservedConversationUnavailable } from '../engines/kit/identityScan.js'vi.mock('./registry.js', () => ({ engineKeepsTranscriptFile: vi.fn(() => true) }))vi.mock('../engines/transcriptBindings.js', () => ({ savedTranscriptEvidence: vi.fn(), controlTranscriptEvidence: vi.fn() }))vi.mock('./sessionRepair.js', () => ({ processSessionEvidence: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))@@ -156,3 +157,34 @@ it.each([null, { sessionId: 'missing' }, { sessionId: 'unsafe', transcriptPath:if (found) await expect(captureResumeIdentity(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })else expect(await captureResumeIdentity(row)).toBe(row)})+// A close of a harness still starting may stop one whose conversation was never seen (stopAgentService+// `withoutConversation`); a conversation seen and then unreadable is held as seen.+it.each([+ ['a resume on its command line', () => { vi.mocked(resumeSessionId).mockReturnValue('exact'); vi.mocked(findResumedTranscript).mockResolvedValue(null) }],+ ['its native record', () => {+ vi.mocked(processSessionEvidence).mockResolvedValue({ session: { sessionId: 'current', transcriptPath: '/current' }, verify: vi.fn() })+ vi.mocked(savedTranscriptEvidence).mockReturnValue({ path: null, fileKey: null, verify: vi.fn() })+ }],+ ['one found live', () => {+ vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'new', transcriptPath: '/new' })+ vi.mocked(savedTranscriptEvidence).mockImplementation(() => { throw new IdentityReadUnavailable('the transcript header is incomplete') })+ }],+] as const)('holds a conversation seen through %s and then unreadable as seen', async (_, arrange) => {+ arrange()+ await expect(captureResumeIdentity(row)).rejects.toBeInstanceOf(ObservedConversationUnavailable)+})+it('a conversation never seen, because its process could not be read, is not held as seen', async () => {+ vi.mocked(findLiveSession).mockRejectedValue(new IdentityReadUnavailable('the native control descriptor type is unavailable'))+ const error = await captureResumeIdentity(row).catch(e => e)+ expect(error).toBeInstanceOf(IdentityReadUnavailable)+ expect(error).not.toBeInstanceOf(ObservedConversationUnavailable)+ const plain = new Error('disk gone')+ vi.mocked(findLiveSession).mockRejectedValue(plain)+ await expect(captureResumeIdentity(row)).rejects.toBe(plain)+ vi.mocked(resumeSessionId).mockReturnValue('exact')+ vi.mocked(findResumedTranscript).mockRejectedValue(plain)+ await expect(captureResumeIdentity(row)).rejects.toBe(plain)+ const seen = new ObservedConversationUnavailable('Conversation identity is held: seen.')+ vi.mocked(findResumedTranscript).mockRejectedValue(seen)+ await expect(captureResumeIdentity(row)).rejects.toBe(seen)+})diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.tsindex c33781758..229fb24d3 100644--- a/cli/src/lib/captureResumeIdentity.ts+++ b/cli/src/lib/captureResumeIdentity.ts@@ -13,6 +13,7 @@ import { findLiveSession, findResumedTranscript, processSessionEvidence, type Reimport { resumeSessionId } from './tmux.js'import { readProcessEvidence } from './processEvidence.js'import { NativeEvidenceBudget, nativeUnavailable } from '../engines/kit/nativeEvidence.js'+import { IdentityReadUnavailable, ObservedConversationUnavailable } from '../engines/kit/identityScan.js'import { isTerminalEngine } from '../engines/types.js'export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {@@ -50,28 +51,39 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise// An engine whose process names its own session in a record (Claude Code's, removed at exit) is read now.const claim = await processSessionEvidence(session.engine, expected.pid, session.cwd, Date.parse(expected.startMarker), budget)const native = claim.session- const found: RepairedSession | null = native ?? (explicit- ? { 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- // pool together. Other finders still need this final process fence before a Stop may proceed.- if (native || explicit || session.engine !== 'codex') await owner.verify()- claim.verify()- if (!found?.sessionId) return session- // A file-backed engine still has to produce a transcript this daemon can point a resume at; a- // database-backed one has nothing to check and is taken on its id alone.- const transcriptPath = found.transcriptPath && keepsFile ? verifiedPath(found.sessionId, found.transcriptPath) : found.transcriptPath- if (keepsFile && !transcriptPath) return nativeUnavailable('the observed conversation file is unavailable')- return {- ...session,- sessionId: found.sessionId,- ...(transcriptPath ? { transcriptPath } : {}),- ...(found.hermesHome ? { hermesHome: found.hermesHome } : {}),- source: 'stop-repair',- boundAt: Date.now(),+ // Once a conversation is seen (a native record, a resume on the command line, one found live), a failure to read it+ // holds it: a close of a harness still starting may stop one whose conversation was never seen, never this one.+ let seen = !!native || !!explicit+ const cwd = session.cwd+ const capture = async (): Promise<RegisteredSession> => {+ const found: RepairedSession | null = native ?? (explicit+ ? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) ?? undefined }+ : await findLiveSession(session.engine, 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,+ }))+ seen ||= !!found?.sessionId+ // Codex's open-file finder verifies this owner, all candidate headers and its descriptor+ // pool together. Other finders still need this final process fence before a Stop may proceed.+ if (native || explicit || session.engine !== 'codex') await owner.verify()+ claim.verify()+ if (!found?.sessionId) return session+ // A file-backed engine still has to produce a transcript this daemon can point a resume at; a+ // database-backed one has nothing to check and is taken on its id alone.+ const transcriptPath = found.transcriptPath && keepsFile ? verifiedPath(found.sessionId, found.transcriptPath) : found.transcriptPath+ if (keepsFile && !transcriptPath) return nativeUnavailable('the observed conversation file is unavailable')+ return {+ ...session,+ sessionId: found.sessionId,+ ...(transcriptPath ? { transcriptPath } : {}),+ ...(found.hermesHome ? { hermesHome: found.hermesHome } : {}),+ source: 'stop-repair',+ boundAt: Date.now(),+ }+ }+ try { return await capture() } catch (error) {+ if (!seen || !(error instanceof IdentityReadUnavailable) || error instanceof ObservedConversationUnavailable) throw error+ throw new ObservedConversationUnavailable(error.message)}}diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex 48ab26525..c5e44cbe4 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -1,5 +1,5 @@import { screenFor } from '../engines/screens.js'-import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { CloseAgentService, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'import { registry, type RegisteredSession } from './registry.js'import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'@@ -471,3 +471,166 @@ it('a concurrent deferred tick never starts a second stop', async () => {function inspectCloseActivity(session: Parameters<typeof inspectCloseReading>[0], capture: string | null, turnOpen: boolean | undefined, needsInput: boolean) {return inspectCloseReading(session, capture === null ? null : screenFor(session.engine).inspect(capture), turnOpen, needsInput)}++// Codex 0.162.1 in a clean macOS VM (2026-10-12): `harness close --now` a second after its start was refused with+// "Conversation identity is held: the native control descriptor type is unavailable." and the harness kept working.+describe('a close of a harness still starting', () => {+ const held = () => new IdentityReadUnavailable('the native control descriptor type is unavailable')+ let slept: number[]+ beforeEach(() => {+ Object.assign(row, { sessionId: '', transcriptPath: null, boundAt: null })+ time = row.registeredAt + 1_000+ slept = []+ deps.sleep = vi.fn(async ms => { slept.push(ms); time += ms })+ service = new CloseAgentService(deps)+ })+ const stops = () => vi.mocked(deps.stop).mock.calls.map(([, options]) => options)+ /** As a hook binds it (registry.register): its first conversation, and no `launch` any more. */+ const bind = (extra: Partial<RegisteredSession> = {}) => { Object.assign(row, { sessionId: 'first', boundAt: time, ...extra }); delete row.launch }++ it('waits for its first conversation to bind, then closes it with that conversation', async () => {+ const asked = request('now')+ vi.mocked(deps.stop).mockRejectedValueOnce(held())+ vi.mocked(deps.sleep!).mockImplementationOnce(async ms => {+ time += ms+ bind({ transcriptPath: '/fixture/first.jsonl' })+ })+ expect(await service.request(asked)).toEqual({ closed: true })+ expect(stops()).toHaveLength(2)+ expect(stops()[1].withoutConversation).toBeUndefined()+ expect(registry.byAgent(row.agentId)).toBeUndefined()+ })+ it('never bound within the wait: stopped without a conversation, and says so', async () => {+ let unbound = 0+ vi.mocked(deps.stop).mockImplementation(async (id, options) => {+ if (!options.withoutConversation) throw held()+ options.withoutConversation()+ unbound+++ registry.removeAgent(id)+ })+ expect(await service.request(request('now'))).toEqual({ closed: true, withoutConversation: true })+ expect(unbound).toBe(1)+ expect(slept.reduce((a, b) => a + b, 0)).toBe(8_000)+ expect(stops().at(-1)?.withoutConversation).toBeTypeOf('function')+ expect(stops().slice(0, -1).every(options => !options.withoutConversation)).toBe(true)+ })+ it('a close that finds it idle stops it the same way; one that finds it working leaves it', async () => {+ vi.mocked(deps.stop).mockImplementation(async (id, options) => {+ if (!options.withoutConversation) throw held()+ registry.removeAgent(id)+ })+ vi.mocked(deps.activity).mockResolvedValue('working')+ expect(await service.request(request('idle'))).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'working' })+ vi.mocked(deps.activity).mockResolvedValue('idle')+ // A stop that never says it went without a conversation is a close that kept what it had.+ expect(await service.request(request('idle'))).toEqual({ closed: true })+ })+ it('a conversation bound while a try ran is closed with it at once, which that try read as a change', async () => {+ vi.mocked(deps.stop).mockImplementationOnce(async () => {+ bind()+ throw Object.assign(new Error('Harness changed while saving its conversation. Try stopping again.'), { code: 'STOP_UNCONFIRMED' })+ })+ expect(await service.request(request('now'))).toEqual({ closed: true })+ expect(deps.sleep).not.toHaveBeenCalled()+ expect(stops()).toHaveLength(2)+ })+ it('bound by the last try of the wait: tried once more with its conversation, not let go', async () => {+ let calls = 0+ vi.mocked(deps.stop).mockImplementation(async (id, options) => {+ if (++calls === 9) bind()+ if (calls < 10) throw held()+ expect(options.withoutConversation).toBeUndefined()+ registry.removeAgent(id)+ })+ expect(await service.request(request('now'))).toEqual({ closed: true })+ expect(calls).toBe(10)+ })+ it('a refusal of its own is answered at once', async () => {+ vi.mocked(deps.stop).mockRejectedValue(Object.assign(new Error('Disk full'), { code: 'HISTORY_NOT_SAVED' }))+ expect(await service.request(request('now'))).toMatchObject({ error: 'HISTORY_NOT_SAVED', detail: 'Disk full' })+ expect(deps.sleep).not.toHaveBeenCalled()+ })+ it('a conversation that binds and still cannot be read is never stopped without it', async () => {+ vi.mocked(deps.stop).mockRejectedValue(held())+ vi.mocked(deps.sleep!).mockImplementationOnce(async ms => { time += ms; bind() })+ expect(await service.request(request('now'))).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', detail: expect.stringContaining('descriptor') })+ expect(stops().every(options => !options.withoutConversation)).toBe(true)+ expect(registry.byAgent(row.agentId)).toBe(row)+ })+ it.each([+ ['launched over a minute ago', () => { time = row.registeredAt + 60_000 }],+ ['an engine typed into a terminal', () => { row.terminalHost = true }],+ ['a resume', () => { row.resumeOnly = true }],+ ['one discovery found', () => { delete row.launch }],+ ['a fork, which starts on a copy of another conversation', () => { row.forkedFrom = { agentId: 'parent', name: 'parent', sessionId: 'theirs' } }],+ ['whose engine started over a minute ago', () => { row.processIdentity!.startMarker = new Date(row.registeredAt - 1_000).toString(); time = row.registeredAt + 60_000 }],+ ['seen through a clock that went back', () => { time = row.registeredAt - 1 }],+ ] as const)('a harness %s is refused at once, as before', async (_, arrange) => {+ arrange()+ service = new CloseAgentService(deps)+ vi.mocked(deps.stop).mockRejectedValue(held())+ expect(await service.request(request('now'))).toMatchObject({ error: 'IDENTITY_UNAVAILABLE' })+ expect(deps.sleep).not.toHaveBeenCalled()+ expect(registry.byAgent(row.agentId)).toBe(row)+ })+ it('an inspect answers at once', async () => {+ vi.mocked(deps.activity).mockRejectedValue(held())+ expect(await service.request(request('inspect'))).toMatchObject({ error: 'IDENTITY_UNAVAILABLE' })+ expect(deps.sleep).not.toHaveBeenCalled()+ })+ it.each(['reopened', 'replaced', 'disposed', 'removed'] as const)('the wait ends when the harness is %s', async change => {+ vi.mocked(deps.stop).mockRejectedValue(held())+ vi.mocked(deps.sleep!).mockImplementationOnce(async ms => {+ time += ms+ if (change === 'reopened') service.cancel(row.agentId)+ else if (change === 'replaced') row.processIdentity = { pid: 778, startMarker: 'reborn', executable: 'codex' }+ else if (change === 'disposed') service.dispose()+ else registry.removeAgent(row.agentId)+ })+ expect(await service.request(request('now'))).toEqual({ error: 'AGENT_CHANGED' })+ expect(stops()).toHaveLength(1)+ })+ it('the harness replaced as the wait ends is not stopped without a conversation', async () => {+ vi.mocked(deps.stop).mockRejectedValue(held())+ vi.mocked(deps.sleep!).mockImplementation(async ms => {+ time += ms+ if (slept.push(ms) === 8) row.processIdentity = { pid: 778, startMarker: 'reborn', executable: 'codex' }+ })+ expect(await service.request(request('now'))).toEqual({ error: 'AGENT_CHANGED' })+ expect(stops().every(options => !options.withoutConversation)).toBe(true)+ })+ it('a harness whose engine installed first is starting from its engine\'s own start', async () => {+ time = row.registeredAt + 5 * 60_000+ row.processIdentity!.startMarker = new Date(time - 2_000).toString()+ vi.mocked(deps.stop).mockImplementationOnce(async () => { throw held() })+ vi.mocked(deps.sleep!).mockImplementationOnce(async ms => { time += ms; bind() })+ expect(await service.request(request('now'))).toEqual({ closed: true })+ expect(deps.sleep).toHaveBeenCalledOnce()+ })+ it('a close asked of it before its first conversation bound still names it', async () => {+ const asked = request('now')+ bind()+ expect(await service.request(asked)).toEqual({ closed: true })+ // Not once it is past starting, nor for a conversation it moved on from.+ const later = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%89' }], cwd: '/tmp' })!+ Object.assign(later, { sessionId: 'second' })+ time = later.registeredAt + 60_000+ expect(await service.request({ agentId: later.agentId, sessionId: '', createdAt: new Date(later.registeredAt).toISOString(), mode: 'now' }))+ .toEqual({ error: 'AGENT_CHANGED' })+ time = later.registeredAt + 1_000+ expect(await service.request({ agentId: later.agentId, sessionId: 'first', createdAt: new Date(later.registeredAt).toISOString(), mode: 'now' }))+ .toEqual({ error: 'AGENT_CHANGED' })+ })+})+it('waits on a real timer when no sleep is given', async () => {+ vi.useFakeTimers()+ Object.assign(row, { sessionId: '', transcriptPath: null, boundAt: null })+ const start = Date.now()+ deps.now = () => Date.now()+ service = new CloseAgentService(deps)+ vi.mocked(deps.stop).mockRejectedValueOnce(new IdentityReadUnavailable('the native control descriptor type is unavailable'))+ const closing = service.request(request('now'))+ await vi.advanceTimersByTimeAsync(1_000)+ expect(await closing).toEqual({ closed: true })+ expect(Date.now() - start).toBe(1_000)+})diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex 046d98abe..334b78404 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -5,6 +5,7 @@ import type { RegisteredSession, registry as liveRegistry } from './registry.js'import { terminalRouteKey } from './terminalRuntime.js'import type { StopAgentOptions } from './stopAgentService.js'import { resumeMode } from './resumeCapability.js'+import { sid } from './log.js'export type CloseActivity = 'idle' | 'working' | 'needs_input' | 'draft' | 'unknown'export type CloseMode = 'inspect' | 'idle' | 'now' | 'after_task' | 'cancel'@@ -16,7 +17,23 @@ export type AgentClosePlan = {detail?: string}export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean }-export type AgentCloseResult = { closed?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }+/** `withoutConversation`: closed while still starting, before Harness could read its conversation, so none is kept. */+export type AgentCloseResult = { closed?: true; withoutConversation?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }++/**+ * How long a close waits for a harness still starting to bind its first conversation, trying again meanwhile.+ * Codex 0.162.1 in a clean macOS VM (2026-10-12): for its first seconds every read of its process was refused ("the+ * native control descriptor type is unavailable"), so `harness close --now` a second after `harness new` was refused+ * with that phrase and the harness kept working; four seconds in, the same close worked.+ */+export const CLOSE_BIND_WAIT_MS = 8_000+const CLOSE_BIND_RETRY_MS = 1_000+/**+ * A harness Harness launched less than this long ago, with no conversation bound yet, is still starting: one that never+ * binds within the wait is stopped without a conversation. Past it, a close whose conversation cannot be read is refused+ * as before: a harness that has run longer may have work that only its conversation holds.+ */+export const CLOSE_STARTING_MS = 60_000type CloseSession = Pick<RegisteredSession, 'engine' | 'sessionId' | 'transcriptPath' | 'boundAt' | 'launch' | 'resumeOnly'>@@ -46,13 +63,41 @@ function identity(s: RegisteredSession): string {return JSON.stringify([s.agentId, s.sessionId, s.engine, s.registeredAt, s.processIdentity?.pid,s.processIdentity?.startMarker, s.processIdentity?.executable, s.runtimes.map(terminalRouteKey).sort()])}+/** The harness, whichever conversation it has bound: its process and panes. */+function harnessIdentity(s: RegisteredSession): string {+ return JSON.stringify([s.agentId, s.engine, s.registeredAt, s.processIdentity?.pid,+ s.processIdentity?.startMarker, s.processIdentity?.executable, s.runtimes.map(terminalRouteKey).sort()])+}+/** How long before [at] the harness started: its engine's own start when that is later than the row's (an engine+ * installed in its pane first starts minutes after the pane opened), its row's otherwise. A clock that went back+ * says nothing: never young. */+function age(s: RegisteredSession, at: number): number {+ const born = Date.parse(s.processIdentity?.startMarker ?? '')+ const since = Number.isFinite(born) && born > s.registeredAt ? Math.min(born, at) : s.registeredAt+ return at - s.registeredAt < 0 ? -1 : at - since+}+/** Started less than CLOSE_STARTING_MS before [at], and not a terminal an engine was typed into, a resume or an adoption. */+function young(s: RegisteredSession, at: number): boolean {+ const old = age(s, at)+ return !s.terminalHost && !s.resumeOnly && !s.externalResume && old >= 0 && old < CLOSE_STARTING_MS+}+/** Launched by Harness, young, and with no conversation bound yet. A fork is not: it starts on a copy of another's+ * conversation. Nor is a row a hook has bound, which loses its `launch` then (registry.register): once bound, never+ * starting again. */+function stillStarting(s: RegisteredSession, at: number): boolean {+ return !!s.launch && !s.forkedFrom && young(s, at) && !s.sessionId && !s.transcriptPath && s.boundAt == null+}/** What makes two requests the same one: the agent, the mode, and whether it holds only while no tab* shows the agent. A cleanup that finds the agent on screen again must not answer the person's own close. */function jobKey(request: AgentCloseRequest): string {return JSON.stringify([request.agentId, request.mode, request.onlyIfHidden === true])}-function matches(s: RegisteredSession | undefined, request: AgentCloseRequest): s is RegisteredSession {- return !!s && s.sessionId === request.sessionId && new Date(s.registeredAt).toISOString() === request.createdAt+function matches(s: RegisteredSession | undefined, request: AgentCloseRequest, at: number): s is RegisteredSession {+ if (!s || new Date(s.registeredAt).toISOString() !== request.createdAt) return false+ // Asked of a harness still starting, which has bound its first conversation since the list the request was made+ // from: the same harness, and the close keeps that conversation. Refused as changed, a close sent in the seconds a+ // Codex binds was answered "changed while closing".+ return s.sessionId === request.sessionId || (request.sessionId === '' && young(s, at))}export interface CloseAgentServiceDeps {@@ -63,6 +108,7 @@ export interface CloseAgentServiceDeps {changed(s: RegisteredSession): voidopenTabs?: { assertHidden(s: RegisteredSession): Promise<void>; isHidden(s: RegisteredSession): boolean }now?: () => number+ sleep?: (ms: number) => Promise<void>}class CloseRefused extends Error {@@ -83,7 +129,11 @@ export class CloseAgentService {private timer: ReturnType<typeof setTimeout> | null = nullprivate disposed = falseprivate readonly now: () => number- constructor(private readonly deps: CloseAgentServiceDeps) { this.now = deps.now ?? Date.now }+ private readonly sleep: (ms: number) => Promise<void>+ constructor(private readonly deps: CloseAgentServiceDeps) {+ this.now = deps.now ?? Date.now+ this.sleep = deps.sleep ?? (ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }))+ }start(): void { this.schedule() }dispose(): void { this.disposed = true; if (this.timer) clearTimeout(this.timer); this.timer = null }@@ -100,7 +150,7 @@ export class CloseAgentService {request(request: AgentCloseRequest): Promise<AgentCloseResult> {const current = this.deps.registry.byAgent(request.agentId)- if (!matches(current, request)) return Promise.resolve({ error: 'AGENT_CHANGED' })+ if (!matches(current, request, this.now())) return Promise.resolve({ error: 'AGENT_CHANGED' })if (request.mode === 'cancel') { this.cancel(request.agentId); return Promise.resolve({ cancelled: true }) }// A job answers only a request of its own kind. When any job running for the agent answered every// request, a close asked for while another window (or the cleanup preview) was inspecting the agent@@ -125,6 +175,54 @@ export class CloseAgentService {}private async execute(request: AgentCloseRequest, target: string, revision: number): Promise<AgentCloseResult> {+ const askedAt = this.now()+ // Read before the try: a row can be changed in place while it runs.+ const asked = this.deps.registry.byAgent(request.agentId)+ const starting = !!asked && identity(asked) === target && stillStarting(asked, askedAt) ? harnessIdentity(asked) : null+ const result = await this.attempt(request, target, revision)+ if (result.closed || (request.mode !== 'now' && request.mode !== 'idle') || !starting) return result+ return this.whileStarting(request, starting, target, revision, askedAt + CLOSE_BIND_WAIT_MS, result)+ }++ /**+ * A harness still starting whose close did not go through: tried again while its conversation cannot be read yet, and+ * at once when it bound its first conversation while a try ran (which a try reads as the harness having changed).+ * Bound, it is closed with that conversation. One that has not bound by [deadline] is stopped without one, as asked:+ * Harness has no conversation of it to keep. Every caller gets this: the CLI and MCP, the windows, closes of many.+ */+ private async whileStarting(request: AgentCloseRequest, harness: string, target: string, revision: number, deadline: number,+ first: AgentCloseResult): Promise<AgentCloseResult> {+ const same = () => {+ const s = this.deps.registry.byAgent(request.agentId)+ return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision && s && harnessIdentity(s) === harness ? s : undefined+ }+ let tried = target, result = first, waiting = false+ for (;;) {+ const s = same()+ if (!s) return { error: 'AGENT_CHANGED' }+ const bound = identity(s) !== tried+ // Neither unreadable nor newly bound: a refusal of its own (working, a failed save), answered as it is.+ if (!bound && result.error !== 'IDENTITY_UNAVAILABLE') return result+ if (this.now() >= deadline) {+ if (bound) return this.attempt(request, identity(s), revision)+ // Bound, and still unreadable: a conversation is never let go this way.+ if (s.sessionId || s.transcriptPath || s.boundAt != null) return result+ console.log(`[close] ${sid(request.agentId)} bound no conversation within ${CLOSE_BIND_WAIT_MS / 1000}s; closing it without one`)+ return this.attempt(request, identity(s), revision, true)+ }+ if (!waiting) console.log(`[close] ${sid(request.agentId)} is still starting (${result.detail ?? result.error}); waiting for its conversation`)+ waiting = true+ if (!bound) await this.sleep(Math.min(CLOSE_BIND_RETRY_MS, deadline - this.now()))+ const latest = same()+ if (!latest) return { error: 'AGENT_CHANGED' }+ tried = identity(latest)+ result = await this.attempt(request, tried, revision)+ if (result.closed) return result+ }+ }++ private async attempt(request: AgentCloseRequest, target: string, revision: number, withoutConversation = false): Promise<AgentCloseResult> {+ let unkept = falseconst current = () => {const s = this.deps.registry.byAgent(request.agentId)return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision@@ -156,6 +254,7 @@ 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(),checkpoint: (s, phase) => this.deps.checkpoint(s, phase),confirmUnusedConversation: async captured => {@@ -180,7 +279,7 @@ export class CloseAgentService {},})this.idleSince.delete(s.agentId)- return { closed: true }+ return unkept ? { closed: true, withoutConversation: true } : { closed: true }} catch (error) {if (error instanceof CloseRefused) return { error: 'SESSION_NOT_IDLE', activity: error.activity }const code = (error as { code?: unknown })?.codediff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.tsindex 33e184f93..fd32ded79 100644--- a/cli/src/lib/stopAgentService.spec.ts+++ b/cli/src/lib/stopAgentService.spec.ts@@ -8,6 +8,7 @@ import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.jsimport { createForgetSession } from '../core/agents/forget.js'import { env } from '../config/env.js'import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'+import { IdentityReadUnavailable, ObservedConversationUnavailable } from '../engines/kit/identityScan.js'vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))vi.mock('../engines/transcriptBindings.js', async original => ({ ...await original<object>(),controlTranscriptEvidence: vi.fn(),@@ -95,6 +96,29 @@ it('preserves an unexpected evidence failure without signalling or hiding its caexpect(terminateDeletedAgent).not.toHaveBeenCalled()expect(deps.forgetSession).not.toHaveBeenCalled()})+// A close of a harness still starting that waited in vain for its first conversation (closeAgentService.ts).+it('stops a harness that never bound a conversation without one, only when its close asks', async () => {+ Object.assign(row, { sessionId: '', transcriptPath: null, boundAt: null })+ vi.mocked(captureResumeIdentity).mockRejectedValue(new IdentityReadUnavailable('the native control descriptor type is unavailable'))+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('descriptor type is unavailable')+ expect(registry.byAgent(row.agentId)).toBe(row)+ const unkept = vi.fn()+ await createStopAgentService(deps)(row.agentId, { withoutConversation: unkept })+ expect(unkept).toHaveBeenCalledOnce()+ expect(stoppedAgents.get(row.agentId)).toMatchObject({ active: false, sessionId: '' })+ expect(registry.byAgent(row.agentId)).toBeUndefined()+})+it.each(['a bound conversation', 'a known transcript', 'a bind time', 'a conversation seen live', 'another failure'] as const)('never lets go of %s that cannot be read', async kind => {+ Object.assign(row, { sessionId: kind === 'a bound conversation' ? 'saved' : '', transcriptPath: kind === 'a known transcript' ? '/fixture/t.jsonl' : null,+ boundAt: kind === 'a bind time' ? 1 : null })+ vi.mocked(captureResumeIdentity).mockRejectedValue(kind === 'another failure' ? new Error('disk gone')+ : kind === 'a conversation seen live' ? new ObservedConversationUnavailable('Conversation identity is held: the observed conversation file is unavailable.')+ : new IdentityReadUnavailable('the transcript is unreadable'))+ const unkept = vi.fn()+ await expect(createStopAgentService(deps)(row.agentId, { withoutConversation: unkept })).rejects.toThrow()+ expect(unkept).not.toHaveBeenCalled()+ expect(registry.byAgent(row.agentId)).toBe(row)+})it.each(['before', 'after'] as const)('honors cancellation at the %s checkpoint before retiring the terminal', async phase => {let current = trueawait expect(createStopAgentService(deps)(row.agentId, {diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.tsindex cd92ab521..4a80907e3 100644--- a/cli/src/lib/stopAgentService.ts+++ b/cli/src/lib/stopAgentService.ts@@ -2,7 +2,7 @@import { externalResumePending } from './externalResume.js'import { captureResumeIdentity } from './captureResumeIdentity.js'import { isTerminalEngine } from '../engines/types.js'-import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'+import { IdentityReadUnavailable, ObservedConversationUnavailable } from '../engines/kit/identityScan.js'import { controlTranscriptEvidence, engineKeepsTranscriptFile } from '../engines/transcriptBindings.js'import type { registry as liveRegistry, RegisteredSession } from './registry.js'import type { StoppedAgentStore } from './stoppedAgents.js'@@ -48,6 +48,11 @@ export interface StopAgentOptions {checkpoint?(session: RegisteredSession, phase: 'before' | 'after'): Promise<void>/** Fresh proof that an unbound chat has never started and its composer is empty. */confirmUnusedConversation?(session: RegisteredSession): Promise<boolean>+ /**+ * A close of a harness still starting that waited for its first conversation in vain (closeAgentService.ts): when its+ * conversation cannot be read, it is stopped without one, and this is called. Never for a conversation once bound.+ */+ withoutConversation?(): void}// Hooks rebuild registry objects. Compare stable values, never JavaScript object@@ -93,7 +98,12 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {return runtimeIdentity(current, !starting) === identity && (!conversation || current!.sessionId === conversation)&& (binding === undefined || bindingIdentity(current!) === binding)}- const captured = await captureResumeIdentity({ ...live })+ const captured = await captureResumeIdentity({ ...live }).catch((error: unknown) => {+ if (!options.withoutConversation || conversation || live.transcriptPath || live.boundAt != null+ || !(error instanceof IdentityReadUnavailable) || error instanceof ObservedConversationUnavailable) throw error+ options.withoutConversation()+ return { ...live }+ })// Discovery or a hook may have updated this row while reading the native store.// A replacement process must never be stopped using an older snapshot.if (!sameTarget() || options.current?.() === false) {diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.mdindex 893e2c643..0c0d01b5b 100644--- a/docs/design/2026-10-11-agent-client.md+++ b/docs/design/2026-10-11-agent-client.md@@ -52,11 +52,15 @@ harness close <name> [--now] # save its screen and stop iText by default, for agents as much as people: they read it as well, and it is a third of JSON's size (`ps` onthe owner's Mac, 21 harnesses: 5.8 KB of text, 16.2 KB of JSON). `--json` for programs. Every error says what to run next.-`wait` exits 0 idle, 3 needs the person, 4 stopped or gone, 124 timed out.+`wait` exits 0 idle, 3 needs the person, 4 stopped or gone, 124 timed out. A harness the caller closed itself is+`closed (you closed it)` and exits 0 (`close` notes it in the ledger): a Codex lead that closed its harness and then+waited on it, as it had queued, was told it had failed (October 12).**Close, not stop** (owner, October 11): `harness stop` stops the daemon, and an agent typing it with a nameleft empty would have stopped Harness. `close` is the app's close (`agent_close`): it saves the screen, stops the-harness and keeps its conversation, and refuses while the harness is working unless `--now`.+harness and keeps its conversation, and refuses while the harness is working unless `--now`. A harness still starting+is closed once its first conversation binds; one that has bound none within eight seconds is closed without one, and+says so (October 12: Codex 0.162.1 closed a second after its start was refused, its conversation not yet readable).The agent's instructions are a skill, [plugins/harness/skills/harness/SKILL.md](../../plugins/harness/skills/harness/SKILL.md):when to use Harness at all, the rule below, the verbs and the limits. Agents outside Harness get it as a Claude Codediff --git a/plugins/harness/skills/harness/SKILL.md b/plugins/harness/skills/harness/SKILL.mdindex 3b3ada9a3..c0394e8d6 100644--- a/plugins/harness/skills/harness/SKILL.md+++ b/plugins/harness/skills/harness/SKILL.md@@ -72,12 +72,13 @@ harness close <name> [--now] # when you are done with onerather than a folder of your own: Claude Code and Codex ask the person to trust a folder Harness did not make.- Put the whole task in `-- <task>`: what to do, where, what done looks like, and what to answer with. A taskholds 2,000 characters; for a longer one, write it to a file and name the file in the task.-- `wait` exits 0 when it is idle, 3 when it needs the person (a question or a permission: only the person- answers those, so tell them), 4 when it stopped or is gone, 124 on timeout. `--timeout 0` waits as long as- it takes.+- `wait` exits 0 when it is idle (or you closed it), 3 when it needs the person (a question or a permission:+ only the person answers those, so tell them), 4 when it stopped or is gone, 124 on timeout. `--timeout 0`+ waits as long as it takes.- Read the result with `show` instead of asking for a summary.- `close` what you started once you have what you need. It keeps the conversation; the person can resume it.- It refuses while the harness is working, unless `--now`.+ It refuses while the harness is working, unless `--now`. One closed while still starting may have no+ conversation to keep yet, and `close` says so.- Add `--json` to any verb for JSON. Every error says what to run next.## Inside a harness, or outside