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
refactor(search): own external session readers and hold adoption safely (#1081)
Dee4cad218c9dcb
diff --git a/cli/e2e/adopt.e2e.ts b/cli/e2e/adopt.e2e.tsindex f5694d652..cf7536e50 100644--- a/cli/e2e/adopt.e2e.ts+++ b/cli/e2e/adopt.e2e.ts@@ -4,11 +4,12 @@* archived does not: Codex refuses to resume it until `codex unarchive <id>` puts it back, and opening it* started a pane that only printed Codex's error. The daemon now says so, and opens nothing.*/-import { mkdirSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, 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 { IsolatedDaemon, until } from './harness/daemon.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'type Row = Record<string, any>@@ -20,7 +21,7 @@ describe('opening a Codex conversation Harness did not start', () => {let daemon: IsolatedDaemon | undefinedafterEach(async () => { await daemon?.close(); daemon = undefined })- it('one from a terminal opens as a harness on it; one Codex archived is refused, saying how to put it back', async () => {+ it('opens a terminal conversation, refuses archives, and never replaces an adopted conversation when restart loses resume support', async () => {const d = await IsolatedDaemon.create()daemon = donTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })@@ -39,6 +40,7 @@ describe('opening a Codex conversation Harness did not start', () => {rollout(join(d.engineConfig.codexHome, 'archived_sessions'), archived)await d.start()const client = await LocalClient.connect(d)+ await until('search to connect before checking known refusals', () => d.log().includes('[services] search connected') || null, 30_000, 100)// As the apps open a search hit: its engine, its folder and its id (desktop `resumeConversation`).const refused = await client.request('agent_create', { engine: 'codex', cwd, resumeSessionId: archived, bypassPermission: true }, 90_000)@@ -52,6 +54,92 @@ describe('opening a Codex conversation Harness did not start', () => {const now = await row(client, opened.agent.id)return now?.sessionId === kept && now.status === 'active' ? now : null}, 60_000, 500)+ // Binding is announced while held restore is still committing its route. Finish a real turn+ // before asking for a second pane operation, as the already-running restart tests do.+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === opened.agent.id, 45_000)+ client.send('message', { agentId: opened.agent.id, content: 'Adopted conversation before the update' })+ await ended+ // An engine update can remove resume. The coordinator must carry the adoption's strict+ // resume requirement into the real pane swap instead of falling back to a new conversation.+ const wrapper = join(d.root, 'bin', 'codex')+ const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).href+ writeFileSync(wrapper + '.new', `#!${process.execPath}\nimport(${JSON.stringify(module)}).then(m => m.run('codex', ${JSON.stringify({ ...d.engineConfig, version: '0.161.0', without: ['resume'] })}))\n`, { mode: 0o755 })+ renameSync(wrapper + '.new', wrapper)+ expect(await client.request('agent_restart', { agentId: opened.agent.id }, 90_000)).toMatchObject({ error: 'RESTART_FAILED' })+ const conversations = (await rows(client)).filter(agent => agent.engine === 'codex' && agent.sessionId)+ expect(conversations.length).toBeGreaterThan(0)+ expect(conversations.every(agent => agent.sessionId === kept)).toBe(true)+ client.close()+ }, 240_000)++ it('holds through a search outage and tmux loss, cancels without archiving, then resumes entirely in core once admitted', async () => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-200).join('\n')}`) })+ const gate = join(d.root, 'hold-search')+ writeFileSync(gate, '')+ d.env.HARNESSD_TEST_HOLD_CONNECT = `search:${gate}`+ const cwd = join(d.projectsDir, 'external-held'); mkdirSync(cwd, { recursive: true })+ const dir = join(d.engineConfig.codexHome, 'sessions', '2026', '10', '09'); mkdirSync(dir, { recursive: true })+ const ids = ['019a0c0d-0000-7000-8000-0000000000b1', '019a0c0d-0000-7000-8000-0000000000b2']+ const paths = ids.map(id => join(dir, `rollout-2026-10-09T00-00-00-${id}.jsonl`))+ for (const [i, path] of paths.entries()) writeFileSync(path, JSON.stringify({ timestamp: new Date().toISOString(), type: 'session_meta',+ payload: { id: ids[i], cli_version: '0.159.0', cwd, source: 'cli' } }) + '\n')+ const untouched = readFileSync(paths[1], 'utf8')+ const started = Date.now(); await d.start()+ expect(Date.now() - started).toBeLessThan(15_000)+ let client = await LocalClient.connect(d)+ const held = []+ for (const id of ids) {+ const answer = await client.request('agent_create', { engine: 'codex', cwd, resumeSessionId: id, bypassPermission: true }, 15_000)+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ held.push(answer.agent.id as string)+ expect(await row(client, answer.agent.id)).toMatchObject({ sessionId: '', launch: { state: 'held', service: 'search' } })+ }+ expect(await client.request('agent_create', { engine: 'codex', cwd, resumeSessionId: ids[0], bypassPermission: true }, 15_000))+ .toMatchObject({ error: 'SESSION_IN_HARNESS' })+ expect((await client.request('agent_delete', { agentId: held[1] }, 10_000)).error).toBeUndefined()+ await until('cancelled adoption removed without an archive', async () => !await row(client, held[1]) || null, 10_000, 100)+ expect(existsSync(join(d.dataDir, 'stopped-agents', `${held[1]}.json`))).toBe(false)+ expect(readFileSync(paths[1], 'utf8')).toBe(untouched)++ // Session control is independent of the catalog: a plain harness starts and closes a turn here.+ const own = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 30_000)+ expect(own.error, JSON.stringify(own)).toBeUndefined()+ await until('plain harness binds while search is unavailable', async () => (await row(client, own.agent.id))?.sessionId || null, 45_000, 100)+ const turn = async (agentId: string, content: string) => {+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === agentId, 45_000)+ client.send('message', { agentId, content }); await ended+ }+ await turn(own.agent.id, 'Core control while search waits')+ client.close(); await d.stop(); await d.tmux.run('kill-server'); await d.start()+ client = await LocalClient.connect(d)+ expect(await row(client, held[0])).toMatchObject({ sessionId: '', launch: { state: 'held', service: 'search' } })+ expect(await row(client, held[1])).toBeUndefined()+ expect(readFileSync(paths[1], 'utf8')).toBe(untouched)++ unlinkSync(gate)+ await until('the held adoption resumes after search returns', async () => {+ const resumed = await row(client, held[0])+ return resumed?.sessionId === ids[0] && resumed.status === 'active' ? resumed : null+ }, 60_000, 250)+ await turn(held[0], 'Admitted conversation continues')++ // Once admitted, both crash restore and Stop/Open use the owned row while search is absent.+ client.close(); await d.stop(); writeFileSync(gate, ''); await d.tmux.run('kill-server'); await d.start()+ client = await LocalClient.connect(d)+ await until('admitted conversation returns without search', async () => {+ const resumed = await row(client, held[0])+ return resumed?.sessionId === ids[0] && resumed.status === 'active' ? resumed : null+ }, 60_000, 250)+ expect((await client.request('agent_delete', { agentId: held[0] }, 30_000)).error).toBeUndefined()+ await until('admitted conversation is stopped', async () => (await row(client, held[0]))?.status === 'stopped' || null, 30_000, 100)+ expect((await client.request('agent_resume', { agentId: held[0] }, 60_000)).error).toBeUndefined()+ await until('admitted conversation opens without search', async () => {+ const resumed = await row(client, held[0])+ return resumed?.sessionId === ids[0] && resumed.status === 'active' ? resumed : null+ }, 60_000, 250)+ await turn(held[0], 'Open remained in core')client.close()}, 240_000)})diff --git a/cli/scripts/handoff-2026-10-08/mutate-external.py b/cli/scripts/handoff-2026-10-08/mutate-external.pynew file mode 100644index 000000000..a426f7e1b--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-external.py@@ -0,0 +1,49 @@+"""Prove the former external shape golden and new safety regressions cross real wiring.++Run with no tests or source edits in flight. Every mutation is restored, even on failure.+"""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+golden = 'src/lib/sessionSearch/externalShapes.golden.spec.ts'+mutations = [+ ('owner observations dropped', 'src/services/externalSessions.ts',+ 'const claim = claims.find(claim => !claim.fromArgs) ?? claims[0]', 'const claim = undefined', golden),+ ('busy observations dropped', 'src/services/externalSessions.ts',+ 'busy: activity.value?.busy !== false', 'busy: false', golden),+ ('archived conversation admitted', 'src/core/agents/adopt.ts',+ 'if (found.archived)', 'if (false)', golden),+ ('Hermes profile stripped at wire', 'src/lib/externalSessionWire.ts',+ '...(value.launchArgs ? { launchArgs: [...value.launchArgs as string[]] } : {})', '...{}', golden),+ ('canonical alias reservation dropped', 'src/core/agents/adopt.ts',+ '[found.sessionId, ...found.aliases ?? []].some(held)', '[found.sessionId].some(held)', golden),+ ('validated launch never dispatched', 'src/core/agents/externalResume.ts',+ ' deps.launch()', ' // disconnected launch wiring', 'src/core/agents/externalResume.spec.ts'),+ ('dispatch journal omitted', 'src/lib/restoreAgents.ts',+ 'const committed = deps.registry.beginExternalDispatch?.(entry.agentId)',+ 'const committed = deps.registry.byAgent(entry.agentId)', 'src/lib/restoreAgents.spec.ts'),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+env.pop('TMUX', None)+env.pop('TMUX_PANE', None)+command = ['node', 'node_modules/vitest/vitest.mjs', 'run', '--maxWorkers=1']+baseline = subprocess.run([*command, *sorted({item[4] for item in mutations})], cwd=cli, env=env,+ capture_output=True, text=True, timeout=90)+if baseline.returncode:+ sys.exit('Baseline did not pass; no mutations were run.\n' + baseline.stdout[-5000:] + baseline.stderr[-5000:])+for name, path, old, new, spec in mutations:+ target = cli / path+ source = target.read_text()+ assert source.count(old) == 1, (name, source.count(old))+ try:+ target.write_text(source.replace(old, new))+ result = subprocess.run([*command, spec], cwd=cli, env=env, capture_output=True, text=True, timeout=90)+ caught = result.returncode != 0 and 'AssertionError' in result.stdout + result.stderr+ print(f'{name}: {"caught by assertion" if caught else "NOT PROVEN"}', flush=True)+ if not caught:+ sys.exit(result.stdout[-5000:] + result.stderr[-5000:])+ finally:+ target.write_text(source)diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 8b78f67e1..7d187035f 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -211,8 +211,8 @@ const EDGE: RegExp[] = [/^lib\/(commander|agentNotifications)\.ts$/,// Package execution belongs to the Store; core retains the installed index and launch contracts./^dsh\/(catalog|install|update|updates|registry|wire|service|lock|builtins|viewer|viewerLedger|verdict|artifacts|runtime|materialize|shell|preparation)\.ts$/,- // Search's index; the readers of other engines' sessions (external.ts, externals/) are the core's, for adoption.- /^lib\/sessionSearch\/(?!external\.ts$|externals\/)/,+ // Search owns external catalogs and provider reads too. Core keeps only the wire's declared types.+ /^lib\/sessionSearch\/(?!externals\/types\.ts$)/,// Downloading builds: the updater's, in a process the master runs (services/updaterProcess.ts). The core// never downloads a build./^lib\/(selfUpdate|runtimeInstall)\.ts$/, /^tui\/(update|install)\.ts$/,@@ -282,7 +282,7 @@ const FACETS_FREE_OF_THEM: Array<[string, string]> = [['lib/engineLaunch.ts', '(o6)'],['lib/gridLaunch.ts', '(o6)'],['lib/subscriptionModel.ts', '(o6)'],- // Adoption: the other engines' readers, each loaded on the first scan or question that needs it.+ // Search's provider composition still loads each engine lazily in its own process.['lib/sessionSearch/externals/index.ts', '(o5)'],['lib/sessionSearch/external.ts', '(o5)'],['core/agents/adopt.ts', '(o5)'],diff --git a/cli/src/core/agents/adopt.spec.ts b/cli/src/core/agents/adopt.spec.tsindex 816b15cf9..4a1a63a52 100644--- a/cli/src/core/agents/adopt.spec.ts+++ b/cli/src/core/agents/adopt.spec.ts@@ -1,163 +1,58 @@import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { RegisteredSession } from '../../lib/registry.js'-import { processAlive, stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'-import { createAdoption, type AdoptDeps } from './adopt.js'--vi.mock('../../lib/sessionSearch/external.js', async (real) => ({- ...await real<object>(),- processAlive: vi.fn(() => true),- stopSessionOwner: vi.fn(async () => true),-}))--const folder = mkdtempSync(join(tmpdir(), 'core-adopt-'))-afterAll(() => rmSync(folder, { recursive: true, force: true }))--const conversation = (over: Record<string, unknown> = {}) => ({ sessionId: 'c1', engine: 'claude', cwd: folder, title: 'Fix the build', ...over })-const owner = (over: Partial<SessionOwner> = {}): SessionOwner =>- ({ pid: 7, engine: 'claude', tty: '/dev/ttys001', fromArgs: false, harness: false, unverified: false, ...over }) as SessionOwner--function setup(over: Partial<AdoptDeps> = {}) {- const found = new Map<string, ReturnType<typeof conversation>>()- let starting = true- const deps: AdoptDeps = {- bySession: vi.fn(() => undefined),- byAgent: vi.fn(() => (starting ? { launch: { state: 'starting' } } : { launch: { state: 'ready' } }) as RegisteredSession),- stoppedAgents: { list: vi.fn(() => []) },- externalSessions: { get: vi.fn((id: string) => found.get(id) as never), scan: vi.fn(async () => []) },- openSessions: { owner: vi.fn(async () => null), busy: vi.fn(async () => false) },- search: null,- ...over,- }- return { deps, found, adoption: createAdoption(deps), launched: () => { starting = false } }-}--describe('whether a conversation can be opened here', () => {- it('refuses one that is already a harness, live, stopped, or under another of its names', async () => {- const live = setup({ bySession: vi.fn((id: string) => id === 'c1' ? ({} as RegisteredSession) : undefined) })- expect(await live.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ ok: false, error: 'SESSION_IN_HARNESS' })- const stopped = setup({ stoppedAgents: { list: vi.fn(() => [{ sessionId: 'c1' } as RegisteredSession]) } })- expect(await stopped.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_IN_HARNESS' })- const alias = setup({ bySession: vi.fn((id: string) => id === 'old-name' ? ({} as RegisteredSession) : undefined) })- alias.found.set('c1', conversation({ aliases: ['old-name'] }))- expect(await alias.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_IN_HARNESS' })- })-- it('looks again for one it has not seen, and refuses one that is gone, of another engine, or whose folder went', async () => {- const run = setup()- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_NOT_FOUND' })- expect(run.deps.externalSessions.scan).toHaveBeenCalled()- run.found.set('c1', conversation({ engine: 'codex' }))- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toEqual({ ok: false, error: 'INVALID_ENGINE', detail: 'This is a codex conversation.' })- run.found.set('c1', conversation({ cwd: join(folder, 'gone') }))- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_FOLDER_GONE' })- })-- // Codex will not resume a conversation it archived ("session <id> is archived. Run `codex unarchive- // <id>` to unarchive it first"). Search finds archived ones, and opening one used to start a pane that- // only printed that error: refused before anything starts or is stopped, with how to get it back.- it('refuses a conversation Codex archived, saying how to put it back, before asking who has it open', async () => {- const run = setup()- run.found.set('c1', conversation({ engine: 'codex', archived: true }))- expect(await run.adoption.adoptableSession('c1', 'codex', 'now')).toEqual({- ok: false, error: 'SESSION_ARCHIVED', detail: 'Codex archived this conversation. Run `codex unarchive c1` in a terminal, then open it here.',- })- expect(run.deps.openSessions.owner).not.toHaveBeenCalled()- })-- it('opens one nobody has open, under its own title, or search\'s, or none', async () => {- const run = setup({ search: { session: () => ({ title: 'From search' }) } })- run.found.set('c1', conversation({ launchArgs: ['--model', 'opus'] }))- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toEqual({- ok: true, cwd: folder, title: 'Fix the build', owner: null, busy: false, launchArgs: ['--model', 'opus'],- })- run.found.set('c1', conversation({ title: '' }))- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ title: 'From search', launchArgs: [] })- const bare = setup({ search: { session: () => undefined } })- bare.found.set('c1', conversation({ title: '' }))- expect(await bare.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ title: '' })- })-- it('never takes one from Harness\'s own pane, an app, or a terminal it cannot be sure of', async () => {- const run = setup()- run.found.set('c1', conversation())- const asked = async (who: SessionOwner) => {- vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(who)- return run.adoption.adoptableSession('c1', 'claude', 'now')+import { afterAll, describe, expect, it } from 'vitest'+import { externalUnavailable, type ExternalSessionObservation } from '../../lib/externalSessionWire.js'+import { adoptionDecision, createAdoption } from './adopt.js'++const cwd = mkdtempSync(join(tmpdir(), 'core-adopt-'))+afterAll(() => rmSync(cwd, { recursive: true, force: true }))+const request = { engine: 'claude' as const, sessionId: 'conversation' }+const fact = { ...request, cwd, title: '', origin: 'terminal' as const, mtime: 1, transcriptPath: join(cwd, 'conversation.jsonl') }+const owner = { pid: 7, engine: 'claude' as const, tty: '/dev/fixture-terminal', record: '/fixture/record' }+const answer = (over: Partial<ExternalSessionObservation> = {}): ExternalSessionObservation =>+ ({ ok: true, request, session: fact, owner: null, generation: null, busy: false, ...over })+const choose = (observation = answer(), takeOver: 'idle' | 'now' | 'wait' | null = null, held = (_: string) => false) =>+ adoptionDecision(request.sessionId, request.engine, takeOver, observation, held)++describe('core admission from search observations', () => {+ it('refuses existing reservations, archived/wrong/missing conversations and missing folders', () => {+ expect(choose(answer(), null, () => true)).toMatchObject({ error: 'SESSION_IN_HARNESS' })+ expect(choose(answer({ session: { ...fact, aliases: ['reserved'] } }), null, id => id === 'reserved')).toMatchObject({ error: 'SESSION_IN_HARNESS' })+ expect(choose(answer({ session: null }))).toMatchObject({ error: 'SESSION_NOT_FOUND' })+ expect(choose(answer({ session: { ...fact, engine: 'codex' } }))).toMatchObject({ error: 'INVALID_ENGINE' })+ expect(choose(answer({ session: { ...fact, archived: true } }))).toMatchObject({ error: 'SESSION_ARCHIVED' })+ expect(choose(answer({ session: { ...fact, cwd: join(cwd, 'gone') } }))).toMatchObject({ error: 'SESSION_FOLDER_GONE' })+ expect(adoptionDecision('conversation', 'claude', null, externalUnavailable(), () => false)).toMatchObject({ error: 'SEARCH_UNAVAILABLE' })+ })+ it('preserves metadata and profile arguments when no other process holds it', () => {+ expect(choose()).toEqual({ ok: true, cwd, title: '', owner: null, busy: false, launchArgs: [] })+ expect(choose(answer({ session: { ...fact, title: 'Named', launchArgs: [] } }))).toMatchObject({ title: 'Named', launchArgs: [] })+ })+ it.each([+ [{ ...owner, harness: true }, 'SESSION_IN_HARNESS'],+ [{ ...owner, fromArgs: true }, 'SESSION_OPEN_ELSEWHERE'],+ [{ ...owner, unverified: true }, 'SESSION_OPEN_ELSEWHERE'],+ [{ ...owner, tty: null }, 'SESSION_OPEN_ELSEWHERE'],+ ] as const)('never takes ownership class %j', (process, error) => {+ expect(choose(answer({ owner: process }), 'now')).toMatchObject({ error })+ })+ it('requires fresh idle consent unless takeover-now was explicitly chosen', () => {+ for (const takeOver of [null, 'idle'] as const) expect(choose(answer({ owner, busy: true }), takeOver)).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })+ expect(choose(answer({ owner }), null)).toMatchObject({ error: 'SESSION_OPEN_IN_TERMINAL' })+ for (const takeOver of ['now', 'wait', 'idle'] as const) expect(choose(answer({ owner }), takeOver)).toMatchObject({ ok: true, owner })+ expect(choose(answer({ owner, busy: true }), 'wait')).toMatchObject({ ok: true, busy: true })+ })+ it('the facade always asks fresh and refuses an invalid engine or an unavailable/moved owner', async () => {+ let value = answer()+ const api = createAdoption({ inspect: async () => value, held: () => false })+ expect(await api.adoptableSession('conversation', 'terminal', null)).toMatchObject({ error: 'SEARCH_UNAVAILABLE' })+ expect(await api.adoptableSession('conversation', 'claude', null)).toMatchObject({ ok: true })+ expect(await api.heldBy('conversation', owner)).toBe('free')+ for (const change of [{ ...owner, pid: 8 }, { ...owner, tty: null }, { ...owner, fromArgs: true }, { ...owner, harness: true }, { ...owner, unverified: true }]) {+ value = answer({ owner: change }); expect(await api.heldBy('conversation', owner)).toBe('other')}- expect(await asked(owner({ harness: true }))).toMatchObject({ error: 'SESSION_IN_HARNESS' })- expect(await asked(owner({ fromArgs: true }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: expect.stringContaining('in a terminal') })- expect(await asked(owner({ unverified: true }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE' })- expect(await asked(owner({ tty: null } as Partial<SessionOwner>))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: expect.stringContaining("Claude's app") })- })-- it('takes one from a terminal only when asked, and says when that terminal is mid-turn', async () => {- const run = setup()- run.found.set('c1', conversation())- vi.mocked(run.deps.openSessions.owner).mockResolvedValue(owner())- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_OPEN_IN_TERMINAL' })- expect(await run.adoption.adoptableSession('c1', 'claude', 'idle')).toMatchObject({ ok: true, busy: false })- vi.mocked(run.deps.openSessions.busy).mockResolvedValue(true)- expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })- expect(await run.adoption.adoptableSession('c1', 'claude', 'idle')).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })- expect(await run.adoption.adoptableSession('c1', 'claude', 'now')).toMatchObject({ ok: true, busy: true })- expect(await run.adoption.adoptableSession('c1', 'claude', 'wait')).toMatchObject({ ok: true, busy: true })- })-})--describe('who holds a conversation now', () => {- it('is the same terminal process only on hard evidence', async () => {- const run = setup()- expect(await run.adoption.heldBy('c1', owner())).toBe('free')- vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(owner())- expect(await run.adoption.heldBy('c1', owner())).toBe('same')- for (const changed of [{ pid: 8 }, { tty: null }, { fromArgs: true }, { harness: true }, { unverified: true }] as Array<Partial<SessionOwner>>) {- vi.mocked(run.deps.openSessions.owner).mockResolvedValueOnce(owner(changed))- expect(await run.adoption.heldBy('c1', owner()), JSON.stringify(changed)).toBe('other')- }- })-})--describe('taking a conversation over when its turn ends', () => {- beforeEach(() => {- vi.useFakeTimers()- vi.spyOn(console, 'log').mockImplementation(() => {})- vi.mocked(processAlive).mockReset().mockReturnValue(true)- vi.mocked(stopSessionOwner).mockReset().mockResolvedValue(true)- })- afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })-- it('waits for the turn to end, then stops the terminal\'s process', async () => {- const log = vi.mocked(console.log)- const run = setup()- vi.mocked(run.deps.openSessions.owner).mockResolvedValue(owner())- vi.mocked(run.deps.openSessions.busy).mockResolvedValueOnce(true).mockResolvedValueOnce(false)- const done = run.adoption.takeOverWhenIdle('a1', owner(), 'c1')- await vi.advanceTimersByTimeAsync(2_000)- await done- expect(stopSessionOwner).toHaveBeenCalledWith(owner())- expect(String(log.mock.calls[0][0])).toContain('turn ended · pid 7 stopped')- vi.mocked(stopSessionOwner).mockResolvedValueOnce(false)- const again = run.adoption.takeOverWhenIdle('a1', owner(), 'c1')- await vi.advanceTimersByTimeAsync(1_000)- await again- expect(String(log.mock.calls[1][0])).toContain('pid 7 did not stop')- })-- it('gives up when the harness stops starting, the process is gone, or the terminal moved on', async () => {- const log = vi.mocked(console.log)- const run = setup()- run.launched()- await (async () => { const done = run.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()- const gone = setup()- vi.mocked(processAlive).mockReturnValueOnce(false)- await (async () => { const done = gone.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()- const moved = setup()- vi.mocked(moved.deps.openSessions.owner).mockResolvedValue(owner({ pid: 8 }))- await (async () => { const done = moved.adoption.takeOverWhenIdle('a1', owner(), 'c1'); await vi.advanceTimersByTimeAsync(1_000); await done })()- expect(stopSessionOwner).not.toHaveBeenCalled()- expect(String(log.mock.calls[0][0])).toContain('pid 7 moved on · left running')+ value = answer({ owner }); expect(await api.heldBy('conversation', owner)).toBe('same')+ expect(await createAdoption({ inspect: async () => externalUnavailable(), held: () => false }).heldBy('conversation', owner)).toBe('other')})})diff --git a/cli/src/core/agents/adopt.ts b/cli/src/core/agents/adopt.tsindex df4814e98..cdd83304e 100644--- a/cli/src/core/agents/adopt.ts+++ b/cli/src/core/agents/adopt.ts@@ -1,44 +1,21 @@-/**- * Adopting a conversation Harness did not start: whether one discovery found can be opened here as a- * harness, and taking it over from a terminal that has it open — now, or once its turn ends — never- * from an app, and never from a pane that is Harness's own.- *- * Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).- */+/** Core decides admission. Search supplies observations, never ownership or control authority. */import { existsSync } from 'node:fs'import type { AgentEngine } from '../../engines/types.js'import { engineLabel } from '../../lib/agentNames.js'-import { sid } from '../../lib/log.js'-import type { RegisteredSession } from '../../lib/registry.js'-import { processAlive, stopSessionOwner, type ExternalSessions, type OpenSessions, type SessionOwner } from '../../lib/sessionSearch/external.js'-import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'+import { externalSessionRequest, externalUnavailable, type ExternalSessionAnswer, type ExternalSessionRequest } from '../../lib/externalSessionWire.js'+import type { SessionOwner } from '../../lib/sessionSearch/external.js'export interface AdoptDeps {- bySession: (sessionId: string) => RegisteredSession | undefined- byAgent: (agentId: string) => RegisteredSession | undefined- stoppedAgents: Pick<StoppedAgentStore, 'list'>- externalSessions: Pick<ExternalSessions, 'get' | 'scan'>- openSessions: Pick<OpenSessions, 'owner' | 'busy'>- /** Session search, when it is on: the title it indexed for a conversation. */- search: { session(sessionId: string): { title?: string } | undefined } | null | undefined+ inspect(request: ExternalSessionRequest): Promise<ExternalSessionAnswer>+ held(id: string): boolean}-export function createAdoption({ bySession, byAgent, stoppedAgents, externalSessions, openSessions, search }: AdoptDeps) {- /**- * Whether a conversation Harness did not start can be opened here as a harness: one discovery found- * (looked for again if it is new), on this engine, not already a harness, and not open in a running- * process — a terminal or the engine's app that still has it would write it too.- *- * One open in a terminal can be taken over ([takeOver]): the terminal's process is stopped and the- * conversation resumes here. Asked without it, the refusal says whether that process is mid-turn,- * so the person can choose to wait for the turn to end or stop it now. An app's is never stopped.- */- const adoptableSession = async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null): Promise<{ ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean; launchArgs: readonly string[] } | { ok: false; error: string; detail: string }> => {- const held = (id: string) => !!bySession(id) || stoppedAgents.list().some((s) => s.sessionId === id)+export function adoptionDecision(sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null, answer: ExternalSessionAnswer, held: (id: string) => boolean): { ok: true; cwd: string; title: string; owner: SessionOwner | null; busy: boolean; launchArgs: readonly string[] } | { ok: false; error: string; detail: string } {if (held(sessionId)) {return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }}- const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))+ if (!answer.ok) return answer+ const found = answer.sessionif (found && [found.sessionId, ...found.aliases ?? []].some(held)) {return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }}@@ -55,9 +32,9 @@ export function createAdoption({ bySession, byAgent, stoppedAgents, externalSessif (!existsSync(found.cwd)) {return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }}- const title = found.title || search?.session(sessionId)?.title || ''+ const title = found.titleconst launchArgs = found.launchArgs ?? []- const owner = await openSessions.owner(sessionId)+ const owner = answer.ownerif (!owner) return { ok: true, cwd: found.cwd, title, owner: null, busy: false, launchArgs }const engineName = engineLabel(engine)// A process in one of Harness's own panes is an agent the daemon is still binding: never stopped.@@ -70,7 +47,7 @@ export function createAdoption({ bySession, byAgent, stoppedAgents, externalSessif (!owner.tty) {return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: `It is open in ${engineName}'s app or an editor. Close it there, then open it here.` }}- const busy = await openSessions.busy(owner)+ const busy = answer.busyif (busy && (takeOver === null || takeOver === 'idle')) {return { ok: false, error: 'SESSION_BUSY_IN_TERMINAL', detail: `${engineName} is working on it in a terminal.` }}@@ -80,40 +57,22 @@ export function createAdoption({ bySession, byAgent, stoppedAgents, externalSessreturn { ok: true, cwd: found.cwd, title, owner, busy, launchArgs }}- /**- * A conversation taken over when its turn ends (`takeOver: 'wait'`): its pane waits for the- * terminal's process to go (engineLaunch `waitForPid`), and this stops that process once the turn- * is over. It gives up when the harness does — closed, or Ctrl-C in its pane — and when the person- * quits it in the terminal themselves, which is the pane's cue as well.- */- const takeOverWhenIdle = async (agentId: string, owner: SessionOwner, sessionId: string): Promise<void> => {- for (;;) {- await new Promise<void>((resolve) => { const timer = setTimeout(resolve, 1_000); timer.unref?.() })- if (byAgent(agentId)?.launch?.state !== 'starting' || !processAlive(owner.pid)) return- // Moved on in that terminal (`/resume`, `/new`): its turn is another conversation's now, and it- // is left alone. The pane still waits for it to quit, and then opens this one.- if (await heldBy(sessionId, owner) !== 'same') {- console.log(`[agent] take over ${sid(sessionId)} · pid ${owner.pid} moved on · left running`)- return- }- if (await openSessions.busy(owner)) continue- const stopped = await stopSessionOwner(owner)- console.log(`[agent] take over ${sid(sessionId)} · turn ended · pid ${owner.pid} ${stopped ? 'stopped' : 'did not stop'}`)- return- }- }- /**- * Who holds [sessionId] now, against the [owner] seen when the person chose: `same` (that process,- * still a terminal's, by hard evidence, not one of Harness's own), `free` (nobody), or `other`.- * Asked again right before anything is stopped: the terminal may have moved to other work since.- */- const heldBy = async (sessionId: string, owner: SessionOwner): Promise<'same' | 'free' | 'other'> => {- const now = await openSessions.owner(sessionId)- if (!now) return 'free'- return now.pid === owner.pid && !!now.tty && !now.fromArgs && !now.harness && !now.unverified ? 'same' : 'other'+export function createAdoption(deps: AdoptDeps) {+ const inspect = (sessionId: string, engine: AgentEngine) => {+ const request = externalSessionRequest({ sessionId, engine })+ return request ? deps.inspect(request) : Promise.resolve(externalUnavailable())+ }+ return {+ adoptableSession: async (sessionId: string, engine: AgentEngine, takeOver: 'idle' | 'now' | 'wait' | null) =>+ adoptionDecision(sessionId, engine, takeOver, await inspect(sessionId, engine), deps.held),+ heldBy: async (sessionId: string, owner: SessionOwner): Promise<'same' | 'free' | 'other'> => {+ const answer = await inspect(sessionId, owner.engine)+ if (!answer.ok) return 'other'+ const now = answer.owner+ if (!now) return 'free'+ return now.pid === owner.pid && !!now.tty && !now.fromArgs && !now.harness && !now.unverified ? 'same' : 'other'+ },}- return { adoptableSession, takeOverWhenIdle, heldBy }}-export type Adoption = ReturnType<typeof createAdoption>diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex e70315718..ef9dafeaa 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -96,9 +96,7 @@ function setup(over: Partial<CreateAgentDeps> = {}) {const deps: CreateAgentDeps = {tmuxBackend: {} as CreateAgentDeps['tmuxBackend'],registry: { setLaunch: vi.fn(() => ({ ...pending, launch: { state: 'ready' } })) } as unknown as CreateAgentDeps['registry'],- adoptableSession: vi.fn(async () => ({ ok: true, cwd: folder(), title: 'Adopted', owner: null, busy: false, launchArgs: [] })) as never,- heldBy: vi.fn(async () => 'same' as const),- takeOverWhenIdle: vi.fn(async () => {}),+ externalResume: vi.fn<CreateAgentDeps['externalResume']>(async () => ({ ok: true, session: pending })),watchNewPane: vi.fn(async () => {}),announceSession: vi.fn(),attachDsh: vi.fn(),@@ -128,6 +126,16 @@ describe('creating an agent', () => {})afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('hands external resume to its durable controller before folder, instructions or engine preparation', async () => {+ const externalResume = vi.fn<CreateAgentDeps['externalResume']>(async () => ({ ok: true, session: pending }))+ const test = setup({ externalResume })+ const input = request({ resumeSessionId: 'conversation' })+ expect(await test.create(input)).toEqual({ ok: true, session: pending })+ expect(externalResume).toHaveBeenCalledWith(input)+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ expect(test.deps.prepareApiTools).not.toHaveBeenCalled()+ })+describe('refusals before any pane opens', () => {it('without tmux, in a folder being purged, or in a folder that is not one', async () => {expect(await setup({ tmuxBackend: null }).create(request())).toEqual({ ok: false, error: 'TMUX_UNAVAILABLE' })@@ -193,15 +201,7 @@ describe('creating an agent', () => {expect(await create(request({ grid }))).toMatchObject({ detail: "could not write claude's grid configuration · worse" })})- it('when opening a conversation that cannot be opened, or that moved or would not quit in its terminal', async () => {- const refused = setup({ adoptableSession: vi.fn(async () => ({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'gone' })) as never })- expect(await refused.create(request({ resumeSessionId: 'c1' }))).toEqual({ ok: false, error: 'SESSION_NOT_FOUND', detail: 'gone' })- const adopted = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: false, launchArgs: [] }))- const moved = setup({ adoptableSession: adopted as never, heldBy: vi.fn(async () => 'other' as const) })- expect(await moved.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE' })- vi.mocked(stopSessionOwner).mockResolvedValueOnce(false)- expect(await setup({ adoptableSession: adopted as never }).create(request({ resumeSessionId: 'c1', takeOver: 'now' }))).toMatchObject({ error: 'SESSION_STOP_FAILED' })- })+it('when the pane itself cannot be made', async () => {vi.mocked(createAndRegisterPane).mockResolvedValueOnce({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' } as never)@@ -218,7 +218,6 @@ describe('creating an agent', () => {expect(deps.announceSession).toHaveBeenCalledWith(pending)expect(deps.attachDsh).not.toHaveBeenCalled()expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, { runtime: { paneId: '%1' } }, ['claude'], { install: 'recipe' }, undefined)- expect(deps.takeOverWhenIdle).not.toHaveBeenCalled()const pane = vi.mocked(createAndRegisterPane).mock.calls[0][0]expect(pane).toMatchObject({ engine: 'claude', sessionLabel: expect.any(String), grid: null, gridLaunchRecord: null, dsh: null, dshRuntime: null, defaultName: null })})@@ -389,47 +388,8 @@ describe('creating an agent', () => {expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, expect.anything(), ['claude'], undefined, undefined)})- it('opens a conversation Harness did not start, in its folder and under its title, resuming it', async () => {- const cwd = folder()- const adopted = vi.fn(async () => ({ ok: true, cwd, title: 'Fix the build', owner: null, busy: false, launchArgs: ['--model', 'opus'] }))- const { create } = setup({ adoptableSession: adopted as never })- await create(request({ resumeSessionId: 'c1' }))- expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ cwd, defaultName: 'Fix the build' })- expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ resumeSessionId: 'c1', extraArgs: ['--model', 'opus'] })- const untitled = vi.fn(async () => ({ ok: true, cwd, title: '', owner: null, busy: false, launchArgs: [] }))- await setup({ adoptableSession: untitled as never }).create(request({ resumeSessionId: 'c1' }))- expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ defaultName: null })- await setup({ adoptableSession: untitled as never }).create(request({ resumeSessionId: 'c1', name: 'Mine' }))- expect(vi.mocked(createAndRegisterPane).mock.calls[2][0]).toMatchObject({ defaultName: 'Mine' })- })- it('takes a conversation over from a terminal: stopped now (mid-turn: told to continue), or once its turn ends', async () => {- const log = vi.mocked(console.log)- const busyOwner = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: true, launchArgs: [] }))- const now = setup({ adoptableSession: busyOwner as never })- await now.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))- expect(stopSessionOwner).toHaveBeenCalledWith(owner)- expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({ firstPrompt: 'continue' })- expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('pid 7 stopped mid-turn'))).toBe(true)- // An engine that cannot open with a message just resumes where it stopped.- vi.mocked(supportsFirstPrompt).mockReturnValueOnce(false)- await now.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))- expect(vi.mocked(buildEngineLaunchArgv).mock.calls[1][1]).not.toHaveProperty('firstPrompt')- const idleOwner = vi.fn(async () => ({ ok: true, cwd: folder(), title: '', owner, busy: false, launchArgs: [] }))- await setup({ adoptableSession: idleOwner as never }).create(request({ resumeSessionId: 'c1', takeOver: 'now' }))- expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.endsWith('pid 7 stopped'))).toBe(true)- // Quit in its terminal meanwhile: nothing to stop.- const free = setup({ adoptableSession: idleOwner as never, heldBy: vi.fn(async () => 'free' as const) })- vi.mocked(stopSessionOwner).mockClear()- await free.create(request({ resumeSessionId: 'c1', takeOver: 'now' }))- expect(stopSessionOwner).not.toHaveBeenCalled()- // To wait for its turn: the pane waits on the process, and the watcher has a day.- const wait = setup({ adoptableSession: busyOwner as never })- await wait.create(request({ resumeSessionId: 'c1', takeOver: 'wait' }))- expect(stopSessionOwner).not.toHaveBeenCalled()- expect(vi.mocked(buildEngineLaunchArgv).mock.lastCall?.[1]).toMatchObject({ waitForPid: { pid: 7, name: 'Claude' } })- expect(wait.deps.watchNewPane).toHaveBeenCalledWith('claude', pending, expect.anything(), ['claude'], { install: 'recipe' }, 24 * 60 * 60_000)- expect(wait.deps.takeOverWhenIdle).toHaveBeenCalledWith('a1', owner, 'c1')- })++})})diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex b84a1a9c3..6cdfe85fb 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -35,13 +35,10 @@ import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/himport { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import { engineHooks } from '../../engines/hooks.js'import { folderTrust } from '../../engines/launchPrep.js'-import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'-import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'import { clearPaneRemainOnExit } from '../../lib/tmux.js'import type { TmuxBackend } from '../../lib/tmuxBackend.js'import { TMUX_SESSION_ENV_MIN, tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'-import type { Adoption } from './adopt.js'import { prepareInstructionWrites, scmLaunchEnv } from '../../scm/scmProjects.js'import { mergedLaunchEnv } from './launchEnv.js'import type { createPaneWatcher } from './newPane.js'@@ -57,9 +54,7 @@ export interface CreateAgentDeps {/** The tmux backend; null where the configuration lists no tmux. */tmuxBackend: TmuxBackend | nullregistry: typeof registry- adoptableSession: Adoption['adoptableSession']- heldBy: Adoption['heldBy']- takeOverWhenIdle: Adoption['takeOverWhenIdle']+ externalResume: CreateAgentwatchNewPane: ReturnType<typeof createPaneWatcher>announceSession: (session: RegisteredSession) => voidattachDsh: (session: RegisteredSession) => void@@ -87,26 +82,14 @@ export interface CreateAgentDeps {}export function createAgentCreator({- tmuxBackend, registry, adoptableSession, heldBy, takeOverWhenIdle, watchNewPane, announceSession, attachDsh,+ tmuxBackend, registry, externalResume, watchNewPane, announceSession, attachDsh,prepareApiTools, hookPort, hooksDisabled, installOpencodePlugin, gridLaunchMachine, buildGridLaunch, terminalHintMachineName, blocksFolder,gridSetup, privateGridName, dshLaunch,}: CreateAgentDeps) {- const createAgent: CreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId, takeOver, scmLaunchRecord }) => {+ const createAgent: CreateAgent = async input => {+ if (input.resumeSessionId) return externalResume(input)+ let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord } = inputif (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }- // A conversation Harness did not start opens in its own folder, under its own title — taken over- // from the terminal that has it, when asked to.- let owner: SessionOwner | null = null- let ownerBusy = false- let resumeArgs: readonly string[] = []- if (resumeSessionId) {- const adopted = await adoptableSession(resumeSessionId, engine, takeOver ?? null)- if (!adopted.ok) return adopted- cwd = adopted.cwd- name = name ?? (adopted.title || null)- owner = adopted.owner- ownerBusy = adopted.busy- resumeArgs = adopted.launchArgs- }if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }@@ -282,29 +265,13 @@ export function createAgentCreator({// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was// checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencode ? opencode.opencodeMajorVersion() : null) : []), ...resumeArgs]+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencode ? opencode.opencodeMajorVersion() : null) : [])]// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).- // Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open- // with a message; any other resumes where it stopped and waits.- const waitFor = owner && takeOver === 'wait' && ownerBusy ? owner : null- const firstPrompt = prompt ?? (owner && !waitFor && ownerBusy && supportsFirstPrompt(engine) ? 'continue' : null)- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), ...(waitFor ? { waitForPid: { pid: waitFor.pid, name: engineLabel(engine) } } : {}), terminalHint: { machineName: terminalHintMachineName() } }+ const firstPrompt = prompt+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), terminalHint: { machineName: terminalHintMachineName() } }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)- // The terminal's process goes last, once nothing here can refuse or fail the launch — the command- // is built — stopped now, or, to wait for its turn, left running for the pane to wait on.- if (owner && !waitFor && resumeSessionId) {- const held = await heldBy(resumeSessionId, owner)- if (held === 'other') {- return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It moved to another process just now. Close it there, then open it here.' }- }- // Quit in its terminal meanwhile: it is free, and nothing is stopped.- if (held === 'same' && !await stopSessionOwner(owner)) {- return { ok: false, error: 'SESSION_STOP_FAILED', detail: 'The terminal that has it did not quit. Close it there, then open it here.' }- }- if (held === 'same') console.log(`[agent] take over ${sid(resumeSessionId)} · pid ${owner.pid} stopped${ownerBusy ? ' mid-turn' : ''}`)- }// A tmux route is enough to stream its screen. Register it before looking for a process so both// loopback and relayed Desktop clients can attach while the login shell/installer is still busy.// `tmuxBackend` exists whenever the CONFIG lists tmux — it is never a probe of the binary, so a@@ -325,7 +292,7 @@ export function createAgentCreator({sessionLabel: label,argv,env: freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? profileEnvironment(engine, codexHome) : undefined), dshEnv),- scmLaunchEnv(scmLaunchRecord)), !!grid || !!resumeSessionId,+ scmLaunchEnv(scmLaunchRecord)), !!grid,permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,@@ -354,9 +321,7 @@ export function createAgentCreator({announceSession(pending)if (pending.dsh) attachDsh(pending)- // A pane waiting out another terminal's turn may wait as long as that turn takes.- void watchNewPane(engine, pending, spawned, command, installIfMissing, waitFor ? 24 * 60 * 60_000 : undefined)- if (waitFor && resumeSessionId) void takeOverWhenIdle(pending.agentId, waitFor, resumeSessionId)+ void watchNewPane(engine, pending, spawned, command, installIfMissing, undefined)console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)return { ok: true, session: pending }}diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.tsindex 66a85820b..f3eb11ee0 100644--- a/cli/src/core/agents/discovery.spec.ts+++ b/cli/src/core/agents/discovery.spec.ts@@ -293,3 +293,14 @@ describe('discovery', () => {expect(run.deps.announceSession).toHaveBeenCalledTimes(1)})})++it('cannot promote an unadmitted external waiting pane into a live engine', async () => {+ const test = setup()+ const pending = row({ active: false, sessionId: '', externalResume: { phase: 'waiting' } as RegisteredSession['externalResume'] })+ test.rows.set(pending.agentId, pending)+ await test.handlers.onObserved(seen(), pending)+ expect(test.deps.registry.updateRuntimes).not.toHaveBeenCalled()+ expect(test.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()+ expect(test.deps.registry.setLaunch).not.toHaveBeenCalled()+ expect(test.deps.bindObservedAgent).not.toHaveBeenCalled()+})diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsindex ebc4ff8e0..d495279b5 100644--- a/cli/src/core/agents/discovery.ts+++ b/cli/src/core/agents/discovery.ts@@ -7,6 +7,7 @@* Moved verbatim out of the reconciler's options in `runForeground` (the core boundary, step 10:* docs/design/2026-10-03-harnessd.md). The reconciler itself, with what it scans, stays there.*/+import { externalResumePending } from '../../lib/externalResume.js'import { isTerminalEngine } from '../../engines/types.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import type { QuestionWatcher } from '../../lib/questionController.js'@@ -87,6 +88,7 @@ export function createDiscoveryHandlers({await bindObservedAgent(observed)}const onObserved = async (observed: DiscoveredTerminalAgent, current: RegisteredSession): Promise<void> => {+ if (externalResumePending(current.externalResume)) returnconst wasDormant = !current.active// Read BEFORE the update, because the update is what overwrites it. `undefined` means the probe// could not look, which never counts as a move — see `probeGridAssignment`'s three answers.diff --git a/cli/src/core/agents/externalInspect.spec.ts b/cli/src/core/agents/externalInspect.spec.tsnew file mode 100644index 000000000..7a0f11da2--- /dev/null+++ b/cli/src/core/agents/externalInspect.spec.ts@@ -0,0 +1,45 @@+import { afterEach, expect, it, vi } from 'vitest'+import { externalUnavailable, type ExternalSessionAnswer } from '../../lib/externalSessionWire.js'+import { createExternalInspector } from './externalInspect.js'+const request = { sessionId: 'conversation', engine: 'claude' as const }+const free: ExternalSessionAnswer = { ok: true, request, session: null, owner: null, generation: null, busy: false }+afterEach(() => vi.useRealTimers())++it('validates exact replies, isolates throws, and fences a response from an old worker generation', async () => {+ let epoch = 1+ let reply!: (value: ExternalSessionAnswer) => void+ const call = vi.fn<() => Promise<ExternalSessionAnswer>>(async () => free)+ const inspect = createExternalInspector({ call, generation: () => epoch })+ expect(await inspect(request)).toEqual(free)+ call.mockRejectedValueOnce(new Error('reader unavailable'))+ expect(await inspect(request)).toEqual(externalUnavailable())+ call.mockImplementationOnce(() => new Promise(resolve => { reply = resolve }))+ const reading = inspect(request)+ await Promise.resolve()+ epoch+++ reply(free)+ expect(await reading).toEqual(externalUnavailable())+ expect(await inspect(request)).toEqual(free)+})++it('holds after a deadline without releasing hung work slots; a replacement worker gets fresh slots', async () => {+ vi.useFakeTimers()+ let epoch = 1+ const replies: Array<(value: ExternalSessionAnswer) => void> = []+ const call = vi.fn(() => new Promise<ExternalSessionAnswer>(resolve => replies.push(resolve)))+ const inspect = createExternalInspector({ call, generation: () => epoch, timeoutMs: 50 })+ const waiting = Array.from({ length: 4 }, () => inspect(request))+ await vi.advanceTimersByTimeAsync(51)+ expect(await Promise.all(waiting)).toEqual(Array(4).fill(externalUnavailable()))+ expect((await inspect(request)).ok).toBe(false)+ expect(call).toHaveBeenCalledTimes(4)+ epoch+++ const fresh = inspect(request)+ await Promise.resolve()+ replies[4](free)+ expect(await fresh).toEqual(free)+ for (const reply of replies.slice(0, 4)) reply(free)+ await Promise.resolve()+ call.mockResolvedValue(free)+ expect(await inspect(request)).toEqual(free)+})diff --git a/cli/src/core/agents/externalInspect.ts b/cli/src/core/agents/externalInspect.tsnew file mode 100644index 000000000..908eeed42--- /dev/null+++ b/cli/src/core/agents/externalInspect.ts@@ -0,0 +1,27 @@+/** Bounded observation admission also applies to the inline/debug service. A hung read occupies a slot. */+import { externalSessionAnswer, externalUnavailable, type ExternalSessionRequest, type ExternalSessionAnswer } from '../../lib/externalSessionWire.js'++export function createExternalInspector(deps: {+ call(request: ExternalSessionRequest): Promise<ExternalSessionAnswer>+ generation(): unknown+ timeoutMs?: number+}) {+ let generation = deps.generation()+ let active = new Set<symbol>()+ return async (request: ExternalSessionRequest): Promise<ExternalSessionAnswer> => {+ const epoch = deps.generation()+ if (epoch !== generation) { generation = epoch; active = new Set() }+ if (active.size >= 4) return externalUnavailable('Waiting for the search service to finish verifying conversations.')+ const token = Symbol(), slots = active+ slots.add(token)+ let timer: ReturnType<typeof setTimeout> | undefined+ const read = Promise.resolve().then(() => deps.call(request)).then(answer =>+ deps.generation() === epoch ? externalSessionAnswer(answer, request) : externalUnavailable(), () => externalUnavailable())+ .finally(() => slots.delete(token))+ try {+ return await Promise.race([read, new Promise<ExternalSessionAnswer>(resolve => {+ timer = setTimeout(() => resolve(externalUnavailable()), deps.timeoutMs ?? 5_000); timer.unref()+ })])+ } finally { clearTimeout(timer) }+ }+}diff --git a/cli/src/core/agents/externalOwner.spec.ts b/cli/src/core/agents/externalOwner.spec.tsnew file mode 100644index 000000000..756c80de3--- /dev/null+++ b/cli/src/core/agents/externalOwner.spec.ts@@ -0,0 +1,86 @@+import { afterEach, expect, it, vi } from 'vitest'+import { stopExternalOwner } from './externalOwner.js'+import { externalProcessGeneration } from '../../lib/externalProcessGeneration.js'+import { processExists } from '../../lib/processLiveness.js'+import { verifiedForegroundJob } from '../../lib/externalOwnerControl.js'+vi.mock('../../lib/externalProcessGeneration.js', () => ({ externalProcessGeneration: vi.fn(() => 'ps:1') }))+vi.mock('../../lib/processLiveness.js', () => ({ processExists: vi.fn(() => true) }))+vi.mock('../../lib/externalOwnerControl.js', () => ({ verifiedForegroundJob: vi.fn(async () => null) }))+const owner = { process: { pid: 7, engine: 'claude' as const, tty: '/dev/fixture-terminal', record: '/fixture/record' }, generation: 'ps:1' }+afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); vi.useRealTimers() })+function setup() {+ let alive = true, valid = true, marker = 'ps:1'+ const deps = { current: () => valid, same: vi.fn(async () => true), generation: () => marker, exists: () => alive,+ job: vi.fn(async (): Promise<number | null | 'unknown'> => 7), kill: vi.fn(() => { alive = false }), sleep: vi.fn(async () => {}) }+ return { deps, gone: () => { alive = false }, cancel: () => { valid = false }, replace: () => { marker = 'ps:2' } }+}+it('rechecks conversation after foreground lookup, journals at the signal and stops only its verified group', async () => {+ const test = setup(), order: string[] = []+ test.deps.job.mockImplementation(async () => { order.push('job'); return 7 })+ test.deps.same.mockImplementation(async () => { order.push('same'); return true })+ const result = await stopExternalOwner(owner, { ...test.deps,+ beforeSignal: () => order.push('intent'), afterSignal: () => order.push('sent') })+ expect(result).toBe(true)+ expect(order).toEqual(['job', 'same', 'intent', 'sent'])+ expect(test.deps.kill).toHaveBeenCalledWith(-7, 'SIGTERM')+})+it('holds unknown foreground evidence and changed or cancelled ownership without signalling', async () => {+ for (const mode of ['unknown', 'throws', 'moved', 'cancelled', 'replaced', 'cancel-after-read'] as const) {+ const test = setup()+ if (mode === 'unknown') test.deps.job.mockResolvedValue('unknown')+ if (mode === 'throws') test.deps.job.mockRejectedValue(new Error('ps failed'))+ if (mode === 'moved') test.deps.same.mockResolvedValue(false)+ if (mode === 'cancelled') test.cancel()+ if (mode === 'replaced') test.replace()+ if (mode === 'cancel-after-read') test.deps.same.mockImplementation(async () => { test.cancel(); return true })+ expect(await stopExternalOwner(owner, test.deps)).toBe(false)+ expect(test.deps.kill).not.toHaveBeenCalled()+ }+})+it('does not signal an exited owner, and checks the incarnation after a durable signal intent', async () => {+ const gone = setup(); gone.gone()+ expect(await stopExternalOwner(owner, gone.deps)).toBe(true)+ expect(gone.deps.kill).not.toHaveBeenCalled()+ for (const change of ['cancel', 'replace'] as const) {+ const test = setup()+ expect(await stopExternalOwner(owner, { ...test.deps, beforeSignal: test[change] })).toBe(false)+ expect(test.deps.kill).not.toHaveBeenCalled()+ }+})+it('rechecks the group and consent before KILL and never kills a replacement or cancelled process', async () => {+ const test = setup()+ test.deps.kill.mockImplementation((_pid?: number, signal?: NodeJS.Signals) => { if (signal === 'SIGKILL') test.gone() })+ expect(await stopExternalOwner(owner, test.deps)).toBe(true)+ expect(test.deps.job).toHaveBeenCalledTimes(2)+ expect(test.deps.same).toHaveBeenCalledTimes(2)+ for (const reason of ['cancel', 'replace', 'moved'] as const) {+ const test = setup(); test.deps.kill.mockImplementation(() => {})+ if (reason === 'moved') test.deps.same.mockResolvedValueOnce(true).mockResolvedValueOnce(false)+ else test.deps.sleep.mockImplementation(async () => { test[reason]() })+ expect(await stopExternalOwner(owner, test.deps)).toBe(false)+ expect(test.deps.kill).toHaveBeenCalledTimes(1)+ }+})+it('reports a stubborn owner or signal failure as unconfirmed, but recognizes exit during a signal race', async () => {+ const stubborn = setup(); stubborn.deps.kill.mockImplementation(() => {})+ expect(await stopExternalOwner(owner, stubborn.deps)).toBe(false)+ for (const gone of [true, false]) {+ const test = setup(); test.deps.job.mockResolvedValue(null)+ test.deps.kill.mockImplementation(() => { if (gone) test.gone(); throw new Error('signal refused') })+ expect(await stopExternalOwner(owner, test.deps)).toBe(gone)+ expect(test.deps.kill).toHaveBeenCalledWith(7, 'SIGTERM')+ }+})+it('uses the core OS controls by default, with a bounded wait and no terminal writes after exit', async () => {+ vi.useFakeTimers()+ vi.mocked(processExists).mockReturnValue(true)+ vi.mocked(externalProcessGeneration).mockReturnValue('ps:1')+ vi.mocked(verifiedForegroundJob).mockResolvedValue(null)+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true)+ const done = stopExternalOwner(owner, { current: () => true, same: async () => true })+ await vi.advanceTimersByTimeAsync(100)+ vi.mocked(processExists).mockReturnValue(false)+ await vi.advanceTimersByTimeAsync(100)+ expect(await done).toBe(true)+ expect(kill).toHaveBeenCalledWith(7, 'SIGTERM')+})diff --git a/cli/src/core/agents/externalOwner.ts b/cli/src/core/agents/externalOwner.tsnew file mode 100644index 000000000..9998d7ea3--- /dev/null+++ b/cli/src/core/agents/externalOwner.ts@@ -0,0 +1,51 @@+/** Only core may stop an external owner. Worker observations are revalidated at every signal. */+import { verifiedForegroundJob } from '../../lib/externalOwnerControl.js'+import { externalProcessGeneration } from '../../lib/externalProcessGeneration.js'+import { processExists } from '../../lib/processLiveness.js'+import type { ExternalResumeIntent } from '../../lib/externalResume.js'++export async function stopExternalOwner(owner: NonNullable<ExternalResumeIntent['owner']>, deps: {+ current(): boolean+ /** Fresh exact conversation, terminal, ownership class and incarnation, after asynchronous work. */+ same(): Promise<boolean>+ generation?: typeof externalProcessGeneration+ exists?: typeof processExists+ job?: typeof verifiedForegroundJob+ beforeSignal?(signal: NodeJS.Signals): void+ afterSignal?(signal: NodeJS.Signals): void+ kill?: (pid: number, signal: NodeJS.Signals) => void+ sleep?: (ms: number) => Promise<void>+}): Promise<boolean> {+ const generation = deps.generation ?? externalProcessGeneration+ const exists = deps.exists ?? processExists+ const sleep = deps.sleep ?? (ms => new Promise<void>(resolve => { const timer = setTimeout(resolve, ms); timer.unref() }))+ const process = owner.process+ const sameProcess = () => generation(process.pid) === owner.generation+ const wait = async (budget: number) => {+ for (let elapsed = 0; elapsed < budget; elapsed += 100) {+ if (!deps.current()) return false+ if (!exists(process.pid)) return true+ if (!sameProcess()) return false+ await sleep(100)+ }+ return deps.current() && !exists(process.pid)+ }+ for (const [signal, budget] of [['SIGTERM', 5_000], ['SIGKILL', 2_000]] as const) {+ if (!deps.current()) return false+ if (!exists(process.pid)) return true+ const job = await (deps.job ?? verifiedForegroundJob)(process.pid).catch(() => 'unknown' as const)+ if (job === 'unknown') return false+ if (!await deps.same() || !deps.current() || !sameProcess()) return false+ try {+ deps.beforeSignal?.(signal)+ if (!deps.current() || !sameProcess()) return false+ ;(deps.kill ?? ((pid, name) => globalThis.process.kill(pid, name)))(job ? -job : process.pid, signal)+ deps.afterSignal?.(signal)+ }+ catch { return deps.current() && !exists(process.pid) }+ if (await wait(budget)) return true+ }+ // The exited process no longer proves who owns its terminal. Do not write escape sequences into+ // a terminal that may already be running another conversation or the person's next command.+ return false+}diff --git a/cli/src/core/agents/externalPreflight.spec.ts b/cli/src/core/agents/externalPreflight.spec.tsnew file mode 100644index 000000000..bda030565--- /dev/null+++ b/cli/src/core/agents/externalPreflight.spec.ts@@ -0,0 +1,46 @@+import { afterEach, expect, it, vi } from 'vitest'+import { loadEngine } from '../../engines/inProcess.js'+import { engineHooks } from '../../engines/hooks.js'+import { buildEngineCommandArgv, refusePermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import { createExternalPreflight } from './externalPreflight.js'+vi.mock('../../engines/inProcess.js', () => ({ loadEngine: vi.fn(async () => ({})) }))+vi.mock('../../engines/hooks.js', () => ({ engineHooks: { codex: { installIn: vi.fn() } } }))+vi.mock('../../lib/engineLaunch.js', () => ({ buildEngineCommandArgv: vi.fn(() => []), refusePermissionFlagIfUnsupported: vi.fn(async () => null) }))+vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))+afterEach(() => { vi.clearAllMocks() })+const session = { sessionId: 'conversation', cwd: '/fixture/work', launchArgs: ['-p', 'work'] } as never+const row = (engine = 'claude', extra = {}) => ({ engine, permissionMode: 'ask', bypassPermission: false, ...extra }) as never+function setup(over = {}) {+ const deps = { blocksFolder: vi.fn(() => false), hooksDisabled: false, hookPort: 4242,+ installOpencodePlugin: vi.fn(async () => true), ...over }+ return { deps, prepare: createExternalPreflight(deps) }+}+it('refuses a missing or changing folder or unsupported permissions before engine preparation', async () => {+ vi.mocked(workspaceMissing).mockReturnValueOnce({ ok: false, error: 'CWD_NOT_FOUND', detail: 'folder gone' })+ expect(await setup().prepare(row(), session)).toMatchObject({ detail: 'folder gone' })+ expect(await setup({ blocksFolder: () => true }).prepare(row(), session)).toMatchObject({ detail: expect.stringContaining('workspace operation') })+ vi.mocked(refusePermissionFlagIfUnsupported).mockResolvedValueOnce({ error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'permission unsupported' } as never)+ expect(await setup().prepare(row(), session)).toMatchObject({ detail: 'permission unsupported' })+ expect(buildEngineCommandArgv).not.toHaveBeenCalled()+})+it('requires OpenCode launch support and hooks before any external owner can be stopped', async () => {+ vi.mocked(loadEngine).mockResolvedValueOnce(null)+ expect(await setup().prepare(row('opencode'), session)).not.toBeNull()+ expect(await setup({ installOpencodePlugin: async () => false }).prepare(row('opencode'), session)).not.toBeNull()+ const enabled = setup()+ expect(await enabled.prepare(row('opencode'), session)).toBeNull()+ expect(enabled.deps.installOpencodePlugin).toHaveBeenCalledWith(4242)+ const disabled = setup({ hooksDisabled: true })+ expect(await disabled.prepare(row('opencode'), session)).toBeNull()+ expect(disabled.deps.installOpencodePlugin).not.toHaveBeenCalled()+})+it('prepares a custom Codex hook home only when hooks are enabled, and verifies exact resume argv', async () => {+ for (const engine of ['claude', 'codex']) expect(await setup().prepare(row(engine), session)).toBeNull()+ expect(engineHooks.codex.installIn).not.toHaveBeenCalled()+ expect(await setup({ hooksDisabled: true }).prepare(row('codex', { codexHome: '/fixture/profile' }), session)).toBeNull()+ expect(engineHooks.codex.installIn).not.toHaveBeenCalled()+ expect(await setup().prepare(row('codex', { codexHome: '/fixture/profile' }), session)).toBeNull()+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/fixture/profile')+ expect(buildEngineCommandArgv).toHaveBeenLastCalledWith('codex', expect.objectContaining({ resumeSessionId: 'conversation', extraArgs: ['-p', 'work'] }))+})diff --git a/cli/src/core/agents/externalPreflight.ts b/cli/src/core/agents/externalPreflight.tsnew file mode 100644index 000000000..159519fd0--- /dev/null+++ b/cli/src/core/agents/externalPreflight.ts@@ -0,0 +1,29 @@+/** Verify a resumable launch before asking an external terminal to quit. */+import { loadEngine } from '../../engines/inProcess.js'+import { engineHooks } from '../../engines/hooks.js'+import { buildEngineCommandArgv, refusePermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'+import { workspaceMissing } from '../../lib/workspaceCheck.js'+import type { ExternalResumeDeps } from './externalResume.js'++export function createExternalPreflight(deps: {+ blocksFolder(cwd: string): boolean | undefined+ hooksDisabled: boolean+ hookPort: number+ installOpencodePlugin(port: number): Promise<boolean>+}): ExternalResumeDeps['preflight'] {+ return async (row, session) => {+ const missing = workspaceMissing(session.cwd)+ if (missing) return missing+ if (deps.blocksFolder(session.cwd)) return { detail: 'Waiting for the workspace operation to finish.' }+ const refused = await refusePermissionFlagIfUnsupported(row.engine, row)+ if (refused) return refused+ if (row.engine === 'opencode' && (!await loadEngine('opencode')+ || !deps.hooksDisabled && !await deps.installOpencodePlugin(deps.hookPort))) {+ return { detail: 'Waiting for OpenCode’s launch support to become available.' }+ }+ if (row.codexHome && !deps.hooksDisabled) engineHooks.codex.installIn(deps.hookPort, row.codexHome)+ buildEngineCommandArgv(row.engine, { cwd: session.cwd, resumeSessionId: session.sessionId,+ bypassPermission: row.bypassPermission, permissionMode: row.permissionMode, extraArgs: session.launchArgs })+ return null+ }+}diff --git a/cli/src/core/agents/externalResume.spec.ts b/cli/src/core/agents/externalResume.spec.tsnew file mode 100644index 000000000..c9f78289d--- /dev/null+++ b/cli/src/core/agents/externalResume.spec.ts@@ -0,0 +1,463 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest'+import { externalReservations, type ExternalResumeIntent } from '../../lib/externalResume.js'+import { externalUnavailable, type ExternalSessionAnswer, type ExternalSessionRequest } from '../../lib/externalSessionWire.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createExternalResumes, type ExternalResumeDeps } from './externalResume.js'+import { stopExternalOwner } from './externalOwner.js'+vi.mock('./externalOwner.js', () => ({ stopExternalOwner: vi.fn(async () => false) }))++const cwd = mkdtempSync(join(tmpdir(), 'external-resume-'))+afterAll(() => rmSync(cwd, { recursive: true, force: true }))+const controllers: ReturnType<typeof createExternalResumes>[] = []+beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(1000); vi.spyOn(console, 'warn').mockImplementation(() => {}) })+afterEach(() => { for (const controller of controllers.splice(0)) controller.stop(); vi.restoreAllMocks(); vi.useRealTimers() })+const fact = { sessionId: 'conversation', engine: 'claude' as const, cwd, title: 'Named conversation', origin: 'terminal' as const, mtime: 1, transcriptPath: join(cwd, 'conversation.jsonl') }+const processOwner = { pid: 7, engine: 'claude' as const, tty: '/dev/fixture-terminal', record: '/fixture/record' }+const free = (request: ExternalSessionRequest): ExternalSessionAnswer => ({ ok: true, request, session: { ...fact, sessionId: request.sessionId }, owner: null, generation: null, busy: false })+const held = (request: ExternalSessionRequest, busy = false): ExternalSessionAnswer => ({ ...free(request), owner: processOwner, generation: 'ps:1', busy,+ ...(busy ? { busyConfirmed: true } : {}) }) as ExternalSessionAnswer+const input = (extra = {}) => ({ engine: 'claude', cwd, bypassPermission: false, permissionMode: null, grid: null, codexHome: null, dsh: null,+ prompt: null, name: null, agent: null, resumeSessionId: 'conversation', takeOver: null, ...extra }) as Parameters<ReturnType<typeof createExternalResumes>['create']>[0]+const defer = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(yes => { resolve = yes }); return { promise, resolve } }++function setup() {+ const rows = new Map<string, RegisteredSession>(), panes = new Map<string, string>()+ let next = 0, cancelled = false+ const conflict: ExternalResumeDeps['registry']['externalConflict'] = (ids, except) => [...rows.values()].find(row => row.agentId !== except && externalReservations(row).some(id => ids.includes(id)))+ const registry: ExternalResumeDeps['registry'] = {+ byAgent: id => rows.get(id), list: () => [...rows.values()], externalConflict: conflict,+ openPendingAgent: vi.fn(given => {+ if (conflict(externalReservations({ sessionId: '', externalResume: given.externalResume }))) return null+ const row = { ...given, schemaVersion: 2, agentId: `agent-${++next}`, sessionId: '', registeredAt: 1,+ boundAt: null, processIdentity: null, active: false, launch: { state: 'held', service: 'search', detail: externalUnavailable().detail },+ tmuxPane: given.runtimes[0].backend === 'tmux' ? given.runtimes[0].paneId : '',+ } as RegisteredSession+ rows.set(row.agentId, row); return row+ }),+ setExternalResume: vi.fn((id, intent) => {+ const old = rows.get(id)+ if (!old || conflict(externalReservations({ sessionId: intent.phase === 'admitted' ? intent.session!.sessionId : '', externalResume: intent }), id)) return null+ const row = { ...old, externalResume: structuredClone(intent), ...(intent.phase === 'admitted' ? { sessionId: intent.session!.sessionId, cwd: intent.session!.cwd, resumeOnly: true as const } : {}) }+ rows.set(id, row); return row+ }),+ setLaunch: vi.fn((id, launch) => { const row = rows.get(id); if (!row) return null; row.launch = launch; return row }),+ finishExternalCancellation: vi.fn(id => rows.delete(id)),+ }+ let paneSequence = 0+ const create = vi.fn<NonNullable<ExternalResumeDeps['tmux']>['create']>(async request => {+ if (request.current?.() === false) return { state: 'failed', dispatch: 'not_started', reason: 'cancelled' }+ const paneId = `%${++paneSequence}`+ panes.set(paneId, request.command!.at(-1)!)+ return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }+ })+ const killHeld = vi.fn<NonNullable<ExternalResumeDeps['tmux']>['killHeld']>(async (runtime, token, current) => {+ if (!current() || panes.has(runtime.paneId) && panes.get(runtime.paneId) !== token) return { state: 'failed', dispatch: 'not_started', reason: 'pane changed' }+ panes.delete(runtime.paneId); return { state: 'succeeded', dispatch: 'executed' }+ })+ const inspect = vi.fn(async (request: ExternalSessionRequest) => free(request))+ const deps: ExternalResumeDeps = {+ registry, tmux: { create, killHeld }, inspect, generation: () => 1,+ stopped: vi.fn(() => []), cancelled: () => cancelled,+ waiting: vi.fn(async row => panes.get(row.tmuxPane) === row.externalResume?.token),+ preflight: vi.fn(async () => null), announce: vi.fn(), launch: vi.fn(),+ forget: vi.fn(id => { expect(rows.has(id)).toBe(false) }),+ stopOwner: vi.fn(async (_owner, control) => {+ if (!control.current() || !await control.same()) return false+ control.beforeSignal?.('SIGTERM'); control.afterSignal?.('SIGTERM')+ inspect.mockImplementation(async request => free(request))+ return true+ }),+ }+ const controller = createExternalResumes(deps); controllers.push(controller); controller.open()+ const stage = async (extra = {}) => {+ const result = await controller.create(input(extra))+ if (!result.ok) throw new Error(result.error)+ return result.session.agentId+ }+ return { deps, registry, rows, panes, inspect, create, killHeld, controller, stage, cancelWork: () => { cancelled = true } }+}++it('persists an inert held intent during search outage, then admits and launches the exact conversation', async () => {+ const test = setup(); test.inspect.mockResolvedValue(externalUnavailable('Reader unavailable.'))+ const id = await test.stage({ name: 'Mine', codexHome: '/fixture/profile' })+ await test.controller.settled()+ expect(test.rows.get(id)).toMatchObject({ sessionId: '', cwd: null, defaultName: 'Mine', launch: { state: 'held', detail: 'Reader unavailable.' }, externalResume: { phase: 'waiting' } })+ expect(test.deps.preflight).not.toHaveBeenCalled(); expect(test.deps.launch).not.toHaveBeenCalled()+ test.inspect.mockImplementation(async request => free(request))+ await vi.advanceTimersByTimeAsync(2000); await test.controller.settled()+ expect(test.rows.get(id)).toMatchObject({ sessionId: 'conversation', cwd, resumeOnly: true, externalResume: { phase: 'admitted' } })+ expect(test.deps.launch).toHaveBeenCalledOnce()+ test.inspect.mockRejectedValue(new Error('search died again'))+ await vi.advanceTimersByTimeAsync(4000)+ expect(test.deps.launch).toHaveBeenCalledOnce()+ expect(await test.controller.cancel(test.rows.get(id)!)).toBe(false)+})++it('preserves known refusals before creating a pane, but holds thrown or malformed observations', async () => {+ for (const value of [externalUnavailable(), { nonsense: true }, new Error('search failed')]) {+ const test = setup()+ if (value instanceof Error) test.inspect.mockRejectedValue(value)+ else test.inspect.mockResolvedValue(value as ExternalSessionAnswer)+ const id = await test.stage(); await test.controller.settled()+ expect(test.rows.get(id)?.launch?.state).toBe('held')+ }+ const test = setup(); test.inspect.mockImplementation(async request => ({ ...free(request), session: null }))+ expect(await test.controller.create(input())).toMatchObject({ ok: false, error: 'SESSION_NOT_FOUND' })+ expect(test.create).not.toHaveBeenCalled()+ expect(await test.controller.create(input({ engine: 'terminal' }))).toMatchObject({ error: 'INVALID_SESSION' })+ test.deps.tmux = null+ expect(await test.controller.create(input())).toMatchObject({ error: 'TMUX_UNAVAILABLE' })+})++it('holds busy waits outside the shared restore queue, pins ownership and journals actual interruption', async () => {+ const test = setup(); test.inspect.mockImplementation(async request => held(request, true))+ const id = await test.stage({ takeOver: 'wait' }); await test.controller.settled()+ expect(test.rows.get(id)?.launch).toMatchObject({ state: 'held', detail: expect.stringContaining('current turn') })+ expect(test.deps.stopOwner).not.toHaveBeenCalled()+ test.inspect.mockImplementation(async request => held(request, false))+ await vi.advanceTimersByTimeAsync(2000); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume).toMatchObject({ phase: 'admitted', signal: 'sent' })+ expect(test.rows.get(id)?.externalResume?.continue).toBeUndefined()+ const now = setup(); now.inspect.mockImplementation(async request => held(request, true))+ const busy = await now.stage({ takeOver: 'now' }); await now.controller.settled()+ expect(now.rows.get(busy)?.externalResume).toMatchObject({ phase: 'admitted', signal: 'sent', continue: true })+})++it('never transfers takeover permission to a replacement owner or interrupts work under idle consent', async () => {+ const test = setup(), waiting = defer<null>()+ test.inspect.mockImplementation(async request => held(request))+ vi.mocked(test.deps.preflight).mockReturnValueOnce(waiting.promise)+ const id = await test.stage({ takeOver: 'idle' })+ await vi.waitFor(() => expect(test.deps.preflight).toHaveBeenCalled())+ test.inspect.mockImplementation(async request => held(request, true))+ waiting.resolve(null); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.signal).toBeUndefined()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('quitting')+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.inspect.mockImplementation(async request => ({ ...held(request), owner: { ...processOwner, pid: 8 }, generation: 'ps:2' }) as ExternalSessionAnswer)+ await vi.advanceTimersByTimeAsync(2000); await test.controller.settled()+ expect(test.rows.get(id)?.launch).toMatchObject({ detail: expect.stringContaining('another process') })+ expect(test.deps.stopOwner).toHaveBeenCalledTimes(1)+})++it('explicit takeover of unknown activity never manufactures a continuation prompt', async () => {+ const test = setup()+ test.inspect.mockImplementation(async request => ({ ...held(request), busy: true }))+ const id = await test.stage({ takeOver: 'now' }); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume).toMatchObject({ phase: 'admitted', signal: 'sent' })+ expect(test.rows.get(id)?.externalResume?.continue).toBeUndefined()+})++it.each([null, 'idle', 'wait'] as const)('holds unknown activity with %s consent and names the missing evidence', async takeOver => {+ const test = setup(); test.inspect.mockImplementation(async request => ({ ...held(request), busy: true }))+ const id = await test.stage({ takeOver }); await test.controller.settled()+ expect(test.rows.get(id)?.launch).toMatchObject({ state: 'held', detail: expect.stringContaining('verify whether') })+ expect(test.deps.stopOwner).not.toHaveBeenCalled(); expect(test.deps.launch).not.toHaveBeenCalled()+ test.inspect.mockImplementation(async request => held(request, true))+ if (takeOver !== 'wait') expect(await test.controller.create(input({ resumeSessionId: 'another', takeOver }))).toMatchObject({ error: 'SESSION_BUSY_IN_TERMINAL' })+})++it.each(['pane', 'cancelled-pane', 'unavailable', 'missing'] as const)('withholds every signal when the last %s observation cannot prove ownership', async point => {+ const test = setup(); test.inspect.mockImplementation(async request => held(request))+ vi.mocked(test.deps.stopOwner!).mockImplementation(async (_owner, control) => {+ if (point === 'pane') vi.mocked(test.deps.waiting).mockResolvedValue(false)+ else if (point === 'cancelled-pane') vi.mocked(test.deps.waiting).mockImplementation(async () => { test.cancelWork(); return true })+ else test.inspect.mockImplementation(async request => point === 'unavailable' ? externalUnavailable() : { ...free(request), session: null })+ expect(await control.same()).toBe(false)+ return false+ })+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.signal).toBeUndefined()+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('rechecks reservations and metadata before signalling and before committing a free admission', async () => {+ for (const mode of ['reserved', 'archived', 'cwd', 'record', 'args', 'busy', 'unavailable'] as const) {+ const test = setup(), waiting = defer<null>()+ test.inspect.mockImplementation(async request => held(request))+ vi.mocked(test.deps.preflight).mockReturnValueOnce(waiting.promise)+ const id = await test.stage({ takeOver: 'idle' })+ await vi.waitFor(() => expect(test.deps.preflight).toHaveBeenCalled())+ if (mode === 'reserved') test.rows.set('other', { agentId: 'other', sessionId: 'conversation' } as RegisteredSession)+ else test.inspect.mockImplementation(async request => mode === 'unavailable' ? externalUnavailable() : ({ ...held(request),+ busy: mode === 'busy', session: { ...fact, ...(mode === 'archived' ? { archived: true } : {}),+ ...(mode === 'cwd' ? { cwd: join(cwd, 'changed') } : {}), ...(mode === 'record' ? { transcriptPath: '/fixture/other' } : {}),+ ...(mode === 'args' ? { launchArgs: ['--unapproved'] } : {}) } }) as ExternalSessionAnswer)+ waiting.resolve(null); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).not.toBe('admitted')+ expect(test.rows.get(id)?.externalResume?.signal).toBeUndefined()+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+ for (const mode of ['owner', 'metadata', 'archived', 'unavailable'] as const) {+ const test = setup(), waiting = defer<null>()+ vi.mocked(test.deps.preflight).mockReturnValueOnce(waiting.promise)+ const id = await test.stage()+ await vi.waitFor(() => expect(test.deps.preflight).toHaveBeenCalled())+ test.inspect.mockImplementation(async request => mode === 'unavailable' ? externalUnavailable() : mode === 'owner' ? held(request) :+ ({ ...free(request), session: { ...fact, ...(mode === 'metadata' ? { transcriptPath: '/fixture/changed' } : { archived: true }) } }))+ waiting.resolve(null); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting')+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+})++it.each(['binding', 'stopped'] as const)('a new %s fences signals even after the final owner read, and holds without another service read', async kind => {+ const test = setup(); test.inspect.mockImplementation(async request => held(request))+ vi.mocked(test.deps.stopOwner!).mockImplementation(async (_owner, control) => {+ expect(await control.same()).toBe(true)+ if (kind === 'binding') test.rows.set('other', { agentId: 'other', sessionId: 'conversation' } as RegisteredSession)+ else vi.mocked(test.deps.stopped).mockReturnValue([{ sessionId: 'conversation' }])+ expect(control.current()).toBe(false)+ expect(() => control.beforeSignal?.('SIGTERM')).toThrow('Signal intent could not be saved')+ return false+ })+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.signal).toBeUndefined()+ test.inspect.mockClear()+ await vi.advanceTimersByTimeAsync(4000); await test.controller.settled()+ expect(test.inspect).not.toHaveBeenCalled()+ expect(test.rows.get(id)?.launch).toMatchObject({ state: 'held', detail: expect.stringContaining('another harness') })+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('Stop cancels a slow read without waiting, closes only its inert pane and durably removes before forgetting', async () => {+ const test = setup(), reading = defer<ExternalSessionAnswer>()+ test.inspect.mockResolvedValueOnce(externalUnavailable()).mockReturnValueOnce(reading.promise)+ const id = await test.stage()+ await vi.waitFor(() => expect(test.inspect).toHaveBeenCalledTimes(2))+ expect(await test.controller.cancel(test.rows.get(id)!)).toBe(true)+ expect(test.registry.finishExternalCancellation).toHaveBeenCalledWith(id)+ expect(test.deps.forget).toHaveBeenCalledWith(id)+ reading.resolve(free({ sessionId: 'conversation', engine: 'claude' })); await test.controller.settled()+ expect(test.rows.size).toBe(0); expect(test.deps.launch).not.toHaveBeenCalled(); expect(test.deps.stopOwner).not.toHaveBeenCalled()+})++it('keeps cancellation durable when the pane was replaced, and cleans it after a crash without asking search', async () => {+ const test = setup(); test.inspect.mockResolvedValue(externalUnavailable())+ const id = await test.stage(); await test.controller.settled()+ const row = test.rows.get(id)!; test.panes.set(row.tmuxPane, 'replacement')+ await expect(test.controller.cancel(row)).rejects.toThrow('stays cancelled')+ expect(test.rows.get(id)?.externalResume?.phase).toBe('cancelled')+ test.inspect.mockClear(); test.controller.stop()+ test.panes.delete(row.tmuxPane)+ const reboot = createExternalResumes(test.deps); controllers.push(reboot); reboot.open(); await reboot.settled()+ expect(test.inspect).not.toHaveBeenCalled(); expect(test.rows.has(id)).toBe(false)+})++it('four held requests cannot starve a later free conversation', async () => {+ const test = setup(); test.inspect.mockImplementation(async request => request.sessionId.startsWith('busy') ? held(request, true) : free(request))+ for (let i = 0; i < 4; i++) await test.stage({ resumeSessionId: `busy-${i}`, takeOver: 'wait' })+ const ready = await test.stage({ resumeSessionId: 'free-later' })+ await vi.advanceTimersByTimeAsync(4000); await test.controller.settled()+ expect(test.rows.get(ready)?.externalResume?.phase).toBe('admitted')+ for (const row of test.rows.values()) if (row.agentId !== ready) expect(row.externalResume?.phase).toBe('waiting')+})++it('fences Stop, changed routes, permission changes, unexpected processes and a replaced waiting shell', async () => {+ for (const change of ['stop', 'route', 'permission', 'process', 'pane'] as const) {+ const test = setup(), waiting = defer<null>()+ vi.mocked(test.deps.preflight).mockReturnValueOnce(waiting.promise)+ const id = await test.stage()+ await vi.waitFor(() => expect(test.deps.preflight).toHaveBeenCalled())+ const row = test.rows.get(id)!+ if (change === 'stop') test.cancelWork()+ if (change === 'route') row.runtimes = [{ backend: 'tmux', paneId: '%99' }]+ if (change === 'permission') row.permissionMode = 'auto'+ if (change === 'process') row.processIdentity = { pid: 8, executable: 'other', startMarker: 'ps:2' }+ if (change === 'pane') test.panes.set(row.tmuxPane, 'replacement')+ waiting.resolve(null); await test.controller.settled()+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+})++it('does no admission before readiness or after shutdown, including an already-running create read', async () => {+ const test = setup(), ready = createExternalResumes(test.deps); controllers.push(ready)+ expect(await ready.create(input())).toMatchObject({ error: 'CORE_NOT_READY' })+ ready.wake(); expect(test.create).not.toHaveBeenCalled()+ const reading = defer<ExternalSessionAnswer>(); test.inspect.mockReturnValue(reading.promise)+ const creating = test.controller.create(input()); await Promise.resolve()+ test.controller.stop(); reading.resolve(free({ sessionId: 'conversation', engine: 'claude' }))+ expect(await creating).toMatchObject({ error: 'CORE_NOT_READY' })+ expect(test.create).not.toHaveBeenCalled()+})++it('holds storage/preflight failures and known late refusals without launching or losing intent', async () => {+ for (const mode of ['storage', 'null-commit', 'preflight', 'throws', 'late-missing'] as const) {+ const test = setup()+ if (mode === 'storage') vi.mocked(test.registry.setExternalResume).mockImplementation(() => { throw new Error('disk full') })+ if (mode === 'null-commit') vi.mocked(test.registry.setExternalResume).mockReturnValue(null)+ if (mode === 'preflight') vi.mocked(test.deps.preflight).mockResolvedValue({ detail: 'Engine unavailable.' })+ if (mode === 'throws') vi.mocked(test.deps.preflight).mockRejectedValue(new Error('preparation unreadable'))+ if (mode === 'late-missing') test.inspect.mockImplementationOnce(async request => free(request)).mockImplementation(async request => ({ ...free(request), session: null }))+ const id = await test.stage(); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting'); expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+})++it('does not begin stopping an owner when the quitting journal cannot commit', async () => {+ const test = setup(); test.inspect.mockImplementation(async request => held(request))+ const save = test.registry.setExternalResume+ test.registry.setExternalResume = (id, intent) => intent.phase === 'quitting' ? null : save(id, intent)+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting')+ expect(test.deps.stopOwner).not.toHaveBeenCalled()+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('reserves stopped conversations before any pane exists and cleans up an allocation whose durable claim fails', async () => {+ const test = setup()+ vi.mocked(test.deps.stopped).mockReturnValue([{ sessionId: 'conversation' }])+ expect(await test.controller.create(input())).toMatchObject({ error: 'SESSION_IN_HARNESS' })+ expect(test.create).not.toHaveBeenCalled()+ vi.mocked(test.deps.stopped).mockReturnValue([])+ vi.mocked(test.registry.openPendingAgent).mockReturnValue(null)+ expect(await test.controller.create(input())).toMatchObject({ ok: false })+ expect(test.panes.size).toBe(0)+ expect(test.killHeld).toHaveBeenCalledTimes(3)+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('refuses every unverified cancellation boundary without forgetting or archiving its intent', async () => {+ for (const failure of ['changed', 'save', 'tmux', 'route', 'commit', 'replaced-during-close'] as const) {+ const test = setup(); test.inspect.mockResolvedValue(externalUnavailable())+ const id = await test.stage(); await test.controller.settled()+ const row = test.rows.get(id)!+ if (failure === 'save') vi.mocked(test.registry.setExternalResume).mockReturnValue(null)+ if (failure === 'tmux') test.deps.tmux = null+ if (failure === 'route') row.runtimes = []+ if (failure === 'commit') vi.mocked(test.registry.finishExternalCancellation).mockReturnValue(false)+ if (failure === 'replaced-during-close') test.killHeld.mockImplementation(async () => {+ test.rows.get(id)!.runtimes = [{ backend: 'tmux', paneId: '%99' }]+ return { state: 'succeeded', dispatch: 'executed' }+ })+ await expect(test.controller.cancel(row, () => failure !== 'changed')).rejects.toThrow()+ expect(test.deps.forget).not.toHaveBeenCalled()+ expect(test.rows.has(id)).toBe(true)+ test.controller.stop()+ }+})++it('requires an inert pane before any observation and discards a check after Stop or a newer route', async () => {+ for (const kind of ['unverified', 'cancelled-during-check', 'process-already-found', 'no-longer-held', 'lost-row'] as const) {+ const test = setup(); test.inspect.mockResolvedValue(externalUnavailable())+ const id = await test.stage(); await test.controller.settled()+ const row = test.rows.get(id)!+ if (kind === 'process-already-found') row.processIdentity = { pid: 8, executable: 'fixture', startMarker: 'fixture' }+ if (kind === 'no-longer-held') row.launch = { state: 'starting' }+ if (kind === 'unverified' || kind === 'lost-row') vi.mocked(test.deps.waiting).mockResolvedValue(false)+ if (kind === 'lost-row') vi.mocked(test.registry.setLaunch).mockReturnValue(null)+ if (kind === 'cancelled-during-check') vi.mocked(test.deps.waiting).mockImplementation(async () => { test.cancelWork(); return true })+ test.inspect.mockClear()+ await vi.advanceTimersByTimeAsync(2000); await test.controller.settled()+ expect(test.inspect).not.toHaveBeenCalled()+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+})++it('keeps exact signal intent and receipt failures from admitting an external conversation', async () => {+ for (const failure of ['before', 'after', 'cancel-before', 'cancel-then-false', 'cancel-then-true', 'kill'] as const) {+ const test = setup(); test.inspect.mockImplementation(async request => held(request))+ vi.mocked(test.deps.stopOwner!).mockImplementation(async (_owner, control) => {+ expect(await control.same()).toBe(true)+ if (failure === 'kill') { control.beforeSignal?.('SIGKILL'); control.afterSignal?.('SIGKILL'); return false }+ if (failure === 'cancel-then-false' || failure === 'cancel-then-true') { test.cancelWork(); return failure === 'cancel-then-true' }+ if (failure === 'before') vi.mocked(test.registry.setExternalResume).mockReturnValue(null)+ if (failure === 'cancel-before') test.cancelWork()+ control.beforeSignal?.('SIGTERM')+ if (failure === 'after') vi.mocked(test.registry.setExternalResume).mockReturnValue(null)+ control.afterSignal?.('SIGTERM')+ return true+ })+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('quitting')+ expect(test.deps.launch).not.toHaveBeenCalled()+ if (failure === 'after') expect(test.rows.get(id)?.externalResume?.signal).toBe('prepared')+ test.controller.stop()+ }+ const test = setup(); test.inspect.mockImplementation(async request => held(request)); test.deps.stopOwner = undefined+ await test.stage({ takeOver: 'idle' }); await test.controller.settled()+ expect(stopExternalOwner).toHaveBeenCalled()+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('fences the last read, the last pane check, and a failed final durable admission', async () => {+ for (const point of ['read', 'pane', 'commit'] as const) {+ const test = setup()+ let calls = 0+ test.inspect.mockImplementation(async request => { if (++calls === 3 && point === 'read') test.cancelWork(); return free(request) })+ let paneChecks = 0+ vi.mocked(test.deps.waiting).mockImplementation(async () => { if (++paneChecks === 2 && point === 'pane') test.cancelWork(); return true })+ const persist = test.registry.setExternalResume+ if (point === 'commit') test.registry.setExternalResume = (id, intent) => intent.phase === 'admitted' ? null : persist(id, intent)+ await test.stage(); await test.controller.settled()+ expect(test.deps.launch).not.toHaveBeenCalled()+ test.controller.stop()+ }+})++it('limits concurrent intents after reboot and lets later ones proceed after the reads finish', async () => {+ const test = setup(); test.inspect.mockResolvedValue(externalUnavailable())+ const id = await test.stage(); await test.controller.settled(); test.controller.stop()+ const sample = test.rows.get(id)!+ for (let i = 1; i <= 5; i++) {+ const agentId = `saved-${i}`, pane = `%${i + 10}`+ const intent = { ...sample.externalResume!, request: { engine: 'claude' as const, sessionId: `saved-conversation-${i}` } }+ test.rows.set(agentId, { ...sample, agentId, tmuxPane: pane, runtimes: [{ backend: 'tmux', paneId: pane }], externalResume: intent })+ test.panes.set(pane, intent.token)+ }+ const reads: Array<() => void> = []+ test.inspect.mockClear().mockImplementation(request => new Promise(resolve => { reads.push(() => resolve(free(request))) }))+ const reboot = createExternalResumes(test.deps); controllers.push(reboot); reboot.open()+ await vi.waitFor(() => expect(reads.length).toBe(4))+ reboot.wake()+ expect(test.inspect).toHaveBeenCalledTimes(4)+ test.inspect.mockImplementation(async request => free(request))+ for (const finish of reads) finish()+ await reboot.settled()+ await vi.advanceTimersByTimeAsync(2000); await reboot.settled()+ expect([...test.rows.values()].every(row => row.externalResume?.phase === 'admitted')).toBe(true)+})++it('ignores a late preparation exception after shutdown', async () => {+ const test = setup()+ let reject!: (error: Error) => void+ vi.mocked(test.deps.preflight).mockImplementation(() => new Promise((_resolve, no) => { reject = no }))+ const id = await test.stage()+ await vi.waitFor(() => expect(test.deps.preflight).toHaveBeenCalled())+ test.controller.stop(); reject(new Error('late failure')); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting')+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it.each(['idle', 'wait'] as const)('does not signal a turn that starts during the pane probe under %s consent', async takeOver => {+ const test = setup(), pane = defer<boolean>()+ test.inspect.mockImplementation(async request => held(request, false))+ vi.mocked(test.deps.waiting).mockResolvedValueOnce(true).mockReturnValueOnce(pane.promise)+ const id = await test.stage({ takeOver })+ await vi.waitFor(() => expect(test.deps.waiting).toHaveBeenCalledTimes(2))+ test.inspect.mockImplementation(async request => held(request, true))+ pane.resolve(true); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume).toMatchObject({ phase: 'quitting' })+ expect(test.rows.get(id)?.externalResume?.signal).toBeUndefined()+ expect(test.deps.launch).not.toHaveBeenCalled()+})++it('does not admit a conversation acquired externally while its final pane probe waits', async () => {+ const test = setup(), pane = defer<boolean>()+ vi.mocked(test.deps.waiting).mockResolvedValueOnce(true).mockReturnValueOnce(pane.promise)+ const id = await test.stage()+ await vi.waitFor(() => expect(test.deps.waiting).toHaveBeenCalledTimes(2))+ test.inspect.mockImplementation(async request => held(request, false))+ pane.resolve(true); await test.controller.settled()+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting')+ expect(test.rows.get(id)?.sessionId).toBe('')+ expect(test.deps.launch).not.toHaveBeenCalled()+})diff --git a/cli/src/core/agents/externalResume.ts b/cli/src/core/agents/externalResume.tsnew file mode 100644index 000000000..b64378c11--- /dev/null+++ b/cli/src/core/agents/externalResume.ts@@ -0,0 +1,200 @@+/** Durable external adoption. Search may hold an intent, but never owns its lifecycle or pane. */+import { randomUUID } from 'node:crypto'+import type { BackendSocket } from '../../backendSocket.js'+import { createAndRegisterPane } from '../../lib/createAgentPane.js'+import { externalSessionRequest, externalUnavailable, type ExternalSessionAnswer, type ExternalSessionRequest } from '../../lib/externalSessionWire.js'+import { externalReservations, externalResumeIds, externalResumePending, type ExternalResumeIntent } from '../../lib/externalResume.js'+import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import { terminalRouteKey } from '../../lib/terminalRuntime.js'+import type { TmuxBackend } from '../../lib/tmuxBackend.js'+import { adoptionDecision } from './adopt.js'+import { heldPaneArgv } from './heldLaunches.js'+import { createExternalInspector } from './externalInspect.js'+import { stopExternalOwner } from './externalOwner.js'++type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>+type Owner = NonNullable<ExternalResumeIntent['owner']>+const sameOwner = (a: Owner, b: Owner) => JSON.stringify(a) === JSON.stringify(b)+const activityUnknown = (answer: ExternalSessionAnswer) => answer.ok && answer.owner && answer.busy && !answer.busyConfirmed+const ACTIVITY_UNKNOWN = 'Waiting to verify whether this conversation is idle in its terminal. Close it there to continue.'+const identity = (row: RegisteredSession | undefined) => row && JSON.stringify([+ row.engine, row.registeredAt, row.sessionId, row.launch, row.processIdentity, row.cwd, row.codexHome, row.permissionMode, row.bypassPermission, row.runtimes.map(terminalRouteKey).sort(), row.externalResume,+])++export interface ExternalResumeDeps {+ registry: Pick<typeof registry, 'byAgent' | 'list' | 'openPendingAgent' | 'externalConflict' | 'setExternalResume' | 'setLaunch' | 'finishExternalCancellation'>+ tmux: Pick<TmuxBackend, 'create' | 'killHeld'> | null+ inspect(request: ExternalSessionRequest): Promise<ExternalSessionAnswer>+ waiting(row: RegisteredSession): Promise<boolean>+ generation(): unknown+ stopped(): readonly Pick<RegisteredSession, 'sessionId' | 'externalResume'>[]+ cancelled(agentId: string): boolean+ preflight(row: RegisteredSession, session: NonNullable<ExternalResumeIntent['session']>): Promise<{ detail: string } | null>+ announce(row: RegisteredSession): void+ launch(): void+ forget(agentId: string): void+ stopOwner?: typeof stopExternalOwner+}++export function createExternalResumes(deps: ExternalResumeDeps) {+ let stopped = false, opened = false+ let timer: ReturnType<typeof setTimeout> | undefined+ const running = new Map<string, Promise<void>>()+ const due = new Map<string, number>()+ const held = (id: string, except?: string) => !!deps.registry.externalConflict([id], except) || deps.stopped().some(row => externalReservations(row).includes(id))+ const inspect = createExternalInspector({ call: deps.inspect, generation: deps.generation })+ const occupied = (row: RegisteredSession) => externalResumeIds(row.externalResume).some(id => held(id, row.agentId))+ const hold = (row: RegisteredSession, detail: string) => {+ if (row.launch?.state === 'held' && row.launch.detail === detail) return+ const changed = deps.registry.setLaunch(row.agentId, { state: 'held', service: 'search', detail })+ if (changed) deps.announce(changed)+ }+ const advance = async (initial: RegisteredSession) => {+ let row = initial+ const current = () => !stopped && !deps.cancelled(row.agentId) && !occupied(row)+ && identity(deps.registry.byAgent(row.agentId)) === identity(row)+ const commit = (intent: ExternalResumeIntent) => {+ if (!current()) return false+ const changed = deps.registry.setExternalResume(row.agentId, intent)+ if (!changed) return false+ row = { ...changed }+ return true+ }+ const intent = row.externalResume!+ if (intent.phase === 'cancelled') { await cancel(row, () => !stopped); return }+ if (occupied(row)) { hold(row, 'This conversation is already open or saved in another harness.'); return }+ if (!current() || row.launch?.state !== 'held' || row.processIdentity) return+ if (!await deps.waiting(row) || !current()) { if (current()) hold(row, 'Waiting to verify this adoption’s terminal pane.'); return }+ let answer = await inspect(intent.request)+ if (!current()) return+ if (!answer.ok) { hold(row, answer.detail); return }+ const decision = adoptionDecision(intent.request.sessionId, intent.request.engine, intent.takeOver, answer, id => held(id, row.agentId))+ if (!decision.ok) { hold(row, decision.error === 'SESSION_BUSY_IN_TERMINAL' && activityUnknown(answer) ? ACTIVITY_UNKNOWN : decision.detail); return }+ const session = answer.session!+ const owner: Owner | undefined = answer.owner && answer.generation ? { process: answer.owner, generation: answer.generation } : undefined+ if (intent.session && owner && (!intent.owner || !sameOwner(intent.owner, owner))) {+ hold(row, 'The conversation moved to another process. Close it there, then open it here again.'); return+ }+ if (!commit({ ...intent, session, ...(owner ? { owner } : {}) })) return+ if (owner && decision.busy && intent.takeOver === 'wait') { hold(row, activityUnknown(answer) ? ACTIVITY_UNKNOWN : 'Waiting for the conversation’s current turn to finish in its terminal.'); return }+ const refusal = await deps.preflight(row, session)+ if (!current()) return+ if (refusal) { hold(row, refusal.detail); return }+ if (owner) {+ // Journal the exact target before a signal. A crash or a later process cannot inherit consent.+ if (!commit({ ...row.externalResume!, phase: 'quitting', owner })) return+ let interrupted = false+ const same = async () => {+ // The pane probe can wait on tmux. Take the decisive owner/turn evidence after it.+ if (!await deps.waiting(row) || !current()) return false+ answer = await inspect(intent.request)+ if (!current() || !answer.ok || !answer.session) return false+ const fresh = adoptionDecision(intent.request.sessionId, intent.request.engine, intent.takeOver, answer, id => held(id, row.agentId))+ interrupted = answer.busyConfirmed === true+ return fresh.ok && answer.session.sessionId === session.sessionId && answer.session.cwd === session.cwd+ && answer.session.transcriptPath === session.transcriptPath+ && JSON.stringify(answer.session.launchArgs) === JSON.stringify(session.launchArgs)+ && !!answer.owner && !!answer.generation && sameOwner(owner, { process: answer.owner, generation: answer.generation })+ && (intent.takeOver === 'now' || !answer.busy)+ }+ if (!await (deps.stopOwner ?? stopExternalOwner)(owner, { current, same,+ beforeSignal: signal => {+ // KILL needs the same locked conflict check after TERM's grace period, even when the+ // durable intent is unchanged. A daemon-down hook can bind another owner meanwhile.+ const next = signal === 'SIGTERM' ? { ...row.externalResume!, signal: 'prepared' as const, continue: interrupted ? true as const : undefined } : row.externalResume!+ if (!commit(next)) throw new Error('Signal intent could not be saved')+ },+ afterSignal: signal => {+ if (signal === 'SIGTERM' && !commit({ ...row.externalResume!, signal: 'sent' })) throw new Error('Signal receipt could not be saved')+ },+ })) {+ if (current()) hold(row, 'Waiting to confirm the original terminal stopped. Close it there to continue.'); return+ }+ if (!current()) return+ }+ if (!await deps.waiting(row) || !current()) {+ if (current()) hold(row, 'Waiting to verify this adoption’s terminal pane.')+ return+ }+ // Neither an exited PID nor an earlier free answer proves this conversation is still free.+ // No asynchronous work may separate this final read from the durable admission.+ answer = await inspect(intent.request)+ if (!current()) return+ const final = adoptionDecision(intent.request.sessionId, intent.request.engine, intent.takeOver, answer, id => held(id, row.agentId))+ if (!final.ok) { hold(row, final.detail); return }+ if (!answer.ok || !answer.session || answer.owner || answer.session.sessionId !== session.sessionId+ || answer.session.cwd !== session.cwd || answer.session.transcriptPath !== session.transcriptPath+ || JSON.stringify(answer.session.launchArgs) !== JSON.stringify(session.launchArgs)) {+ hold(row, 'The conversation changed while preparing to open it. Waiting to verify it again.'); return+ }+ if (!commit({ ...row.externalResume!, phase: 'admitted', session: answer.session })) return+ deps.announce(row)+ deps.launch()+ }+ const wake = () => {+ if (stopped || !opened) return+ if (timer) { clearTimeout(timer); timer = undefined }+ const pending = deps.registry.list().filter(row => externalResumePending(row.externalResume)).sort((a, b) => (due.get(a.agentId) ?? 0) - (due.get(b.agentId) ?? 0))+ for (const id of due.keys()) if (!pending.some(row => row.agentId === id)) due.delete(id)+ for (const entry of pending) {+ if (running.size >= 4) break+ if (running.has(entry.agentId) || (due.get(entry.agentId) ?? 0) > Date.now() || deps.cancelled(entry.agentId)) continue+ due.set(entry.agentId, Date.now() + 2_000)+ const task = advance({ ...entry }).catch(() => {+ const row = deps.registry.byAgent(entry.agentId)+ if (!stopped && !deps.cancelled(entry.agentId) && row?.externalResume && row.externalResume.token === entry.externalResume?.token && externalResumePending(row.externalResume)+ && row.externalResume.phase !== 'cancelled') hold(row, 'Waiting for a durable adoption record. No new process has been started.')+ }).finally(() => { running.delete(entry.agentId); if (!stopped) schedule() })+ running.set(entry.agentId, task)+ }+ if (pending.length) schedule()+ }+ const schedule = () => { if (!timer && !stopped) { timer = setTimeout(() => { timer = undefined; wake() }, 2_000); timer.unref() } }+ const create: CreateAgent = async input => {+ if (stopped || !opened) return { ok: false, error: 'CORE_NOT_READY' }+ if (!deps.tmux) return { ok: false, error: 'TMUX_UNAVAILABLE' }+ const request = externalSessionRequest({ sessionId: input.resumeSessionId, engine: input.engine })+ if (!request) return { ok: false, error: 'INVALID_SESSION' }+ const answer = await inspect(request)+ if (stopped) return { ok: false, error: 'CORE_NOT_READY' }+ const decision = adoptionDecision(request.sessionId, request.engine, input.takeOver ?? null, answer, held)+ if (!decision.ok && decision.error !== 'SEARCH_UNAVAILABLE'+ && !(decision.error === 'SESSION_BUSY_IN_TERMINAL' && activityUnknown(answer))) return decision+ const intent: ExternalResumeIntent = { token: randomUUID(), request, takeOver: input.takeOver ?? null, phase: 'waiting',+ ...(answer.ok && answer.session ? { session: answer.session } : {}),+ ...(answer.ok && answer.owner && answer.generation ? { owner: { process: answer.owner, generation: answer.generation } } : {}) }+ const result = await createAndRegisterPane({+ tmuxBackend: { create: req => deps.tmux!.create({ ...req, current: () => !stopped }), kill: runtime => deps.tmux!.killHeld(runtime, intent.token, () => true) },+ registry: deps.registry, engine: input.engine, sessionLabel: buildHarnessSessionLabel(input.engine),+ argv: heldPaneArgv(externalUnavailable().detail, intent.token), cwd: null, externalResume: intent,+ codexHome: input.codexHome, bypassPermission: input.bypassPermission, permissionMode: input.permissionMode,+ defaultName: input.name ?? (answer.ok ? answer.session?.title : undefined),+ })+ if (!result.ok) return result+ deps.announce(result.pending)+ wake()+ return { ok: true, session: result.pending }+ }+ const cancel = async (initial: RegisteredSession, allowed: () => boolean = () => true) => {+ if (!externalResumePending(initial.externalResume)) return false+ const target = identity(initial)+ const current = () => allowed() && identity(deps.registry.byAgent(initial.agentId)) === target+ if (!current()) throw new Error('The adoption changed before cancellation.')+ const cancelled = deps.registry.setExternalResume(initial.agentId, { ...initial.externalResume!, phase: 'cancelled' })+ if (!cancelled) throw new Error('The adoption cancellation could not be saved.')+ const saved = identity(cancelled)+ const owns = () => allowed() && identity(deps.registry.byAgent(initial.agentId)) === saved+ const panes = cancelled.runtimes.filter(runtime => runtime.backend === 'tmux')+ if (!deps.tmux || !panes.length) throw new Error('The waiting pane could not be verified.')+ for (const pane of panes) {+ const result = await deps.tmux.killHeld(pane, cancelled.externalResume!.token, owns)+ if (!owns() || result.state !== 'succeeded') throw new Error('The waiting pane could not be verified. Adoption stays cancelled.')+ }+ if (!deps.registry.finishExternalCancellation(initial.agentId)) throw new Error('The cancellation could not be committed.')+ deps.forget(initial.agentId)+ return true+ }+ return { create, cancel, wake, open: () => { opened = true; wake() }, stop: () => { stopped = true; if (timer) clearTimeout(timer) },+ settled: async () => { await Promise.all(running.values()) } }+}diff --git a/cli/src/core/agents/heldLaunches.ts b/cli/src/core/agents/heldLaunches.tsindex 0ccb10582..e246e4060 100644--- a/cli/src/core/agents/heldLaunches.ts+++ b/cli/src/core/agents/heldLaunches.ts@@ -107,6 +107,6 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)* What a held agent's pane runs while it waits: the reason, and nothing to type into. It survives the interrupt a* person might send it, and the agent's launch takes the pane over (`respawn`) once the service is ready.*/-export function heldPaneArgv(detail: string): string[] {- return ['/bin/sh', '-c', 'trap "" INT QUIT TSTP; printf "%s\\n" "$1"; while :; do sleep 3600; done', 'harness-held', detail]+export function heldPaneArgv(detail: string, token?: string): string[] {+ return ['/bin/sh', '-c', 'trap "" INT QUIT TSTP; printf "%s\\n" "$1"; while :; do sleep 3600; done', 'harness-held', detail, ...(token ? [token] : [])]}diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.tsindex 49463090a..b00f0dfc1 100644--- a/cli/src/core/agents/launch.spec.ts+++ b/cli/src/core/agents/launch.spec.ts@@ -75,6 +75,18 @@ describe('relaunch helpers', () => {expect(deps.setGridLaunch).toHaveBeenCalledWith('a1', record)})+ it('retains an imported Hermes profile for every relaunch, without applying it after an engine change', async () => {+ const { helpers } = setup()+ const externalResume = { request: { engine: 'hermes' }, session: { launchArgs: ['-p', 'work'] }, phase: 'admitted' } as unknown as RegisteredSession['externalResume']+ vi.mocked(buildLaunchOverrides).mockResolvedValueOnce({ ok: true, overrides: { extraArgs: ['--fixture'] } as LaunchOverrides })+ expect(await helpers.relaunchOverrides(session({ engine: 'hermes', externalResume }))).toMatchObject({ ok: true, overrides: { extraArgs: ['--fixture', '-p', 'work'] } })+ expect(await helpers.relaunchOverrides(session({ engine: 'claude', externalResume }))).toEqual({ ok: true })+ vi.mocked(buildLaunchOverrides).mockResolvedValueOnce({ ok: true, overrides: { extraArgs: [] } as unknown as LaunchOverrides })+ expect(await helpers.relaunchOverrides(session({ engine: 'hermes', externalResume: { ...externalResume!, session: undefined } }))).toMatchObject({ ok: true, overrides: { extraArgs: [] } })+ vi.mocked(buildLaunchOverrides).mockResolvedValueOnce({ ok: false, error: 'SERVICE_UNAVAILABLE', detail: 'unavailable' })+ expect(await helpers.relaunchOverrides(session({ engine: 'hermes', externalResume }))).toMatchObject({ ok: false })+ })+it('drops a permission flag the engine no longer takes, says so, and keeps the pane', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})const { helpers } = setup()diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.tsindex 9d49bb550..24fccc254 100644--- a/cli/src/core/agents/launch.ts+++ b/cli/src/core/agents/launch.ts@@ -54,7 +54,11 @@ export function createLaunchHelpers({ prepareApiTools, launchOverridesDeps, setG}await prepareInstructionWrites(session.cwd)prepareApiTools(session.cwd, session.engine)- return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, session.agentId)+ const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, session.agentId)+ if (result.ok && session.externalResume?.request.engine === session.engine) {+ result.overrides.extraArgs.push(...session.externalResume.session?.launchArgs ?? [])+ }+ return result}/**diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 08a068d2e..a4569cc59 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -276,7 +276,7 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAengineTrust.record(preparedFolder)}} catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }- } else if (!dsh && asker.local && dirname(input.cwd) === projectsRoot()) {+ } else if (!dsh && !resumeSessionId && asker.local && dirname(input.cwd) === projectsRoot()) {// On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain// cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a// `new` project is — but only on evidence, and only where those workspaces live:diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex 1a7349542..8ad12388d 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -16,6 +16,7 @@ import type { ResumeAgent } from './launches.js'export interface LifecycleDeps {settlePane?: StopAgentServiceDeps['settlePane']+ cancelExternal?: StopAgentServiceDeps['cancelExternal']registry: typeof registrystoppedAgents: StoppedAgentStorerestartJobs: StopAgentServiceDeps['restartJobs']@@ -43,7 +44,7 @@ export interface LifecycleDeps {}export function createAgentLifecycle({- registry, stoppedAgents, restartJobs, tmuxBackend, agentReconciler, forgetSession, markDeleted, clearDeleted, stopNative, settlePane,+ registry, stoppedAgents, restartJobs, tmuxBackend, agentReconciler, forgetSession, markDeleted, clearDeleted, stopNative, settlePane, cancelExternal,sessionCheckpoints, mirror, sessionSearch, send, pinnedControls, retainExitedSession, announceSession,relaunchOverrides, prepareSessionResume, refreshGridWebSearch, attachDsh, attachSession, relaunchMarks,}: LifecycleDeps) {@@ -55,7 +56,7 @@ export function createAgentLifecycle({const stopJobs = new Map<string, Promise<void>>()const stopAgent = createStopAgentService({registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,- forgetSession, markDeleted, clearDeleted, stopNative, settlePane,+ forgetSession, markDeleted, clearDeleted, stopNative, settlePane, cancelExternal,})const purgeAgentService = new PurgeAgentService({live: id => registry.byAgent(id), sessions: () => [...registry.list(), ...stoppedAgents.list()],diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.tsindex 02f0a9a98..18cce6e67 100644--- a/cli/src/core/agents/restart.spec.ts+++ b/cli/src/core/agents/restart.spec.ts@@ -76,6 +76,21 @@ describe('restarting an agent', () => {beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('never starts a fresh conversation when an admitted external resume fails', async () => {+ const actual = await vi.importActual<typeof import('../../lib/restartAgent.js')>('../../lib/restartAgent.js')+ vi.mocked(restartAgent).mockImplementationOnce(actual.restartAgent)+ const respawn = vi.fn(async () => ({ ok: true }))+ const keepAbandoned = vi.fn(), buildArgv = vi.fn(options => ['fixture-engine', options.resumeSessionId ?? 'fresh'])+ const run = setup(agent({ resumeOnly: true }), { paneSwapDeps: () => ({+ holdOpen: async () => ({ ok: true }), terminate: async () => 'gone', respawn,+ waitForProcess: async () => null, buildArgv, keepAbandoned, log: () => {},+ }) })+ expect(await run.restart('a1')).toMatchObject({ ok: false, error: 'RESTART_FAILED' })+ expect(respawn).toHaveBeenCalledExactlyOnceWith(['fixture-engine', 's1'])+ expect(keepAbandoned).not.toHaveBeenCalled()+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()+ })+describe('refusals before anything is touched', () => {it('for an agent being purged, stopped or answered, and for one that is not there', async () => {expect(await setup(agent(), { purgeBusy: () => true }).restart('a1')).toEqual({ ok: false, error: 'AGENT_BUSY' })diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex 4d9340bc5..5e62a3a8b 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -170,7 +170,7 @@ export function createAgentRestarter({const restartPermission = await downgradedPermission(session,await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart')const outcome = await restartAgent(- { engine, sessionId: session.sessionId },+ { engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },restartPermission.bypassPermission === true,{ ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null), isCurrent: current },)diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.tsindex 15f0a5cba..448ccceee 100644--- a/cli/src/core/agents/restoreLaunch.spec.ts+++ b/cli/src/core/agents/restoreLaunch.spec.ts@@ -70,3 +70,16 @@ describe('restore preparation keeps session authority in core', () => {expect(deps.refreshGridWebSearch).not.toHaveBeenCalled()})})++it('keeps unadmitted external work held before workspace checks, service preparation or transcript writes', async () => {+ for (const phase of ['waiting', 'quitting', 'cancelled'] as const) {+ for (const launch of [undefined, { state: 'held', service: 'search', detail: 'Waiting for the old terminal.' }]) {+ const { deps, build } = setup()+ const pending = { ...entry, sessionId: '', externalResume: { phase }, launch } as RegisteredSession+ expect(await build(pending, { current: () => true })).toMatchObject({ held: 'search', holdScope: 'workspace' })+ expect(deps.workspaceMissing).not.toHaveBeenCalled()+ expect(deps.relaunchOverrides).not.toHaveBeenCalled()+ expect(deps.prepareSessionResume).not.toHaveBeenCalled()+ }+ }+})diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.tsindex e51a6b67e..37f127f75 100644--- a/cli/src/core/agents/restoreLaunch.ts+++ b/cli/src/core/agents/restoreLaunch.ts@@ -1,4 +1,5 @@/** Restore may wait for preparation; session ownership must survive that wait before core writes. */+import { externalResumePending } from '../../lib/externalResume.js'import type { RegisteredSession } from '../../lib/registry.js'import type { LaunchOverrides, LaunchOverridesResult } from '../../lib/launchOverrides.js'import type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.js'@@ -15,6 +16,8 @@ interface RestoreLaunchDeps {export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps['buildLaunch'] {return async (entry, { current, ...opts }) => {+ if (externalResumePending(entry.externalResume)) return { held: 'search', holdScope: 'workspace',+ detail: entry.launch?.state === 'held' ? entry.launch.detail : 'Waiting to verify this external conversation.' }const missing = deps.workspaceMissing(entry.cwd)if (missing) return missingconst built = await deps.relaunchOverrides(entry)diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsindex f08a3ae33..0a2a27c80 100644--- a/cli/src/core/agents/retarget.spec.ts+++ b/cli/src/core/agents/retarget.spec.ts@@ -84,6 +84,21 @@ describe('retargeting an agent', () => {})afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('keeps an admitted external conversation when its retarget resume fails', async () => {+ const actual = await vi.importActual<typeof import('../../lib/restartAgent.js')>('../../lib/restartAgent.js')+ vi.mocked(restartAgent).mockImplementationOnce(actual.restartAgent)+ const respawn = vi.fn(async () => ({ ok: true }))+ const keepAbandoned = vi.fn(), buildArgv = vi.fn(options => ['fixture-engine', options.resumeSessionId ?? 'fresh'])+ const run = setup(agent({ resumeOnly: true }), { paneSwapDeps: () => ({+ holdOpen: async () => ({ ok: true }), terminate: async () => 'gone', respawn,+ waitForProcess: async () => null, buildArgv, keepAbandoned, log: () => {},+ }) })+ expect(await run.retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'RESPAWN_FAILED' })+ expect(respawn).toHaveBeenCalledExactlyOnceWith(['fixture-engine', 's1'])+ expect(keepAbandoned).not.toHaveBeenCalled()+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()+ })+describe('refusals before anything is touched', () => {it('invalidates an older restore as soon as retarget takes control', async () => {const { deps, retarget, release } = setup()diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex 5af053931..1546aa9c8 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -229,7 +229,7 @@ export function createAgentRetargeter({const retargetPermission = await downgradedPermission(session,await bypassPermissionFor(session, () => liveBypassPermission(session)), 'retarget')const outcome = await restartAgent(- { engine: session.engine, sessionId: session.sessionId },+ { engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },retargetPermission.bypassPermission === true,paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null),)diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 34a7c5bd3..38c339f46 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -41,8 +41,6 @@ describe('the core API services stand on', () => {} as unknown as CoreApiDeps['registry'],stoppedAgents: { list: vi.fn(() => [row('stopped')]) } as unknown as CoreApiDeps['stoppedAgents'],databaseHistory: vi.fn(),- externalSessions: { list: vi.fn(), scan: vi.fn() } as unknown as CoreApiDeps['externalSessions'],- openSessions: { known: vi.fn(), fresh: vi.fn() } as unknown as CoreApiDeps['openSessions'],syncSession: vi.fn(),runtimeModels: vi.fn(async () => []),viewerChanged: vi.fn(),@@ -99,8 +97,6 @@ describe('the core API services stand on', () => {expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])expect(core.agents.displayName).toBe(projectDisplayName)expect(core.transcripts.databaseHistory).toBe(deps.databaseHistory)- expect(core.external.sessions).toBe(deps.externalSessions)- expect(core.external.open).toBe(deps.openSessions)expect(core.agents.byAgent('live')?.agentId).toBe('live')expect(core.agents.byAgent('gone')).toBeUndefined()expect(core.agents.resolve('s-live')?.agentId).toBe('live')diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 3cb781f96..35351fd4a 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -33,7 +33,7 @@ import type { SessionRecaps } from '../lib/recapReads.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'-import type { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'+import { externalUnavailable, type ExternalSessionAnswer, type ExternalSessionRequest } from '../lib/externalSessionWire.js'import type { SessionSearchIndex } from '../lib/sessionSearch/indexer.js'import type { StoppedAgentStore } from '../lib/stoppedAgents.js'import type { TerminalBinaryClear } from '../lib/terminalBinary.js'@@ -203,11 +203,6 @@ export interface CoreApi {* there is none yet. Read from the end of its transcript, bounded (core/transcripts/lastTurn.ts). */lastTurn(sessionId: string): Promise<LastTurnText | null>}- /** Conversations on this machine that Harness did not start, and which of them a process has open. */- external: {- sessions: Pick<ExternalSessions, 'list' | 'scan'>- open: Pick<OpenSessions, 'known' | 'fresh'>- }/** The sign-in the core holds for every service: a service never holds a credential itself. */account: {/** The account's private grid name, minted and remembered by the backend; null when an older@@ -590,11 +585,13 @@ export const ORCHESTRATOR_FALLBACKS: PortFallbacks<OrchestratorPort> = { roleOf:/** The core's calls into session search: index a session at its turn boundaries, forget a purged* conversation, the title it indexed for one being adopted, and stopping its sweeps. The apps' own* requests (`session_search`, `session_tail`) are its `ServiceRequests`, not the core's calls. */-export type SearchPort = Pick<SessionSearchIndex, 'touch' | 'deleteHistory' | 'session' | 'stop'>+export type SearchPort = Pick<SessionSearchIndex, 'touch' | 'deleteHistory' | 'session' | 'stop'> & {+ inspect(request: ExternalSessionRequest): Promise<ExternalSessionAnswer>+}/** What the core gets when search fails: nothing indexed and no title. */export const SEARCH_FALLBACKS: PortFallbacks<SearchPort> = {- touch: undefined, deleteHistory: undefined, session: undefined, stop: undefined,+ touch: undefined, deleteHistory: undefined, session: undefined, stop: undefined, inspect: later(externalUnavailable()),}/*@@ -1336,8 +1333,6 @@ export interface CoreApiDeps {registry: Pick<typeof registry, 'list' | 'byAgent' | 'resolve' | 'advertised' | 'terminalAvailable'>stoppedAgents: Pick<StoppedAgentStore, 'list'>databaseHistory: CoreApi['transcripts']['databaseHistory']- externalSessions: CoreApi['external']['sessions']- openSessions: CoreApi['external']['open']syncSession: CoreApi['agents']['sync']runtimeModels: CoreApi['agents']['runtimeModels']viewerChanged: CoreApi['clients']['viewerChanged']@@ -1385,7 +1380,7 @@ export interface CoreApiDeps {}export function createCoreApi({- dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,+ dataDir, registry, stoppedAgents, databaseHistory, syncSession, runtimeModels, viewerChanged,gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, observer, privateGridName, machineName, backend, onNotice,runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText,signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, lastTurn, turnCard, turnSummary,@@ -1423,7 +1418,6 @@ export function createCoreApi({turns,questions,transcripts: { databaseHistory, lastTurn },- external: { sessions: externalSessions, open: openSessions },account: { mintGridName, accessToken, lane, observerKey, privateGridName, machineName, backend, onNotice, signedIn, environment, machines },clients: {viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows, observer, hasWindow, devicesChanged, dialWatching,diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex f44f8fe80..a7380862e 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -52,7 +52,7 @@ import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readimport { ENGINES, enginePathOverride } from '../lib/engineBin.js'import { isTerminalEngine, type AgentEngine } from '../engines/types.js'import { engineInstallRecipe } from '../lib/engineInstall.js'-import { buildEngineLaunchArgv } from '../lib/engineLaunch.js'+import { buildEngineLaunchArgv, supportsFirstPrompt } from '../lib/engineLaunch.js'import { workspaceMissing } from '../lib/workspaceCheck.js'import { HERMES_SYSTEM_MANAGED_DIR, type GridLaunchMachine } from '../lib/gridLaunchWire.js'import { writeGridConfigDir } from '../lib/gridConfigDir.js'@@ -70,8 +70,8 @@ import { OpenTabProtection } from '../lib/openTabProtection.js'import { sessionCheckpoints } from '../lib/sessionCheckpoint.js'import { repairProjectCwds } from '../lib/cwdRepair.js'import { stoppedAgents } from '../lib/stoppedAgents.js'-import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'-import { externalProviders } from '../lib/sessionSearch/externals/index.js'+import { externalSessionAnswer, externalUnavailable } from '../lib/externalSessionWire.js'+import { externalResumePending } from '../lib/externalResume.js'import { type LaunchOverridesDeps } from '../lib/launchOverrides.js'import { buildHarnessSessionLabel } from '../lib/harnessSessionLabel.js'import { adoptLegacyHarnessSessions, listTmuxPanes } from '../lib/tmuxAgentDiscovery.js'@@ -130,7 +130,8 @@ import { createRestoreLaunch } from './agents/restoreLaunch.js'import { createHeldLaunches, heldPaneArgv } from './agents/heldLaunches.js'import { createCancel, createCancelRequest } from './turns/cancel.js'import { createPaneWatcher } from './agents/newPane.js'-import { createAdoption } from './agents/adopt.js'+import { createExternalResumes } from './agents/externalResume.js'+import { createExternalPreflight } from './agents/externalPreflight.js'import { createAgentCreator } from './agents/create.js'import { createAgentForker } from './agents/fork.js'import { createPaneSwap } from './agents/swap.js'@@ -420,6 +421,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {const restartJobs = new AgentRestartCoordinator()const forgetRestartRevision = (agentId: string): void => restartJobs.forget(agentId)const restoreRevision = (agentId: string): number => restartJobs.revision(agentId)+ let externalResumes: ReturnType<typeof createExternalResumes> | null = null+ let searchGeneration = 0let restoreCancelled = (_agentId: string): boolean => falselet restoreOnly: ((only: ReadonlySet<string>) => Promise<RestoreSummary>) | null = nullconst heldLaunches = createHeldLaunches({@@ -663,9 +666,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Conversations on this machine that Harness did not start, found where each engine keeps them so// Cmd-P can find them and open one here; and which sessions a process has open right now. Harness's// own byproducts (recaps run in its data folder) are never among them.- const externalEngines = externalProviders()- const externalSessions = new ExternalSessions({ providers: externalEngines, excluded: [env.ADAPTER_DATA_DIR], log: (line) => console.warn(line) })- const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })+// The core's one session manager: the backend link, the gateway's dials, the fleet's lane and the dial's// transcriber all take their tokens from it, so a refresh in flight is shared rather than raced.const auth = new AuthSessionManager(backendHttpBase())@@ -720,8 +721,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {registry,stoppedAgents,databaseHistory,- externalSessions,- openSessions,syncSession,runtimeModels,viewerChanged: () => {}, // nothing in the core forwards to a viewer: the viewers follow their own (services/viewers.ts)@@ -1295,6 +1294,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {engineLinks.connected(service)modelControls.connected(service)questionControls.connected(service)+ if (service === 'search') { searchGeneration++; externalResumes?.wake() }if (service === 'usage') usageLink.connected()if (service === 'gateway') gatewayLink?.connected()if (service === 'teams') teamsLink.on()@@ -1305,6 +1305,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {void heldLaunches.restoreHeld(service)},disconnected: (service) => {+ if (service === 'search') searchGeneration++if (service === 'usage') usageLink.disconnected()engineReaders.disconnected(service)liveTransport.disconnected(service)@@ -1332,6 +1333,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// where the core tells it what changed. A purge's forgetting waits for it if it is down.if (outOfProcess.has('search')) {ports.search = {+ inspect: async request => externalSessionAnswer(await serviceLinks.call('search', 'external_inspect', { ...request }, 4_000), request),touch: (sessionId) => { serviceLinks.notify('search', { type: 'service_event', payload: { kind: 'touch', sessionId } }) },deleteHistory: (sessionId) => { serviceLinks.notify('search', { type: 'service_event', payload: { kind: 'deleteHistory', sessionId } }, { untilDelivered: true }) },session: () => undefined,@@ -2029,6 +2031,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// and a pane that outlived the daemon in a session discovery no longer lists still has its// engine, which a second pane resuming the same session would collide with.survey: () => tmuxSurvey(() => listTmuxPanes(), lookupPaneEngineProcess),+ waitingPane: (runtime, token) => backend.isHeld(runtime, token),liveProcess: (entry, runtime) => tmuxSurvey(() => listTmuxPanes(), lookupPaneEngineProcess).liveProcess(entry, runtime),buildLaunch: createRestoreLaunch({workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,@@ -2037,6 +2040,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const { env: launchEnv, extraArgs, clearEnv } = overridesconst argv = buildEngineLaunchArgv(entry.engine, {...opts,+ ...(entry.externalResume?.continue && entry.externalResume.signal === 'sent' && !entry.externalResume.dispatched && supportsFirstPrompt(entry.engine) ? { firstPrompt: 'continue' } : {}),bypassPermission: permission.bypassPermission === true,...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),installIfMissing: enginePathOverride(entry.engine) ? undefined : engineInstallRecipe(entry.engine),@@ -2077,8 +2081,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },log: (message) => console.log(message),// A grid's or a saved API's launch asks models: not before the core is ready (core/agents/heldLaunches.ts).- needs: (entry) => [...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : [])],- waitingLaunch: (_entry, held) => ({ argv: heldPaneArgv(held.detail) }),+ needs: (entry) => [...(externalResumePending(entry.externalResume) ? ['search'] : []), ...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : [])],+ waitingLaunch: (entry, held) => ({ argv: heldPaneArgv(held.detail, entry.externalResume?.token) }),killPane: async (runtime) => { await backend.kill(runtime) },}// Later passes launch the held agents, into the panes they wait in, outside this pass's transaction.@@ -2236,26 +2240,23 @@ async function runForeground(session: AuthSession | null): Promise<void> {})// Opening a conversation Harness did not start, and taking it over from a terminal (core/agents/adopt.ts).- const adoption = createAdoption({- bySession: (sessionId) => registry.bySession(sessionId),- byAgent: (agentId) => registry.byAgent(agentId),- stoppedAgents,- externalSessions,- openSessions,- search: sessionSearch,+ externalResumes = createExternalResumes({+ registry, tmux: tmuxBackend, stopped: () => stoppedAgents.list(), cancelled: id => restoreCancelled(id),+ generation: () => searchGeneration,+ waiting: row => tmuxBackend?.isHeld({ backend: 'tmux', paneId: row.tmuxPane }, row.externalResume!.token).then(value => value === true) ?? Promise.resolve(false),+ inspect: request => ports.search?.inspect(request) ?? Promise.resolve(externalUnavailable()),+ preflight: createExternalPreflight({ blocksFolder: cwd => backend.purgeAgentService?.blocksFolder(cwd),+ hookPort, hooksDisabled: env.DISABLE_HOOK_INSTALL, installOpencodePlugin: installOpencodePluginBeforeSpawn }),+ announce: announceSession, launch: () => { void heldLaunches.restoreHeld('search') },+ forget: id => forgetSession(id, { force: true }),})- const adoptableSession = adoption.adoptableSession- const takeOverWhenIdle = adoption.takeOverWhenIdle- const heldBy = adoption.heldBy// Creating an agent (core/agents/create.ts).backend.onCreateAgent = createAgentCreator({dshLaunch,tmuxBackend,registry,- adoptableSession,- heldBy,- takeOverWhenIdle,+ externalResume: externalResumes.create,watchNewPane,announceSession,attachDsh,@@ -2328,6 +2329,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Stopping, purging and resuming an agent (core/agents/lifecycle.ts).const lifecycle = createAgentLifecycle({settlePane: restorePanes.settle,+ cancelExternal: externalResumes.cancel,registry,stoppedAgents,restartJobs,@@ -2443,7 +2445,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// stops being `bootHandoff` HERE, and not a line earlier: everything the teardown releases exists by now.// A straight-line assignment, never a wait: if the body never reaches this line the handler stays// `bootHandoff`, and the fix still lands.- const updateTeardown = (): TeardownStep[] => [+ const updateTeardown = (): TeardownStep[] => { externalResumes?.stop(); return [['the registry', () => registry.flush({ exiting: true })], ['the updater', () => daemonBoot.updaterBeside?.()],['the reconciler', () => agentReconciler.stop()],['the timers', () => { clearInterval(logTrimTimer); clearInterval(runtimeReconcileTimer); clearInterval(paneTitleSyncTimer) }],@@ -2461,11 +2463,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// next daemon's dial, and esptool, fail as if the hardware had died.['the devices', () => ports.devices?.stop()],// The successor starts its own viewers for the agents it restores; ours must not hold the ports.+ ['external adoption', () => externalResumes?.stop()],['usage observations', () => { usageLink.port.stop(); ports.usage?.stop() }],['the viewers', () => ports.viewers?.stop()], ['the gateway', () => gateway.stop()],// A graceful close releases the backend's one-machine claim, given a moment before the reclaim.['the backend', () => backend.stop()], ['a grace', () => new Promise((r) => setTimeout(r, 1000))],- ]+ ] }daemonBoot.applyStagedUpdate = (v) => updateHandoff.restartForUpdate(v, updateTeardown())// A core an older release's own handoff started (it spawned this `cli.js __run` and judged it) has no// master, and so no updater: it would run this build until its next start. Once that release has gone,@@ -2479,6 +2482,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* which restarts any other exit (harnessd/protocol.ts). */const forGood = (reason: string): boolean => reason === 'revoked' || reason === 'busy'const shutdown = async (signal: string): Promise<void> => {+ externalResumes?.stop()console.log(`\n[cli] ${signal} — shutting down`)// A slow teardown may exhaust the master's grace. Persist already acknowledged bindings first.registry.flush({ exiting: true })@@ -2511,6 +2515,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {await localWsServer.close()hookServer.close()nativeControls.close()+ externalResumes?.stop()usageLink.port.stop(); ports.usage?.stop()await ports.viewers?.stop()await gateway.stop()@@ -2605,6 +2610,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.log('[cli] ready')// Ready first, never after a service: the agents the boot held for one are launched now, in the background.void heldLaunches.restoreHeld()+ externalResumes.open()}/**diff --git a/cli/src/core/serviceHost.spec.ts b/cli/src/core/serviceHost.spec.tsindex 87f990df0..638e247f0 100644--- a/cli/src/core/serviceHost.spec.ts+++ b/cli/src/core/serviceHost.spec.ts@@ -5,6 +5,7 @@ import { createServiceHost, FAIL, later, ServiceUnavailableError, testFaults, ty// A port whose members cover every shape: sync and async, value and FAIL fallbacks, a stop.class FakeSearch {+ inspect: SearchPort['inspect'] = async () => ({ ok: false, error: 'SEARCH_UNAVAILABLE', detail: 'unavailable' })readonly calls: string[] = []touch(sessionId: string): void { this.calls.push(`touch ${sessionId}`) }deleteHistory(sessionId: string): void { this.calls.push(`delete ${sessionId}`) }diff --git a/cli/src/engines/facets/adoption.ts b/cli/src/engines/facets/adoption.tsindex 7323187af..bc20f6477 100644--- a/cli/src/engines/facets/adoption.ts+++ b/cli/src/engines/facets/adoption.ts@@ -1,10 +1,10 @@import type { ExternalOrigin } from '../../lib/sessionSearch/externals/types.js'/**- * How core finds an engine's conversations on this machine that Harness did not start, which process holds one+ * How search finds an engine's conversations on this machine that Harness did not start, which process holds one* open, and whether a turn is running there: adoption (Cmd-P, opening one here, and stopping its owner first).- * Declared data, applied in core by the kit (kit/adoption.ts): taking a conversation over stops a process, so it- * never waits on an engine worker (docs/design/2026-10-08-engine-launch.md, (c5)).+ * Declared data, applied in search by the kit (kit/adoption.ts). Core owns takeover consent, cancellation and+ * signals; unavailable or uncertain observations hold adoption (docs/design/2026-10-09-external-session-boundary.md).*/export interface AdoptionContract {/**diff --git a/cli/src/engines/kit/adoption.ts b/cli/src/engines/kit/adoption.tsindex 86b40ebd2..419b4c295 100644--- a/cli/src/engines/kit/adoption.ts+++ b/cli/src/engines/kit/adoption.ts@@ -5,6 +5,7 @@* nothing else: it never writes, never starts the engine, and never logs a process's arguments (they can carry a key).*/import { join } from 'node:path'+import { externalEvidenceActive, externalReadFailed } from '../../lib/sessionSearch/evidence.js'import { agentCommandOwnershipSnapshot } from '../../lib/engineBin.js'import { absoluteFolder, entries, fileStamp, firstLine, parseLine, readHead, readJson, readTail, readText, record, text } from '../../lib/sessionSearch/externals/support.js'@@ -147,7 +148,7 @@ export async function turnOpen(path: string, tail: Tail, unknown: boolean | nullreturn unknown}-async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { records: unknown }>['records'], dirs: string[], view: ProcessView): Promise<OwnerClaim[]> {+async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { records: unknown }>['records'], pattern: RegExp, dirs: string[], view: ProcessView): Promise<OwnerClaim[]> {const claims: OwnerClaim[] = []for (const dir of dirs) {const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith(owners.suffix))@@ -158,28 +159,54 @@ async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { reconst path = join(dir, file.name)const row = record(await readJson(path))const pid = row?.[owners.pid]+ if (externalEvidenceActive() && (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0 || pid > 0x7fffffff+ || !pattern.test(text(row?.[owners.id])))) {+ externalReadFailed(new Error('incomplete owner record'), 'owner record'); continue+ }if (typeof pid !== 'number' || !text(row?.[owners.id]) || !view.alive(pid)) continue// A record outlives a crash, and its pid can be handed to anything after — a shell in another tab. Only a// process of this engine already running when the record says it started still has it.const process = processes.get(pid)+ if (!process && externalEvidenceActive()) externalReadFailed(new Error('missing owner process'), 'owner process')if (!process || engineProcessMatch(process, engine as never, ownership).score <= 0) continueconst started = row?.[owners.started]+ if (externalEvidenceActive() && (typeof started !== 'number' || !Number.isFinite(started) || started <= 0+ || !Number.isFinite(process.started) || process.started! <= 0)) {+ externalReadFailed(new Error('incomplete owner incarnation'), 'owner record'); continue+ }if (process.started !== undefined && typeof started === 'number' && process.started > started + owners.slackMs) continueclaims.push({ sessionId: text(row?.[owners.id]), pid, record: path })}}+ if (externalEvidenceActive()) {+ const ownership = agentCommandOwnershipSnapshot()+ for (const process of await view.list()) {+ if (!view.alive(process.pid) || engineProcessMatch(process, engine as never, ownership).score <= 0) continue+ const ids = new Set(claims.filter(claim => claim.pid === process.pid).map(claim => claim.sessionId))+ if (ids.size !== 1) externalReadFailed(new Error('no unambiguous current process record'), 'current owner')+ }+ }return claims}-async function openFileOwners(open: Extract<Owners, { open: unknown }>['open'], view: ProcessView): Promise<OwnerClaim[]> {+async function openFileOwners(engine: ExternalEngine, open: Extract<Owners, { open: unknown }>['open'], view: ProcessView): Promise<OwnerClaim[]> {const claims: OwnerClaim[] = []const held = await view.openFilesOf(open.commands)if (!held.size) return claimsconst processes = new Map((await view.list()).map((row): [number, RunningProcess] => [row.pid, row]))+ const ownership = agentCommandOwnershipSnapshot()for (const [pid, files] of held) {+ const records = files.filter(path => open.id.test(path) && path.includes(open.contains))+ if (!records.length) continue+ // lsof -c selects command prefixes; a codex-audit helper can hold a rollout too. The exact+ // process snapshot must identify the engine before an FD claim can authorize its termination.+ const process = processes.get(pid)+ if (externalEvidenceActive() && (!process || !view.alive(pid) || engineProcessMatch(process, engine as never, ownership).score <= 0)) {+ externalReadFailed(new Error('unverified file owner process'), 'owner process'); continue+ }// A server holding a thread is never stopped from here, even when a terminal started it.const app = servesOthers(processes.get(pid), open.servers)- for (const path of files) {+ for (const path of records) {const id = open.id.exec(path)?.[1]if (id && path.includes(open.contains)) claims.push({ sessionId: id, pid, record: path, ...(app ? { app: true } : {}) })}@@ -234,8 +261,20 @@ export function adoptionProvider(engine: ExternalEngine, contract: AdoptionContrreturn found},owners: (view: ProcessView) => 'records' in owners- ? recordOwners(engine, owners.records, places.records?.() ?? places.roots().map((root) => join(root, '..', owners.records.folder)), view)- : openFileOwners(owners.open, view),+ ? recordOwners(engine, owners.records, head.id.pattern, places.records?.() ?? places.roots().map((root) => join(root, '..', owners.records.folder)), view)+ : openFileOwners(engine, owners.open, view),+ async confirmOwner(owner, process) {+ if (!('records' in owners) || !('record' in busy)) return null+ // Claude's one record carries the session, PID, incarnation and activity together. A final+ // transcript read cannot offer this guarantee when ownership lives in a separate store.+ const row = record(await readJson(owner.record)), fields = owners.records+ const started = row?.[fields.started]+ if (!process || process.pid !== owner.pid || row?.[fields.pid] !== owner.pid || row?.[fields.id] !== owner.sessionId+ || typeof started !== 'number' || !Number.isFinite(started) || started <= 0+ || !Number.isFinite(process.started) || process.started! <= 0 || process.started! > started + fields.slackMs)+ return { current: false, busy: null }+ return { current: true, busy: row?.[busy.record.field] === busy.record.busy ? true : row?.[busy.record.field] === busy.record.idle ? false : null }+ },async busy(owner): Promise<boolean | null> {if ('tail' in busy) return turnOpen(owner.record, busy.tail, null)const row = record(await readJson(owner.record))diff --git a/cli/src/lib/__fixtures__/external-owner-control.golden.json b/cli/src/lib/__fixtures__/external-owner-control.golden.jsonnew file mode 100644index 000000000..c96c21d84--- /dev/null+++ b/cli/src/lib/__fixtures__/external-owner-control.golden.json@@ -0,0 +1,362 @@+{+ "darwin/term": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/kill": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "signal",+ 7,+ "SIGKILL"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 5000+ },+ "darwin/stuck": {+ "ok": false,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "signal",+ 7,+ "SIGKILL"+ ]+ ],+ "waited": 7000+ },+ "darwin/gone": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/group": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ -7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/job-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/signal-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/tty-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "darwin/no-tty": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ]+ ],+ "waited": 0+ },+ "linux/term": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/kill": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "signal",+ 7,+ "SIGKILL"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 5000+ },+ "linux/stuck": {+ "ok": false,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "signal",+ 7,+ "SIGKILL"+ ]+ ],+ "waited": 7000+ },+ "linux/gone": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/group": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ -7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/job-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/signal-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/tty-failed": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ],+ [+ "tty",+ "/dev/fixture-terminal",+ "\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?1049l\u001b[?25h"+ ]+ ],+ "waited": 0+ },+ "linux/no-tty": {+ "ok": true,+ "effects": [+ [+ "foreground",+ 7+ ],+ [+ "signal",+ 7,+ "SIGTERM"+ ]+ ],+ "waited": 0+ }+}diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 8877ad365..ac610aa2b 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -19,6 +19,7 @@ import type { ForkOrigin, RegisteredSession } from './registry.js'import type { TerminalBackend } from './terminalBackend.js'import type { TerminalCreateResult, TmuxRuntimeRef } from './terminalTypes.js'import { terminalRouteKey } from './terminalRuntime.js'+import type { ExternalResumeIntent } from './externalResume.js'const DEFAULT_MAX_ATTEMPTS = 3@@ -41,6 +42,7 @@ export interface CreateAgentPaneDeps {defaultName?: string | nulllabel?: string | nullforkedFrom?: ForkOrigin | null+ externalResume?: ExternalResumeIntent}) => RegisteredSession | null }engine: AgentEnginecwd?: string | null@@ -74,6 +76,7 @@ export interface CreateAgentPaneDeps {agent?: string | null/** The agent this pane is a fork of (`agent_fork`), recorded on the row; null otherwise. */forkedFrom?: ForkOrigin | null+ externalResume?: ExternalResumeIntentmaxAttempts?: number}@@ -116,6 +119,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<defaultName: deps.defaultName,label: deps.label,forkedFrom: deps.forkedFrom,+ ...(deps.externalResume ? { externalResume: deps.externalResume } : {}),})if (pending) return { ok: true, spawned, pending }console.warn(`[agent] create ${deps.engine} registration failed · pane ${spawned.runtime.paneId} · `diff --git a/cli/src/lib/externalOwnerControl.golden.spec.ts b/cli/src/lib/externalOwnerControl.golden.spec.tsnew file mode 100644index 000000000..36c6944f8--- /dev/null+++ b/cli/src/lib/externalOwnerControl.golden.spec.ts@@ -0,0 +1,38 @@+/** Former-code record of external-owner control effects, before moving them into a core-only leaf. */+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname } from 'node:path'+import { fileURLToPath } from 'node:url'+import { expect, it, vi } from 'vitest'++process.env.TZ = 'UTC'+const fixture = fileURLToPath(new URL('./__fixtures__/external-owner-control.golden.json', import.meta.url))++it('preserves ordered terminal-owner signals, bounded waits and terminal restoration on both platforms', async () => {+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+ const out: Record<string, unknown> = {}+ try {+ for (const os of ['darwin', 'linux']) {+ Object.defineProperty(process, 'platform', { value: os })+ vi.resetModules()+ const { stopSessionOwner } = await import('./externalOwnerControl.js')+ for (const mode of ['term', 'kill', 'stuck', 'gone', 'group', 'job-failed', 'signal-failed', 'tty-failed', 'no-tty']) {+ const effects: unknown[] = []+ let alive = mode !== 'gone', signals = 0, waited = 0+ const ok = await stopSessionOwner({ pid: 7, tty: mode === 'no-tty' ? null : '/dev/fixture-terminal' }, {+ alive: () => alive,+ kill: (pid, signal) => {+ effects.push(['signal', pid, signal]); signals+++ if (mode === 'signal-failed') { alive = false; throw new Error('gone') }+ if (mode !== 'stuck' && (mode !== 'kill' || signals === 2)) alive = false+ },+ sleep: async ms => { waited += ms },+ job: async pid => { effects.push(['foreground', pid]); if (mode === 'job-failed') throw new Error('ps unavailable'); return mode === 'group' ? pid : null },+ writeTty: async (tty, value) => { effects.push(['tty', tty, value]); if (mode === 'tty-failed') throw new Error('closed') },+ })+ out[`${os}/${mode}`] = { ok, effects, waited }+ }+ }+ if (process.env.RECORD_EXTERNAL_CONTROL === '1') { mkdirSync(dirname(fixture), { recursive: true }); writeFileSync(fixture, JSON.stringify(out, null, 2) + '\n') }+ expect(out).toEqual(JSON.parse(readFileSync(fixture, 'utf8')))+ } finally { Object.defineProperty(process, 'platform', platform); vi.resetModules() }+})diff --git a/cli/src/lib/externalOwnerControl.spec.ts b/cli/src/lib/externalOwnerControl.spec.tsnew file mode 100644index 000000000..7f0f3cca3--- /dev/null+++ b/cli/src/lib/externalOwnerControl.spec.ts@@ -0,0 +1,8 @@+import { expect, it } from 'vitest'+import { verifiedForegroundJob } from './externalOwnerControl.js'+it('distinguishes verified group leadership from unreadable foreground evidence', async () => {+ for (const [answer, expected] of [[null, 'unknown'], ['', 'unknown'], ['bad', 'unknown'], ['7 0', 'unknown'], ['0 7', 'unknown'],+ ['7 7 extra', 'unknown'], ['7 7', 7], ['8 7', null], ['7 -1', null]] as const) {+ expect(await verifiedForegroundJob(7, async () => answer)).toBe(expected)+ }+})diff --git a/cli/src/lib/externalOwnerControl.ts b/cli/src/lib/externalOwnerControl.tsnew file mode 100644index 000000000..b018ce0af--- /dev/null+++ b/cli/src/lib/externalOwnerControl.ts@@ -0,0 +1,82 @@+/** Session-control primitives stay in core's eager import closure, independent of search readers. */+import { open } from 'node:fs/promises'+import { execFile } from 'node:child_process'+import { processExists as processAlive } from './processLiveness.js'+import type { SessionOwner } from './sessionSearch/external.js'++function run(command: string, args: string[], timeout: number): Promise<string | null> {+ return new Promise(resolve => execFile(command, args, { timeout, encoding: 'utf8' }, (error, stdout) => resolve(error ? null : stdout)))+}++export interface StopOptions {+ alive?: (pid: number) => boolean+ kill?: (pid: number, signal: NodeJS.Signals) => void+ sleep?: (ms: number) => Promise<void>+ /** Writes to the owner's terminal; tests replace it. */+ writeTty?: (tty: string, text: string) => Promise<void>+ /** The foreground job [pid] leads, if it leads one; tests replace it. */+ job?: (pid: number) => Promise<number | null>+}++/**+ * The foreground job an engine leads in its terminal: the process group it heads, when that group is+ * the one the terminal is showing. Its whole job is signalled then, so what it started for its screen+ * goes with it (Hermes's terminal UI runs a Node child its Python does not pass SIGTERM to). An+ * engine that does not lead its job (Codex's native binary under its Node launcher, anything run+ * without job control) is signalled alone: its group may hold the shell it runs in.+ */+export async function foregroundJob(pid: number, exec: typeof run = run): Promise<number | null> {+ const out = await exec('ps', ['-o', 'pgid=,tpgid=', '-p', String(pid)], 3_000)+ const [pgid, tpgid] = (out ?? '').trim().split(/\s+/).map(Number)+ return pgid === pid && tpgid === pid ? pid : null+}++/** Failed process evidence is distinct from verified non-leadership for new core admissions. */+export async function verifiedForegroundJob(pid: number, exec: typeof run = run): Promise<number | null | 'unknown'> {+ const out = await exec('ps', ['-o', 'pgid=,tpgid=', '-p', String(pid)], 3_000)+ if (!out) return 'unknown'+ const values = out.trim().split(/\s+/).map(Number)+ if (values.length !== 2 || !values.every(Number.isSafeInteger) || values[0] <= 0 || values[1] === 0) return 'unknown'+ return values[0] === pid && values[1] === pid ? pid : null+}++/**+ * What a terminal gets back after its engine is stopped from outside: the main screen, no mouse+ * reporting, and a cursor. A TUI that quit cleanly already restored them, and then these change+ * nothing; Codex leaves its cursor hidden, and a TUI made to quit leaves whatever it had on.+ */+export const TERMINAL_RESTORE = '\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h'++/**+ * Stops the terminal process that has a session open, so Harness can resume it: asked to quit+ * (SIGTERM, which the engines answer by saving and restoring the terminal), then made to after five+ * seconds, and the terminal put back. Whether the process is gone.+ */+export async function stopSessionOwner(owner: Pick<SessionOwner, 'pid' | 'tty'>, opts: StopOptions = {}): Promise<boolean> {+ const alive = opts.alive ?? processAlive+ const kill = opts.kill ?? ((pid: number, signal: NodeJS.Signals) => { process.kill(pid, signal) })+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const gone = async (ms: number): Promise<boolean> => {+ for (let waited = 0; waited < ms; waited += 100) {+ if (!alive(owner.pid)) return true+ await sleep(100)+ }+ return !alive(owner.pid)+ }+ const job = await (opts.job ?? foregroundJob)(owner.pid).catch(() => null)+ const signal = (name: NodeJS.Signals): void => {+ try { kill(job ? -job : owner.pid, name) } catch { /* already gone */ }+ }+ signal('SIGTERM')+ if (!await gone(5_000)) {+ signal('SIGKILL')+ if (!await gone(2_000)) return false+ }+ if (owner.tty) await (opts.writeTty ?? writeTty)(owner.tty, TERMINAL_RESTORE).catch(() => undefined)+ return true+}++export async function writeTty(tty: string, content: string): Promise<void> {+ const handle = await open(tty, 'w')+ try { await handle.write(content) } finally { await handle.close() }+}diff --git a/cli/src/lib/externalProcessGeneration.spec.ts b/cli/src/lib/externalProcessGeneration.spec.tsnew file mode 100644index 000000000..96d7510e4--- /dev/null+++ b/cli/src/lib/externalProcessGeneration.spec.ts@@ -0,0 +1,13 @@+import { expect, it, vi } from 'vitest'+import { externalProcessGeneration } from './externalProcessGeneration.js'+import { processStartMarker } from './processLiveness.js'+vi.mock('./processLiveness.js', () => ({ processStartMarker: vi.fn() }))+it('normalizes OS incarnation markers without using the host clock or timezone', () => {+ for (const [marker, expected] of [+ ['linux:1234', 'linux:1234'], ['ps-c:Thu Oct 8 10:00:00 2026', 'ps:1791453600000'],+ ['ps-c:unreadable', null], ['old marker', null], [null, null],+ ]) {+ vi.mocked(processStartMarker).mockReturnValue(marker)+ expect(externalProcessGeneration(7)).toBe(expected)+ }+})diff --git a/cli/src/lib/externalProcessGeneration.ts b/cli/src/lib/externalProcessGeneration.tsnew file mode 100644index 000000000..672584608--- /dev/null+++ b/cli/src/lib/externalProcessGeneration.ts@@ -0,0 +1,10 @@+/** The process incarnation used by external adoption, checked again by core before any signal. */+import { processStartMarker } from './processLiveness.js'++export function externalProcessGeneration(pid: number): string | null {+ const marker = processStartMarker(pid)+ if (marker?.startsWith('linux:')) return marker+ if (!marker?.startsWith('ps-c:')) return null+ const started = Date.parse(`${marker.slice(5)} UTC`)+ return Number.isFinite(started) ? `ps:${started}` : null+}diff --git a/cli/src/lib/externalResume.spec.ts b/cli/src/lib/externalResume.spec.tsnew file mode 100644index 000000000..491deeb16--- /dev/null+++ b/cli/src/lib/externalResume.spec.ts@@ -0,0 +1,39 @@+import { expect, it } from 'vitest'+import { externalReservations, externalResumeIds, externalResumePending, parseExternalResume, type ExternalResumeIntent } from './externalResume.js'+const request = { sessionId: 'alias', engine: 'hermes' as const }+const session = { sessionId: 'canonical', engine: 'hermes' as const, cwd: '/fixture/work', transcriptPath: null,+ aliases: ['alias', 'second'], title: 'Conversation', origin: 'terminal' as const, mtime: 1, launchArgs: ['-p', 'work'] }+const waiting: ExternalResumeIntent = { token: '12345678-1234-1234-1234-123456789012', request, phase: 'waiting', takeOver: 'wait' }+const owner = { process: { pid: 7, engine: 'hermes' as const, record: '/fixture/record', tty: '/dev/fixture-terminal' }, generation: 'ps:1' }+it('clones only valid durable data and preserves reservations until a real conversation change', () => {+ const value = { ...waiting, session, owner, ignored: 'discard' }+ const parsed = parseExternalResume(value)!+ expect(parsed).toEqual({ ...waiting, session, owner })+ session.aliases.push('new-alias')+ expect(parsed.session?.aliases).toEqual(['alias', 'second'])+ session.aliases.pop()+ expect(externalResumeIds(parsed)).toEqual(['alias', 'canonical', 'second'])+ const admitted: ExternalResumeIntent = { ...parsed, phase: 'admitted', signal: 'sent', continue: true, dispatched: true }+ expect(parseExternalResume(admitted)).toEqual(admitted)+ expect(externalResumePending(admitted)).toBe(false)+ for (const sessionId of ['', 'canonical']) expect(externalReservations({ sessionId, externalResume: admitted })).toContain('alias')+ expect(externalReservations({ sessionId: 'new-conversation', externalResume: admitted })).toEqual(['new-conversation'])+ expect(externalResumeIds({ ...parsed, phase: 'cancelled' })).toEqual([])+ expect(externalResumePending({ ...parsed, phase: 'cancelled' })).toBe(true)+ expect(externalResumeIds(undefined)).toEqual([])+ expect(externalResumePending(undefined)).toBe(false)+})+it('refuses malformed, oversize and contradictory journal states instead of creating a fresh launch', () => {+ const cyclic: Record<string, unknown> = { ...waiting }; cyclic.loop = cyclic+ for (const value of [null, [], cyclic, { ...waiting, extra: 'x'.repeat(65_536) },+ { ...waiting, token: 'unsafe;token' }, { ...waiting, phase: 'unknown' }, { ...waiting, request: {} },+ { ...waiting, takeOver: 'new-choice' }, { ...waiting, continue: false }, { ...waiting, continue: true },+ { ...waiting, dispatched: true }, { ...waiting, signal: 'sent', session, owner },+ { ...waiting, session: { ...session, engine: 'claude' } }, { ...waiting, session: { ...session, aliases: [] } },+ { ...waiting, session: {} }, { ...waiting, phase: 'admitted' }, { ...waiting, phase: 'quitting' },+ { ...waiting, phase: 'quitting', session, owner, takeOver: null }, { ...waiting, owner: {} },+ { ...waiting, owner: { ...owner, generation: 'unknown' } }, { ...waiting, owner: { ...owner, process: { ...owner.process, harness: true } } },+ ]) expect(parseExternalResume(value), JSON.stringify(value === cyclic ? 'cyclic' : value)).toBeNull()+ expect(parseExternalResume({ ...waiting, phase: 'quitting', session, owner })).not.toBeNull()+ expect(parseExternalResume({ ...waiting, phase: 'quitting', session, owner, signal: 'prepared', continue: true })).not.toBeNull()+})diff --git a/cli/src/lib/externalResume.ts b/cli/src/lib/externalResume.tsnew file mode 100644index 000000000..a3e5f1bdb--- /dev/null+++ b/cli/src/lib/externalResume.ts@@ -0,0 +1,62 @@+/** A pending adoption is not yet an owned conversation. Persist it before exposing its inert pane. */+import { externalSessionFact, externalSessionOwner, externalSessionRequest,+ type ExternalSessionFact, type ExternalSessionRequest } from './externalSessionWire.js'+import type { SessionOwner } from './sessionSearch/external.js'++export interface ExternalResumeIntent {+ token: string+ request: ExternalSessionRequest+ takeOver: 'idle' | 'now' | 'wait' | null+ phase: 'waiting' | 'quitting' | 'admitted' | 'cancelled'+ session?: ExternalSessionFact+ signal?: 'prepared' | 'sent'+ continue?: true+ dispatched?: true+ /** Only this exact process may inherit an already-dispatched takeover across a daemon restart. */+ owner?: { process: SessionOwner; generation: string }+}++export function parseExternalResume(value: unknown): ExternalResumeIntent | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null+ try { if (Buffer.byteLength(JSON.stringify(value)) > 64 * 1024) return null } catch { return null }+ const row = value as Record<string, unknown>+ const request = externalSessionRequest(row.request)+ if (!request || typeof row.token !== 'string' || !/^[a-f0-9-]{36}$/.test(row.token)+ || !['waiting', 'quitting', 'admitted', 'cancelled'].includes(String(row.phase))+ || !(row.signal === undefined || row.signal === 'prepared' || row.signal === 'sent')+ || !['continue', 'dispatched'].every(key => row[key] === undefined || row[key] === true)+ || !(row.takeOver === null || ['idle', 'now', 'wait'].includes(String(row.takeOver)))) return null+ const session = row.session === undefined ? undefined : externalSessionFact(row.session)+ if (session === null || session && (session.engine !== request.engine+ || session.sessionId !== request.sessionId && !session.aliases?.includes(request.sessionId))) return null+ let owner: ExternalResumeIntent['owner']+ if (row.owner !== undefined) {+ const raw = row.owner as Record<string, unknown> | null+ const process = externalSessionOwner(raw?.process)+ if (!process || process.engine !== request.engine || !process.tty || process.harness || process.unverified || process.fromArgs+ || typeof raw?.generation !== 'string' || !/^(linux|ps):\d+$/.test(raw.generation)) return null+ owner = { process, generation: raw.generation }+ }+ if (row.phase === 'admitted' && !session || row.phase === 'quitting' && (!session || !owner || row.takeOver === null)+ || row.signal && (!session || !owner || row.takeOver === null || row.phase === 'waiting')+ || row.continue && !row.signal || row.dispatched && row.phase !== 'admitted') return null+ return { token: row.token, request, takeOver: row.takeOver as ExternalResumeIntent['takeOver'],+ phase: row.phase as ExternalResumeIntent['phase'], ...(row.signal ? { signal: row.signal as 'prepared' | 'sent' } : {}), ...(row.continue ? { continue: true } : {}), ...(row.dispatched ? { dispatched: true } : {}), ...(session ? { session } : {}), ...(owner ? { owner } : {}) }+}++/** A cancelled intent no longer reserves a conversation, but can never silently become a fresh launch. */+export function externalResumeIds(intent: ExternalResumeIntent | undefined): readonly string[] {+ return !intent || intent.phase === 'cancelled' ? [] :+ [...new Set([intent.request.sessionId, ...(intent.session ? [intent.session.sessionId, ...intent.session.aliases ?? []] : [])])]+}++export function externalResumePending(intent: ExternalResumeIntent | undefined): boolean {+ return !!intent && intent.phase !== 'admitted'+}++/** Keep admitted aliases until this harness demonstrably moves to another conversation. */+export function externalReservations(row: { sessionId: string; externalResume?: ExternalResumeIntent }): readonly string[] {+ const intent = row.externalResume+ return [row.sessionId, ...(intent?.phase === 'admitted' && row.sessionId && row.sessionId !== intent.session!.sessionId+ ? [] : externalResumeIds(intent))].filter(Boolean)+}diff --git a/cli/src/lib/externalSessionWire.spec.ts b/cli/src/lib/externalSessionWire.spec.tsnew file mode 100644index 000000000..0990731ff--- /dev/null+++ b/cli/src/lib/externalSessionWire.spec.ts@@ -0,0 +1,52 @@+import { expect, it } from 'vitest'+import { externalSessionAnswer, externalSessionFact, externalSessionRequest } from './externalSessionWire.js'++const request = { engine: 'claude' as const, sessionId: 'conversation' }+const session = { ...request, cwd: '/workspace', title: 'A conversation', origin: 'terminal', mtime: 1, transcriptPath: '/store/conversation.jsonl' }+const answer = { ok: true, request, session, owner: null, generation: null, busy: false }++it('copies bounded facts, never history readers, and matches the exact request and canonical aliases', () => {+ const source = { ...answer, session: { ...session, aliases: ['old'], launchArgs: [], readHistory: () => ['private history'] } }+ const accepted = externalSessionAnswer(source, request)+ expect(accepted.ok).toBe(true)+ if (!accepted.ok) throw new Error('valid observation refused')+ expect(accepted.session).not.toHaveProperty('readHistory')+ source.session.aliases.push('later')+ expect(accepted.session?.aliases).toEqual(['old'])+ expect(externalSessionAnswer({ ...answer, request: { ...request, sessionId: 'old' }, session: source.session }, { ...request, sessionId: 'old' }).ok).toBe(true)+ expect(externalSessionRequest({ ...request, secret: 'discard' })).toEqual(request)+})++it('holds mismatched, oversized, malformed or unavailable answers instead of reporting free', () => {+ for (const value of [null, [], {}, { ...answer, request: { ...request, engine: 'codex' } },+ { ...answer, session: { ...session, sessionId: 'other' } }, { ...answer, extra: 'x'.repeat(65536) },+ { ...answer, busy: true }, { ...answer, busyConfirmed: true }, { ...answer, busyConfirmed: false }, { ...answer, generation: 'marker' }, { ...answer, session: undefined },+ { ...answer, owner: { pid: -1 } }, { ok: false, detail: '\u0000' }, { ...answer, owner: {}, session: null }]) {+ expect(externalSessionAnswer(value, request)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+ }+ const cyclic: any = { ...answer }; cyclic.self = cyclic+ expect(externalSessionAnswer(cyclic, request).ok).toBe(false)+ expect(externalSessionAnswer({ ok: false, detail: 'Waiting for the reader.' }, request)).toMatchObject({ detail: 'Waiting for the reader.' })+})++it('refuses invalid metadata and owner boundaries', () => {+ for (const patch of [{ cwd: 'relative' }, { transcriptPath: 'relative' }, { title: 'x'.repeat(4097) },+ { aliases: [''] }, { aliases: Array(257).fill('id') }, { launchArgs: ['\u0000'] }, { launchArgs: ['-p', 'work'] }, { archived: false },+ { engine: 'terminal' }, { origin: 'arbitrary' }, { mtime: NaN }]) expect(externalSessionFact({ ...session, ...patch })).toBeNull()+ const owner = { pid: 7, engine: 'claude', tty: '/dev/fixture-terminal', record: '/store/record', harness: true }+ const owned = { ...answer, owner, generation: 'ps:1000', busy: true }+ expect(externalSessionAnswer(owned, request)).toMatchObject({ ok: true, owner })+ expect(externalSessionAnswer({ ...owned, owner: { ...owner, harness: undefined }, busyConfirmed: true }, request)).toMatchObject({ ok: true, busyConfirmed: true })+ for (const patch of [{ harness: true }, { fromArgs: true }, { unverified: true }, { tty: null }])+ expect(externalSessionAnswer({ ...owned, owner: { ...owner, harness: undefined, ...patch }, busyConfirmed: true }, request).ok).toBe(false)+ for (const patch of [{ pid: 0 }, { pid: 2 ** 32 }, { tty: '/workspace' }, { record: '\u0000' },+ { harness: false }, { engine: 'codex' }]) expect(externalSessionAnswer({ ...owned, owner: { ...owner, ...patch } }, request).ok).toBe(false)+ expect(externalSessionAnswer({ ...owned, owner: { ...owner, harness: undefined }, generation: null }, request).ok).toBe(false)+})++it('accepts only the declarative Hermes profile launch option', () => {+ expect(externalSessionFact({ ...session, engine: 'hermes', launchArgs: ['-p', 'work'] })?.launchArgs).toEqual(['-p', 'work'])+ for (const launchArgs of [['--command', 'shell'], ['-p', '../escape'], ['-p', 'work', 'extra'], ['-p', 1]]) {+ expect(externalSessionFact({ ...session, engine: 'hermes', launchArgs })).toBeNull()+ }+})diff --git a/cli/src/lib/externalSessionWire.ts b/cli/src/lib/externalSessionWire.tsnew file mode 100644index 000000000..a1d29750f--- /dev/null+++ b/cli/src/lib/externalSessionWire.ts@@ -0,0 +1,88 @@+/** Search supplies bounded observations. Core alone reserves, admits, signals and launches. */+import { isAbsolute } from 'node:path'+import { EXTERNAL_ENGINES, type ExternalEngine, type ExternalSession } from './sessionSearch/externals/types.js'+import type { SessionOwner } from './sessionSearch/external.js'++export interface ExternalSessionRequest { sessionId: string; engine: ExternalEngine }+export type ExternalSessionFact = Omit<ExternalSession, 'readHistory'>+export interface ExternalSessionObservation {+ ok: true+ request: ExternalSessionRequest+ session: ExternalSessionFact | null+ owner: SessionOwner | null+ /** A process generation read with ownership evidence, never a bare PID grant. */+ generation: string | null+ busy: boolean+ /** Unknown activity blocks idle takeover, but must never manufacture a continuation prompt. */+ busyConfirmed?: true+}+export interface ExternalSessionUnavailable {+ ok: false+ error: 'SEARCH_UNAVAILABLE'+ detail: string+}+export type ExternalSessionAnswer = ExternalSessionObservation | ExternalSessionUnavailable+export const externalUnavailable = (detail = 'Waiting for the search service to verify this conversation.'): ExternalSessionUnavailable =>+ ({ ok: false, error: 'SEARCH_UNAVAILABLE', detail })++const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)+const text = (value: unknown, max: number): value is string => typeof value === 'string' && value.length <= max && !/[\x00-\x1f\x7f]/.test(value)+const id = (value: unknown): value is string => text(value, 200) && value.length > 0+const engine = (value: unknown): value is ExternalEngine => typeof value === 'string' && EXTERNAL_ENGINES.includes(value as ExternalEngine)+const path = (value: unknown): value is string => text(value, 4096) && isAbsolute(value)+const strings = (value: unknown, count: number, max: number): value is string[] => Array.isArray(value) && value.length <= count && value.every(item => text(item, max))++export function externalSessionRequest(value: unknown): ExternalSessionRequest | null {+ return object(value) && id(value.sessionId) && engine(value.engine) ? { sessionId: value.sessionId, engine: value.engine } : null+}++/** Copy only metadata; no history reader or native database can cross the boundary. */+export function externalSessionFact(value: unknown): ExternalSessionFact | null {+ if (!object(value) || !id(value.sessionId) || !engine(value.engine) || !path(value.cwd)+ || !['terminal', 'editor', 'app', 'claude-app', 'codex-app'].includes(String(value.origin))+ || !text(value.title, 4096) || typeof value.mtime !== 'number' || !Number.isFinite(value.mtime) || value.mtime < 0+ || !(value.transcriptPath === null || path(value.transcriptPath))+ || !(value.aliases === undefined || strings(value.aliases, 256, 200) && value.aliases.every(id))+ || !(value.launchArgs === undefined || Array.isArray(value.launchArgs) && (value.launchArgs.length === 0+ || value.engine === 'hermes' && value.launchArgs.length === 2 && value.launchArgs[0] === '-p'+ && typeof value.launchArgs[1] === 'string' && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(value.launchArgs[1])))+ || !(value.archived === undefined || value.archived === true)) return null+ return {+ sessionId: value.sessionId, engine: value.engine, cwd: value.cwd, origin: value.origin as ExternalSessionFact['origin'],+ title: value.title, mtime: value.mtime, transcriptPath: value.transcriptPath,+ ...(value.aliases ? { aliases: [...value.aliases as string[]] } : {}),+ ...(value.launchArgs ? { launchArgs: [...value.launchArgs as string[]] } : {}),+ ...(value.archived ? { archived: true } : {}),+ }+}++export function externalSessionOwner(value: unknown): SessionOwner | null {+ if (!object(value) || !Number.isSafeInteger(value.pid) || (value.pid as number) <= 0 || (value.pid as number) > 0x7fffffff+ || !engine(value.engine) || !text(value.record, 4096) || !(value.tty === null || path(value.tty) && value.tty.startsWith('/dev/'))+ || !['harness', 'fromArgs', 'unverified'].every(key => value[key] === undefined || value[key] === true)) return null+ return { pid: value.pid as number, engine: value.engine, record: value.record, tty: value.tty,+ ...(value.harness ? { harness: true } : {}), ...(value.fromArgs ? { fromArgs: true } : {}),+ ...(value.unverified ? { unverified: true } : {}) }+}++/** A reply belongs to this exact request. Invalid/oversize/unavailable never means missing or free. */+export function externalSessionAnswer(value: unknown, request: ExternalSessionRequest): ExternalSessionAnswer {+ try {+ if (!object(value) || Buffer.byteLength(JSON.stringify(value)) > 64 * 1024) return externalUnavailable()+ if (value.ok === false) return externalUnavailable(text(value.detail, 4096) ? value.detail : undefined)+ const target = externalSessionRequest(value.request)+ if (value.ok !== true || !target || target.sessionId !== request.sessionId || target.engine !== request.engine+ || typeof value.busy !== 'boolean' || !(value.busyConfirmed === undefined || value.busyConfirmed === true && value.busy === true)+ || !(value.generation === null || text(value.generation, 200) && /^(linux|ps):\d+$/.test(value.generation))) return externalUnavailable()+ const session = value.session === null ? null : externalSessionFact(value.session)+ const owner = value.owner === null ? null : externalSessionOwner(value.owner)+ if (value.session !== null && !session || value.owner !== null && !owner+ || session && session.sessionId !== request.sessionId && !session.aliases?.includes(request.sessionId)+ || owner && (!session || owner.engine !== session.engine)+ || value.busyConfirmed && (!owner?.tty || owner.harness || owner.fromArgs || owner.unverified)+ || owner?.tty && !owner.harness && !owner.fromArgs && !owner.unverified && value.generation === null+ || !owner && (value.generation !== null || value.busy)) return externalUnavailable()+ return { ok: true, request: target, session, owner, generation: value.generation as string | null, busy: value.busy,+ ...(value.busyConfirmed ? { busyConfirmed: true } : {}) }+ } catch { return externalUnavailable() }+}diff --git a/cli/src/lib/registry.externalResume.spec.ts b/cli/src/lib/registry.externalResume.spec.tsnew file mode 100644index 000000000..b48498f26--- /dev/null+++ b/cli/src/lib/registry.externalResume.spec.ts@@ -0,0 +1,217 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import type { ExternalResumeIntent } from './externalResume.js'+import type { RegisteredSession } from './registry.js'+import { createExternalResumes } from '../core/agents/externalResume.js'+import { stopExternalOwner } from '../core/agents/externalOwner.js'+vi.mock('./bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'linux:12345678-1234-1234-1234-123456789012' }))++let root: string+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'registry-adoption-'))+ vi.stubEnv('ADAPTER_DATA_DIR', root)+ vi.stubEnv('CLAUDE_PROJECTS_DIR', root)+ writeFileSync(join(root, 'record.jsonl'), '{}\n')+ vi.spyOn(console, 'error').mockImplementation(() => {})+})+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }) })+const intent = (extra: Partial<ExternalResumeIntent> = {}): ExternalResumeIntent => ({+ token: '12345678-1234-1234-1234-123456789012', request: { engine: 'claude', sessionId: 'alias' }, takeOver: null, phase: 'waiting', ...extra,+})+const fact = () => ({ engine: 'claude' as const, sessionId: 'canonical', aliases: ['alias', 'other-alias'], cwd: root,+ origin: 'terminal' as const, title: 'Saved conversation', mtime: 1, transcriptPath: join(root, 'record.jsonl') })+async function load() { vi.resetModules(); const mod = await import('./registry.js'); mod.registry.load(); return mod.registry }+const disk = (): RegisteredSession[] => JSON.parse(readFileSync(join(root, 'registry.json'), 'utf8'))+const write = (rows: RegisteredSession[]) => writeFileSync(join(root, 'registry.json'), JSON.stringify(rows), { mode: 0o600 })+const pending = async (extra: Partial<ExternalResumeIntent> = {}) => {+ const registry = await load()+ const row = registry.openPendingAgent({ engine: 'claude', cwd: null, runtimes: [{ backend: 'tmux', paneId: '%1' }], externalResume: intent(extra) })!+ expect(row).toBeTruthy()+ return { registry, row }+}++it('persists an unbound held intent atomically, reserves all aliases and survives a reload through strict dispatch', async () => {+ let { registry, row } = await pending()+ expect(disk()).toMatchObject([{ agentId: row.agentId, active: false, sessionId: '', launch: { state: 'held' }, externalResume: intent() }])+ expect(registry.get('alias')).toBeUndefined()+ registry = await load(); row = registry.byAgent(row.agentId)!+ expect(registry.externalConflict(['alias'])).toBe(row)+ const pinned = intent({ session: fact() })+ expect(registry.setExternalResume(row.agentId, pinned)).toBeTruthy()+ for (const id of ['canonical', 'alias', 'other-alias']) {+ expect(registry.externalConflict([id])?.agentId).toBe(row.agentId)+ expect(registry.openPendingAgent({ engine: 'claude', cwd: null, runtimes: [{ backend: 'tmux', paneId: '%2' }], externalResume: intent({ request: { engine: 'claude', sessionId: id } }) })).toBeNull()+ }+ const admitted = registry.setExternalResume(row.agentId, { ...pinned, phase: 'admitted' })!+ expect(admitted).toMatchObject({ sessionId: 'canonical', cwd: root, resumeOnly: true, launch: { state: 'held' } })+ registry = await load()+ expect(registry.externalConflict(['alias'])?.agentId).toBe(row.agentId)+ expect(registry.beginExternalDispatch(row.agentId)).toMatchObject({ launch: { state: 'starting' }, externalResume: { dispatched: true } })+ expect(disk()[0]).toMatchObject({ launch: { state: 'starting' }, externalResume: { dispatched: true } })+ expect(registry.beginExternalDispatch(row.agentId)).toBeNull()+ registry = await load()+ expect(registry.byAgent(row.agentId)).toMatchObject({ sessionId: 'canonical', resumeOnly: true, externalResume: { phase: 'admitted', dispatched: true } })+})++it('refuses process discovery and hooks for an inert route, across engines too', async () => {+ const { registry, row } = await pending()+ for (const engine of ['claude', 'codex'] as const) {+ expect(registry.openProcessAgent({ engine, tmuxPane: '%1', cwd: root, processIdentity: { pid: 7001, executable: engine, startMarker: 'fixture' } })).toBeNull()+ expect(registry.register({ engine, sessionId: 'unexpected', tmuxPane: '%1', cwd: root, transcriptPath: join(root, 'record') })).toBeNull()+ }+ expect(registry.byAgent(row.agentId)).toMatchObject({ sessionId: '', processIdentity: null, launch: { state: 'held' } })+ registry.setExternalResume(row.agentId, intent({ session: fact() }))+ const other = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: root, processIdentity: { pid: 7002, executable: 'claude', startMarker: 'fixture' } })!+ expect(registry.register({ engine: 'claude', sessionId: 'canonical', tmuxPane: '%2', transcriptPath: join(root, 'record.jsonl') })?.entry.agentId).toBe(other.entry.agentId)+ expect(registry.byAgent(other.entry.agentId)?.sessionId).toBe('canonical')+ expect(disk()).toEqual(expect.arrayContaining([+ expect.objectContaining({ agentId: row.agentId, sessionId: '', externalResume: expect.objectContaining({ phase: 'waiting' }) }),+ expect.objectContaining({ agentId: other.entry.agentId, sessionId: 'canonical' }),+ ]))+ expect(registry.setExternalResume(row.agentId, intent({ session: fact(), phase: 'admitted' }))).toBeNull()+})++it('keeps a verified binding even when a provisional reservation appeared on disk after discovery', async () => {+ const { registry, row } = await pending()+ const provisional = disk()[0]+ registry.removeAgent(row.agentId)+ const other = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: root, processIdentity: { pid: 7002, executable: 'claude', startMarker: 'fixture' } })!+ write([...disk(), provisional])+ expect(registry.register({ engine: 'claude', sessionId: 'alias', tmuxPane: '%2', transcriptPath: join(root, 'record.jsonl') })?.entry.agentId).toBe(other.entry.agentId)+ expect(disk()).toHaveLength(2)+ expect(registry.byAgent(row.agentId)?.externalResume?.phase).toBe('waiting')+ expect(registry.bySession('alias')?.agentId).toBe(other.entry.agentId)+})++it('transfers an admitted canonical binding normally and releases its old aliases atomically', async () => {+ const { registry, row } = await pending()+ registry.setExternalResume(row.agentId, intent({ session: fact(), phase: 'admitted' }))+ const original = { pid: 7001, executable: 'claude', startMarker: 'fixture' }+ registry.updateProcessIdentity(row.agentId, original)+ registry.setActive(row.agentId, true)+ expect(registry.register({ engine: 'claude', sessionId: 'canonical', tmuxPane: '%1', transcriptPath: join(root, 'record.jsonl'), processIdentity: original })).toBeTruthy()+ const other = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: root, processIdentity: { pid: 7002, executable: 'claude', startMarker: 'fixture' } })!+ expect(registry.register({ engine: 'claude', sessionId: 'canonical', tmuxPane: '%2', transcriptPath: join(root, 'record.jsonl') })?.entry.agentId).toBe(other.entry.agentId)+ expect(registry.byAgent(row.agentId)?.externalResume).toBeUndefined()+ expect(registry.externalConflict(['alias'])).toBeUndefined()+ const reboot = await load()+ expect(reboot.bySession('canonical')?.agentId).toBe(other.entry.agentId)+ expect(reboot.byAgent(row.agentId)?.externalResume).toBeUndefined()+})++it('never revives a cancelled intent, changes its request or escalates its takeover consent', async () => {+ const { registry, row } = await pending()+ expect(registry.setExternalResume(row.agentId, intent({ takeOver: 'now' }))).toBeNull()+ expect(registry.setExternalResume(row.agentId, intent({ request: { engine: 'claude', sessionId: 'different' } }))).toBeNull()+ expect(registry.setExternalResume(row.agentId, intent({ phase: 'cancelled' }))).toBeTruthy()+ expect(registry.setExternalResume(row.agentId, intent())).toBeNull()+ expect(registry.externalConflict(['alias'])).toBeUndefined()+ const reboot = await load()+ expect(reboot.byAgent(row.agentId)?.externalResume?.phase).toBe('cancelled')+ expect(reboot.finishExternalCancellation(row.agentId)).toBe(true)+ expect(disk()).toEqual([])+ expect(reboot.finishExternalCancellation(row.agentId)).toBe(false)+})++it.each(['waiting', 'quitting', 'prepared', 'sent', 'admitted'] as const)('refuses an alias claimed on disk before %s, leaving both durable owners untouched', async phase => {+ const { registry, row } = await pending({ takeOver: 'idle' })+ const pinned = intent({ takeOver: 'idle', session: fact(), owner: { process: { engine: 'claude', pid: 101, tty: '/dev/fixture-terminal', record: '/fixture/record' }, generation: 'ps:1' } })+ const previous = disk()[0]+ const foreign = { ...previous, agentId: 'foreign-owner', externalResume: undefined, sessionId: 'canonical', boundAt: 1,+ runtimes: [{ backend: 'tmux' as const, paneId: '%2' }], primaryRuntimeKey: 'tmux\u0000%2', tmuxPane: '%2', launch: { state: 'ready' as const }, active: true }+ write([previous, foreign])+ const before = readFileSync(join(root, 'registry.json'), 'utf8')+ expect(() => registry.setExternalResume(row.agentId, { ...pinned, phase: phase === 'prepared' || phase === 'sent' ? 'quitting' : phase,+ ...(phase === 'prepared' || phase === 'sent' ? { signal: phase } : {}) })).toThrow('another durable owner')+ expect(readFileSync(join(root, 'registry.json'), 'utf8')).toBe(before)+ expect(registry.byAgent(row.agentId)).toMatchObject({ sessionId: '', externalResume: { phase: 'waiting' } })+})++it('never overwrites a concurrent durable cancellation or commits dispatch against a changed row', async () => {+ const { registry, row } = await pending()+ const previous = disk()[0]+ write([{ ...previous, externalResume: intent({ phase: 'cancelled' }) }])+ expect(() => registry.setExternalResume(row.agentId, intent({ session: fact(), phase: 'admitted' }))).toThrow('durable adoption changed')+ expect(disk()[0].externalResume?.phase).toBe('cancelled')+ const next = await load()+ expect(next.finishExternalCancellation(row.agentId)).toBe(true)+})++it('refuses KILL when another writer durably binds the conversation during the TERM grace period', async () => {+ const { registry, row } = await pending({ takeOver: 'idle' })+ const owner = { engine: 'claude' as const, pid: 101, tty: '/dev/fixture-terminal', record: '/fixture/record' }+ const kill = vi.fn(), launch = vi.fn()+ let written = false+ const controller = createExternalResumes({ registry, tmux: null, stopped: () => [], cancelled: () => false,+ generation: () => 1, waiting: async () => true, preflight: async () => null, announce: () => {}, forget: () => {}, launch,+ inspect: async request => ({ ok: true, request, session: fact(), owner, generation: 'ps:1', busy: false }),+ stopOwner: (target, control) => stopExternalOwner(target, { ...control, exists: () => true, generation: () => 'ps:1',+ job: async () => null, kill, sleep: async () => {+ if (written) return+ written = true+ const saved = disk()+ write([...saved, { ...saved[0], agentId: 'foreign-owner', externalResume: undefined, sessionId: 'canonical', boundAt: 1,+ runtimes: [{ backend: 'tmux', paneId: '%2' }], primaryRuntimeKey: 'tmux\u0000%2', tmuxPane: '%2', launch: { state: 'ready' }, active: true }])+ } }),+ })+ try {+ controller.open(); await controller.settled()+ expect(written).toBe(true)+ expect(kill.mock.calls).toEqual([[101, 'SIGTERM']])+ expect(launch).not.toHaveBeenCalled()+ expect(registry.byAgent(row.agentId)?.externalResume?.phase).toBe('quitting')+ expect(disk().find(value => value.agentId === 'foreign-owner')?.sessionId).toBe('canonical')+ } finally { controller.stop() }+})++it('rolls back strict persistence failures before acknowledging admission, dispatch or cleanup', async () => {+ const { registry, row } = await pending()+ const old = disk()+ writeFileSync(join(root, 'registry.json'), '{unreadable', { mode: 0o600 })+ expect(() => registry.setExternalResume(row.agentId, intent({ phase: 'admitted', session: fact() }))).toThrow()+ expect(registry.byAgent(row.agentId)?.externalResume?.phase).toBe('waiting')+ write(old)+ registry.setExternalResume(row.agentId, intent({ phase: 'admitted', session: fact() }))+ const admitted = disk()+ writeFileSync(join(root, 'registry.json'), '{unreadable', { mode: 0o600 })+ expect(() => registry.beginExternalDispatch(row.agentId)).toThrow()+ expect(registry.byAgent(row.agentId)).toMatchObject({ launch: { state: 'held' }, active: false, externalResume: { phase: 'admitted' } })+ expect(registry.byAgent(row.agentId)?.externalResume?.dispatched).toBeUndefined()+ write(admitted)+ const reloaded = await load()+ expect(reloaded.setExternalResume(row.agentId, intent({ phase: 'cancelled' }))).toBeNull()+ // A separate unadmitted intent has a durable cleanup boundary too.+ const other = reloaded.openPendingAgent({ engine: 'claude', cwd: null, runtimes: [{ backend: 'tmux', paneId: '%2' }], externalResume: intent({ request: { engine: 'claude', sessionId: 'second' } }) })!+ reloaded.setExternalResume(other.agentId, { ...other.externalResume!, phase: 'cancelled' })+ writeFileSync(join(root, 'registry.json'), '{unreadable', { mode: 0o600 })+ expect(() => reloaded.finishExternalCancellation(other.agentId)).toThrow()+ expect(reloaded.byAgent(other.agentId)?.externalResume?.phase).toBe('cancelled')+ expect(reloaded.openPendingAgent({ engine: 'claude', cwd: null, runtimes: [{ backend: 'tmux', paneId: '%3' }], externalResume: intent({ request: { engine: 'claude', sessionId: 'third' } }) })).toBeNull()+ expect(reloaded.byPaneEngine('%3', 'claude')).toBeUndefined()+})++it('blocks malformed persisted adoption instead of silently loading a fresh launch', async () => {+ const { row } = await pending()+ for (const change of [{ externalResume: { ...intent(), session: { nonsense: true } } }, { sessionId: 'unexpected' }, { launch: { state: 'ready' } }]) {+ write([{ ...row, ...change } as RegisteredSession])+ const before = readFileSync(join(root, 'registry.json'), 'utf8')+ const registry = await load()+ expect(registry.list()).toEqual([])+ expect(registry.openPendingAgent({ engine: 'claude', cwd: null, runtimes: [{ backend: 'tmux', paneId: '%2' }] })).toBeNull()+ expect(readFileSync(join(root, 'registry.json'), 'utf8')).toBe(before)+ }+})++it('drops adoption constraints when its engine becomes a terminal', async () => {+ const { registry, row } = await pending()+ registry.setExternalResume(row.agentId, intent({ session: fact(), phase: 'admitted' }))+ const shell = registry.releaseEngine(row.agentId)!+ expect(shell.engine).toBe('terminal')+ expect(shell.externalResume).toBeUndefined()+ expect(shell.resumeOnly).toBeUndefined()+ const reboot = await load()+ expect(reboot.byAgent(row.agentId)?.engine).toBe('terminal')+ expect(reboot.externalConflict(['alias'])).toBeUndefined()+})diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 04388aa22..4e34557ae 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -56,6 +56,7 @@ import { lockOwnerAlive, lockStartMarker, processLockIdentity } from './processLimport { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'import { mergeTerminalRuntimes, processIdentityKey, sameProcessIdentity, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'+import { externalReservations, externalResumePending, externalResumeIds, parseExternalResume, type ExternalResumeIntent } from './externalResume.js'export type { ProcessIdentity } from './terminalTypes.js'@@ -91,6 +92,8 @@ export interface RegisteredSession {launch?: AgentLaunch/** Enter on stopped work must never become a fresh conversation, including after a daemon restart. */resumeOnly?: true+ /** External admission survives a crash independently of any conversation Harness already owns. */+ externalResume?: ExternalResumeIntent/*** THE AGENT. Public identity: this is what web tabs, device tiles and every inbound frame address.*@@ -562,8 +565,11 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {const active = row.active === trueconst projectedTmuxPane = tmuxProjection(runtimes)const launch = normalizedLaunch(row.launch)+ const externalResume = row.externalResume === undefined ? undefined : parseExternalResume(row.externalResume)if (row.schemaVersion !== 2|| typeof row.active !== 'boolean'+ || externalResume === null || externalResume && externalResume.request.engine !== row.engine+ || externalResume && externalResumePending(externalResume) && (row.sessionId !== '' || row.processIdentity !== null || launch?.state !== 'held')|| typeof row.agentId !== 'string' || !row.agentId|| typeof row.sessionId !== 'string'|| typeof row.engine !== 'string' || !AGENT_ENGINES.has(row.engine as AgentEngine)@@ -581,12 +587,13 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {// Taken out of the spread and put back only when it is a real moment: the spread would otherwise// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.- const { lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, ...rest } = row+ const { lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, ...rest } = rowconst lastOpenedAt = normalizedOpenedAt(rawOpenedAt)// Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.const scmLaunch = parseScmLaunchRecord(rawScmLaunch)return {...rest,+ ...(externalResume ? { externalResume } : {}),...(scmLaunch ? { scmLaunch } : {}),...(normalizedClosePlan(rawClosePlan) ? { closePlan: normalizedClosePlan(rawClosePlan)! } : {}),schemaVersion: 2,@@ -689,15 +696,19 @@ function validatedRows(values: readonly unknown[]): RegisteredSession[] | null {const rows: RegisteredSession[] = []const agents = new Set<string>()const sessions = new Set<string>()+ const provisionalSessions = new Set<string>()const processes = new Set<string>()const routes = new Set<string>()for (const value of values) {const row = strictPersistedRow(value)if (!row || agents.has(row.agentId)) return nullagents.add(row.agentId)- if (row.sessionId) {- if (sessions.has(row.sessionId)) return null- sessions.add(row.sessionId)+ // A waiting adoption is an intention, not ownership. A real hook may bind while search is+ // unavailable; that fact holds the intention without surrendering the process's binding.+ const claimed = externalResumePending(row.externalResume) ? provisionalSessions : sessions+ for (const id of new Set(externalReservations(row))) {+ if (claimed.has(id)) return null+ claimed.add(id)}if (row.processIdentity) {const key = processIdentityKey(row.engine, row.processIdentity)@@ -1108,7 +1119,8 @@ class Registry {}const { rows: parsed, dropped, changed: strippedRetired } = withoutRetiredRows(stored)if (dropped) console.log(`[registry] dropped ${dropped} agent(s) that lived only in a retired Herdr terminal`)- if (parsed.some(hasUnknownRowSchema)) {+ if (parsed.some(hasUnknownRowSchema) || parsed.some(value => !!value && typeof value === 'object'+ && Object.hasOwn(value, 'externalResume') && !strictPersistedRow(value))) {this.writeBlocked = trueconsole.error('[registry] registry contains an unknown row schema; refusing to overwrite it')return@@ -1208,6 +1220,7 @@ class Registry {active,...(launch ? { launch } : {}),...(raw.resumeOnly === true ? { resumeOnly: true } : {}),+ ...(raw.externalResume ? { externalResume: parseExternalResume(raw.externalResume)! } : {}),agentId,boundAt: bound ? (typeof raw.boundAt === 'number' ? raw.boundAt : (raw.registeredAt ?? now)) : null,engine,@@ -1370,6 +1383,7 @@ class Registry {const { engine, processIdentity } = inputconst runtimes = normalizedRuntimes(input.runtimes, input.tmuxPane)if (!runtimes.length || !validProcessIdentity(processIdentity)) return null+ if (runtimes.some(runtime => externalResumePending(this.agents.get(this.runtimeIndex.get(terminalRouteKey(runtime)) ?? '')?.externalResume))) return nullconst processAgentId = this.processIndex.get(processIdentityKey(engine, processIdentity))const processAgent = processAgentId ? this.agents.get(processAgentId) : undefinedconst routeAgent = runtimes@@ -1505,8 +1519,12 @@ class Registry {label?: string | null/** The agent this one is a fork of — see RegisteredSession.forkedFrom. */forkedFrom?: ForkOrigin | null+ externalResume?: ExternalResumeIntent}): RegisteredSession | null {if (this.writeBlocked) return null+ const externalResume = input.externalResume === undefined ? undefined : parseExternalResume(input.externalResume)+ if (externalResume === null || externalResume && (externalResume.phase !== 'waiting' || externalResume.request.engine !== input.engine+ || this.externalConflict(externalResumeIds(externalResume)))) return nullconst runtimes = normalizedRuntimes(input.runtimes)if (!runtimes.length) return nullif (runtimes.some((runtime) => this.runtimeIndex.has(terminalRouteKey(runtime)))) return null@@ -1514,8 +1532,9 @@ class Registry {const agentId = randomUUID()const entry: RegisteredSession = {schemaVersion: 2,- active: true,- launch: { state: 'starting' },+ active: !externalResume,+ launch: externalResume ? { state: 'held', service: 'search', detail: 'Waiting for the search service to verify this conversation.' } : { state: 'starting' },+ ...(externalResume ? { externalResume } : {}),defaultName: normalizedDefaultName(input.defaultName) ?? this.automaticName(input.label?.trim() || engineLabel(input.engine), new Date(now)),agentId,sessionId: '',@@ -1555,8 +1574,12 @@ class Registry {}this.index(entry)this.terminalAvailableAgents.add(entry.agentId)- this.save()- return entry+ try { this.save(!!externalResume, false, externalResume ? agentId : undefined) } catch {+ this.drop(entry)+ this.terminalAvailableAgents.delete(entry.agentId)+ return null+ }+ return this.byAgent(entry.agentId) ?? null}/** A stopped agent gets a new terminal route while keeping its saved conversation and identity.@@ -1655,6 +1678,11 @@ class Registry {.map((agent) => this.adoptEngine(agent.agentId, engine, validProcessIdentity(input.processIdentity) ? input.processIdentity : null)).find((agent): agent is RegisteredSession => !!agent))const agentId = processAgent?.agentId ?? ''+ // An inert adoption pane cannot bind a hook before core has admitted its external conversation.+ if (processAgent?.externalResume && processAgent.externalResume.phase !== 'admitted') return null+ const admittedAlias = this.list().find(row => row.agentId !== agentId && row.externalResume?.phase === 'admitted'+ && row.sessionId !== sessionId && externalReservations(row).includes(sessionId))+ if (admittedAlias) return nullif (!sessionId|| !agentId@@ -1709,6 +1737,9 @@ class Registry {console.log(`[registry] session ${sessionId.slice(0, 8)} moved from agent ${stolenFrom.agentId.slice(0, 8)} to ${agentId.slice(0, 8)}`)const wasDormant = !stolenFrom.activethis.releaseBinding(stolenFrom)+ // The verified canonical conversation moved. Its old row no longer owns the admission or+ // its aliases, and cannot later replay that resume as though it still owned the conversation.+ if (stolenFrom.externalResume) { delete stolenFrom.externalResume; delete stolenFrom.resumeOnly }if (wasDormant) {orphaned = { agentId: stolenFrom.agentId, sessionId }this.drop(stolenFrom)@@ -1812,6 +1843,8 @@ class Registry {...(existing?.bypassPermission ? { bypassPermission: true } : {}),...(existing?.permissionMode ? { permissionMode: existing.permissionMode } : {}),...(existing?.resumeOnly ? { resumeOnly: true, launch: { state: 'ready' as const } } : {}),+ // Keep alias reservations and profile arguments across the first hook and daemon restart.+ ...(existing?.externalResume && existing.engine === engine ? { externalResume: existing.externalResume } : {}),...(existing?.terminalHost ? { terminalHost: true } : {}),processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,registeredAt: existing?.registeredAt ?? now,@@ -1952,6 +1985,7 @@ class Registry {const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, dshRuntime: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : originalthis.releaseBinding(entry)delete entry.resumeOnly+ delete entry.externalResumeentry.engine = 'terminal'entry.terminalHost = trueentry.processIdentity = null@@ -2025,6 +2059,61 @@ class Registry {return entry}+ /** A canonical conversation and every alias have one core owner, including pending adoptions. */+ externalConflict(ids: readonly string[], except?: string): RegisteredSession | undefined {+ const sought = new Set(ids)+ return this.list().find(row => row.agentId !== except &&+ externalReservations(row).some(id => sought.has(id)))+ }++ /** No await between the reservation, ownership transition and durable save. */+ setExternalResume(agentId: string, value: ExternalResumeIntent): RegisteredSession | null {+ if (this.writeBlocked) return null+ const row = this.byAgent(agentId), intent = parseExternalResume(value)+ if (!row?.externalResume || !intent || row.externalResume.token !== intent.token || row.engine !== intent.request.engine+ || row.externalResume.request.sessionId !== intent.request.sessionId || row.externalResume.takeOver !== intent.takeOver+ || this.externalConflict(externalResumeIds(intent), agentId)) return null+ if (row.externalResume.phase === 'cancelled' && intent.phase !== 'cancelled'+ || row.externalResume.phase === 'admitted' && intent.phase !== 'admitted') return null+ const next: RegisteredSession = { ...row, externalResume: intent }+ if (intent.phase === 'admitted') {+ const session = intent.session!+ Object.assign(next, { sessionId: session.sessionId, cwd: session.cwd, title: session.title || row.title,+ transcriptPath: session.transcriptPath, resumeOnly: true })+ }+ this.drop(row)+ this.index(next)+ try { this.save(true, false, agentId) } catch (error) {+ this.drop(next)+ this.index(row)+ throw error+ }+ return this.byAgent(agentId) ?? null+ }++ /** A cancelled external intent has no owned conversation to archive. Its deletion must be durable. */+ finishExternalCancellation(agentId: string): boolean {+ const row = this.byAgent(agentId)+ if (row?.externalResume?.phase !== 'cancelled') return false+ const available = this.terminalAvailable(agentId)+ this.drop(row); this.terminalAvailableAgents.delete(agentId)+ try { this.save(true, false, agentId) } catch (error) {+ this.index(row); if (available) this.terminalAvailableAgents.add(agentId)+ throw error+ }+ return true+ }++ /** A launch dispatch is durable before tmux may replace the inert shell. */+ beginExternalDispatch(agentId: string): RegisteredSession | null {+ const row = this.byAgent(agentId)+ if (row?.externalResume?.phase !== 'admitted' || row.launch?.state !== 'held') return null+ const prior = row.launch, active = row.active, intent = row.externalResume+ row.launch = { state: 'starting' }; row.active = true; row.externalResume = { ...intent, dispatched: true }+ try { this.save(true, false, agentId) } catch (error) { row.launch = prior; row.active = active; row.externalResume = intent; throw error }+ return row+ }+setClosePlan(agentId: string, plan: RegisteredSession['closePlan'] | null): RegisteredSession | null {const entry = this.agents.get(agentId)if (!entry) return null@@ -2332,7 +2421,7 @@ class Registry {this.saveNames()}- private save(strict = false, exiting = false): void {+ private save(strict = false, exiting = false, externalAgentId?: string): void {if (this.transactionDepth > 0 && !exiting) {if (strict) throw new Error('Cannot acknowledge a close intent inside an uncommitted registry transaction')this.savePending = true@@ -2369,7 +2458,8 @@ class Registry {const stored = JSON.parse(readPrivateStateFile(FILE)) as unknownif (!Array.isArray(stored)) throw new Error('registry root changed to a non-array value')const parsed = withoutRetiredRows(stored).rows- if (parsed.some(hasUnknownRowSchema)) {+ if (parsed.some(hasUnknownRowSchema) || parsed.some(value => !!value && typeof value === 'object'+ && Object.hasOwn(value, 'externalResume') && !strictPersistedRow(value))) {throw new Error('registry contains an unknown row schema')}const legacyRows = parsed.filter((row) => !row || typeof row !== 'object' || !Object.hasOwn(row, 'schemaVersion'))@@ -2387,6 +2477,26 @@ class Registry {if (id) latest.set(id, value as Record<string, unknown>)}+ if (externalAgentId && (latest.has(externalAgentId) ? rowFingerprint(latest.get(externalAgentId)) : undefined)+ !== this.persistedBaseline.get(externalAgentId)) {+ throw new Error('The durable adoption changed while it was being prepared')+ }+ // Adoption never uses the normal winner/eviction policy. A daemon-down hook may have+ // claimed its conversation since the core's last read; refuse admission inside this lock.+ for (const [id, value] of currentRows) {+ const intent = parseExternalResume(value.externalResume)+ // Every strict admission/signal/dispatch transition earns permission here. Ordinary+ // observations may persist a held provisional overlap; they never authorize a signal.+ if (id !== externalAgentId || !intent || intent.phase === 'cancelled') continue+ const claims = new Set(externalReservations(value as unknown as RegisteredSession))+ for (const [otherId, otherValue] of latest) {+ if (otherId === id) continue+ const other = strictPersistedRow(otherValue)+ if (other && externalReservations(other).some(claim => claims.has(claim))) {+ throw new Error('The external conversation has another durable owner')+ }+ }+ }const merged = mergedForSave(latest, currentRows, this.persistedBaseline, this.intended)const rows = validatedRows([...merged.values()])if (!rows) throw new Error('registry transaction would violate global identity invariants')diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.tsindex 4c8aef32d..a4c476cdf 100644--- a/cli/src/lib/restartAgent.spec.ts+++ b/cli/src/lib/restartAgent.spec.ts@@ -148,6 +148,15 @@ describe('restartAgent', () => {expect(d.calls.filter((c) => c === 'terminate')).toHaveLength(1)})+ it('keeps a strict imported conversation bound when its resume cannot be verified', async () => {+ const buildArgv = vi.fn(() => ['claude', '--resume', 'imported'])+ const d = deps({ buildArgv, waitForProcess: async () => null })+ expect(await restartAgent({ engine: 'claude', sessionId: 'imported', resumeOnly: true }, false, d)).toMatchObject({ ok: false })+ expect(buildArgv).toHaveBeenCalledExactlyOnceWith({ bypassPermission: false, resumeSessionId: 'imported' })+ expect(d.calls.filter(call => call === 'respawn')).toHaveLength(1)+ expect(d.calls).not.toContain('keepAbandoned')+ })+it('fails outright when even the fresh fallback relaunch never comes up', async () => {const d = deps({ waitForProcess: async () => null })const outcome = await restartAgent({ engine: 'codex', sessionId: 'sess-1' }, false, d)diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.tsindex 834477d62..ec58d473c 100644--- a/cli/src/lib/restartAgent.ts+++ b/cli/src/lib/restartAgent.ts@@ -113,7 +113,7 @@ export interface RestartAgentDeps {const KILL_CONFIRMED: ReadonlySet<TerminateOutcome> = new Set(['gone', 'terminated', 'killed'])export async function restartAgent(- session: { engine: AgentEngine; sessionId: string },+ session: { engine: AgentEngine; sessionId: string; resumeOnly?: true },bypassPermission: boolean,deps: RestartAgentDeps,): Promise<RestartOutcome> {@@ -165,7 +165,7 @@ export async function restartAgent(let resumed = !!resumeSessionIdlet identity = await spawnAndWait(resumed)if (!current()) return changed- if (!identity && resumed) {+ if (!identity && resumed && !session.resumeOnly) {// Safe degradation: a working agent with a FRESH session under the same agentId/pane beats a dead// pane. Retry once with no resume attempt before giving up entirely.deps.log(`[restart] ${session.engine} did not come back up resuming its session — retrying fresh`)diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.tsindex a6527047e..f5b51f6cd 100644--- a/cli/src/lib/restoreAgents.spec.ts+++ b/cli/src/lib/restoreAgents.spec.ts@@ -1217,3 +1217,98 @@ describe('missing held panes against the durable registry', () => {expect(h.respawns).toBe(0)})})++describe('external adoption crash boundaries', () => {+ const imported = (phase: 'waiting' | 'admitted' | 'cancelled', starting = false) => row({+ sessionId: phase === 'admitted' ? 'imported-session' : '', resumeOnly: phase === 'admitted' ? true : undefined,+ externalResume: { token: '12345678-1234-1234-1234-123456789012', request: { engine: 'claude', sessionId: 'imported-session' },+ takeOver: null, phase, ...(phase === 'admitted' ? { session: { sessionId: 'imported-session', engine: 'claude', cwd: '/fixture',+ origin: 'terminal', title: '', mtime: 1, transcriptPath: '/fixture/record' }, ...(starting ? { dispatched: true } : {}) } : {}) },+ launch: starting ? { state: 'starting' } : heldLaunch('search'),+ })+ function dispatch(h: Harness) {+ h.deps.registry.beginExternalDispatch = id => {+ const row = h.rows.get(id)!+ expect(row.launch?.state).toBe('held')+ h.calls.push('journal:dispatch')+ row.launch = { state: 'starting' }; row.externalResume = { ...row.externalResume!, dispatched: true }+ return row+ }+ }++ it('never recreates a durably cancelled waiting pane, even when tmux is gone', async () => {+ const h = harness([imported('cancelled')])+ expect((await restoreAgents(h.deps)).skipped).toContainEqual({ agentId: 'agent-a', reason: 'external adoption cancelled' })+ expect(h.paneCreates).toBe(0); expect(h.respawns).toBe(0)+ })++ it('journals before dispatch, and recovers a crash before tmux by recognizing its exact waiting shell', async () => {+ for (const starting of [false, true]) {+ const h = harness([imported('admitted', starting)], { alivePanes: ['%3'] })+ dispatch(h)+ h.deps.waitingPane = vi.fn(async () => true)+ h.deps.respawn = vi.fn(async (_pane, launch, control) => {+ expect(control?.expectedHeldToken).toBe(h.rows.get('agent-a')?.externalResume?.token)+ control?.onDispatch?.()+ expect(h.rows.get('agent-a')).toMatchObject({ launch: { state: 'starting' }, externalResume: { dispatched: true } })+ expect(control?.current?.()).toBe(true)+ expect(launch.argv).toContain('imported-session')+ return { ok: true }+ })+ h.probes.set('%3', [identity(9)])+ expect((await restoreAgents(h.deps)).restored).toEqual(['agent-a'])+ await settled(h, 1, 1)+ expect(h.deps.respawn).toHaveBeenCalledOnce()+ }+ })++ it('observes a dispatch that may have run before the crash instead of replaying over it', async () => {+ for (const known of [false, 'unknown'] as const) {+ const h = harness([imported('admitted', true)], { alivePanes: ['%3'] })+ h.deps.waitingPane = async () => known+ h.probes.set('%3', [identity(10)])+ const summary = await restoreAgents(h.deps)+ expect(summary.restored).toEqual([])+ await settled(h, 1, 1)+ expect(h.paneCreates).toBe(0); expect(h.respawns).toBe(0)+ expect(h.rows.get('agent-a')?.processIdentity?.pid).toBe(10)+ }+ })++ it('retries a failed strict journal without dispatch, and retries an uncertain dispatch only with inert-pane proof', async () => {+ for (const failure of ['journal', 'before-tmux', 'after-tmux'] as const) {+ const h = harness([imported('admitted')], { alivePanes: ['%3'] })+ dispatch(h)+ if (failure === 'journal') h.deps.registry.beginExternalDispatch = () => { throw new Error('disk full') }+ h.deps.waitingPane = async () => failure === 'before-tmux'+ const executed = vi.fn()+ h.deps.respawn = async (_pane, _launch, control) => {+ control?.onDispatch?.(); executed(); return { ok: false, reason: 'lost tmux reply' }+ }+ h.probes.set('%3', [identity(11)])+ const summary = await restoreAgents(h.deps)+ if (failure === 'after-tmux') {+ await settled(h, 1, 1)+ expect(summary.retry).toBeUndefined()+ expect(h.rows.get('agent-a')?.processIdentity?.pid).toBe(11)+ } else {+ expect(summary.retry).toBe(true)+ expect(h.rows.get('agent-a')?.launch?.state).toBe('held')+ if (failure === 'journal') expect(executed).not.toHaveBeenCalled()+ }+ }+ })++ it('resumes a committed external conversation after tmux loss, retaining strict identity without search or a fresh fallback', async () => {+ const h = harness([imported('admitted', true)])+ dispatch(h)+ h.deps.retainStopped = vi.fn()+ h.deps.waitingLaunch = () => ({ argv: ['waiting-shell'] })+ h.states.set('%0', [{ dead: true }])+ expect((await restoreAgents(h.deps)).restored).toEqual(['agent-a'])+ await settled(h, 1)+ expect(h.deps.retainStopped).not.toHaveBeenCalled()+ expect(h.launches).toEqual([{ agentId: 'agent-a', resumeSessionId: 'imported-session' }])+ expect(h.rows.get('agent-a')).toMatchObject({ sessionId: 'imported-session', launch: { state: 'failed', error: 'RESUME_FAILED' } })+ })+})diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.tsindex a8272348c..f1f269154 100644--- a/cli/src/lib/restoreAgents.ts+++ b/cli/src/lib/restoreAgents.ts@@ -80,6 +80,7 @@ export interface RestoreAgentsDeps {clearProcessIdentity(agentId: string): booleanupdateRuntimes(agentId: string, runtimes: readonly TerminalRuntimeRef[], primaryRuntimeKey?: string): booleansetLaunch(agentId: string, launch: AgentLaunch): RegisteredSession | null+ beginExternalDispatch?(agentId: string): RegisteredSession | nullupdateProcessIdentity(agentId: string, processIdentity: ProcessIdentity): booleanunbindSession(sessionId: string): booleaninheritName(fromSessionId: string, toSessionId: string): void@@ -93,6 +94,7 @@ export interface RestoreAgentsDeps {* without tmux inventory (tests) treats a pane with no engine process as gone. `'unknown'` when the* inventory could not be read.*/+ waitingPane?: (runtime: TmuxRuntimeRef, token: string) => Promise<boolean | 'unknown'>livePane?: (runtime: TmuxRuntimeRef) => Promise<boolean | 'unknown'>/** The engine process still running in this row's pane, or null when tmux does not know the pane* at all — including when no tmux server is running — or the pane has become something else.@@ -218,7 +220,7 @@ function tmuxRuntime(entry: RegisteredSession): TmuxRuntimeRef | null {function restoreOwner(deps: RestoreAgentsDeps, entry: RegisteredSession, committing = false): () => boolean {const identity = (row: RegisteredSession | undefined) => row && JSON.stringify([row.registeredAt, row.boundAt, row.sessionId, row.engine, row.cwd, row.dsh, row.dshRuntime,- row.runtimes.map(terminalRouteKey).sort(), row.launch,+ row.runtimes.map(terminalRouteKey).sort(), row.launch, row.externalResume,])const owned = identity(entry)const revision = deps.revision?.(entry.agentId)@@ -387,6 +389,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu}try {const runtime = tmuxRuntime(entry)+ if (entry.externalResume?.phase === 'cancelled') { summary.skipped.push({ agentId: entry.agentId, reason: 'external adoption cancelled' }); continue }if (!runtime) { summary.skipped.push({ agentId: entry.agentId, reason: 'no tmux pane' }); continue }if (entry.launch?.state === 'failed') { summary.skipped.push({ agentId: entry.agentId, reason: 'last launch failed' }); continue }// Held: its pane, alive, runs no engine on purpose, so it is neither a stopped engine nor a terminal. Its@@ -411,6 +414,20 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu// clock misread; a tmux server that outlived the daemon) is re-identified right here, so the// reconciler adopts it by process instead of treating it as an unbound route.if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)+ } else if (entry.externalResume?.phase === 'admitted' && entry.launch?.state === 'starting') {+ // The dispatch journal precedes tmux. If its exact waiting shell remains, no engine ran;+ // otherwise an installer/engine may still be starting: observe it, never respawn over it.+ const waiting = await deps.waitingPane?.(runtime, entry.externalResume.token)+ if (!current()) continue+ if (waiting === true) {+ const row = deps.registry.setLaunch(entry.agentId, { state: 'held', service: 'search', detail: 'Restoring this conversation.' })!+ const copy = { ...row }+ missing.push({ entry: copy, runtime, alive: true, current: restoreOwner(deps, copy) })+ } else {+ const route = terminalRouteKey(runtime)+ const release = deps.holdRoute(route, (deps.budgetMs ?? DEFAULT_BUDGET_MS) + HOLD_SLACK_MS) ?? (() => deps.releaseRoute(route))+ void watchRestoredPane(deps, entry, runtime, true, deps.budgetMs ?? DEFAULT_BUDGET_MS, current, release)+ }} else if (!isTerminalEngine(entry.engine)) {if (deps.retainStopped) deps.retainStopped(entry, true)else deps.registry.releaseEngine(entry.agentId)@@ -426,7 +443,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu// (`relaunchFresh` refuses it for a resume-only row). Measured: a harness opened from the// catalog, then `harness stop` + `tmux kill-server` + app relaunch — every other tile came// back, this one sat on "no verified terminal pane" with nothing to press.- if (entry.resumeOnly && entry.launch?.state !== 'ready' && deps.retainStopped) {+ if (entry.resumeOnly && !entry.externalResume && entry.launch?.state !== 'ready' && deps.retainStopped) {deps.retainStopped(entry, false)summary.skipped.push({ agentId: entry.agentId, reason: 'saved conversation awaits explicit Open' })continue@@ -503,7 +520,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu} else if (entry.launch?.state === 'held' && entry.launch.detail !== launch.detail && deps.waitingLaunch) {// A grid harness can finish waiting for models and then wait for Store preparation. Its pane// must show the current reason as well as its row, including an unconfirmed workspace write.- await deps.respawn(pane, deps.waitingLaunch(entry, launch), { current })+ await deps.respawn(pane, deps.waitingLaunch(entry, launch), { current, ...(entry.externalResume ? { expectedHeldToken: entry.externalResume.token } : {}) })if (!owns()) return false}deps.registry.setLaunch(entry.agentId, launch)@@ -550,7 +567,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSucontinue}await inPane(deps, entry, current, async initialOwner => {- const owns = initialOwner+ let owns = initialOwnerconst pane = deadconst existing = !!aliveconst dispatchCurrent = () => owns() && !deps.cancelled?.(entry.agentId)@@ -562,17 +579,41 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu}let watching = falsetry {- const control = { current: dispatchCurrent, onDispatch: () => {+ const control = { current: dispatchCurrent, ...(entry.externalResume ? { expectedHeldToken: entry.externalResume.token } : {}), onDispatch: () => {+ if (entry.externalResume?.phase === 'admitted') {+ const committed = deps.registry.beginExternalDispatch?.(entry.agentId)+ if (!committed) throw new Error('External resume dispatch could not be committed')+ owns = restoreOwner(deps, committed, !!deps.paneOperation)+ }// Before the engine can hook/attach, not after tmux's asynchronous reply.if (resumeSessionId) deps.engineStarted?.(resumeSessionId)} }- const created = existing- ? await deps.respawn(pane, launch, control).then(spawned => spawned.ok+ const created = await (existing+ ? deps.respawn(pane, launch, control).then(spawned => spawned.ok? { ok: true as const, runtime: pane } : { ok: false as const, reason: spawned.reason ?? 'the pane could not be reused' })- : await deps.createPane(entry, launch, control)+ : deps.createPane(entry, launch, control)).catch(error => ({ ok: false as const, reason: String(error) }))if (!owns()) returnif (!created.ok) {if (!dispatchCurrent()) return+ if (entry.externalResume) {+ const row = deps.registry.byAgent(entry.agentId)!+ if (row.launch?.state === 'held') summary.retry = true+ else {+ // A journaled dispatch can fail before or after tmux received it. Retry only while+ // its exact inert shell proves that no engine ran; otherwise observe the launch.+ const waiting = await deps.waitingPane?.(pane, entry.externalResume.token)+ if (!dispatchCurrent()) return+ if (waiting === true) {+ deps.registry.setLaunch(entry.agentId, { state: 'held', service: 'search', detail: 'Waiting to restore this conversation’s terminal.' })+ summary.retry = true+ } else {+ const currentWatch = restoreOwner(deps, deps.registry.byAgent(entry.agentId)!)+ const releaseWatch = release!+ watching = true+ watches.push(() => watchRestoredPane(deps, entry, pane, true, budgetMs, currentWatch, releaseWatch))+ }+ }+ }summary.failed.push({ agentId: entry.agentId, reason: created.reason })deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · could not open a pane · ${created.reason}`)returndiff --git a/cli/src/lib/sessionSearch/evidence.spec.ts b/cli/src/lib/sessionSearch/evidence.spec.tsnew file mode 100644index 000000000..07135fdc9--- /dev/null+++ b/cli/src/lib/sessionSearch/evidence.spec.ts@@ -0,0 +1,19 @@+import { expect, it } from 'vitest'+import { externalEvidence, externalReadFailed } from './evidence.js'++it('keeps display fallbacks but refuses swallowed errors for admission, independently per async read', async () => {+ externalReadFailed(new Error('display fallback'))+ const [healthy, broken] = await Promise.all([+ externalEvidence(async () => { await Promise.resolve(); return ['session'] }),+ externalEvidence(async () => { await Promise.resolve(); externalReadFailed(new Error('permission denied'), 'owner record'); return [] }),+ ])+ expect(healthy).toEqual({ ok: true, value: ['session'] })+ expect(broken).toEqual({ ok: false, detail: "The conversation's owner record could not be verified." })+ expect(await externalEvidence(async () => { throw new Error('unavailable') })).toMatchObject({ ok: false })+})++it('treats absent optional stores as empty but missing expected owner records as unknown', async () => {+ const read = async () => { externalReadFailed({ code: 'ENOENT' }); return false }+ expect(await externalEvidence(read)).toEqual({ ok: true, value: false })+ expect(await externalEvidence(read, true)).toMatchObject({ ok: false })+})diff --git a/cli/src/lib/sessionSearch/evidence.ts b/cli/src/lib/sessionSearch/evidence.tsnew file mode 100644index 000000000..2fabb4660--- /dev/null+++ b/cli/src/lib/sessionSearch/evidence.ts@@ -0,0 +1,28 @@+/** Display readers may keep last-good data. Admission must know when one of those reads failed. */+import { AsyncLocalStorage } from 'node:async_hooks'++interface Evidence { reason?: string; requirePresent: boolean }+const evidence = new AsyncLocalStorage<Evidence>()+export const externalEvidenceActive = (): boolean => evidence.getStore() !== undefined++/** Called even by readers which intentionally swallow errors for their display-only callers. */+export function externalReadFailed(error: unknown, operation = 'read'): void {+ const current = evidence.getStore()+ if (!current || current.reason) return+ if (!current.requirePresent && (error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return+ current.reason = `The conversation's ${operation} could not be verified.`+}++export async function externalEvidence<T>(read: () => Promise<T>, requirePresent = false): Promise<+ { ok: true; value: T } | { ok: false; detail: string }+> {+ const current: Evidence = { requirePresent }+ return evidence.run(current, async () => {+ try {+ const value = await read()+ return current.reason ? { ok: false, detail: current.reason } : { ok: true, value }+ } catch {+ return { ok: false, detail: current.reason ?? 'The conversation could not be verified.' }+ }+ })+}diff --git a/cli/src/lib/sessionSearch/external.ts b/cli/src/lib/sessionSearch/external.tsindex af3d212d3..973fde021 100644--- a/cli/src/lib/sessionSearch/external.ts+++ b/cli/src/lib/sessionSearch/external.ts@@ -9,14 +9,22 @@* the machine's processes, and one way to stop a terminal's process.*/-import { open } from 'node:fs/promises'--import { harnessTtys as readHarnessTtys, processAlive, processTtys, processView, run, scanMemo } from './externals/support.js'+import { harnessTtys as readHarnessTtys, processAlive, processTtys, processView, scanMemo } from './externals/support.js'import type { ExternalEngine, ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from './externals/types.js'+import { externalReadFailed } from './evidence.js'export type { ExternalEngine, ExternalOrigin, ExternalProvider, ExternalSession } from './externals/types.js'export { processAlive } from './externals/support.js'+/** Canonical records outrank aliases; the newest canonical record wins across stores and homes. */+export function externalSessionCatalog(rows: readonly ExternalSession[]): { found: ExternalSession[]; byId: Map<string, ExternalSession> } {+ const byId = new Map<string, ExternalSession>()+ for (const row of [...rows].sort((a, b) => b.mtime - a.mtime)) if (!byId.has(row.sessionId)) byId.set(row.sessionId, row)+ const found = [...byId.values()]+ for (const row of found) for (const alias of row.aliases ?? []) if (!byId.has(alias)) byId.set(alias, row)+ return { found, byId }+}+export interface ExternalSessionsOptions {providers: readonly ExternalProvider[]/** Folders whose sessions are Harness's own byproducts (its data folder): never offered. */@@ -55,22 +63,16 @@ export class ExternalSessions {this.lastGood.set(provider.engine, sessions)all.push(...sessions)} catch (error) {+ externalReadFailed(error, 'session store')// One engine's store failing (locked, mid-migration) keeps what it said last time.this.opts.log?.(`[search] ${provider.engine} sessions not read: ${error instanceof Error ? error.message : error}`)all.push(...this.lastGood.get(provider.engine) ?? [])}}this.memo.prune()- all.sort((a, b) => b.mtime - a.mtime)- // One id, one conversation: the newest record of it wins.- const byId = new Map<string, ExternalSession>()- for (const session of all) if (!byId.has(session.sessionId)) byId.set(session.sessionId, session)- this.found = [...byId.values()]- // An older id of a conversation that carried on under a new one finds the conversation.- for (const session of this.found) {- for (const alias of session.aliases ?? []) if (!byId.has(alias)) byId.set(alias, session)- }- this.byId = byId+ const catalog = externalSessionCatalog(all)+ this.found = catalog.found+ this.byId = catalog.byIdreturn this.found}}@@ -209,66 +211,4 @@ export class OpenSessions {}}-export interface StopOptions {- alive?: (pid: number) => boolean- kill?: (pid: number, signal: NodeJS.Signals) => void- sleep?: (ms: number) => Promise<void>- /** Writes to the owner's terminal; tests replace it. */- writeTty?: (tty: string, text: string) => Promise<void>- /** The foreground job [pid] leads, if it leads one; tests replace it. */- job?: (pid: number) => Promise<number | null>-}--/**- * The foreground job an engine leads in its terminal: the process group it heads, when that group is- * the one the terminal is showing. Its whole job is signalled then, so what it started for its screen- * goes with it (Hermes's terminal UI runs a Node child its Python does not pass SIGTERM to). An- * engine that does not lead its job (Codex's native binary under its Node launcher, anything run- * without job control) is signalled alone: its group may hold the shell it runs in.- */-export async function foregroundJob(pid: number, exec: typeof run = run): Promise<number | null> {- const out = await exec('ps', ['-o', 'pgid=,tpgid=', '-p', String(pid)], 3_000)- const [pgid, tpgid] = (out ?? '').trim().split(/\s+/).map(Number)- return pgid === pid && tpgid === pid ? pid : null-}--/**- * What a terminal gets back after its engine is stopped from outside: the main screen, no mouse- * reporting, and a cursor. A TUI that quit cleanly already restored them, and then these change- * nothing; Codex leaves its cursor hidden, and a TUI made to quit leaves whatever it had on.- */-export const TERMINAL_RESTORE = '\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l\x1b[?25h'--/**- * Stops the terminal process that has a session open, so Harness can resume it: asked to quit- * (SIGTERM, which the engines answer by saving and restoring the terminal), then made to after five- * seconds, and the terminal put back. Whether the process is gone.- */-export async function stopSessionOwner(owner: Pick<SessionOwner, 'pid' | 'tty'>, opts: StopOptions = {}): Promise<boolean> {- const alive = opts.alive ?? processAlive- const kill = opts.kill ?? ((pid: number, signal: NodeJS.Signals) => { process.kill(pid, signal) })- const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))- const gone = async (ms: number): Promise<boolean> => {- for (let waited = 0; waited < ms; waited += 100) {- if (!alive(owner.pid)) return true- await sleep(100)- }- return !alive(owner.pid)- }- const job = await (opts.job ?? foregroundJob)(owner.pid).catch(() => null)- const signal = (name: NodeJS.Signals): void => {- try { kill(job ? -job : owner.pid, name) } catch { /* already gone */ }- }- signal('SIGTERM')- if (!await gone(5_000)) {- signal('SIGKILL')- if (!await gone(2_000)) return false- }- if (owner.tty) await (opts.writeTty ?? writeTty)(owner.tty, TERMINAL_RESTORE).catch(() => undefined)- return true-}--export async function writeTty(tty: string, content: string): Promise<void> {- const handle = await open(tty, 'w')- try { await handle.write(content) } finally { await handle.close() }-}+export { foregroundJob, stopSessionOwner, writeTty, TERMINAL_RESTORE, type StopOptions } from '../externalOwnerControl.js'diff --git a/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts b/cli/src/lib/sessionSearch/externalShapes.golden.spec.tsindex b7555be6e..f0c0af836 100644--- a/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts+++ b/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts@@ -65,7 +65,7 @@ it('preserves external lists, exact ownership, conservative busy answers and corconst found = session('conversation', test.extra)const p: ExternalProvider = { engine: found.engine, scan: async () => [found],owners: async () => test.claim ? [{ sessionId: found.sessionId, pid: 7, record: '/fixture/record', ...test.claim }] : [],- busy: async () => test.busy ?? null }+ busy: async () => test.busy ?? null, confirmOwner: async () => ({ current: true, busy: test.busy ?? null }) }const one = externalShapes({ providers: [p] }, { ...openOptions, providers: [p],ttys: async () => new Map([[7, test.tty ?? null]]), harnessTtys: async () => test.harness === null ? null : new Set(test.harness ? [test.tty!] : []) },{ ...own, bySession: () => test.owned ? {} as never : undefined, stoppedAgents: { list: () => test.saved ? [{ sessionId: 'held' } as never] : [] } })diff --git a/cli/src/lib/sessionSearch/externals/agy.ts b/cli/src/lib/sessionSearch/externals/agy.tsindex d244808a6..64831b465 100644--- a/cli/src/lib/sessionSearch/externals/agy.ts+++ b/cli/src/lib/sessionSearch/externals/agy.ts@@ -1,3 +1,4 @@+import { externalReadFailed } from '../evidence.js'/*** Antigravity (`agy`): `<home>/brain/<id>/.system_generated/logs/transcript_full.jsonl` is each* conversation's history, and `<home>/presence/<id>.lock` is made only for a top-level one (a@@ -68,7 +69,7 @@ async function memoFile<T>(ctx: ScanContext, path: string, read: (path: string)}async function isFile(path: string): Promise<boolean> {- return (await stat(path).catch(() => null))?.isFile() ?? false+ return (await stat(path).catch(error => { externalReadFailed(error, 'record'); return null }))?.isFile() ?? false}export interface AgyOptions { home: string }@@ -85,7 +86,7 @@ export function agyProvider(options: AgyOptions): ExternalProvider {if (!entry.isDirectory() || !UUID.test(entry.name)) continueconst id = entry.nameconst transcriptPath = agyTranscriptPath(options.home, id)!- const transcript = await stat(transcriptPath).catch(() => null)+ const transcript = await stat(transcriptPath).catch(error => { externalReadFailed(error, 'record'); return null })// A conversation nobody has spoken in yet has an empty transcript, or none.if (!transcript?.isFile() || !transcript.size || !await isFile(join(presence, `${id}.lock`))) continueawait ctx.pace()@@ -103,7 +104,7 @@ export function agyProvider(options: AgyOptions): ExternalProvider {const pids = (await view.list()).filter((row) => engineProcessMatch(row, 'agy', NO_FILE_OWNERS).score).map((row) => row.pid)if (!pids.length) return []// lsof names a file by its real path: the presence folder may be reached through a link.- const folders = new Set([presence, await realpath(presence).catch(() => presence)])+ const folders = new Set([presence, await realpath(presence).catch(error => { externalReadFailed(error, 'folder'); return presence })])const claims: OwnerClaim[] = []for (const [pid, files] of await view.openFiles(pids)) {for (const path of files) {diff --git a/cli/src/lib/sessionSearch/externals/commandcode.ts b/cli/src/lib/sessionSearch/externals/commandcode.tsindex c1776e4f5..852c9b0d2 100644--- a/cli/src/lib/sessionSearch/externals/commandcode.ts+++ b/cli/src/lib/sessionSearch/externals/commandcode.ts@@ -17,6 +17,7 @@*/import { join } from 'node:path'+import { externalReadFailed } from '../evidence.js'import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'import { engineProcessMatch, resumeSessionId } from '../../tmux.js'@@ -135,6 +136,7 @@ export function commandcodeProvider(options: CommandcodeOptions): ExternalProvidconst claims: OwnerClaim[] = []for (const row of await view.list()) {if (!engineProcessMatch(row, 'commandcode', NO_FILE_OWNERS).score) continue+ if (view.alive(row.pid)) externalReadFailed(new Error('only launch arguments identify this live process'), 'current owner')// `--resume <id>`, `-r <id>` or `--session <id>`: a title, a path or a prefix names no session exactly.const sessionId = resumeSessionId('commandcode', row.args)// Only the arguments say so, and a /resume inside moves on: never stopped on this.diff --git a/cli/src/lib/sessionSearch/externals/copilot.spec.ts b/cli/src/lib/sessionSearch/externals/copilot.spec.tsindex e1a0b5517..c5e8449ad 100644--- a/cli/src/lib/sessionSearch/externals/copilot.spec.ts+++ b/cli/src/lib/sessionSearch/externals/copilot.spec.ts@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'+import { externalEvidence } from '../evidence.js'import { copilotMovedAt, copilotOrigin, copilotProvider, copilotTurnOpen, readCopilotSession, workspaceYaml } from './copilot.js'import { scanMemo } from './support.js'@@ -240,6 +241,20 @@ describe('copilotProvider.owners', () => {utimesSync(path, at, at)}+ it('holds admission for equal newest locks or a live process whose start cannot be proved', async () => {+ const root = home(); session(root, ID); session(root, ID2)+ lock(root, ID, 4242, 1_700_000_000)+ const provider = copilotProvider({ home: root })+ expect(await externalEvidence(() => provider.owners!(view([cli(4242)])))).toMatchObject({ ok: false })+ expect(await externalEvidence(() => provider.owners!(view([])))).toMatchObject({ ok: false })+ const processes = view([{ ...cli(4242), started: 1_700_000_000_000 }])+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: true, value: [{ sessionId: ID }] })+ lock(root, ID2, 4242, 1_700_000_000)+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: false })+ lock(root, ID2, 4242, 1_700_000_100)+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: true, value: [{ sessionId: ID2 }] })+ })+it('claims the session a live Copilot holds a lock on', async () => {const root = home()session(root, ID)diff --git a/cli/src/lib/sessionSearch/externals/copilot.ts b/cli/src/lib/sessionSearch/externals/copilot.tsindex 17ec077f4..5a5ca474e 100644--- a/cli/src/lib/sessionSearch/externals/copilot.ts+++ b/cli/src/lib/sessionSearch/externals/copilot.ts@@ -1,3 +1,4 @@+import { externalEvidenceActive, externalReadFailed } from '../evidence.js'/*** GitHub Copilot CLI: one folder per conversation, `<COPILOT_HOME>/session-state/<id>/`, holding its* event stream (`events.jsonl`, whose first line is `session.start`) and `workspace.yaml` (its folder@@ -203,7 +204,8 @@ async function streamHead(path: string): Promise<{ start: Record<string, unknown},shouldStop: () => prompted,}))- } catch {+ } catch (error) {+ externalReadFailed(error, 'conversation stream')return null}// Not one whole line yet.@@ -213,7 +215,7 @@ async function streamHead(path: string): Promise<{ start: Record<string, unknown/** The first answer [pick] gives, reading lines back from the end of [path]. */async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {- const size = (await stat(path).catch(() => null))?.size ?? 0+ const size = (await stat(path).catch(error => { externalReadFailed(error, 'record'); return null }))?.size ?? 0for (const bytes of TAIL_BYTES) {const lines = (await readTail(path, bytes)).split('\n')// A window that starts mid-file starts mid-line.@@ -240,7 +242,7 @@ export function copilotMovedAt(path: string): Promise<number | null> {* the stream holds no turn event at all.*/export async function copilotTurnOpen(path: string): Promise<boolean | null> {- const size = (await stat(path).catch(() => null))?.size ?? 0+ const size = (await stat(path).catch(error => { externalReadFailed(error, 'record'); return null }))?.size ?? 0for (const bytes of TAIL_BYTES) {const lines = (await readTail(path, bytes)).split('\n').filter((line) => {// A window that starts mid-file starts mid-line, and half a line is not JSON.@@ -264,7 +266,7 @@ export async function readCopilotSession(dir: string, sessionId: string): Promisif (!head || head.start?.type !== 'session.start' || !data) return skip('unreadable')if (text(data.sessionId) && data.sessionId !== sessionId) return skip('mismatch')if (text(data.detachedFromSpawningParentSessionId)) return skip('detached')- const workspace = workspaceYaml(await readFile(join(dir, 'workspace.yaml'), 'utf8').catch(() => ''))+ const workspace = workspaceYaml(await readFile(join(dir, 'workspace.yaml'), 'utf8').catch(error => { externalReadFailed(error, 'record'); return '' }))if (workspace.get('mc_task_id')) return skip('cloud-task')const origin = copilotOrigin(workspace.get('client_name') ?? '')if (!origin) return skip('automation')@@ -300,7 +302,7 @@ export function copilotProvider(options: CopilotOptions): ExternalProvider {if (!stamp) continueconst workspace = await fileStamp(join(dir, 'workspace.yaml'))const read = await ctx.memo(`copilot:${dir}`, `${stamp.stamp}|${workspace?.stamp ?? '-'}`, () => readCopilotSession(dir, entry.name))- .catch(() => null)+ .catch(error => { externalReadFailed(error, 'record'); return null })await ctx.pace()// Half-written: nothing was remembered, and the next scan reads it again.if (read?.kind !== 'session' || ctx.excluded(read.cwd)) continue@@ -314,6 +316,7 @@ export function copilotProvider(options: CopilotOptions): ExternalProvider {async owners(view: ProcessView): Promise<OwnerClaim[]> {// Each pid's newest lock: the session it is in now.const newest = new Map<number, { sessionId: string; at: number }>()+ const tied = new Set<number>()for (const entry of await entries(root)) {if (!entry.isDirectory() || !UUID.test(entry.name)) continuefor (const file of await entries(join(root, entry.name))) {@@ -321,19 +324,25 @@ export function copilotProvider(options: CopilotOptions): ExternalProvider {const stamp = pid > 0 ? await fileStamp(join(root, entry.name, file.name)) : nullif (!stamp) continueconst held = newest.get(pid)+ if (!held || stamp.mtime > held.at) tied.delete(pid)+ else if (stamp.mtime === held.at && entry.name !== held.sessionId) tied.add(pid)if (!held || stamp.mtime > held.at || (stamp.mtime === held.at && entry.name > held.sessionId)) {newest.set(pid, { sessionId: entry.name, at: stamp.mtime })}}}- if (!newest.size) return []+ if (!newest.size && !externalEvidenceActive()) return []const rows = new Map((await view.list()).map((row) => [row.pid, row]))const ownership = agentCommandOwnershipSnapshot()const claims: OwnerClaim[] = []for (const [pid, held] of newest) {const row = rows.get(pid)+ if (externalEvidenceActive() && !row && view.alive(pid)) externalReadFailed(new Error('missing owner process'), 'owner process')// A crash leaves its lock behind, and the pid can be reused: only a live Copilot counts.const kind = row && view.alive(pid) ? copilotProcess(row, ownership) : null+ if (kind && externalEvidenceActive() && (!Number.isFinite(row!.started) || tied.has(pid))) {+ externalReadFailed(new Error('ambiguous owner lock'), 'owner record'); continue+ }// A lock older than the process that has its pid was left by an earlier one.if (!kind || (row!.started !== undefined && held.at + START_SLACK_MS < row!.started)) continueclaims.push({@@ -341,6 +350,11 @@ export function copilotProvider(options: CopilotOptions): ExternalProvider {...(kind === 'server' ? { app: true } : {}),})}+ if (externalEvidenceActive()) for (const row of rows.values()) {+ if (view.alive(row.pid) && copilotProcess(row, ownership) && !claims.some(claim => claim.pid === row.pid)) {+ externalReadFailed(new Error('no current lock for a live process'), 'current owner')+ }+ }return claims},busy: (owner) => copilotTurnOpen(owner.record),diff --git a/cli/src/lib/sessionSearch/externals/cursor.spec.ts b/cli/src/lib/sessionSearch/externals/cursor.spec.tsindex 5b674c19b..1cbaa6338 100644--- a/cli/src/lib/sessionSearch/externals/cursor.spec.ts+++ b/cli/src/lib/sessionSearch/externals/cursor.spec.ts@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'import { basename, dirname, join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'+import { externalEvidence } from '../evidence.js'import { builtinSqlite } from '../../sqliteBuiltin.js'import { cursorBucket, cursorProvider, cursorSlug, cursorTurnOpen, readChat, type CursorDatabase } from './cursor.js'@@ -368,6 +369,16 @@ describe('cursorProvider.owners', () => {expect(await provider().owners!(processes)).toEqual([{ sessionId: ID, pid: 70, record: store }])})+ it('preserves different open stores in admission, but combines each store with its WAL and SHM', async () => {+ const { config, provider } = roots()+ const one = join(chat(config, CWD, ID), 'store.db')+ const two = join(chat(config, '/work/another', ID), 'store.db')+ const { processes } = view([cursorRow(70)], { 70: [one, `${one}-wal`, `${one}-shm`, two, `${two}-wal`] })+ expect(await provider().owners!(processes)).toHaveLength(1)+ expect(await externalEvidence(() => provider().owners!(processes))).toMatchObject({ ok: true, value: [{ record: one }, { record: two }] })+ expect(await externalEvidence(() => provider().owners!(view([cursorRow(70)]).processes))).toMatchObject({ ok: false })+ })+it('reads the files of Cursor processes only, and nothing when none runs', async () => {const { provider } = roots()const { processes, asked } = view([{ pid: 5, ppid: 1, executable: '/usr/bin/python3', args: 'python3 cursor-agent.py' }, cursorRow(71)], undefined, (pid) => pid !== 71)diff --git a/cli/src/lib/sessionSearch/externals/cursor.ts b/cli/src/lib/sessionSearch/externals/cursor.tsindex dc1cab832..2522197aa 100644--- a/cli/src/lib/sessionSearch/externals/cursor.ts+++ b/cli/src/lib/sessionSearch/externals/cursor.ts@@ -1,3 +1,4 @@+import { externalEvidenceActive, externalReadFailed } from '../evidence.js'/*** Cursor (`cursor-agent`, also `agent`): a chat is `<configDir>/chats/<md5(folder)>/<id>/`, holding its* `store.db` (SQLite, WAL) and `meta.json`, which says its title, when it last moved, the folder it@@ -128,7 +129,7 @@ export async function readStoreMeta(storePath: string, Database: CursorDatabase/** The first answer [pick] gives, reading lines back from the end of [path]. */async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {- const size = (await stat(path).catch(() => null))?.size ?? 0+ const size = (await stat(path).catch(error => { externalReadFailed(error, 'record'); return null }))?.size ?? 0for (const bytes of TAIL_BYTES) {const lines = (await readTail(path, bytes)).split('\n')// A window that starts mid-file starts mid-line.@@ -231,14 +232,15 @@ export async function readChat(ctx: ScanContext, chatDir: string, Database: () =read = await ctx.memo(`cursor:${chatDir}`, `${meta?.stamp ?? '-'}|${db.stamp}|${wal?.stamp ?? '-'}`, async () => {// A `meta.json` Cursor is still writing is not JSON yet, and throws: nothing is remembered, and// the next scan reads it again. One that is not a sidecar is read past, as Cursor reads past it.- const source = await readFile(join(chatDir, 'meta.json'), 'utf8').catch(() => null)+ const source = await readFile(join(chatDir, 'meta.json'), 'utf8').catch(error => { externalReadFailed(error, 'record'); return null })return (source === null ? null : parseCursorMeta(JSON.parse(source))) ?? readStoreMeta(store, Database())})- } catch {+ } catch (error) {+ externalReadFailed(error, 'conversation metadata')// Half-written, or a store that could not be opened: read again next scan.read = null}- if (!read) return { kind: 'skip', reason: 'unreadable' }+ if (!read) { externalReadFailed(new Error('unreadable'), 'conversation metadata'); return { kind: 'skip', reason: 'unreadable' } }if (read.isSubagent) return { kind: 'skip', reason: 'subagent' }if (!read.hasConversation) return { kind: 'skip', reason: 'empty' }return { kind: 'chat', chat: { sessionId: basename(chatDir), meta: read, movedAt: read.updatedAt ?? Math.max(db.mtime, wal?.mtime ?? 0) } }@@ -317,7 +319,7 @@ export function cursorProvider(options: CursorOptions): ExternalProvider {const cursor = rows.filter((row) => engineProcessMatch(row, 'cursor', ownership).score > 0 && view.alive(row.pid))if (!cursor.length) return []const byPid = new Map(rows.map((row) => [row.pid, row]))- const roots = new Set([chatsRoot, join(await realpath(options.configDir).catch(() => options.configDir), 'chats')])+ const roots = new Set([chatsRoot, join(await realpath(options.configDir).catch(error => { externalReadFailed(error, 'folder'); return options.configDir }), 'chats')])const files = await view.openFiles(cursor.map((row) => row.pid))const claims: OwnerClaim[] = []for (const row of cursor) {@@ -328,11 +330,13 @@ export function cursorProvider(options: CursorOptions): ExternalProvider {const chatDir = dirname(store)const sessionId = basename(chatDir)if (basename(store) !== 'store.db' || !UUID.test(sessionId) || !BUCKET.test(basename(dirname(chatDir)))) continue- if (!roots.has(dirname(dirname(chatDir))) || held.has(sessionId)) continue- held.add(sessionId)+ const key = externalEvidenceActive() ? store : sessionId+ if (!roots.has(dirname(dirname(chatDir))) || held.has(key)) continue+ held.add(key)claims.push({ sessionId, pid: row.pid, record: store, ...app })}if (held.size) continue+ externalReadFailed(new Error('no current open store for a live process'), 'current owner')// No chat store open (yet, or `lsof` could not say): the chat its arguments name.const resumed = resumeSessionId('cursor', row.args)// A guess: an in-app `/resume` leaves the arguments naming the first chat. Never stopped on it.diff --git a/cli/src/lib/sessionSearch/externals/devin.spec.ts b/cli/src/lib/sessionSearch/externals/devin.spec.tsindex 4b2e31822..605f64173 100644--- a/cli/src/lib/sessionSearch/externals/devin.spec.ts+++ b/cli/src/lib/sessionSearch/externals/devin.spec.ts@@ -15,6 +15,7 @@ import { builtinSqlite, closeSqliteHandles, overrideBuiltinSqlite } from '../../import { devinListSql, devinProvider, devinTurnOpen, lockPid } from './devin.js'import { LIST_LIMIT, ownerRecord, readSql, type SqlRead } from './opencode.js'import { scanMemo } from './support.js'+import { externalEvidence } from '../evidence.js'import type { ProcessView, RunningProcess, ScanContext } from './types.js'const Database = builtinSqlite()!@@ -265,6 +266,18 @@ describe('Devin owners', () => {alive: (pid) => !dead.includes(pid),})+ it('keeps a competing resumed process visible beside the exact lock during admission', async () => {+ const home = tempDir(), locks = join(home, 'session_locks')+ mkdirSync(locks)+ writeFileSync(join(locks, 'brisk-otter.lock'), '501')+ const provider = devinProvider({ home })+ const processes = view([{ ...devin(501), started: S0 * 1000 }, { ...devin(502, '-r brisk-otter'), started: S0 * 1000 }])+ expect(await provider.owners!(processes)).toHaveLength(1)+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: false })+ writeFileSync(join(locks, 'brisk-otter.lock'), '{"pid":')+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: false })+ })+it('claims a session from a live Devin holding its lock, or resumed with its id', async () => {const home = tempDir()const locks = join(home, 'session_locks')diff --git a/cli/src/lib/sessionSearch/externals/devin.ts b/cli/src/lib/sessionSearch/externals/devin.tsindex 1f125057f..684badbd7 100644--- a/cli/src/lib/sessionSearch/externals/devin.ts+++ b/cli/src/lib/sessionSearch/externals/devin.ts@@ -22,11 +22,12 @@ import { hasSqliteReader } from '../../sqliteAvailability.js'import type { SqliteRow } from '../../sqliteRead.js'import { resumeSessionId } from '../../tmux.js'import {- LIST_LIMIT, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts, storeStamp,+ LIST_LIMIT, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, checkedSql, rowsOf, splitCounts, storeStamp,tableColumns, tally, type Counting, type SqlRead, type Tally,} from './opencode.js'import { absoluteFolder, entries, epochMs, parseLine, record, text } from './support.js'import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'+import { externalEvidenceActive, externalReadFailed } from '../evidence.js'export interface DevinOptions {home: string@@ -83,11 +84,13 @@ const LOCK_SLACK_MS = 2_000/** A lock's pid and when it was written; null when it cannot be read. */async function readLock(path: string): Promise<{ pid: number | null; written: number } | null> {- const handle = await open(path, 'r').catch(() => null)+ const handle = await open(path, 'r').catch(error => { externalReadFailed(error, 'record'); return null })if (!handle) return nulltry {const [info, content] = await Promise.all([handle.stat(), handle.readFile('utf8')])- return { pid: lockPid(content), written: info.mtimeMs }+ const pid = lockPid(content)+ if (pid === null) externalReadFailed(new Error('invalid lock PID'), 'owner record')+ return { pid, written: info.mtimeMs }} finally {await handle.close()}@@ -114,7 +117,7 @@ export function devinTurnOpen(rows: readonly SqliteRow[]): boolean | null {export function devinProvider(options: DevinOptions): ExternalProvider & Counting {const { home } = optionsconst dbPath = join(home, 'sessions.db')- const read = options.read ?? readSql+ const read = checkedSql(options.read ?? readSql)const available = options.available ?? hasSqliteReaderlet counts: Tally = {}return {@@ -122,7 +125,7 @@ export function devinProvider(options: DevinOptions): ExternalProvider & CountinlastScan: () => counts,async scan(ctx: ScanContext): Promise<ExternalSession[]> {counts = {}- if (!available()) return []+ if (!available()) { externalReadFailed(new Error('SQLite unavailable'), 'conversation reader'); return [] }const stamp = await storeStamp(dbPath)if (!stamp) return []const listed = await ctx.memo(`devin:${dbPath}`, stamp, () => listSessions(read, dbPath))@@ -153,8 +156,9 @@ export function devinProvider(options: DevinOptions): ExternalProvider & Countinconst isDevin = engineProcess('devin')const claims = new Map<string, OwnerClaim>()const add = (sessionId: string, row: RunningProcess, fromArgs: boolean): void => {- if (claims.has(sessionId)) return- claims.set(sessionId, {+ const key = externalEvidenceActive() ? JSON.stringify([sessionId, row.pid, fromArgs]) : sessionId+ if (claims.has(key)) return+ claims.set(key, {sessionId, pid: row.pid, record: ownerRecord(dbPath, sessionId),...(SERVERS.has(argvSubcommand(row.args, VALUE_FLAGS)) ? { app: true } : {}),...(fromArgs ? { fromArgs: true } : {}),@@ -170,13 +174,18 @@ export function devinProvider(options: DevinOptions): ExternalProvider & Countin// A lock outlives a crash, and its pid can be handed to anything after, another Devin among// them: one written before the process under its pid began was that earlier process's.const row = byPid.get(lock.pid)+ if (externalEvidenceActive() && !row && view.alive(lock.pid)) externalReadFailed(new Error('missing owner process'), 'owner process')if (!row || !view.alive(lock.pid) || !isDevin(row)) continue+ if (!Number.isFinite(row.started)) externalReadFailed(new Error('missing owner start time'), 'owner record')if (row.started !== undefined && lock.written < row.started - LOCK_SLACK_MS) continueadd(sessionId, row, false)}// The id a process was started on, where no lock says more: it may have moved on since.for (const row of processes) {if (!isDevin(row)) continue+ if (view.alive(row.pid) && ![...claims.values()].some(claim => claim.pid === row.pid && !claim.fromArgs)) {+ externalReadFailed(new Error('no exact lock for a live process'), 'current owner')+ }const sessionId = resumeSessionId('devin', row.args)if (sessionId) add(sessionId, row, true)}diff --git a/cli/src/lib/sessionSearch/externals/grok.spec.ts b/cli/src/lib/sessionSearch/externals/grok.spec.tsindex 2add5aa41..745070ebd 100644--- a/cli/src/lib/sessionSearch/externals/grok.spec.ts+++ b/cli/src/lib/sessionSearch/externals/grok.spec.ts@@ -5,6 +5,7 @@ import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'import { grokMovedAt, grokProvider, grokTurnOpen, readGrokSession } from './grok.js'+import { externalEvidence } from '../evidence.js'import { scanMemo } from './support.js'import type { ProcessView, RunningProcess, ScanContext } from './types.js'@@ -249,6 +250,25 @@ describe('when a Grok conversation last moved', () => {describe('grokProvider.owners', () => {const stream = (root: string, cwd = '/work/app', id = ID) => join(root, 'sessions', encodeURIComponent(cwd), id, 'updates.jsonl')+ it('holds missing or ambiguous live-process records, including equally recent conversations', async () => {+ const root = home(), at = 1_787_839_648_000, provider = grokProvider({ home: root })+ session(root, ID); session(root, ID2)+ const processes = view([{ ...grokRow(41), started: at }])+ expect((await externalEvidence(() => provider.owners!(processes))).ok).toBe(false)+ for (const listed of [[], null, {}, [+ { session_id: ID, pid: 41, opened_at: at, cwd: '/work/app' },+ { session_id: ID2, pid: 41, opened_at: at, cwd: '/work/app' },+ ]]) {+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify(listed))+ expect((await externalEvidence(() => provider.owners!(processes))).ok).toBe(false)+ }+ writeFileSync(join(root, 'active_sessions.json'), JSON.stringify([+ { session_id: ID, pid: 41, opened_at: at, cwd: '/work/app' },+ { session_id: ID2, pid: 41, opened_at: at + 1, cwd: '/work/app' },+ ]))+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: true, value: [{ sessionId: ID2 }] })+ })+it('claims each live Grok in `active_sessions.json`, with the stream that says whether it is mid-turn', async () => {const root = home()session(root, ID)diff --git a/cli/src/lib/sessionSearch/externals/grok.ts b/cli/src/lib/sessionSearch/externals/grok.tsindex 1ecf0160b..7fe64df7d 100644--- a/cli/src/lib/sessionSearch/externals/grok.ts+++ b/cli/src/lib/sessionSearch/externals/grok.ts@@ -1,3 +1,4 @@+import { externalEvidenceActive, externalReadFailed } from '../evidence.js'/*** Grok: one folder per conversation, `<GROK_HOME>/sessions/<group>/<id>/`, where the group is the* folder it ran in (URL-encoded, or a slug and hash with the path in `.cwd` when that is too long).@@ -55,7 +56,7 @@ const skip = (reason: GrokSkip): GrokRead => ({ kind: 'skip', reason })* throws, so a scan's memo keeps nothing of it and the next scan reads it again.*/async function jsonFile(path: string): Promise<unknown> {- const source = await readFile(path, 'utf8').catch(() => null)+ const source = await readFile(path, 'utf8').catch(error => { externalReadFailed(error, 'record'); return null })return source === null ? undefined : JSON.parse(source)}@@ -75,7 +76,7 @@ function update(line: string): { kind: string; at: number | null; event: string* mid-file starts mid-line, so its first line is never read.*/async function fromEnd<T>(path: string, pick: (line: string) => T | null): Promise<T | null> {- const size = (await stat(path).catch(() => null))?.size ?? 0+ const size = (await stat(path).catch(error => { externalReadFailed(error, 'record'); return null }))?.size ?? 0for (const bytes of TAIL_BYTES) {const lines = (await readTail(path, bytes)).split('\n')for (let i = lines.length - 1; i >= (size > bytes ? 1 : 0); i--) {@@ -92,7 +93,8 @@ async function prompted(path: string): Promise<boolean> {let found = falsetry {await forEachLine(path, 0, () => { found = true }, { skip: (head) => !PROMPT.test(head), shouldStop: () => found })- } catch {+ } catch (error) {+ externalReadFailed(error, 'conversation stream')return false}return found@@ -200,7 +202,7 @@ export function grokProvider(options: GrokOptions): ExternalProvider {fileStamp(join(dir, 'summary.json')), fileStamp(join(dir, 'prompt_context.json')),])const fingerprint = `${stamp.stamp}|${summary?.stamp ?? '-'}|${context?.stamp ?? '-'}`- const read = await ctx.memo(`grok:${dir}`, fingerprint, () => readGrokSession(dir, entry.name)).catch(() => null)+ const read = await ctx.memo(`grok:${dir}`, fingerprint, () => readGrokSession(dir, entry.name)).catch(error => { externalReadFailed(error, 'record'); return null })await ctx.pace()// Half-written: nothing was remembered, and the next scan reads it again.if (read?.kind !== 'session' || ctx.excluded(read.cwd)) continue@@ -215,34 +217,54 @@ export function grokProvider(options: GrokOptions): ExternalProvider {async owners(view: ProcessView): Promise<OwnerClaim[]> {const listed = await readJson(join(options.home, 'active_sessions.json'))// Grok itself starts over from an empty list when this file is corrupt.- if (!Array.isArray(listed) || !listed.length) return []+ if (!Array.isArray(listed) && listed !== null) externalReadFailed(new Error('invalid active sessions'), 'owner record')+ if ((!Array.isArray(listed) || !listed.length) && !externalEvidenceActive()) return []const byPid = new Map<number, Array<{ sessionId: string; cwd: string; at: number }>>()- for (const item of listed) {+ for (const item of Array.isArray(listed) ? listed : []) {const entry = record(item)const sessionId = text(entry?.session_id)const pid = entry?.pid- if (!UUID.test(sessionId) || typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) continue- byPid.set(pid, [...byPid.get(pid) ?? [], { sessionId, cwd: text(entry?.cwd), at: epochMs(entry?.opened_at) ?? 0 }])+ if (!UUID.test(sessionId) || typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0 || pid > 0x7fffffff) {+ externalReadFailed(new Error('invalid active session'), 'owner record'); continue+ }+ const at = epochMs(entry?.opened_at)+ if (externalEvidenceActive() && (!Number.isFinite(at) || at! <= 0)) {+ externalReadFailed(new Error('missing owner start'), 'owner record'); continue+ }+ byPid.set(pid, [...byPid.get(pid) ?? [], { sessionId, cwd: text(entry?.cwd), at: at ?? 0 }])}const rows = new Map((await view.list()).map((row) => [row.pid, row]))const ownership = agentCommandOwnershipSnapshot()const claims: OwnerClaim[] = []for (const [pid, held] of byPid) {const row = rows.get(pid)+ if (externalEvidenceActive() && !row && view.alive(pid)) externalReadFailed(new Error('missing owner process'), 'owner process')// An entry outlives a crash, and its pid can be reused: only a live Grok counts.if (!row || !view.alive(pid) || !isGrok(row, ownership)) continue+ if (externalEvidenceActive() && (!Number.isFinite(row.started) || row.started! <= 0)) {+ externalReadFailed(new Error('missing process start'), 'owner process'); continue+ }// An entry opened before the process that has its pid started was an earlier process's. An// entry that does not say when it was opened is kept.const current = held.filter((entry) => !entry.at || row.started === undefined || entry.at + START_SLACK_MS >= row.started)if (!current.length) continueconst app = shared(row)// A terminal's Grok has one session open: an older entry under its pid is a crashed Grok's.- const open = app ? current : [current.reduce((newest, entry) => (entry.at >= newest.at ? entry : newest))]+ const newest = current.reduce((latest, entry) => entry.at >= latest.at ? entry : latest)+ if (!app && externalEvidenceActive() && new Set(current.filter(entry => entry.at === newest.at)+ .map(entry => JSON.stringify([entry.sessionId, entry.cwd]))).size > 1) {+ externalReadFailed(new Error('ambiguous current process record'), 'current owner'); continue+ }+ const open = app ? current : [newest]for (const entry of open) {const stream = await streamOf(options.home, entry.sessionId, entry.cwd)claims.push({ sessionId: entry.sessionId, pid, record: stream ?? '', ...(app ? { app: true } : {}) })}}+ if (externalEvidenceActive()) for (const row of rows.values()) {+ if (view.alive(row.pid) && isGrok(row, ownership) && !claims.some(claim => claim.pid === row.pid))+ externalReadFailed(new Error('no current process record'), 'current owner')+ }return claims},async busy(owner): Promise<boolean | null> {diff --git a/cli/src/lib/sessionSearch/externals/hermes.spec.ts b/cli/src/lib/sessionSearch/externals/hermes.spec.tsindex cb702f6d8..4de91c9e6 100644--- a/cli/src/lib/sessionSearch/externals/hermes.spec.ts+++ b/cli/src/lib/sessionSearch/externals/hermes.spec.ts@@ -17,6 +17,7 @@ import {} from './hermes.js'import { LIST_LIMIT, ownerRecord, readSql, type SqlRead } from './opencode.js'import { scanMemo } from './support.js'+import { externalEvidence } from '../evidence.js'import type { ProcessView, RunningProcess, ScanContext } from './types.js'const Database = builtinSqlite()!@@ -442,6 +443,27 @@ describe('Hermes owners', () => {return { root, main, work }}+ it('keeps competing exact leases visible to admission, while display deduplication stays unchanged', async () => {+ const { root, main, work } = homes()+ mkdirSync(join(root, 'runtime'))+ const leases = [501, 502].map(pid => ({ session_id: id(1), surface: 'cli', pid, process_start_time: S0 }))+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: leases }))+ const processes = view([501, 502].map(pid => ({ ...py(pid, 1, ''), started: S0 * 1000 })))+ const provider = hermesProvider({ root })+ expect(await provider.owners!(processes)).toHaveLength(1)+ const observed = await externalEvidence(() => provider.owners!(processes))+ expect(observed).toMatchObject({ ok: true, value: [{ pid: 501 }, { pid: 502 }] })+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [{ ...leases[0], pid: 'unfinished' }] }))+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: false })+ for (const malformed of [null, { entries: [null] }, { entries: [{}] }, { entries: [{ pid: 501 }] }, { entries: [{ ...leases[0], process_start_time: null }] }]) {+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify(malformed))+ expect(await externalEvidence(() => provider.owners!(processes))).toMatchObject({ ok: false })+ }+ writeFileSync(join(root, 'runtime', 'active_sessions.json'), JSON.stringify({ entries: [{ surface: 'gateway-chat', session_id: 'not-a-store-id' }] }))+ expect(await externalEvidence(() => provider.owners!(view([])))).toMatchObject({ ok: true, value: [] })+ main.close(); work.close()+ })+it('claims from the id a Hermes process was resumed with, in the home it runs in, at its chain\'s tip', async () => {const { root, main, work } = homes()const claims = await hermesProvider({ root }).owners!(view([diff --git a/cli/src/lib/sessionSearch/externals/hermes.ts b/cli/src/lib/sessionSearch/externals/hermes.tsindex a27869594..f1f7bbcfe 100644--- a/cli/src/lib/sessionSearch/externals/hermes.ts+++ b/cli/src/lib/sessionSearch/externals/hermes.ts@@ -29,11 +29,12 @@ import { hasSqliteReader } from '../../sqliteAvailability.js'import type { SqliteParam, SqliteRow } from '../../sqliteRead.js'import { argvTokens, resumeSessionId } from '../../tmux.js'import {- LIST_LIMIT, ancestry, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts,+ LIST_LIMIT, ancestry, argvSubcommand, engineProcess, ownerRecord, parseOwnerRecord, readSql, checkedSql, rowsOf, splitCounts,storeStamp, tableColumns, tally, type Counting, type SqlRead, type Tally,} from './opencode.js'import { absoluteFolder, entries, epochMs, readJson, record, text } from './support.js'import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView, RunningProcess, ScanContext } from './types.js'+import { externalEvidenceActive, externalReadFailed } from '../evidence.js'export interface HermesOptions {root: string@@ -74,7 +75,7 @@ export interface HermesHome {/** The profile `hermes profile use <name>` made sticky, or null for the default. */export async function activeProfile(root: string): Promise<string | null> {- const name = (await readFile(join(root, 'active_profile'), 'utf8').catch(() => '')).trim()+ const name = (await readFile(join(root, 'active_profile'), 'utf8').catch(error => { externalReadFailed(error, 'record'); return '' })).trim()return PROFILE_ID.test(name) && name !== 'default' ? name : null}@@ -302,7 +303,7 @@ const START_SLACK_MS = 2_000export async function hermesLeases(home: string): Promise<HermesLease[]> {const file = await readJson(join(home, 'runtime', 'active_sessions.json'))const list = Array.isArray(file) ? file : record(file)?.entries- if (!Array.isArray(list)) return []+ if (!Array.isArray(list)) { if (file !== null) externalReadFailed(new Error('invalid leases'), 'owner record'); return [] }const leases: HermesLease[] = []for (const item of list) {const entry = record(item)@@ -310,9 +311,12 @@ export async function hermesLeases(home: string): Promise<HermesLease[]> {const pid = entry?.pidconst started = entry?.process_start_time// A gateway's lease names a chat's key, not a stored session.- if (!HERMES_HISTORY_ID_RE.test(sessionId) || text(entry?.surface).startsWith('gateway')) continue- if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) continue- leases.push({ sessionId, pid, ...(typeof started === 'number' && started > 0 ? { started: started * 1000 } : {}) })+ if (text(entry?.surface).startsWith('gateway')) continue+ if (!HERMES_HISTORY_ID_RE.test(sessionId)) { externalReadFailed(new Error('invalid lease session'), 'owner record'); continue }+ if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0 || pid > 0x7fffffff) {+ externalReadFailed(new Error('invalid lease PID'), 'owner record'); continue+ }+ leases.push({ sessionId, pid, ...(typeof started === 'number' && Number.isFinite(started) && started > 0 ? { started: started * 1000 } : {}) })}return leases}@@ -341,7 +345,7 @@ export function hermesTurnOpen(rows: readonly SqliteRow[]): boolean | null {export function hermesProvider(options: HermesOptions): ExternalProvider & Counting {const { root } = options- const read = options.read ?? readSql+ const read = checkedSql(options.read ?? readSql)const available = options.available ?? hasSqliteReaderconst now = options.now ?? Date.nowconst lastGood = new Map<string, Listed | null>()@@ -384,7 +388,7 @@ export function hermesProvider(options: HermesOptions): ExternalProvider & CountlastScan: () => counts,async scan(ctx: ScanContext): Promise<ExternalSession[]> {counts = {}- if (!available()) return []+ if (!available()) { externalReadFailed(new Error('SQLite unavailable'), 'conversation reader'); return [] }const active = await activeProfile(root)const sessions: HermesSession[] = []const failures: unknown[] = []@@ -399,6 +403,7 @@ export function hermesProvider(options: HermesOptions): ExternalProvider & CountlastGood.set(home.dbPath, listed)} catch (error) {// One home locked or broken keeps what it said last time; the others still answer.+ externalReadFailed(error, 'conversation store')failures.push(error)listed = lastGood.get(home.dbPath) ?? null}@@ -432,8 +437,9 @@ export function hermesProvider(options: HermesOptions): ExternalProvider & Countat = { dbPath: home.dbPath, sessionId: await compressionTip(read, home.dbPath, sessionId) }break}- if (claims.has(at.sessionId)) return- claims.set(at.sessionId, {+ const key = externalEvidenceActive() ? JSON.stringify([at.sessionId, owner.pid, at.dbPath, fromArgs, served(owner)]) : at.sessionId+ if (claims.has(key)) return+ claims.set(key, {sessionId: at.sessionId, pid: owner.pid, record: ownerRecord(at.dbPath, at.sessionId),...(served(owner) ? { app: true } : {}),...(fromArgs ? { fromArgs: true } : {}),@@ -442,6 +448,9 @@ export function hermesProvider(options: HermesOptions): ExternalProvider & Count// A lease is exact, so it is read first and wins over the same session named in arguments.for (const home of homes) {for (const lease of await hermesLeases(home.home)) {+ if (externalEvidenceActive() && (!Number.isFinite(lease.started) || !Number.isFinite(byPid.get(lease.pid)?.started)) && view.alive(lease.pid)) {+ externalReadFailed(new Error('missing owner generation'), 'owner record'); continue+ }if (!view.alive(lease.pid) || !leaseHeldBy(lease, byPid.get(lease.pid))) continue// The lease's pid is the REPL itself, or a terminal UI's gateway two levels under its// `hermes` (hermes → node UI → python gateway). A pid that is neither was reused.@@ -452,6 +461,9 @@ export function hermesProvider(options: HermesOptions): ExternalProvider & Count// The id a process was started on: it may have moved to another conversation since (`/resume`).for (const row of processes) {if (!isHermes(row)) continue+ if (view.alive(row.pid) && ![...claims.values()].some(claim => claim.pid === row.pid && !claim.fromArgs)) {+ externalReadFailed(new Error('no exact lease for a live process'), 'current owner')+ }const sessionId = resumeSessionId('hermes', row.args)if (!sessionId) continueconst profile = argvProfile(row.args)diff --git a/cli/src/lib/sessionSearch/externals/index.ts b/cli/src/lib/sessionSearch/externals/index.tsindex 90af325ca..60ed5db07 100644--- a/cli/src/lib/sessionSearch/externals/index.ts+++ b/cli/src/lib/sessionSearch/externals/index.ts@@ -15,6 +15,7 @@ import { adoptionProviderOf } from '../../../engines/adoptions.js'import { loadEngine, type InProcessModules, type OtherEngine } from '../../../engines/inProcess.js'import { claudeProjectsRoots, codexHomeRoots } from '../../engineHomes.js'import type { ExternalEngine, ExternalProvider } from './types.js'+import { externalReadFailed } from '../evidence.js'export interface ExternalPaths {claudeProjectsDir: string@@ -73,15 +74,19 @@ export function externalPaths(vars: NodeJS.ProcessEnv = process.env): ExternalPa*/function loaded<Name extends OtherEngine>(engine: ExternalEngine, name: Name, build: (code: InProcessModules[Name]) => ExternalProvider): ExternalProvider {let provider: Promise<ExternalProvider | null> | null = null- const reader = (): Promise<ExternalProvider | null> => provider ??= loadEngine(name).then((code) => {- if (!code) return null- try {- return build(code)- } catch (error) {- console.error(`[engine ${name}] adoption reader unavailable · ${error instanceof Error ? error.message : error}`)- return null- }- })+ const reader = async (): Promise<ExternalProvider | null> => {+ const found = await (provider ??= loadEngine(name).then((code) => {+ if (!code) return null+ try {+ return build(code)+ } catch (error) {+ console.error(`[engine ${name}] adoption reader unavailable · ${error instanceof Error ? error.message : error}`)+ return null+ }+ }))+ if (!found) externalReadFailed(new Error('engine reader unavailable'), 'engine reader')+ return found+ }return {engine,scan: async (ctx) => await (await reader())?.scan(ctx) ?? [],diff --git a/cli/src/lib/sessionSearch/externals/muse.ts b/cli/src/lib/sessionSearch/externals/muse.tsindex 90643e883..c9fc04f1c 100644--- a/cli/src/lib/sessionSearch/externals/muse.ts+++ b/cli/src/lib/sessionSearch/externals/muse.ts@@ -1,3 +1,4 @@+import { externalReadFailed } from '../evidence.js'/*** Muse: `<home>/sessions/YYYY/MM/DD/<id>/session.jsonl`, one append-only log per session. Nothing in* the path names the project: the first record, the session's metadata, carries `workspace_root`,@@ -78,7 +79,7 @@ export async function museOwnRun(path: string, sessionId: string): Promise<booleawait forEachLine(path, 0, ({ text: line }) => {const own = ownRecord(line, sessionId)if (own?.run && own.kind === 'started') ran = true- }, { skip: (head) => ran || !head.includes(sessionId), shouldStop: () => ran }).catch(() => undefined)+ }, { skip: (head) => ran || !head.includes(sessionId), shouldStop: () => ran }).catch(error => { externalReadFailed(error, 'record'); return undefined })return ran}@@ -170,6 +171,7 @@ export function museProvider(options: MuseOptions): ExternalProvider {const claims: OwnerClaim[] = []for (const row of await view.list()) {if (!engineProcessMatch(row, 'muse', NO_FILE_OWNERS).score) continue+ if (view.alive(row.pid)) externalReadFailed(new Error('only launch arguments identify this live process'), 'current owner')const sessionId = resumeSessionId('muse', row.args)// Only the arguments say so, and a /resume inside moves on: never stopped on this.if (sessionId) claims.push({ sessionId, pid: row.pid, record: known.get(sessionId) ?? '', fromArgs: true })diff --git a/cli/src/lib/sessionSearch/externals/opencode.ts b/cli/src/lib/sessionSearch/externals/opencode.tsindex 5ca9cc3a5..6d67959e9 100644--- a/cli/src/lib/sessionSearch/externals/opencode.ts+++ b/cli/src/lib/sessionSearch/externals/opencode.ts@@ -1,3 +1,4 @@+import { externalReadFailed } from '../evidence.js'/*** OpenCode and Kilo (an OpenCode fork): one SQLite store each, `opencode.db` and `kilo.db`, with the* same `session` / `message` / `part` tables (measured: opencode 1.18.31, kilo 7.4.20). One list query@@ -121,7 +122,7 @@ export function opencodeTurnOpen(rows: readonly SqliteRow[]): boolean | null {export function opencodeProvider(options: OpencodeOptions): ExternalProvider & Counting {const { engine, dbPath } = options- const read = options.read ?? readSql+ const read = checkedSql(options.read ?? readSql)const available = options.available ?? hasSqliteReaderlet counts: Tally = {}const history = (sessionId: string) => engine === 'kilo'@@ -132,7 +133,7 @@ export function opencodeProvider(options: OpencodeOptions): ExternalProvider & ClastScan: () => counts,async scan(ctx: ScanContext): Promise<ExternalSession[]> {counts = {}- if (!available()) return []+ if (!available()) { externalReadFailed(new Error('SQLite unavailable'), 'conversation reader'); return [] }const stamp = await storeStamp(dbPath)if (!stamp) return []const listed = await ctx.memo(`${engine}:${dbPath}`, stamp, () => listSessions(read, dbPath))@@ -166,6 +167,7 @@ export function opencodeProvider(options: OpencodeOptions): ExternalProvider & Cconst claims: OwnerClaim[] = []for (const row of processes) {if (!isEngine(row)) continue+ if (view.alive(row.pid)) externalReadFailed(new Error('only launch arguments identify this live process'), 'current owner')const sessionId = resumeSessionId(engine, row.args)if (!sessionId) continue// The session it was started on: the TUI may have switched to another since.@@ -192,6 +194,15 @@ export type SqlRead = (dbPath: string, sql: string, params?: SqliteParam[]) => Pexport const readSql: SqlRead = (dbPath, sql, params = []) => sqliteReadAll(dbPath, sql, params)+/** A swallowed failed statement must never authorize absence of an external owner. */+export function checkedSql(read: SqlRead): SqlRead {+ return async (...args) => {+ const answer = await read(...args)+ if (!answer.ok) externalReadFailed(new Error('SQLite read failed'), 'conversation store')+ return answer+ }+}+/** How many rows each rule kept out of a scan, and how many it found. */export type Tally = Record<string, number>diff --git a/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts b/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.tsnew file mode 100644index 000000000..580034360--- /dev/null+++ b/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts@@ -0,0 +1,26 @@+import { expect, it } from 'vitest'+import { externalEvidence } from '../evidence.js'+import { opencodeProvider } from './opencode.js'+import { piProvider } from './pi.js'+import { commandcodeProvider } from './commandcode.js'+import { museProvider } from './muse.js'+import type { ExternalProvider, ProcessView } from './types.js'++const providers: Array<[string, () => ExternalProvider]> = [+ ['opencode', () => opencodeProvider({ engine: 'opencode', dbPath: '/fixture/store.db' })],+ ['kilo', () => opencodeProvider({ engine: 'kilo', dbPath: '/fixture/store.db' })],+ ['pi', () => piProvider({ agentDir: '/fixture/pi' })],+ ['commandcode', () => commandcodeProvider({ home: '/fixture/commandcode' })],+ ['muse', () => museProvider({ home: '/fixture/muse' })],+]+it.each(providers)('%s launch arguments cannot establish that another conversation is free', async (engine, create) => {+ const provider = create()+ for (const suffix of ['', '--resume 11111111-1111-4111-8111-111111111111']) {+ const view: ProcessView = { list: async () => [{ pid: 501, ppid: 1, executable: engine, args: `${engine} ${suffix}` }],+ alive: () => true, openFiles: async () => new Map(), openFilesOf: async () => new Map() }+ expect(await externalEvidence(() => provider.owners!(view)), suffix).toMatchObject({ ok: false })+ // The display reader may still show the original argv claim; strict admission never uses it as absence.+ await expect(provider.owners!(view)).resolves.toBeInstanceOf(Array)+ expect(await externalEvidence(() => provider.owners!({ ...view, list: async () => [] }))).toEqual({ ok: true, value: [] })+ }+})diff --git a/cli/src/lib/sessionSearch/externals/pi.ts b/cli/src/lib/sessionSearch/externals/pi.tsindex d6991e921..9c9863604 100644--- a/cli/src/lib/sessionSearch/externals/pi.ts+++ b/cli/src/lib/sessionSearch/externals/pi.ts@@ -1,3 +1,4 @@+import { externalReadFailed } from '../evidence.js'/*** Pi: `<agentDir>/sessions/--<folder>--/<time>_<id>.jsonl`, or one flat folder when the person moved* them (`PI_CODING_AGENT_SESSION_DIR`, else `sessionDir` in `<agentDir>/settings.json`; Pi then@@ -88,14 +89,14 @@ export interface PiTitleRead { end: number; lead: string; title: string }* header) is read again from the start. Only lines that name `session_info` are parsed.*/export async function readPiTitle(path: string, prior?: PiTitleRead): Promise<PiTitleRead> {- const [start, info] = await Promise.all([readHead(path, LEAD_BYTES), stat(path).catch(() => null)])+ const [start, info] = await Promise.all([readHead(path, LEAD_BYTES), stat(path).catch(error => { externalReadFailed(error, 'record'); return null })])const lead = start.split('\n')[0]const from = prior && info && prior.lead === lead && info.size >= prior.end ? prior : { end: 0, lead, title: '' }let title = from.titleconst read = await forEachLine(path, from.end, ({ text: line }) => {const row = record(parseLine(line))if (row?.type === 'session_info') title = text(row.name).trim()- }, { skip: (head) => !head.includes('"session_info"') }).catch(() => null)+ }, { skip: (head) => !head.includes('"session_info"') }).catch(error => { externalReadFailed(error, 'record'); return null })// Unreadable now (gone, or being replaced): nothing is carried over, and the next change reads it whole.return read ? { end: read.end, lead, title } : { end: 0, lead: '', title: '' }}@@ -202,6 +203,7 @@ async function argvClaims(view: ProcessView, recordOf: (sessionId: string) => stconst claims: OwnerClaim[] = []for (const row of await view.list()) {if (!engineProcessMatch(row, 'pi', NO_FILE_OWNERS).score) continue+ if (view.alive(row.pid)) externalReadFailed(new Error('only launch arguments identify this live process'), 'current owner')const sessionId = resumeSessionId('pi', row.args)// Only the arguments say so, and Pi can move to another session inside: never stopped on this.if (sessionId) claims.push({ sessionId, pid: row.pid, record: recordOf(sessionId), fromArgs: true })diff --git a/cli/src/lib/sessionSearch/externals/support.spec.ts b/cli/src/lib/sessionSearch/externals/support.spec.tsindex 4b7257080..3643389e6 100644--- a/cli/src/lib/sessionSearch/externals/support.spec.ts+++ b/cli/src/lib/sessionSearch/externals/support.spec.ts@@ -229,9 +229,10 @@ describe('processes', () => {expect(await listProcesses(async () => null)).toEqual([])const row = { pid: 5, parentPid: 1, executable: 'grok', args: 'grok', startMarker: 'Sun Sep 27 09:05:03 2026' }expect(await listProcesses(async () => [row, { ...row, pid: 6, startMarker: 'soon' }])).toEqual([- { pid: 5, ppid: 1, executable: 'grok', args: 'grok', started: Date.parse('Sun Sep 27 09:05:03 2026') },+ { pid: 5, ppid: 1, executable: 'grok', args: 'grok', started: Date.parse(row.startMarker), generation: `ps:${Date.parse(row.startMarker)}` },{ pid: 6, ppid: 1, executable: 'grok', args: 'grok' },])+ expect((await listProcesses(async () => [{ ...row, startTicks: 42 }]))[0].generation).toBe('linux:42')})it("knows Harness's own panes by their tmux session names, and by a daemon's tag wherever they moved", async () => {diff --git a/cli/src/lib/sessionSearch/externals/support.ts b/cli/src/lib/sessionSearch/externals/support.tsindex b02bc531e..a43b0ac6f 100644--- a/cli/src/lib/sessionSearch/externals/support.ts+++ b/cli/src/lib/sessionSearch/externals/support.ts@@ -12,15 +12,16 @@ import { isHarnessSession, paneOwnerFormat } from '../../harnessSessionLabel.js'import { processRows } from '../../tmux.js'import { tmuxFeatures } from '../../tmuxVersion.js'import { type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'+import { externalReadFailed } from '../evidence.js'/** A folder's entries, or none when it is missing or unreadable. */export async function entries(dir: string): Promise<Dirent[]> {- return readdir(dir, { withFileTypes: true }).catch(() => [])+ return readdir(dir, { withFileTypes: true }).catch(error => { externalReadFailed(error, 'folder'); return [] })}/** Up to [bytes] from the start of a file; '' when it cannot be read. */export async function readHead(path: string, bytes: number): Promise<string> {- const handle = await open(path, 'r').catch(() => null)+ const handle = await open(path, 'r').catch(error => { externalReadFailed(error, 'file'); return null })if (!handle) return ''try {const buffer = Buffer.alloc(bytes)@@ -33,7 +34,7 @@ export async function readHead(path: string, bytes: number): Promise<string> {/** Up to [bytes] from the end of a file; '' when it cannot be read. */export async function readTail(path: string, bytes: number): Promise<string> {- const handle = await open(path, 'r').catch(() => null)+ const handle = await open(path, 'r').catch(error => { externalReadFailed(error, 'file'); return null })if (!handle) return ''try {const { size } = await handle.stat()@@ -55,14 +56,17 @@ export async function firstLine(path: string, bytes: number): Promise<string | n/** A file's text, or '' when it is missing or unreadable. */export async function readText(path: string): Promise<string> {- return readFile(path, 'utf8').catch(() => '')+ return readFile(path, 'utf8').catch(error => { externalReadFailed(error, 'file'); return '' })}/** A JSON file's value, or null when it is missing, unreadable or being written. */export async function readJson(path: string): Promise<unknown> {try {- return JSON.parse(await readFile(path, 'utf8'))- } catch {+ const value: unknown = JSON.parse(await readFile(path, 'utf8'))+ if (value === null) externalReadFailed(new Error('null document'), 'record')+ return value+ } catch (error) {+ externalReadFailed(error, 'record')return null}}@@ -78,7 +82,7 @@ export function parseLine(line: string): unknown {/** A file's size and change time, the fingerprint a memo is keyed on; null when it is not a file. */export async function fileStamp(path: string): Promise<{ stamp: string; mtime: number } | null> {- const info = await stat(path).catch(() => null)+ const info = await stat(path).catch(error => { externalReadFailed(error, 'file metadata'); return null })if (!info?.isFile()) return nullreturn { stamp: `${info.size}:${info.mtimeMs}`, mtime: Math.floor(info.mtimeMs) }}@@ -174,7 +178,10 @@ type Run = (command: string, args: readonly string[], timeout: number) => Promis/** A command's output; what it printed even when it exits non-zero (lsof does, for a gone pid). */export const run: Run = (command, args, timeout) => new Promise((resolve) => {- execFile(command, [...args], { timeout, maxBuffer: 16 * 1024 * 1024 }, (error, stdout) => {+ execFile(command, [...args], { timeout, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {+ // lsof's documented empty match is exit 1 with no diagnostic. Timeouts, truncation and errors+ // remain unknown even if they produced a partial list; display callers retain their old answer.+ if (error && !(command === 'lsof' && Number(error.code) === 1 && !stderr)) externalReadFailed(error, 'process files')resolve(error && !stdout ? null : String(stdout))})})@@ -209,9 +216,13 @@ export function parseTtys(stdout: string): Map<number, string | null> {* none when `ps` could not be read. */export async function listProcesses(read: typeof processRows = processRows): Promise<RunningProcess[]> {const rows = await read()+ if (!rows) externalReadFailed(new Error('process table unavailable'), 'process table')return (rows ?? []).map((row) => {const started = Date.parse(row.startMarker)- return { pid: row.pid, ppid: row.parentPid, executable: row.executable, args: row.args, ...(Number.isFinite(started) ? { started } : {}) }+ return { pid: row.pid, ppid: row.parentPid, executable: row.executable, args: row.args,+ ...(Number.isFinite(started) ? { started } : {}),+ ...(row.startTicks !== undefined ? { generation: `linux:${row.startTicks}` }+ : Number.isFinite(started) ? { generation: `ps:${started}` } : {}) }})}@@ -262,7 +273,7 @@ export async function harnessTtys(): Promise<Set<string> | null> {const format = `#{pane_tty}\t#{session_name}\t${paneOwnerFormat(paneOptions ?? (await tmuxFeatures()).paneOptions)}`const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', format], 3_000)- if (failed && !/no server running|error connecting to/i.test(stderr)) return null+ if (failed && !/no server running|error connecting to .*\(No such file or directory\)/i.test(stderr)) return nullconst ttys = new Set<string>()for (const line of stdout.split('\n')) {const [tty, session, tag] = line.split('\t')diff --git a/cli/src/lib/sessionSearch/externals/types.ts b/cli/src/lib/sessionSearch/externals/types.tsindex 82548866c..1623010ee 100644--- a/cli/src/lib/sessionSearch/externals/types.ts+++ b/cli/src/lib/sessionSearch/externals/types.ts@@ -81,6 +81,8 @@ export interface RunningProcess {* the process named in it was left by another process that once had the same pid.*/started?: number+ /** Stable across wall-clock corrections on Linux; otherwise the locale-pinned process start. */+ generation?: string}/** What a provider may ask about the machine's processes. One view serves one look. */@@ -117,4 +119,7 @@ export interface ExternalProvider {owners?(view: ProcessView): Promise<OwnerClaim[]>/** Whether the owner is mid-turn; null when the engine's store cannot say. */busy?(owner: { pid: number; record: string }): Promise<boolean | null>+ /** Final admission proof from one coherent record: exact ownership and activity together.+ * Separate process/file reads cannot prove idle. Missing support means unknown, never idle. */+ confirmOwner?(owner: OwnerClaim, process: RunningProcess | null): Promise<{ current: boolean; busy: boolean | null } | null>}diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.tsindex 31713a07a..a1a5ba544 100644--- a/cli/src/lib/stopAgentService.spec.ts+++ b/cli/src/lib/stopAgentService.spec.ts@@ -245,3 +245,41 @@ it('does not forget a new agent published while its old pane was being retired',await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('changed while pausing')expect(deps.forgetSession).not.toHaveBeenCalled()})++it('cancels an external intent through core without archiving, signalling or waiting for search', async () => {+ Object.assign(row, { sessionId: '', processIdentity: null, launch: { state: 'held', service: 'search', detail: 'Reader unavailable' },+ externalResume: { phase: 'waiting' } })+ deps.cancelExternal = vi.fn(async (entry, current) => { expect(entry).toBe(row); expect(current()).toBe(true); return true })+ const save = vi.spyOn(stoppedAgents, 'save')+ await createStopAgentService(deps)(row.agentId)+ expect(deps.cancelExternal).toHaveBeenCalledOnce()+ expect(save).not.toHaveBeenCalled()+ expect(captureResumeIdentity).not.toHaveBeenCalled()+ expect(terminateDeletedAgent).not.toHaveBeenCalled()+ expect(deps.stopNative).not.toHaveBeenCalled()+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()+ expect(deps.forgetSession).not.toHaveBeenCalled()+})++it.each(['missing', 'refused', 'error', 'unknown', 'cancelled'] as const)('keeps an external intent intact when cancellation is %s', async failure => {+ Object.assign(row, { sessionId: '', processIdentity: null, launch: { state: 'held', service: 'search', detail: 'Reader unavailable' },+ externalResume: { phase: 'waiting' } })+ if (failure !== 'missing') deps.cancelExternal = vi.fn(async (_entry, current) => {+ if (failure === 'error') throw new Error('Journal is unavailable')+ if (failure === 'unknown') throw 'unavailable'+ if (failure === 'cancelled') { expect(current()).toBe(false); return current() }+ return false+ })+ const save = vi.spyOn(stoppedAgents, 'save')+ await expect(createStopAgentService(deps)(row.agentId, { current: () => failure !== 'cancelled' }))+ .rejects.toMatchObject({ code: 'STOP_UNCONFIRMED', message: failure === 'error' ? 'Journal is unavailable'+ : failure === 'unknown' ? 'Adoption could not be cancelled.' : 'Adoption cancellation is unavailable.' })+ expect(registry.byAgent(row.agentId)).toBe(row)+ expect(deps.stopJobs.size).toBe(0)+ expect(save).not.toHaveBeenCalled()+ expect(captureResumeIdentity).not.toHaveBeenCalled()+ expect(terminateDeletedAgent).not.toHaveBeenCalled()+ expect(deps.stopNative).not.toHaveBeenCalled()+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled()+ expect(deps.forgetSession).not.toHaveBeenCalled()+})diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.tsindex ad6ce575a..6df0c78fa 100644--- a/cli/src/lib/stopAgentService.ts+++ b/cli/src/lib/stopAgentService.ts@@ -1,4 +1,5 @@/** Stop retains the logical session before retiring its process and terminal. */+import { externalResumePending } from './externalResume.js'import { captureResumeIdentity } from './captureResumeIdentity.js'import { isTerminalEngine } from '../engines/types.js'import type { registry as liveRegistry, RegisteredSession } from './registry.js'@@ -11,6 +12,7 @@ import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.jsexport interface StopAgentServiceDeps {settlePane?: (agentId: string) => Promise<void>+ cancelExternal?: (entry: RegisteredSession, current: () => boolean) => Promise<boolean>registry: Pick<typeof liveRegistry, 'resolve'>stoppedAgents: StoppedAgentStorerestartJobs: AgentRestartCoordinator@@ -66,6 +68,12 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {await deps.settlePane?.(sessionId)const live = registry.resolve(sessionId)if (!live) return+ if (externalResumePending(live.externalResume)) {+ try {+ if (!deps.cancelExternal || !await deps.cancelExternal(live, () => options.current?.() !== false)) throw new Error('Adoption cancellation is unavailable.')+ } catch (error) { throw new AgentStopError(error instanceof Error ? error.message : 'Adoption could not be cancelled.') }+ return+ }// A row still starting has no process yet, and the one it gains while this stop runs is the engine// it launched, not a replacement. Comparing it refused every Stop pressed on a starting agent with// "Harness changed… Try stopping again" (e2e/races.e2e.ts). The process is still checked exactlydiff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 346818e17..9e3a97984 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -60,6 +60,8 @@ export type TerminalActionResult =export interface TerminalDispatchControl {current?: () => booleanonDispatch?: () => void+ /** A held adoption may replace only its exact inert shell, checked inside tmux. */+ expectedHeldToken?: string}export interface TerminalCreateRequest extends TerminalDispatchControl {diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex fc2970ae1..fb06a241f 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -226,6 +226,8 @@ esac// exact-pane check must see it and refuse a false successful pause.const discovery = vi.spyOn(backend, 'inventory').mockResolvedValue({ state: 'available', roots: [] })expect((await backend.kill({ backend: 'tmux', paneId: '%42' })).state).toBe(mode === 'gone' || mode === 'no server' || mode === 'no socket' ? 'succeeded' : 'unknown')+ expect((await backend.killHeld({ backend: 'tmux', paneId: '%42' }, '12345678-1234-1234-1234-123456789012', () => true)).state)+ .toBe(mode === 'gone' || mode === 'no server' || mode === 'no socket' ? 'succeeded' : 'failed')expect(discovery).not.toHaveBeenCalled()})diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex cd27f28e0..04f345644 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -1,4 +1,5 @@import { execFile } from 'node:child_process'+import { shellSingleQuote } from './shellQuote.js'import { patientExec } from './patientExec.js'import type { TerminalBackend } from './terminalBackend.js'import {@@ -249,20 +250,26 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// The engine-exit marker is the pane's, and a respawned pane is a new launch: cleared here, in// the same invocation, or the new engine would read as exited the moment it started. A `-p` here// before tmux 3.0 failed the whole list, the respawn with it, so no agent could restart there.- const args = [- 'set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on', ';',- 'set-option', scope, '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, '', ';',- 'respawn-pane', '-k',+ const setup = [+ ['set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on'],+ ['set-option', scope, '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, ''],]+ const args = ['respawn-pane', '-k']if (request.cwd) args.push('-c', request.cwd)for (const [key, value] of variables) args.push('-e', `${key}=${value}`)// A respawn replaces the pane's start command, which carries its tag before tmux 3.0 (`create`).args.push('-t', runtime.paneId, ...this.ownedCommand(features, this.owner(), request.command))+ const commands = [...setup, args]+ if (request.expectedHeldToken && !/^[a-f0-9-]{36}$/.test(request.expectedHeldToken)) return terminalActionNotStarted('invalid waiting pane identity')+ const command = request.expectedHeldToken+ ? ['if-shell', '-F', '-t', runtime.paneId, `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${request.expectedHeldToken}*,#{pane_start_command}}}`,+ commands.map(parts => parts.map(shellSingleQuote).join(' ')).join('; '), 'display-message -p adoption-mismatch']+ : commands.flatMap((parts, index) => index ? [';', ...parts] : parts)const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {if (request.current?.() === false) { resolve({ error: Object.assign(new Error('The harness changed before pane dispatch'), { code: 'HARNESS_CANCELLED' }), stderr: '' }); return }request.onDispatch?.()- run('tmux', args, { timeout: 5_000 }, (error, _stdout, stderr) => resolve({- error: error as NodeJS.ErrnoException | null,+ run('tmux', command, { timeout: 5_000 }, (error, stdout, stderr) => resolve({+ error: stdout.trim() === 'adoption-mismatch' ? Object.assign(new Error('The waiting pane changed'), { code: 'HARNESS_CANCELLED' }) : error as NodeJS.ErrnoException | null,stderr,}))})@@ -275,6 +282,33 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return terminalActionPossiblyExecuted(`tmux could not respawn the pane: ${detail}`)}+ /** Read only. The dispatch repeats this predicate inside tmux; this read grants no later write. */+ async isHeld(runtime: TmuxRuntimeRef, token: string): Promise<boolean | 'unknown'> {+ if (!/^%\d+$/.test(runtime.paneId) || !/^[a-f0-9-]{36}$/.test(token)) return 'unknown'+ return new Promise(resolve => run('tmux', ['display-message', '-p', '-t', runtime.paneId,+ `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${token}*,#{pane_start_command}}}`], { timeout: 2_000 }, (error, stdout) => {+ if (error) { resolve(isNoTmuxServerError(error.message) || /can't find pane: %\d+/.test(error.message) ? false : 'unknown'); return }+ resolve(stdout.trim() === '1' ? true : stdout.trim() === '0' ? false : 'unknown')+ }))+ }++ /** A pending adoption may close only its own inert shell, even after tmux recycled the pane ID. */+ async killHeld(runtime: TmuxRuntimeRef, token: string, current: () => boolean): Promise<TerminalActionResult> {+ if (!/^%\d+$/.test(runtime.paneId) || !/^[a-f0-9-]{36}$/.test(token)) return terminalActionNotStarted('invalid waiting pane identity')+ const result = await inTmuxRoom('notify', () => new Promise<{ error: Error | null; stdout: string }>(resolve => {+ if (!current()) { resolve({ error: new Error('Adoption changed before pane close'), stdout: '' }); return }+ // Evaluated inside the tmux server, in the same command that kills: no check/use gap for %N.+ run('tmux', ['if-shell', '-F', '-t', runtime.paneId, `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${token}*,#{pane_start_command}}}`,+ `kill-pane -t ${runtime.paneId}`, 'display-message -p adoption-mismatch'], { timeout: 5_000 },+ (error, stdout) => resolve({ error, stdout }))+ }))+ if (!result.error && !result.stdout.trim() || result.error && (isNoTmuxServerError(result.error.message) || /can't find pane: %\d+/.test(result.error.message))) return TERMINAL_ACTION_SUCCEEDED+ // if-shell can evaluate against the active pane when its target has already gone. A mismatch+ // is an idempotent close only when an authoritative inventory confirms this exact pane is gone.+ if (await this.paneAbsent(runtime)) return TERMINAL_ACTION_SUCCEEDED+ return terminalActionNotStarted('The waiting pane no longer has this adoption identity')+ }+async kill(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {if (!/^%\d+$/.test(runtime.paneId)) return terminalActionNotStarted('invalid tmux pane identity')// Discovered harnesses can share a tmux session with unrelated work. The@@ -289,7 +323,12 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// check completed. Only authoritative inventory makes that an idempotent success.// Use all panes here: discovery deliberately hides sessions that were renamed// or created elsewhere, and their absence from discovery is not proof of exit.- const absent = await new Promise<boolean>(resolve => {+ if (await this.paneAbsent(runtime)) return TERMINAL_ACTION_SUCCEEDED+ return legacyActionResult(false, 'tmux pane close')+ }++ private paneAbsent(runtime: TmuxRuntimeRef): Promise<boolean> {+ return new Promise<boolean>(resolve => {run('tmux', ['list-panes', '-a', '-F', '#{pane_id}'], { timeout: 2_000 }, (error, stdout) => {if (error) { resolve(isNoTmuxServerError(error.message)); return }const ids = stdout.trim().split('\n').filter(Boolean)@@ -297,8 +336,6 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {resolve(ids.length > 0 && ids.every(id => /^%\d+$/.test(id)) && !ids.includes(runtime.paneId))})})- if (absent) return TERMINAL_ACTION_SUCCEEDED- return legacyActionResult(false, 'tmux pane close')}/**diff --git a/cli/src/lib/tmuxExternalAdoption.spec.ts b/cli/src/lib/tmuxExternalAdoption.spec.tsnew file mode 100644index 000000000..6d9fedad5--- /dev/null+++ b/cli/src/lib/tmuxExternalAdoption.spec.ts@@ -0,0 +1,65 @@+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { randomUUID } from 'node:crypto'+import { mkdirSync, readFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'+import { resolveBinaryOnPath } from './binaryOnPath.js'+import { TmuxBackend } from './tmuxBackend.js'+import { heldPaneArgv } from '../core/agents/heldLaunches.js'+import { resetTmuxVersionCache } from './tmuxVersion.js'++// Every command, including bare calls from the backend, uses this fixture's captured private socket.+// Neither TMUX nor the default socket inherited from a coding session may take precedence.+describe.skipIf(!resolveBinaryOnPath('tmux'))('external adoption on a private tmux server', () => {+ let tmux: IsolatedTmux+ let home: string+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'adoption-tmux-home-'))+ vi.stubEnv('HOME', home); vi.stubEnv('ZDOTDIR', home)+ tmux = await isolatedTmux()+ vi.stubEnv('TMUX', undefined); vi.stubEnv('TMUX_PANE', undefined); vi.stubEnv('TMUX_TMPDIR', tmux.root)+ resetTmuxVersionCache()+ // Start with the helper's explicit empty config before any bare backend call can create it.+ await tmux.run('new-session', '-d', '-s', 'fixture-anchor', '/bin/sleep', '300')+ })+ afterAll(async () => { await tmux?.close(); if (home) rmSync(home, { recursive: true, force: true }); vi.unstubAllEnvs(); resetTmuxVersionCache() })+ const backend = new TmuxBackend(undefined, () => 'adoption-test', () => {})+ const waiting = async (token: string) => {+ const pane = await backend.create({ label: `harness-fixture-${randomUUID()}`, command: heldPaneArgv('Waiting for fixture.', token) })+ if (pane.state !== 'succeeded') throw new Error(pane.reason)+ return pane.runtime+ }++ it('atomically requires the waiting token and preserves literal argv, environment and cwd in its dispatch', async () => {+ const token = randomUUID(), pane = await waiting(token), onDispatch = vi.fn()+ const folder = join(tmux.root, "work '; dollars$"); mkdirSync(folder)+ const output = join(tmux.root, 'literal-result'), value = "an apostrophe ' and ; $literal"+ const request = { command: ['/bin/sh', '-c', 'printf "%s\\n" "$SAMPLE" "$PWD" "$1" > "$2"; exec sleep 30', 'fixture', value, output],+ cwd: folder, env: { SAMPLE: value }, expectedHeldToken: randomUUID(), current: () => true, onDispatch }+ expect(await backend.isHeld(pane, token)).toBe(true)+ expect(await backend.respawn(pane, request)).toMatchObject({ dispatch: 'not_started' })+ expect(existsSync(output)).toBe(false)+ expect(await backend.isHeld(pane, token)).toBe(true)+ expect(await backend.respawn(pane, { ...request, expectedHeldToken: token })).toMatchObject({ state: 'succeeded' })+ await vi.waitFor(() => expect(existsSync(output)).toBe(true))+ expect(readFileSync(output, 'utf8').split('\n')).toEqual([value, folder, value, ''])+ expect(await backend.isHeld(pane, token)).toBe(false)+ expect(await backend.killHeld(pane, token, () => true)).toMatchObject({ dispatch: 'not_started' })+ await backend.kill(pane)+ })++ it('cannot cancel a replacement waiting shell, and an uncommitted dispatch never replaces its pane', async () => {+ const token = randomUUID(), next = randomUUID(), pane = await waiting(token)+ await expect(backend.respawn(pane, { command: ['/bin/false'], expectedHeldToken: token, onDispatch: () => { throw new Error('disk full') } })).rejects.toThrow('disk full')+ expect(await backend.isHeld(pane, token)).toBe(true)+ expect(await backend.respawn(pane, { command: ['/bin/false'], expectedHeldToken: token, current: () => false })).toMatchObject({ dispatch: 'not_started' })+ expect(await backend.killHeld(pane, token, () => false)).toMatchObject({ dispatch: 'not_started' })+ expect(await backend.respawn(pane, { command: heldPaneArgv('Replacement intent.', next), expectedHeldToken: token })).toMatchObject({ state: 'succeeded' })+ expect(await backend.killHeld(pane, token, () => true)).toMatchObject({ dispatch: 'not_started' })+ expect(await backend.isHeld(pane, next)).toBe(true)+ expect(await backend.killHeld(pane, next, () => true)).toMatchObject({ state: 'succeeded' })+ expect(await backend.isHeld(pane, next)).toBe(false)+ expect(await backend.killHeld(pane, next, () => true)).toMatchObject({ state: 'succeeded' })+ })+})diff --git a/cli/src/services/devicesProcess.spec.ts b/cli/src/services/devicesProcess.spec.tsindex 42cbe3df8..ee528bcc2 100644--- a/cli/src/services/devicesProcess.spec.ts+++ b/cli/src/services/devicesProcess.spec.ts@@ -229,7 +229,6 @@ describe('the core\'s doors, across the link', () => {])// What the devices never ask answers as every other service's does.expect(api.transcripts.databaseHistory({} as RegisteredSession)).toBeUndefined()- expect(api.external.sessions.list()).toEqual([])await expect(api.account.mintGridName()).resolves.toBeNull()// Gone from the core: told nothing, and a bridge's ask says it did not go.f.options().onDisconnected!()diff --git a/cli/src/services/devicesProcess.ts b/cli/src/services/devicesProcess.tsindex 04d6167ef..711639266 100644--- a/cli/src/services/devicesProcess.ts+++ b/cli/src/services/devicesProcess.ts@@ -145,7 +145,6 @@ export function runDevicesService(options: DevicesServiceOptions): ServiceProcesanswerReviewed: async (answer) => (await ask('answerReviewed', { answer })).ok === true,},transcripts: unasked.transcripts,- external: unasked.external,account: {...unasked.account,// The core's sign-in and the gateway's seal, asked at every use: this process holds no credential anddiff --git a/cli/src/services/externalSessions.providers.spec.ts b/cli/src/services/externalSessions.providers.spec.tsnew file mode 100644index 000000000..4ebd5dac6--- /dev/null+++ b/cli/src/services/externalSessions.providers.spec.ts@@ -0,0 +1,109 @@+/** Real provider records cross the admission service; no host processes or native homes are used. */+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it } from 'vitest'+import { claudeProvider } from '../lib/sessionSearch/externals/claude.js'+import { codexProvider } from '../lib/sessionSearch/externals/codex.js'+import { grokProvider } from '../lib/sessionSearch/externals/grok.js'+import type { ProcessView, RunningProcess } from '../lib/sessionSearch/externals/types.js'+import { createExternalSessions } from './externalSessions.js'++const roots: string[] = []+afterEach(() => { for (const path of roots.splice(0)) rmSync(path, { recursive: true, force: true }) })+const id = '11111111-1111-4111-8111-111111111111', started = 1_787_839_600_000+const json = (path: string, value: unknown) => { mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value) + '\n') }+function setup(engine: 'claude' | 'grok') {+ const root = mkdtempSync(join(tmpdir(), 'adoption-provider-')); roots.push(root)+ const cwd = join(root, 'project'); mkdirSync(cwd)+ const process: RunningProcess = { pid: 101, ppid: 1, executable: engine, args: engine, started, generation: `ps:${started}` }+ const view: ProcessView = { list: async () => [process], alive: pid => pid === 101,+ openFiles: async () => new Map(), openFilesOf: async () => new Map() }+ const path = engine === 'claude' ? join(root, 'sessions', '101.json') : join(root, 'active_sessions.json')+ if (engine === 'claude') json(join(root, 'projects', 'project', `${id}.jsonl`), {+ type: 'user', sessionId: id, cwd, entrypoint: 'cli', message: { role: 'user', content: 'Fixture' },+ })+ else {+ const folder = join(root, 'sessions', encodeURIComponent(cwd), id)+ json(join(folder, 'summary.json'), { info: { id, cwd }, generated_title: 'Fixture' })+ json(join(folder, 'prompt_context.json'), { audience: 'primary', is_non_interactive: false, working_directory: cwd })+ json(join(folder, 'updates.jsonl'), { method: 'session/update', params: { sessionId: id,+ update: { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'Fixture' } } } })+ }+ const provider = engine === 'claude' ? claudeProvider({ projectsDir: join(root, 'projects'), home: root }) : grokProvider({ home: root })+ const reader = createExternalSessions({ providers: [provider], generation: () => `ps:${started}`,+ open: { view: () => ({ ...view }), ttys: async () => new Map([[101, '/dev/fixture-terminal']]), harnessTtys: async () => new Set() } })+ const write = (record: unknown) => json(path, engine === 'claude' ? record : [record])+ const valid = engine === 'claude' ? { pid: 101, sessionId: id, startedAt: started + 400, status: 'idle' }+ : { pid: 101, session_id: id, opened_at: started + 400, cwd }+ write(valid)+ return { reader, provider, process, write, valid, request: { engine, sessionId: id } }+}++it.each(['claude', 'grok'] as const)('%s admission requires complete owner records and incarnation evidence', async engine => {+ const test = setup(engine)+ expect(await test.reader.inspect(test.request)).toMatchObject({ ok: true, owner: { pid: 101 } })+ const time = engine === 'claude' ? 'startedAt' : 'opened_at', session = engine === 'claude' ? 'sessionId' : 'session_id'+ for (const value of [undefined, null, 'invalid', Number.NaN, Number.POSITIVE_INFINITY]) {+ test.write({ ...test.valid, [time]: value })+ expect(await test.reader.inspect(test.request), `${time}=${value}`).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+ }+ for (const value of [undefined, '', 'invalid id!', 42]) {+ test.write({ ...test.valid, [session]: value })+ expect(await test.reader.inspect(test.request), `${session}=${value}`).toMatchObject({ ok: false })+ }+ for (const value of [undefined, '101', 0, -1, 1.5, 0x80000000]) {+ test.write({ ...test.valid, pid: value })+ expect(await test.reader.inspect(test.request), `pid=${value}`).toMatchObject({ ok: false })+ }+ test.write(test.valid)+ for (const value of [undefined, Number.NaN, Number.POSITIVE_INFINITY]) {+ test.process.started = value+ expect(await test.reader.inspect(test.request), `process.started=${value}`).toMatchObject({ ok: false })+ }+ test.process.started = started + 60_000+ expect(await test.reader.inspect(test.request)).toMatchObject({ ok: false })+ test.process.executable = 'sh'; test.process.args = 'sh'+ expect(await test.reader.inspect(test.request)).toMatchObject({ ok: true, owner: null })+})++it('Claude proves current ownership and activity in one final record; changed or incomplete records cannot grant idle takeover', async () => {+ const test = setup('claude'), confirm = test.provider.confirmOwner!.bind(test.provider)+ test.provider.confirmOwner = async (owner, process) => {+ test.write({ ...test.valid, status: 'busy' })+ return confirm(owner, process)+ }+ expect(await test.reader.inspect(test.request)).toMatchObject({ ok: true, busy: true, busyConfirmed: true })+ for (const patch of [{ sessionId: '22222222-2222-4222-8222-222222222222' }, { pid: 102 }, { startedAt: undefined }, { startedAt: started - 60_000 }]) {+ test.write(test.valid)+ test.provider.confirmOwner = async (owner, process) => { test.write({ ...test.valid, ...patch }); return confirm(owner, process) }+ expect(await test.reader.inspect(test.request)).toMatchObject({ ok: false })+ }+ test.write(test.valid)+ test.provider.confirmOwner = async (owner, process) => { test.write({ ...test.valid, status: 'unreadable' }); return confirm(owner, process) }+ const unknown = await test.reader.inspect(test.request)+ expect(unknown).toMatchObject({ ok: true, busy: true })+ expect(unknown).not.toHaveProperty('busyConfirmed')+})++it('Codex FD claims require an actual engine process; a command-prefix helper is never stoppable', async () => {+ const root = mkdtempSync(join(tmpdir(), 'adoption-codex-')); roots.push(root)+ const cwd = join(root, 'project'); mkdirSync(cwd)+ const file = join(root, 'sessions', 'rollout-2026-10-09T00-00-00-' + id + '.jsonl')+ json(file, { type: 'session_meta', payload: { id, cwd, source: 'cli' } })+ const process: RunningProcess = { pid: 101, ppid: 1, executable: '/fixture/codex-audit', args: '/fixture/codex-audit --read-history', started }+ let listed = true, alive = true+ const view: ProcessView = { list: async () => listed ? [process] : [], alive: () => alive,+ openFiles: async () => new Map(), openFilesOf: async () => new Map([[101, [file]]]) }+ const reader = createExternalSessions({ providers: [codexProvider({ home: root })], generation: () => `ps:${started}`,+ open: { view: () => ({ ...view }), ttys: async () => new Map([[101, '/dev/fixture-terminal']]), harnessTtys: async () => new Set() } })+ const request = { engine: 'codex' as const, sessionId: id }+ expect(await reader.inspect(request)).toMatchObject({ ok: false })+ process.executable = 'codex'; process.args = 'codex'+ listed = false; expect(await reader.inspect(request)).toMatchObject({ ok: false })+ listed = true; alive = false; expect(await reader.inspect(request)).toMatchObject({ ok: false })+ alive = true+ const valid = await reader.inspect(request)+ expect(valid).toMatchObject({ ok: true, owner: { pid: 101 }, busy: true })+ expect(valid).not.toHaveProperty('busyConfirmed')+})diff --git a/cli/src/services/externalSessions.spec.ts b/cli/src/services/externalSessions.spec.tsnew file mode 100644index 000000000..0340f6037--- /dev/null+++ b/cli/src/services/externalSessions.spec.ts@@ -0,0 +1,216 @@+import { expect, it, vi } from 'vitest'+import { createExternalSessions } from './externalSessions.js'+import { externalReadFailed } from '../lib/sessionSearch/evidence.js'+import { externalProcessGeneration } from '../lib/externalProcessGeneration.js'+import { processView, processTtys, harnessTtys } from '../lib/sessionSearch/externals/support.js'+import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from '../lib/sessionSearch/externals/types.js'+vi.mock('../lib/externalProcessGeneration.js', () => ({ externalProcessGeneration: vi.fn(() => 'ps:1000') }))+vi.mock('../lib/sessionSearch/externals/support.js', async original => ({ ...await original<object>(),+ processView: vi.fn(), processTtys: vi.fn(), harnessTtys: vi.fn() }))++const target = { sessionId: 'conversation', engine: 'claude' as const }+const session: ExternalSession = { ...target, cwd: '/workspace', origin: 'terminal', title: '', mtime: 10, transcriptPath: '/store/conversation.jsonl' }+function fixture() {+ const claim: OwnerClaim = { sessionId: target.sessionId, pid: 7, record: '/store/process.json' }+ const provider: ExternalProvider = { engine: 'claude', scan: vi.fn(async () => [session]), owners: vi.fn(async () => []),+ confirmOwner: vi.fn(async () => ({ current: true, busy: false })) }+ const view: ProcessView = { list: vi.fn(async () => [{ pid: 7, ppid: 1, executable: 'fixture', args: '', generation: 'ps:1000' }]),+ openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }+ const generation = vi.fn((): string | null => 'ps:1000')+ const options = { providers: [provider], generation, title: () => 'Indexed title',+ open: { view: () => view, ttys: vi.fn(async () => new Map([[7, '/dev/fixture-terminal']])), harnessTtys: vi.fn(async (): Promise<Set<string> | null> => new Set()) } }+ return { claim, provider, view, options, generation, reader: createExternalSessions(options) }+}++it.each(['terminal', 'activity'] as const)('rejects same-PID conversation changes during the %s read', async point => {+ const f = fixture()+ let finish!: () => void+ const gate = new Promise<void>(resolve => { finish = resolve })+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ if (point === 'terminal') f.options.open.ttys.mockImplementation(async () => { await gate; return new Map([[7, '/dev/fixture-terminal']]) })+ else vi.mocked(f.provider.confirmOwner!).mockImplementation(async () => { await gate; return { current: false, busy: false } })+ const answer = f.reader.inspect(target)+ await vi.waitFor(() => expect(point === 'terminal' ? f.options.open.ttys : f.provider.confirmOwner).toHaveBeenCalled())+ vi.mocked(f.provider.owners!).mockResolvedValue([{ ...f.claim, sessionId: 'another-conversation' }])+ finish()+ expect(await answer).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+})++it.each(['record', 'contender', 'app'] as const)('rejects %s owner evidence that changes while terminal evidence is read', async change => {+ const f = fixture()+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ f.options.open.ttys.mockImplementation(async () => {+ vi.mocked(f.provider.owners!).mockResolvedValue(change === 'record' ? [{ ...f.claim, record: '/other-record' }]+ : change === 'app' ? [{ ...f.claim, app: true }] : [f.claim, { ...f.claim, pid: 8 }])+ return new Map([[7, '/dev/fixture-terminal']])+ })+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+})++it('supplies fresh metadata and ownership without a SQLite index, preserving canonical aliases', async () => {+ const f = fixture()+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, session: { title: 'Indexed title' }, owner: null, busy: false })+ vi.mocked(f.provider.scan).mockResolvedValue([{ ...session, aliases: ['old'] }])+ expect(await f.reader.inspect({ ...target, sessionId: 'old' })).toMatchObject({ ok: true, session: { sessionId: 'conversation' } })+ vi.mocked(f.provider.scan).mockResolvedValue([])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, session: null })+ expect(await f.reader.inspect({})).toMatchObject({ ok: false })+ expect(await f.reader.inspect({ ...target, engine: 'codex' })).toMatchObject({ ok: false })+})++it('never uses last-good catalog data to authorize an unavailable reader', async () => {+ const f = fixture()+ await f.reader.sessions.scan()+ vi.mocked(f.provider.scan).mockImplementation(async () => { externalReadFailed({ code: 'EACCES' }); return [] })+ expect(f.reader.sessions.get('conversation')).toBeDefined()+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+ vi.mocked(f.provider.scan).mockRejectedValue(new Error('unloaded'))+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+})++it('uses the newest canonical record before aliases, exactly as the catalog does', async () => {+ const f = fixture()+ vi.mocked(f.provider.scan).mockResolvedValue([+ { ...session, cwd: '/older', mtime: 1 },+ { ...session, sessionId: 'other', aliases: ['conversation'], cwd: '/alias', mtime: 100 },+ { ...session, cwd: '/newest', mtime: 50 },+ ])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, session: { cwd: '/newest' } })+})++it('holds conflicting exact records/app evidence and missing terminal evidence', async () => {+ const f = fixture()+ for (const other of [{ ...f.claim, record: '/different' }, { ...f.claim, app: true }]) {+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim, other])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ }+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim, { ...f.claim }])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true })+ f.options.open.ttys.mockResolvedValue(new Map())+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+})++it.each(['initial', 'later'] as const)('holds a same-PID unrelated exact conversation seen in the %s ownership pass', async when => {+ const f = fixture(), both = [f.claim, { ...f.claim, sessionId: 'another-conversation', record: '/store/another.json' }]+ vi.mocked(f.provider.owners!).mockResolvedValue(both)+ if (when === 'later') vi.mocked(f.provider.owners!).mockResolvedValueOnce([f.claim])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+ expect(f.provider.confirmOwner).not.toHaveBeenCalled()+ // Startup arguments can name a previous conversation; they do not contradict an exact record.+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim, { ...both[1], fromArgs: true }])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true })+})++it('checks process generation after the activity read and treats tmux permission failure as unknown', async () => {+ const f = fixture()+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ vi.mocked(f.provider.confirmOwner!).mockImplementation(async () => { f.generation.mockReturnValue(null); return { current: true, busy: false } })+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ f.generation.mockReturnValue('ps:1000')+ vi.mocked(f.provider.confirmOwner!).mockResolvedValue({ current: true, busy: false })+ const { harnessTtys } = await vi.importActual<typeof import('../lib/sessionSearch/externals/support.js')>('../lib/sessionSearch/externals/support.js')+ f.options.open.harnessTtys.mockImplementation(() => harnessTtys(async () => ({ failed: true, stdout: '',+ stderr: 'error connecting to /fixture/socket (Permission denied)' }), true))+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, owner: { unverified: true } })+})++it('refuses unavailable or conflicting owners and changed process incarnations', async () => {+ const f = fixture()+ vi.mocked(f.provider.owners!).mockRejectedValueOnce(new Error('unreadable'))+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ vi.mocked(f.provider.owners!).mockResolvedValueOnce([f.claim, { ...f.claim, pid: 8 }])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ f.generation.mockReturnValue(null)+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ f.generation.mockReturnValue('ps:1000')+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, owner: { pid: 7 }, generation: 'ps:1000', busy: false })+ f.provider.owners = undefined+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+})++it('keeps app, argument-only, Harness and unverifiable pane owners distinguishable; unknown activity stays busy', async () => {+ const f = fixture()+ vi.mocked(f.provider.confirmOwner!).mockResolvedValue({ current: true, busy: true })+ for (const flags of [{ app: true }, { fromArgs: true }, {}]) {+ vi.mocked(f.provider.owners!).mockResolvedValue([{ ...f.claim, ...flags }])+ const answer = await f.reader.inspect(target)+ expect(answer).toMatchObject({ ok: true, owner: flags.app ? { tty: null } : flags.fromArgs ? { fromArgs: true } : { tty: '/dev/fixture-terminal' } })+ if (flags.app || flags.fromArgs) expect(answer).not.toHaveProperty('busyConfirmed')+ }+ f.options.open.harnessTtys.mockResolvedValue(new Set(['/dev/fixture-terminal']))+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, owner: { harness: true } })+ f.options.open.harnessTtys.mockResolvedValue(null)+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, owner: { unverified: true } })+ vi.mocked(f.provider.confirmOwner!).mockImplementation(async () => { externalReadFailed({ code: 'ENOENT' }); return { current: true, busy: false } })+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false })+ f.provider.confirmOwner = undefined+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true, busy: true })+})++it('reads coherent activity after a deferred second ownership pass and never turns unknown into an interrupted turn', async () => {+ const f = fixture()+ let finish!: () => void+ const gate = new Promise<void>(resolve => { finish = resolve })+ vi.mocked(f.provider.owners!).mockResolvedValueOnce([f.claim]).mockImplementationOnce(async () => { await gate; return [f.claim] })+ const reading = f.reader.inspect(target)+ await vi.waitFor(() => expect(f.provider.owners).toHaveBeenCalledTimes(2))+ vi.mocked(f.provider.confirmOwner!).mockResolvedValue({ current: true, busy: true })+ finish()+ expect(await reading).toMatchObject({ ok: true, busy: true, busyConfirmed: true })+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ for (const proof of [null, { current: true, busy: null }]) {+ vi.mocked(f.provider.confirmOwner!).mockResolvedValue(proof)+ const answer = await f.reader.inspect(target)+ expect(answer).toMatchObject({ ok: true, busy: true })+ expect(answer).not.toHaveProperty('busyConfirmed')+ }+})++it('uses fresh provider facts after cold discovery finds an ID from another engine', async () => {+ for (const result of ['found', 'missing', 'failed'] as const) {+ const f = fixture()+ vi.mocked(f.provider.scan).mockResolvedValue([])+ const other: ExternalProvider = { engine: 'codex', scan: vi.fn(async () => [{ ...session, engine: 'codex' as const }]) }+ vi.mocked(other.scan).mockImplementationOnce(async () => [{ ...session, engine: 'codex' }])+ if (result === 'missing') vi.mocked(other.scan).mockResolvedValue([])+ if (result === 'failed') vi.mocked(other.scan).mockImplementation(async () => { throw new Error('reader failed') })+ const reader = createExternalSessions({ ...f.options, providers: [f.provider, other] })+ expect(await reader.inspect(target)).toMatchObject(result === 'failed' ? { ok: false } :+ { ok: true, session: result === 'missing' ? null : { engine: 'codex' } })+ expect(other.scan).toHaveBeenCalledTimes(2)+ }+})++it('bounds the actual provider reads even when callers give up waiting', async () => {+ const f = fixture(), finish: Array<(sessions: ExternalSession[]) => void> = []+ vi.mocked(f.provider.scan).mockImplementation(() => new Promise(resolve => finish.push(resolve)))+ const pending = Array.from({ length: 4 }, () => f.reader.inspect(target))+ expect(await f.reader.inspect(target)).toMatchObject({ ok: false, detail: expect.stringContaining('finish verifying') })+ expect(f.provider.scan).toHaveBeenCalledTimes(4)+ for (const resolve of finish) resolve([session])+ expect((await Promise.all(pending)).every(answer => answer.ok)).toBe(true)+ vi.mocked(f.provider.scan).mockResolvedValue([session])+ expect(await f.reader.inspect(target)).toMatchObject({ ok: true })+})++it('rechecks the OS incarnation from its snapshot using default readers and preserves unknown terminals', async () => {+ const f = fixture()+ vi.mocked(processView).mockReturnValue(f.view)+ vi.mocked(processTtys).mockResolvedValue(new Map([[7, '/dev/fixture-terminal']]))+ vi.mocked(harnessTtys).mockResolvedValue(new Set())+ vi.mocked(externalProcessGeneration).mockReturnValue('ps:1000')+ vi.mocked(f.provider.owners!).mockResolvedValue([f.claim])+ const reader = createExternalSessions({ providers: [f.provider] })+ expect(await reader.inspect(target)).toMatchObject({ ok: true, generation: 'ps:1000', session: { title: '' } })+ vi.mocked(externalProcessGeneration).mockReturnValue('ps:2000')+ expect(await reader.inspect(target)).toMatchObject({ ok: false })+ vi.mocked(f.view.list).mockResolvedValue([{ pid: 7, ppid: 1, executable: 'fixture', args: '' }])+ expect(await reader.inspect(target)).toMatchObject({ ok: false })+ vi.mocked(f.view.list).mockResolvedValue([])+ expect(await reader.inspect(target)).toMatchObject({ ok: false })+ vi.mocked(processTtys).mockResolvedValue(new Map([[7, null]]))+ expect(await reader.inspect(target)).toMatchObject({ ok: true, owner: { tty: null } })+ vi.mocked(f.provider.owners!).mockResolvedValue([{ ...f.claim, pid: 0 }])+ expect(await reader.inspect(target)).toMatchObject({ ok: false })+})diff --git a/cli/src/services/externalSessions.ts b/cli/src/services/externalSessions.tsnew file mode 100644index 000000000..a007c4d52--- /dev/null+++ b/cli/src/services/externalSessions.ts@@ -0,0 +1,114 @@+/** Search owns external readers even when its optional SQLite index cannot open. */+import { externalProcessGeneration } from '../lib/externalProcessGeneration.js'+import { externalSessionAnswer, externalSessionRequest, externalUnavailable,+ type ExternalSessionAnswer } from '../lib/externalSessionWire.js'+import { ExternalSessions, OpenSessions, externalSessionCatalog, type ExternalSessionsOptions, type OpenSessionsOptions,+ type SessionOwner } from '../lib/sessionSearch/external.js'+import { externalEvidence } from '../lib/sessionSearch/evidence.js'+import { harnessTtys, processTtys, processView, scanMemo } from '../lib/sessionSearch/externals/support.js'+import type { OwnerClaim, RunningProcess } from '../lib/sessionSearch/externals/types.js'++export interface ExternalReaderOptions extends ExternalSessionsOptions {+ open?: Omit<OpenSessionsOptions, 'providers'>+ /** Process snapshot plus a second incarnation check. Tests provide private synthetic processes. */+ generation?: (pid: number, processes: readonly RunningProcess[]) => string | null+ title?: (sessionId: string) => string | undefined+}++export function createExternalSessions(options: ExternalReaderOptions) {+ const sessions = new ExternalSessions(options)+ const open = new OpenSessions({ ...options.open, providers: options.providers })+ const generation = options.generation ?? ((pid, processes) => {+ const expected = processes.find(row => row.pid === pid)?.generation+ return expected && externalProcessGeneration(pid) === expected ? expected : null+ })+ const inspectOne = async (payload: unknown): Promise<ExternalSessionAnswer> => {+ const request = externalSessionRequest(payload)+ if (!request) return externalUnavailable('The conversation request could not be verified.')+ // A catalog alias can name another engine. Re-read that provider rather than admit stale display data.+ const known = sessions.get(request.sessionId)+ let provider = options.providers.find(p => p.engine === (known?.engine ?? request.engine))+ if (!provider) return externalUnavailable('The conversation reader is unavailable.')+ const initialProvider = provider+ let found = await externalEvidence(async () => {+ const rows = await initialProvider.scan(scanMemo({ excluded: options.excluded ?? [] }).context())+ return externalSessionCatalog(rows).byId.get(request.sessionId) ?? null+ })+ if (!found.ok) return externalUnavailable(found.detail)+ if (!found.value) {+ // A cold catalog may not yet know that the requested ID belongs to another engine. Refresh+ // its display discovery, then re-read that provider before returning a wrong-engine fact.+ await sessions.scan()+ const elsewhere = sessions.get(request.sessionId)+ const other = elsewhere && options.providers.find(candidate => candidate.engine === elsewhere.engine)+ if (other) {+ provider = other+ found = await externalEvidence(async () => externalSessionCatalog(await other.scan(scanMemo({ excluded: options.excluded ?? [] }).context())).byId.get(request.sessionId) ?? null)+ if (!found.ok) return externalUnavailable(found.detail)+ }+ }+ const session = found.value+ if (!session || session.engine !== request.engine || session.archived) return externalSessionAnswer({+ ok: true, request, session, owner: null, generation: null, busy: false,+ }, request)+ if (!provider.owners) return externalUnavailable('The conversation owner could not be verified.')+ const observed = await externalEvidence(async () => {+ const view = (options.open?.view ?? processView)()+ // The process table precedes ownership evidence, so a recycled PID cannot inherit that evidence.+ const processes = await view.list()+ const matching = (claims: readonly OwnerClaim[]) => claims.filter(claim =>+ [session.sessionId, ...session.aliases ?? []].includes(claim.sessionId))+ const signature = (claims: readonly OwnerClaim[]) => JSON.stringify([...new Set(claims.map(claim =>+ JSON.stringify([claim.sessionId, claim.pid, claim.record, !!claim.app, !!claim.fromArgs])))].sort())+ const allClaims = await provider.owners!(view)+ const claims = matching(allClaims)+ const pids = new Set(claims.map(claim => claim.pid))+ if (pids.size > 1) throw new Error('conflicting owners')+ const exact = claims.filter(claim => !claim.fromArgs)+ if (new Set(exact.map(claim => JSON.stringify([claim.record, !!claim.app]))).size > 1+ || new Set(claims.map(claim => !!claim.app)).size > 1) throw new Error('conflicting owner evidence')+ const claim = claims.find(claim => !claim.fromArgs) ?? claims[0]+ if (!claim) return { owner: null, generation: null, busy: false }+ const candidateClaims = (all: readonly OwnerClaim[]) => all.filter(other => other.pid === claim.pid || matching([other]).length > 0)+ // A terminal process with another exact conversation open cannot be stopped for this one.+ // Keep its other claims in the second-pass comparison too: filtering to this ID hid that race.+ if (allClaims.some(other => other.pid === claim.pid && !other.fromArgs && !matching([other]).length)) throw new Error('process holds another conversation')+ if (!Number.isSafeInteger(claim.pid) || claim.pid <= 0 || claim.pid > 0x7fffffff) throw new Error('invalid owner PID')+ const [ttys, harness] = await Promise.all([+ (options.open?.ttys ?? processTtys)([claim.pid]), (options.open?.harnessTtys ?? harnessTtys)(),+ ])+ if (!claim.app && !ttys.has(claim.pid)) throw new Error('missing terminal evidence')+ const tty = claim.app ? null : ttys.get(claim.pid) ?? null+ const owner: SessionOwner = { pid: claim.pid, engine: provider.engine, record: claim.record, tty,+ ...(tty && harness?.has(tty) ? { harness: true } : {}), ...(tty && !harness ? { unverified: true } : {}),+ ...(claim.fromArgs ? { fromArgs: true } : {}) }+ // A process can switch conversations while terminal reads wait. Its PID surviving+ // does not prove it still owns this conversation. Re-read ownership with a fresh process view.+ const fresh = (options.open?.view ?? processView)()+ await fresh.list()+ if (signature(candidateClaims(await provider.owners!(fresh))) !== signature(candidateClaims(allClaims))) throw new Error('owner changed during observation')+ // Nothing asynchronous follows this proof. Idle must come from a record that also proves+ // the exact current owner; a separate activity read could belong to a previous conversation.+ const activity = await externalEvidence(async () => await provider.confirmOwner?.(claim, processes.find(row => row.pid === claim.pid) ?? null) ?? null, true)+ if (!activity.ok || activity.value && !activity.value.current) throw new Error('current ownership/activity could not be verified')+ const identity = generation(claim.pid, processes)+ if (!identity && tty && !owner.harness && !owner.fromArgs && !owner.unverified) throw new Error('unverified process incarnation')+ // Unknown activity cannot grant an idle takeover. Explicit take-over-now still requires ownership.+ return { owner, generation: identity, busy: activity.value?.busy !== false,+ ...(activity.value?.busy === true && owner.tty && !owner.harness && !owner.fromArgs && !owner.unverified ? { busyConfirmed: true as const } : {}) }+ })+ if (!observed.ok) return externalUnavailable(observed.detail)+ return externalSessionAnswer({ ok: true, request,+ session: { ...session, title: session.title || options.title?.(request.sessionId) || '' }, ...observed.value,+ }, request)+ }+ let active = 0+ const inspect = async (payload: unknown): Promise<ExternalSessionAnswer> => {+ // RPC deadlines do not stop a native read. Charge the actual work until it settles, so a hung+ // provider cannot accumulate another set of scans on every retry from core.+ if (active >= 4) return externalUnavailable('Waiting for the search service to finish verifying conversations.')+ active+++ try { return await inspectOne(payload) } finally { active-- }+ }+ return { sessions, open, inspect }+}diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.tsindex f3ea77397..dd6ad07b1 100644--- a/cli/src/services/modelsProcess.spec.ts+++ b/cli/src/services/modelsProcess.spec.ts@@ -264,10 +264,6 @@ describe('the core API models runs on in its own process', () => {expect(await api.questions.answerReviewed({} as never)).toBe(false)expect(api.transcripts.databaseHistory({} as never)).toBeUndefined()expect(await api.transcripts.lastTurn('s1')).toBeNull()- expect(api.external.sessions.list()).toEqual([])- expect(await api.external.sessions.scan()).toEqual([])- expect(api.external.open.known()).toEqual(new Map())- expect(await api.external.open.fresh()).toEqual(new Map())api.clients.viewerChanged('a1')expect(api.clients.viewerFrame('c1', 'viewer_data', {})).toBe(false)api.clients.dshInstallStatus({})diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex 63a1c368b..f623086f5 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -101,10 +101,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Paturns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },- external: {- sessions: { list: () => [], scan: async () => [] },- open: { known: () => new Map(), fresh: async () => new Map() },- },+account: {mintGridName: async () => {const answer = await ask('mintGridName')diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex a85cde70b..fe3ea2d3e 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -54,10 +54,6 @@ describe('the core API a light service runs on in its own process', () => {await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)expect(api.transcripts.databaseHistory(agent('a1'))).toBeUndefined()expect(await api.transcripts.lastTurn('s1')).toBeNull()- expect(api.external.sessions.list()).toEqual([])- await expect(api.external.sessions.scan()).resolves.toEqual([])- expect(api.external.open.known().size).toBe(0)- await expect(api.external.open.fresh()).resolves.toEqual(new Map())await expect(api.account.mintGridName()).resolves.toBeNull()// A service holds no credential, and says which one asked.await expect(api.account.accessToken()).rejects.toThrow('usage holds no credential')diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex ca82369a7..b3280b636 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -131,10 +131,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie},questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },- external: {- sessions: { list: () => [], scan: async () => [] },- open: { known: () => new Map(), fresh: async () => new Map() },- },+account: {mintGridName: async () => null,accessToken: () => Promise.reject(new Error(`${service} holds no credential`)),diff --git a/cli/src/services/search.spec.ts b/cli/src/services/search.spec.tsindex 621ae7e48..c99b599b0 100644--- a/cli/src/services/search.spec.ts+++ b/cli/src/services/search.spec.ts@@ -5,8 +5,12 @@ import type { RegisteredSession } from '../lib/registry.js'import type { SessionSearchIndexOptions } from '../lib/sessionSearch/indexer.js'import { fakeCore } from '../testing/fakeCore.js'import { SESSION_SEARCH_FILE, SessionSearchStore } from '../lib/sessionSearch/store.js'+import { createExternalSessions } from './externalSessions.js'import { SEARCH_REQUESTS, searchRequests, startSearch } from './search.js'+const captures = vi.hoisted(() => ({ index: null as unknown }))+vi.mock('../lib/sessionSearch/externals/index.js', () => ({ externalProviders: () => [] }))+vi.mock('./externalSessions.js', () => ({ createExternalSessions: vi.fn() }))vi.mock('../lib/sessionSearch/store.js', () => ({ SESSION_SEARCH_FILE: 'session-search.db', SessionSearchStore: { open: vi.fn() } }))// The index, recording what it was built with so its callbacks can be driven directly.vi.mock('../lib/sessionSearch/indexer.js', async (real) => {@@ -15,7 +19,11 @@ vi.mock('../lib/sessionSearch/indexer.js', async (real) => {...actual,SessionSearchIndex: class {started = false- constructor(readonly opts: SessionSearchIndexOptions) {}+ constructor(readonly opts: SessionSearchIndexOptions) { captures.index = this }+ touch = vi.fn()+ deleteHistory = vi.fn()+ session = vi.fn(() => ({ title: 'Indexed' }))+ stop = vi.fn()start() { this.started = true }},}@@ -34,14 +42,14 @@ function setup(agents: RegisteredSession[] = [], external: unknown[] = [], ownedconst core = fakeCore({agents: { all: vi.fn(() => agents), displayName: vi.fn((s: RegisteredSession) => `name of ${s.agentId}`) },transcripts: { databaseHistory: vi.fn((s: RegisteredSession) => (s.engine === 'opencode' ? reader : undefined)) },- external: {- sessions: { list: vi.fn(() => external), scan: vi.fn(async () => []) } as unknown as CoreApi['external']['sessions'],- open: { known: vi.fn(), fresh: vi.fn() } as unknown as CoreApi['external']['open'],- },+})+ const readers = { sessions: { list: vi.fn(() => external), scan: vi.fn(async () => []) },+ open: { known: vi.fn(), fresh: vi.fn() }, inspect: vi.fn(async () => ({ ok: true })) }+ vi.mocked(createExternalSessions).mockReturnValue(readers as never)const ports = emptyPorts()const requests = startSearch(core, ports)- return { core, ports, store, requests, index: ports.search as unknown as Recorded }+ return { core, ports, store, requests, readers, index: captures.index as Recorded }}describe('the session search service', () => {@@ -54,10 +62,10 @@ describe('the session search service', () => {describe('starting', () => {it('opens the index in the core\'s data folder, starts it, and answers the core through its port and the apps through its requests', () => {- const { core, index, requests } = setup()+ const { readers, index, requests } = setup()expect(SessionSearchStore.open).toHaveBeenCalledWith(join('/data', SESSION_SEARCH_FILE))expect(index.started).toBe(true)- expect(index.opts.openSessions).toBe(core.external.open)+ expect(index.opts.openSessions).toBe(readers.open)expect(Object.keys(requests ?? {})).toEqual([...SEARCH_REQUESTS])})@@ -65,8 +73,8 @@ describe('the session search service', () => {const { core } = setup()vi.mocked(SessionSearchStore.open).mockReturnValueOnce(null)const ports = emptyPorts()- expect(startSearch(core, ports)).toBeUndefined()- expect(ports.search).toBeNull()+ expect(startSearch(core, ports)).toEqual({})+ expect(ports.search?.inspect).toBeTypeOf('function')expect(console.warn).toHaveBeenCalledWith('[search] node:sqlite is not available on this Node — session search is off')})@@ -75,7 +83,7 @@ describe('the session search service', () => {const { core } = setup()vi.mocked(SessionSearchStore.open).mockImplementationOnce(() => { throw new Error('disk I/O error') })startSearch(core, ports)- expect(ports.search).toBeNull()+ expect(ports.search?.inspect).toBeTypeOf('function')expect(console.error).toHaveBeenCalledWith('[search] could not open the session index:', 'disk I/O error')vi.mocked(SessionSearchStore.open).mockImplementationOnce(() => { throw 'locked' })startSearch(core, ports)@@ -191,12 +199,31 @@ describe('the session search service', () => {})it('keeps every agent\'s sessions while the agent exists, looks again for others, and logs as the daemon does', async () => {- const { core, index } = setup([row({ agentId: 'a1' }), row({ agentId: 'a2' })])+ const { readers, index } = setup([row({ agentId: 'a1' }), row({ agentId: 'a2' })])expect([...index.opts.agents!()]).toEqual(['a1', 'a2'])await index.opts.discover!()- expect(core.external.sessions.scan).toHaveBeenCalled()+ expect(readers.sessions.scan).toHaveBeenCalled()index.opts.log!('[search] indexed 3 sessions')expect(console.log).toHaveBeenCalledWith('[search] indexed 3 sessions')})})})++it('keeps external inspection available without SQLite and sends every port through the owned readers/index', async () => {+ const { core, ports, requests, readers } = setup()+ const request = { engine: 'claude' as const, sessionId: 'conversation' }+ expect(Object.keys(requests)).toEqual([...SEARCH_REQUESTS])+ expect(await ports.search!.inspect(request)).toEqual({ ok: true })+ expect(readers.inspect).toHaveBeenCalledWith(request)+ const options = vi.mocked(createExternalSessions).mock.calls.at(-1)![0]+ expect(options.title?.('conversation')).toBe('Indexed')+ ports.search!.touch('conversation'); ports.search!.deleteHistory('conversation'); ports.search!.session('conversation'); ports.search!.stop()+ vi.mocked(SessionSearchStore.open).mockReturnValueOnce(null)+ const offline = startSearch(core, ports, { providers: [], title: id => id === 'named' ? 'Name' : undefined })+ const withoutIndex = vi.mocked(createExternalSessions).mock.calls.at(-1)![0]+ expect(withoutIndex.title?.('named')).toBe('Name')+ expect(withoutIndex.title?.('unnamed')).toBeUndefined()+ expect(offline).toEqual({})+ expect(await ports.search!.inspect(request)).toEqual({ ok: true })+ ports.search!.touch('conversation'); ports.search!.deleteHistory('conversation'); expect(ports.search!.session('conversation')).toBeUndefined(); ports.search!.stop()+})diff --git a/cli/src/services/search.ts b/cli/src/services/search.tsindex 190b53957..d48dd6aee 100644--- a/cli/src/services/search.ts+++ b/cli/src/services/search.ts@@ -8,6 +8,8 @@* there is no index, and the apps through the two requests it answers.*/import { join } from 'node:path'+import { createExternalSessions, type ExternalReaderOptions } from './externalSessions.js'+import { externalProviders } from '../lib/sessionSearch/externals/index.js'import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'import { SessionSearchIndex, folderWords, type SearchSource } from '../lib/sessionSearch/indexer.js'import { SESSION_SEARCH_FILE, SessionSearchStore, type ExternalHit } from '../lib/sessionSearch/store.js'@@ -47,13 +49,19 @@ export function searchRequests(index: Pick<SessionSearchIndex, 'search' | 'tail'}/** Start search: its port for the core, and its requests for the apps, both on one index. */-export function startSearch(core: CoreApi, ports: CorePorts): ServiceRequests | void {- const index = openIndex(core)- ports.search = index- if (index) return searchRequests(index)+export function startSearch(core: CoreApi, ports: CorePorts, options?: ExternalReaderOptions): ServiceRequests {+ let index: SessionSearchIndex | null = null+ const readers = createExternalSessions({ ...(options ?? { providers: externalProviders(), excluded: [core.dataDir], log: console.warn }),+ title: id => options?.title?.(id) ?? index?.session(id)?.title })+ index = openIndex(core, readers)+ ports.search = {+ touch: id => index?.touch(id), deleteHistory: id => index?.deleteHistory(id), session: id => index?.session(id),+ inspect: readers.inspect, stop: () => index?.stop(),+ }+ return index ? searchRequests(index) : {}}-function openIndex(core: CoreApi): SessionSearchIndex | null {+function openIndex(core: CoreApi, readers: ReturnType<typeof createExternalSessions>): SessionSearchIndex | null {try {const store = SessionSearchStore.open(join(core.dataDir, SESSION_SEARCH_FILE))if (!store) {@@ -63,7 +71,7 @@ function openIndex(core: CoreApi): SessionSearchIndex | null {const index = new SessionSearchIndex({store,catalogMetadata: () => {- const entries = new Map<string, ExternalHit>(core.external.sessions.list().flatMap(s =>+ const entries = new Map<string, ExternalHit>(readers.sessions.list().flatMap(s =>[s.sessionId, ...(s.aliases ?? [])].map(id => [id, { title: s.title, cwd: s.cwd, origin: s.origin }] as const)))for (const s of core.agents.all()) if (s.sessionId) entries.set(s.sessionId,{ title: s.title || core.agents.displayName(s), cwd: s.cwd || '', origin: 'harness' })@@ -88,7 +96,7 @@ function openIndex(core: CoreApi): SessionSearchIndex | null {// Conversations Harness did not start — any Harness agent's, earlier ones included, are not.const known = store.ownedSessionIds()for (const s of own) if (s.sessionId) known.add(s.sessionId)- for (const e of core.external.sessions.list()) {+ for (const e of readers.sessions.list()) {// A conversation Harness holds under any of its ids is Harness's.if (known.has(e.sessionId) || e.aliases?.some((id) => known.has(id)) || (!e.transcriptPath && !e.readHistory)) continuesources.push({@@ -100,8 +108,8 @@ function openIndex(core: CoreApi): SessionSearchIndex | null {return sources},agents: () => core.agents.all().map((s) => s.agentId),- discover: () => core.external.sessions.scan(),- openSessions: core.external.open,+ discover: () => readers.sessions.scan(),+ openSessions: readers.open,log: (line) => console.log(line),})index.start()diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.tsindex 825ed100f..32913fe45 100644--- a/cli/src/services/searchProcess.spec.ts+++ b/cli/src/services/searchProcess.spec.ts@@ -83,6 +83,7 @@ describe('search in its own process', () => {const { dataDir, options } = setup()const agent = conversation(dataDir, 'a heron')options.onConnected!(core([agent]))+ await Promise.resolve(); await Promise.resolve()options.onConnected!({ query: vi.fn(async () => { throw new Error('the core went away') }) })options.onConnected!({ query: vi.fn(async () => ({ error: 'UNKNOWN_QUERY' })) })options.onEvent!({ kind: 'touch', sessionId: SESSION })@@ -92,10 +93,12 @@ describe('search in its own process', () => {})it('without an index (no node:sqlite) says search is off, as the core would', async () => {- const { options } = setup({ start: () => {} })+ const { options } = setup({ start: () => ({}) })const off = { error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: false }expect(await options.requests.session_search({ query: 'anything' }, ASKER)).toEqual(off)expect(await options.requests.session_tail({ sessionId: SESSION }, ASKER)).toEqual(off)+ expect(await options.requests.external_inspect({ engine: 'claude', sessionId: SESSION }, ASKER)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })+ expect(await options.requests.external_inspect({}, ASKER)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })options.onEvent!({ kind: 'touch', sessionId: SESSION })})@@ -103,7 +106,7 @@ describe('search in its own process', () => {const { stop, service } = setup()service.stop()expect(stop).toHaveBeenCalledOnce()- const unindexed = setup({ start: () => {} })+ const unindexed = setup({ start: () => ({}) })unindexed.service.stop()expect(unindexed.stop).toHaveBeenCalledOnce()})@@ -111,7 +114,7 @@ describe('search in its own process', () => {it('runs on a core API of the agents the core last named, answering what search never asks as nothing', async () => {const live = { agentId: 'live', active: true, displayName: 'Live one' }const stopped = { agentId: 'stopped', active: false }- const api = searchCoreApi('/data', () => [live, stopped] as never, [])+ const api = searchCoreApi('/data', () => [live, stopped] as never)expect(api.dataDir).toBe('/data')expect(api.agents.all()).toEqual([live, stopped])expect(api.agents.live()).toEqual([live])@@ -134,7 +137,6 @@ describe('search in its own process', () => {await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)expect(api.transcripts.databaseHistory({ engine: 'claude' } as never)).toBeUndefined()expect(await api.transcripts.lastTurn('s1')).toBeNull()- expect(api.external.sessions.list()).toEqual([])await expect(api.account.mintGridName()).resolves.toBeNull()await expect(api.account.accessToken()).rejects.toThrow('search holds no credential')await expect(api.account.privateGridName()).resolves.toBeNull()@@ -158,9 +160,31 @@ describe('search in its own process', () => {expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'search', socketPath: '/data/daemon-1.sock' }))})- it('reaches the core as `search`, through the socket and token it was given', () => {+ it('reaches the core as `search`, through the socket and token it was given', async () => {const { options } = setup()expect(options).toMatchObject({ name: 'search', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })- expect(Object.keys(options.requests).sort()).toEqual(['session_search', 'session_tail'])+ expect(Object.keys(options.requests).sort()).toEqual(['external_inspect', 'session_search', 'session_tail'])+ expect(await options.requests.external_inspect({ engine: 'claude', sessionId: SESSION }, ASKER)).toMatchObject({ ok: false, error: 'SEARCH_UNAVAILABLE' })})})++it('discards an old core reply after disconnect, replacement or shutdown', async () => {+ let options!: ServiceProcessOptions, captured!: ReturnType<typeof searchCoreApi>+ const service = runSearchService({ dataDir: '/fixture/data', socketPath: '/fixture/socket', machineId: 'fixture', token: 'fixture', providers: [],+ start: core => { captured = core as ReturnType<typeof searchCoreApi>; return {} },+ run: given => { options = given; return { stop: vi.fn() } },+ })+ const pending: Array<(value: Record<string, unknown>) => void> = []+ const connection = () => ({ query: vi.fn(() => new Promise<Record<string, unknown>>(resolve => pending.push(resolve))) })+ options.onConnected!(connection())+ options.onDisconnected!()+ pending.shift()!({ agents: [{ agentId: 'old' }] }); await Promise.resolve(); await Promise.resolve()+ expect(captured.agents.all()).toEqual([])+ options.onConnected!(connection()); options.onConnected!(connection())+ pending[1]({ agents: [{ agentId: 'current' }] }); await Promise.resolve(); await Promise.resolve()+ pending[0]({ agents: [{ agentId: 'stale' }] }); await Promise.resolve(); await Promise.resolve()+ expect(captured.agents.all()).toMatchObject([{ agentId: 'current' }])+ options.onConnected!(connection()); service.stop()+ pending[2]({ agents: [{ agentId: 'late' }] }); await Promise.resolve(); await Promise.resolve()+ expect(captured.agents.all()).toEqual([])+})diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex 5bc32998d..d9209c0a7 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -10,7 +10,7 @@import type { CoreApi } from '../core/api.js'import { ACCOUNT_BACKEND_OFF, CONVERSATIONS_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'import { databaseHistory } from '../lib/databaseHistory.js'-import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'+import { externalSessionRequest, externalUnavailable } from '../lib/externalSessionWire.js'import { externalProviders } from '../lib/sessionSearch/externals/index.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'@@ -37,7 +37,6 @@ export interface SearchServiceOptions {export function searchCoreApi(dataDir: string,agents: () => Array<RegisteredSession & { displayName?: string }>,- providers: ReturnType<typeof externalProviders>,): CoreApi {return {dataDir,@@ -64,10 +63,7 @@ export function searchCoreApi(turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory, lastTurn: UNASKED.lastTurn },- external: {- sessions: new ExternalSessions({ providers, excluded: [dataDir], log: console.warn }),- open: new OpenSessions({ providers, log: console.warn }),- },+// Search holds no credential, runs no model and talks to no window: these are never asked of it.account: {mintGridName: async () => null,@@ -89,12 +85,13 @@ export function runSearchService(options: SearchServiceOptions): ServiceProcesslet core: CoreConnection | null = nullconst refresh = async (): Promise<void> => {if (!core) return- const answer = await core.query('agents').catch(() => null)- if (Array.isArray(answer?.agents)) agents = answer.agents as typeof agents+ const connection = core+ const answer = await connection.query('agents').catch(() => null)+ if (core === connection && Array.isArray(answer?.agents)) agents = answer.agents as typeof agents}- const api = searchCoreApi(options.dataDir, () => agents, options.providers ?? externalProviders())+ const api = searchCoreApi(options.dataDir, () => agents)const ports = emptyPorts()- const answers = (options.start ?? startSearch)(api, ports)+ const answers = (options.start ?? startSearch)(api, ports, { providers: options.providers ?? externalProviders(), excluded: [options.dataDir], log: console.warn })const index = ports.search// No index here (a Node without `node:sqlite`): search is off, as it would be in the core's process.const off = { error: 'SERVICE_UNAVAILABLE', service: 'search', retryable: false }@@ -105,7 +102,11 @@ export function runSearchService(options: SearchServiceOptions): ServiceProcessmachineId: options.machineId,token: options.token,// The same handlers as in the core's process (services/search.ts `searchRequests`).- requests: answers ?? Object.fromEntries(SEARCH_REQUESTS.map((type) => [type, () => off])),+ requests: { ...Object.fromEntries(SEARCH_REQUESTS.map(type => [type, () => off])), ...answers,+ external_inspect: async payload => {+ const request = externalSessionRequest(payload)+ return { ...(request && index ? await index.inspect(request) : externalUnavailable()) }+ } },onEvent: (payload) => {const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : ''if (!sessionId || !index) return@@ -115,6 +116,7 @@ export function runSearchService(options: SearchServiceOptions): ServiceProcessif (payload.kind === 'touch') return refresh().then(() => index.touch(sessionId))if (payload.kind === 'deleteHistory') index.deleteHistory(sessionId)},+ onDisconnected: () => { core = null; agents = [] },onConnected: (connection) => {core = connectionvoid refresh()@@ -122,6 +124,7 @@ export function runSearchService(options: SearchServiceOptions): ServiceProcess})return {stop: () => {+ core = null; agents = []service.stop()index?.stop()},diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.tsindex 661bb202d..17fd885d9 100644--- a/cli/src/services/viewersProcess.spec.ts+++ b/cli/src/services/viewersProcess.spec.ts@@ -263,10 +263,6 @@ describe('the viewers in their own process', () => {expect(tell.mock.calls).toEqual([['a1'], ['a1']])expect(api.transcripts.databaseHistory(agent())).toBeUndefined()expect(await api.transcripts.lastTurn('s1')).toBeNull()- expect(api.external.sessions.list()).toEqual([])- await expect(api.external.sessions.scan()).resolves.toEqual([])- expect(api.external.open.known().size).toBe(0)- await expect(api.external.open.fresh()).resolves.toEqual(new Map())await expect(api.account.mintGridName()).resolves.toBeNull()await expect(api.account.accessToken()).rejects.toThrow('the viewers hold no credential')await expect(api.account.privateGridName()).resolves.toBeNull()diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 5d23991a4..186d7e1ec 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -82,10 +82,7 @@ export function viewersCoreApi(turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },- external: {- sessions: { list: () => [], scan: async () => [] },- open: { known: () => new Map(), fresh: async () => new Map() },- },+account: {mintGridName: async () => null,accessToken: () => Promise.reject(new Error('the viewers hold no credential')),diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.tsindex f2a9a6459..64449d1b6 100644--- a/cli/src/services/workspacesProcess.spec.ts+++ b/cli/src/services/workspacesProcess.spec.ts@@ -160,10 +160,6 @@ describe('workspaces in their own process', () => {expect(renamed).toHaveBeenCalledWith('a1')expect(api.transcripts.databaseHistory(agent())).toBeUndefined()expect(await api.transcripts.lastTurn('s1')).toBeNull()- expect(api.external.sessions.list()).toEqual([])- await expect(api.external.sessions.scan()).resolves.toEqual([])- expect(api.external.open.known().size).toBe(0)- await expect(api.external.open.fresh()).resolves.toEqual(new Map())await expect(api.account.mintGridName()).resolves.toBeNull()await expect(api.account.accessToken()).rejects.toThrow('workspaces hold no credential')await expect(api.account.privateGridName()).resolves.toBeNull()diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 218566a0d..c7193f331 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -73,10 +73,7 @@ export function workspacesCoreApi(turns: { send: () => {}, stop: () => {}, recent: async () => [], asks: async () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },- external: {- sessions: { list: () => [], scan: async () => [] },- open: { known: () => new Map(), fresh: async () => new Map() },- },+account: {mintGridName: async () => null,accessToken: () => Promise.reject(new Error('workspaces hold no credential')),diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex c8283b8c4..710100801 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -253,7 +253,7 @@ describe('the core\'s request gate (core/main.ts)', () => {// Readiness never waits on a service: the agents the boot held for one are launched after it, in the background// (core/agents/heldLaunches.ts).expect(tail).toEqual(['backend.openRequests()', 'daemonBoot.openRequests = null', 'coreLink.ready()', "console.log('[cli] ready')",- 'void heldLaunches.restoreHeld()'])+ 'void heldLaunches.restoreHeld()', 'externalResumes.open()'])expect(logged).toBeGreaterThan(ready)})})diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 59d716a78..0051fc071 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -45,11 +45,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {},questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => false), ...over.questions },transcripts: { databaseHistory: vi.fn(() => undefined), lastTurn: vi.fn(async () => null), ...over.transcripts },- external: {- sessions: { list: vi.fn(() => []), scan: vi.fn(async () => []) },- open: { known: vi.fn(() => new Map()), fresh: vi.fn(async () => new Map()) },- ...over.external,- },+account: {mintGridName: vi.fn(async () => null),accessToken: vi.fn(async () => 'token'),diff --git a/cli/src/testing/observerShapes.ts b/cli/src/testing/observerShapes.tsindex 48988e2b7..86aede60c 100644--- a/cli/src/testing/observerShapes.ts+++ b/cli/src/testing/observerShapes.ts@@ -4,13 +4,19 @@ import type { AgentUsageTarget } from '../lib/agentUsageWire.js'/** Former-code composition for moving optional search and usage observations out of core. */import type { AgentTokenUsageCache } from '../lib/agentTokenUsage.js'import { ExternalSessions, OpenSessions, type ExternalSessionsOptions, type OpenSessionsOptions } from '../lib/sessionSearch/external.js'-import { createAdoption, type AdoptDeps } from '../core/agents/adopt.js'+import { createExternalSessions } from '../services/externalSessions.js'+import { externalSessionAnswer } from '../lib/externalSessionWire.js'+import type { RegisteredSession } from '../lib/registry.js'+import { createAdoption } from '../core/agents/adopt.js'export function externalShapes(sessionsOptions: ExternalSessionsOptions, openOptions: OpenSessionsOptions,- own: Pick<AdoptDeps, 'bySession' | 'byAgent' | 'stoppedAgents' | 'search'>) {- const sessions = new ExternalSessions(sessionsOptions)- const open = new OpenSessions(openOptions)- const adoption = createAdoption({ ...own, externalSessions: sessions, openSessions: open })+ own: { bySession(id: string): RegisteredSession | undefined; byAgent(id: string): RegisteredSession | undefined;+ stoppedAgents: { list(): Pick<RegisteredSession, 'sessionId'>[] }; search: { session(id: string): { title?: string } | undefined } }) {+ const readers = createExternalSessions({ ...sessionsOptions, open: openOptions,+ generation: () => 'ps:1', title: id => own.search.session(id)?.title })+ const { sessions, open } = readers+ const adoption = createAdoption({ inspect: async request => externalSessionAnswer(JSON.parse(JSON.stringify(await readers.inspect(request))), request),+ held: id => !!own.bySession(id) || own.stoppedAgents.list().some(row => row.sessionId === id) })return {scan: () => sessions.scan(),lookup: async (id: string) => sessions.get(id) ?? (await sessions.scan(), sessions.get(id)),diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex 5ddcc1bce..3f7c6a0f6 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -59,7 +59,6 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixture},questions: { answer: () => {}, answerReviewed: async () => false },transcripts: { databaseHistory: () => undefined, lastTurn: async () => null },- external: { sessions: { list: () => [], scan: async () => [] }, open: { known: () => new Map(), fresh: async () => new Map() } },account: {mintGridName: async () => null, accessToken: () => Promise.reject(new Error('no credential')), lane: LANE_OFF,privateGridName: async () => null, machineName: () => null,diff --git a/docs/design/2026-10-09-external-session-boundary.md b/docs/design/2026-10-09-external-session-boundary.mdnew file mode 100644index 000000000..9554dcf8e--- /dev/null+++ b/docs/design/2026-10-09-external-session-boundary.md@@ -0,0 +1,21 @@+# Item 5b implementation notes++The former external behavior golden is already recorded in commit 12d6b640b before any move. Preserve its fixture bytes and make the adapter cross the actual service factory and JSON validators. New safety behavior needs separate regressions.++Search owns ExternalSessions, OpenSessions, providers, metadata and index. Adoption metadata remains available when SQLite indexing cannot open. Core accepts a bounded exact requested-ID/engine response with explicit unavailable vs authoritative missing/free. Display last-good scans cannot authorize adoption. Lazy provider failure, failed process listing, partial/unreadable owner reads and conflicting owners are unknown, never free.++Core retains adoption decisions, canonical/alias reservations, process-incarnation checks, signals and pane dispatch. An external intent remains separate from an owned session until admission; initial row atomically contains launch:held and validated externalResume. Malformed persisted intent must never degrade to a fresh launch. Include intent phase/generation in restore ownership. Known refusals retain existing error/detail; unavailable facts produce a durable held tile before any trust/config/engine write. Skip launch-receipt pre-trust for external resume.++A pending adoption survives daemon/tmux restart. Stop cancels it and its verified inert pane without archiving/deleting the external conversation, signalling its owner, or allowing delayed work to revive it. Owner busy uses a per-intent hold, not the pass-wide service outage map. A bounded coalesced refresh must return held promptly, never idle-poll inside heldLaunches global queue.++Before any signal, recheck core generation, route, exact owner PID/start marker/session/TTY and non-Harness ownership. Recheck after foreground-group lookup and before TERM and KILL. Do not reset the TTY after exit: its ownership can no longer be proved. A signal already sent cannot be undone; persist that phase. An identity replacement cannot inherit permission to terminate. Never trust worker to signal anything.++Each signal takes the strict registry lock and rechecks durable reservations, including an unchanged intent before KILL after TERM's grace period. A verified core binding may overlap a held provisional reservation; the held adoption never gains authority from that overlap. An exact owner with another non-alias conversation in the same process cannot be stopped. FD ownership also requires a positively identified engine process; lsof's command-prefix match is not enough.++Idle takeover requires a final coherent record proving the exact session, PID, incarnation and activity together, after all asynchronous process/terminal work. Claude's process record supports this. Providers whose ownership and activity live in separate stores report unknown activity for this purpose: idle/wait stays held with the missing-evidence reason, and explicit takeover can stop the verified owner without inventing a continuation prompt. The optional validated `busyConfirmed` wire bit alone permits automatic continuation; unknown never does. No asynchronous work follows the final proof before the service's synchronous generation check.++Admission/dispatch must have a durable boundary. Generic restore currently treats held panes as inert: crash after respawn but before its starting commit would replay. Record dispatch phase before the side effect and reconcile exact pane/process on restart. Once admitted, resume is core owned and strict (never fresh fallback), and never asks search again. Keep launch prep outside the pane-operation lock so Stop can cancel it immediately.++Review feedback from independent reviewer: wire and read failures must hold; separate unadmitted identity; initial held row atomic; strict resume; phase/generation in restoreOwner; per-intent waits outside global queue; distinguish busy from outage; fail closed malformed persistence. A buildLaunch-only wrapper is insufficient because it cannot mutate cwd/sessionId/launch without invalidating current(), and resumeOnly+empty session is rejected before buildLaunch. Use an explicit guarded transition/fresh snapshot.++New owner steering: two panes of the same agent started in the same millisecond fail. buildHarnessSessionLabel currently formats engine + Date.now() with no nonce. Fix with regression in core follow-ups; nonblocking for #1078.diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.mdindex d8783fb2e..fcb8e24e2 100644--- a/docs/research/2026-10-09-daemon-separation-progress.md+++ b/docs/research/2026-10-09-daemon-separation-progress.md@@ -73,3 +73,40 @@ Usage transcript, SQLite and private checkpoint reads belong to the usage servicIndependent review identified starvation when continuous same-target events invalidated pending reads, omitted-field rejection in inline project readers, unbounded PR URLs, and a reader-capacity refusal that looked like a valid null. Each is corrected with a regression. Same-target progress is published while a later refresh is pending; identity changes still discard old replies. Checkpoint filenames remain compatible. In-memory reader entries additionally include the complete read target so concurrent target changes cannot mutate an in-flight read.Validation selected before execution: typecheck, architecture, unchanged goldens and mutations, core/harnessd 100% gates, affected frame/usage/Git/backend specs, and isolated usage, edge and services e2e. Initial core validation passed 1,713 tests at 100%; affected validation failed two old backend fixtures that still composed usage as a service without a port. Initial usage e2e failed fixture assumptions: Stop's RPC is `agent_delete`, and transcript attachment can follow session binding. The existing five edge and fourteen services cases passed. Failed receipts remain failed; final evidence follows the corrections. No release is authorized or attempted.+++### Usage completed++[PR #1078](https://github.com/autonomous-ai/openharness/pull/1078) merged after independent approval of head `e8e98bb22` against base `f5c0f2979`, and [automatic CI](https://github.com/autonomous-ai/openharness/actions/runs/37877120111) passed every selected check including `ci/required`. The final main integration changed only pnpm's lock entries for pngjs packages already declared in package.json and npm's lock; the local tested production, tests and installed npm dependencies stayed identical.++The unchanged former-code usage golden crosses the production service and wire validators. Six deliberate wiring mutations fail assertions. Final local gates passed 1,716 core tests at per-file 100% statements and branches, 265 harnessd tests at 100% with one existing skip, typecheck, architecture and 410 affected specs (`20261009T025300.053066Z-85987`). Three isolated usage e2e cases passed in 73.7 seconds (`20261009T025258.053880Z-85910`), covering unavailable boot, recovery, stopped work, a replacement core receiving an unchanged warm snapshot, and explicit inline mode. The prior warm-worker case failed because it connected after core spawn but before socket readiness; the corrected test waits for the new ready event. The failed receipt is not passing evidence. Five edge-host and fourteen service cases had passed earlier; the final production also passed a 93.9-second two-agent soak/chaos smoke, not a claim about long-term growth.++The matched four-agent/two-active performance sample (`20261009T025602.069419Z-2829`, 69.8 seconds) measured core CPU at 0.55/1.50/6.94% of one logical CPU, and mean RSS 82.5/95.9/101.7 MiB across empty/idle/active windows. Loop-delay p95 stayed near 12.1 ms; both turns completed with p95 7.015 seconds. Same Node 22.23.2, Intel macOS, 16 logical CPUs, 64 GiB, tmux 3.5a, two windows/four streams, ten-second phases, two-second warmup and no history as the L2 baseline. This small fake-engine sample excludes service, engine, tmux and USB costs and sets no threshold.++Time accounting (UTC): production and review corrections through 02:44; the final test-only readiness correction at 02:52. Final local checks ran 02:52:58–about 02:55; performance ran 02:56:02–02:57:12. Main advanced with a lockfile correction; integration and independent review completed about 03:00. Final CI waiting ended about 03:03; the merge helper started at 03:03:27. Request time since 23:26:41 includes all diagnosis, implementation, review and waiting, not just Actions. Publication remains zero.++## Item 5: external sessions++PR [#1081](https://github.com/autonomous-ai/openharness/pull/1081) moves provider and process observations into search, including when SQLite indexing is unavailable. Core retains policy, alias reservations, verified signals, durable admission, cancellation and dispatch. An unavailable reader leaves an inert held pane with a reason. Once admitted, crash restore and Stop/Open use the core's exact conversation identity without search.++Former-code owner-control golden commit `7972e9824` supplements the existing external golden before the move; both fixture files remain unchanged. The new safety rules have separate regression tests. Seven mutations fail assertions: missing owner/busy observations, archived admission, missing Hermes profile, alias reservation loss, suppressed launch and omitted dispatch journal. These checks use pinned platforms, UTC, `/tmp`, and placeholder binaries. The retained former owner-control golden covers the extracted primitive; the new controller's tighter signal fences have direct tests.++Validation selected before final execution: typecheck; architecture and unchanged goldens; core and harnessd per-file 100% gates; resume and portability gates; provider, persistence, restore and real private-tmux tests; isolated adoption, machine, core, lifecycle and search/service e2e; a short process-boundary soak/chaos smoke and the matched four-agent performance sample. Full Linux unit coverage comes from automatic PR CI. Preliminary full-core tests passed but coverage was incomplete; added boundary tests reach 100% in the focused run. The provider diagnostic initially failed an invalid Devin test command (`resume` instead of `-r`); the corrected four-file diagnostic passes 105 tests. Final receipts and independent approval are still pending.++Independent review of the initial checkpoint found races across the pane probe and owner reads, omitted strict-resume forwarding through restart/retarget, incomplete or ambiguous owner records, and a provisional reservation vetoing a real binding. Regression commit `0d992f216` reproduces twelve failures before corrections. The corrected service rereads exact ownership after activity and terminal observations. Ambiguous live engine records and argv-only ownership hold admission. Core checks current bindings and stopped reservations at every signal/journal boundary; verified binding remains independent of search. Provisional and owned reservations are validated separately, while every strict adoption transition still excludes a foreign owner.++The first broad receipt passed core/harnessd/resume/portability coverage but failed one stale startup-order expectation; automatic CI failed the same expectation. The initial control/service e2e run passed 54 cases and failed two inline-search cases because an internal request was returned as a public handler. That wiring is corrected: inline inspection uses the port and only the process wrapper declares the private request. These failed receipts are not passing evidence. Isolating the real tmux fixture with a private home and an empty startup config exposed a vanished-pane cancellation edge; authoritative inventory now makes the repeated close idempotent. All seven wiring mutations still fail assertions after these corrections.++The second review tightened the authority to signal further. A final coherent ownership/activity record is required for idle consent. Unknown activity stays held for idle/wait and cannot generate a continuation prompt under explicit takeover. Every signal, including KILL after the TERM grace period, takes the strict durable reservation check even for an unchanged intent. Same-PID claims for unrelated conversations and Codex-prefix helper processes cannot become stoppable exact owners. Regression tests cross the real registry and controller with synthetic OS signals. The new search request typing and two early-return coverage gaps found in the final gate are corrected; the failed combined receipt remains failed. Its affected, harnessd, resume and portability checks passed, and both adoption plus the two corrected inline-search e2e cases passed separately.++Independent review approved production head `1aced4484` against main `e130ad8e1`, including the coherent activity proof, per-signal durable reservation check, contradictory owner claims and real engine process identity. The final main integration changes no CLI source. Automatic CI [37887475290](https://github.com/autonomous-ai/openharness/actions/runs/37887475290) passed every selected check including `ci/required`.++Final broad receipt `20261009T051228.567255Z-74018` passed typecheck, 1,785 core tests at per-file 100% statements and branches, 265 harnessd tests with one existing skip at 100%, 1,004 affected tests including architecture and the unchanged goldens, 298 resume tests at 100%, and the portability gate at 100%. The two corrected inline-search e2e cases passed. The new strict restart case initially requested a second pane operation before adoption committed its route; its test-only correction completes one private turn first and passes in isolation. The failed combined e2e receipt remains failed. The final adoption lane is rerun after that correction; broad production evidence remains applicable because the final change touches only that test and this note.++A two-agent soak/chaos smoke passed in 105.0 seconds (`20261009T051533.050394Z-3315`). The matched performance run passed in 70.7 seconds (`20261009T051852.532251Z-32229`): empty/idle/active core CPU was 0.75/1.65/6.91% of one logical CPU, mean RSS 81.2/95.1/98.8 MiB and event-loop p95 11.07/11.08/11.12 ms. Both turns completed with p95 6.976 seconds. The preceding usage baseline was 0.55/1.50/6.94%, 82.5/95.9/101.7 MiB and 7.015 seconds, on the same Node, machine, tmux and four-agent/two-active workload. These ten-second windows measure only the core PID, exclude services, engines, tmux and USB, and support neither a new threshold nor a long-term growth claim.++Time accounting (UTC): implementation and diagnosis began after the usage merge at 03:03:42 and production corrections ended at 05:11. Independent production approval followed at about 05:13; the final test-only readiness correction passed at 05:14. Final broad local validation ran 05:12:28–05:17:21, overlapping the short soak/chaos run. The matched measurement ran 05:18:52–05:20:03. Final test/documentation review and head checks follow before the authorized merge. All daemons, homes and tmux servers used for testing are disposable. Publication remains zero.++## Added core follow-up++The owner reported that two panes of the same agent started in one millisecond fail. Onboarding avoids it today; the fix belongs in core. The current session-label generator contains only the engine and a millisecond timestamp, so concurrent same-engine creates can collide. Reproduce with a pinned clock, fix the shared label generation, and verify two isolated panes can start together. This is not blocking the completed usage separation.