Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(cli): an unrelated Claude process no longer blocks adopting every conversation (#1098)

0xdiego257034afd59b17
diff --git a/cli/src/core/agents/externalResume.spec.ts b/cli/src/core/agents/externalResume.spec.ts
index c9f78289d..a1c66f03e 100644
--- a/cli/src/core/agents/externalResume.spec.ts
+++ b/cli/src/core/agents/externalResume.spec.ts
@@ -1,10 +1,13 @@
-import { mkdtempSync, rmSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { claudeProvider } from '../../lib/sessionSearch/externals/claude.js'
+import type { ProcessView, RunningProcess } from '../../lib/sessionSearch/externals/types.js'
+import { createExternalSessions } from '../../services/externalSessions.js'
import { createExternalResumes, type ExternalResumeDeps } from './externalResume.js'
import { stopExternalOwner } from './externalOwner.js'
vi.mock('./externalOwner.js', () => ({ stopExternalOwner: vi.fn(async () => false) }))
@@ -461,3 +464,37 @@ it('does not admit a conversation acquired externally while its final pane probe
expect(test.rows.get(id)?.sessionId).toBe('')
expect(test.deps.launch).not.toHaveBeenCalled()
})
+
+it('launches a conversation held behind a record-less Claude in its folder once that process goes, and never waits on one elsewhere', async () => {
+ // CLI 0.3.70: "[restore] held · search · launched 0 of 4 · 4 still waiting" behind two old TUIs with no record.
+ // The real search reader answers here, over a private Claude home and a fake process table.
+ const home = mkdtempSync(join(tmpdir(), 'external-resume-claude-'))
+ try {
+ const project = join(home, 'project'), elsewhere = join(home, 'elsewhere'), conversation = '33333333-3333-4333-8333-333333333333'
+ mkdirSync(project); mkdirSync(elsewhere); mkdirSync(join(home, 'projects', 'project'), { recursive: true })
+ writeFileSync(join(home, 'projects', 'project', `${conversation}.jsonl`), JSON.stringify({
+ type: 'user', sessionId: conversation, cwd: project, entrypoint: 'cli', message: { role: 'user', content: 'Fixture' } }) + '\n')
+ const tui = (pid: number): RunningProcess => ({ pid, ppid: 1, executable: 'claude', args: 'claude --append-system-prompt "be brief"', started: 1 })
+ let processes = [tui(201), tui(202)]
+ const cwds = new Map([[201, elsewhere], [202, project]])
+ const reader = createExternalSessions({ providers: [claudeProvider({ projectsDir: join(home, 'projects'), home })], generation: () => null,
+ open: { ttys: async () => new Map(), harnessTtys: async () => new Set(), view: (): ProcessView => {
+ const listed = processes
+ return { list: async () => listed, alive: pid => listed.some(row => row.pid === pid), openFiles: async () => new Map(),
+ openFilesOf: async () => new Map(), cwds: async pids => new Map([...cwds].filter(([pid]) => pids.includes(pid))) }
+ } } })
+ const test = setup(); test.inspect.mockImplementation(request => reader.inspect(request))
+ const id = await test.stage({ resumeSessionId: conversation, cwd: project })
+ await test.controller.settled()
+ expect(test.rows.get(id)).toMatchObject({ launch: { state: 'held', service: 'search', detail: "The conversation's current owner could not be verified." },
+ externalResume: { phase: 'waiting' } })
+ expect(test.deps.launch).not.toHaveBeenCalled()
+ // The one in the conversation's folder quits; the one elsewhere runs on and holds nothing here.
+ processes = [tui(201)]
+ await vi.advanceTimersByTimeAsync(2000); await test.controller.settled()
+ expect(test.rows.get(id)).toMatchObject({ sessionId: conversation, cwd: project, resumeOnly: true, externalResume: { phase: 'admitted' } })
+ expect(test.deps.launch).toHaveBeenCalledOnce()
+ await vi.advanceTimersByTimeAsync(4000)
+ expect(test.deps.launch).toHaveBeenCalledOnce()
+ } finally { rmSync(home, { recursive: true, force: true }) }
+})
diff --git a/cli/src/engines/claude/adoption.ts b/cli/src/engines/claude/adoption.ts
index cdb8957c6..54e6a5aa9 100644
--- a/cli/src/engines/claude/adoption.ts
+++ b/cli/src/engines/claude/adoption.ts
@@ -24,6 +24,9 @@ export const adoption: AdoptionContract = {
},
// A running Claude Code keeps `<home>/sessions/<pid>.json` naming its session and saying `idle` between turns:
// the owner and its state, exactly. `ps` gives a start to the second, and Claude stamps its record a moment after.
- owners: { records: { folder: record!.folder, suffix: record!.suffix, pid: record!.pid, id: record!.id, started: 'startedAt', slackMs: 2_000 } },
+ // `--session-id <uuid>` starts a conversation under that id, so a process with no record has it open as surely
+ // as one that resumed it.
+ owners: { records: { folder: record!.folder, suffix: record!.suffix, pid: record!.pid, id: record!.id, started: 'startedAt', slackMs: 2_000,
+ sessionFlags: ['--session-id'] } },
busy: { record: { field: 'status', busy: 'busy', idle: 'idle' } },
}
diff --git a/cli/src/engines/facets/adoption.ts b/cli/src/engines/facets/adoption.ts
index bc20f6477..053efb80a 100644
--- a/cli/src/engines/facets/adoption.ts
+++ b/cli/src/engines/facets/adoption.ts
@@ -42,10 +42,11 @@ export interface AdoptionContract {
* folder, naming its pid and conversation; a record whose pid now runs another engine, or a process that started
* after the record says (past `slackMs`), is someone else's. `open`: the session file a process of these
* `commands` holds open, its conversation the id the file's name holds; a server's (an app's or an editor's) is
- * never stopped from here.
+ * never stopped from here. A live process with no record says at most, in its arguments, the conversation it
+ * started on: the engine's resume flags (`resumeArgs`, lib/tmux.ts) or one of `sessionFlags`.
*/
owners:
- | { records: { folder: string; suffix: string; pid: string; id: string; started: string; slackMs: number } }
+ | { records: { folder: string; suffix: string; pid: string; id: string; started: string; slackMs: number; sessionFlags?: readonly string[] } }
| { open: { commands: readonly string[]; id: RegExp; contains: string; servers: { executable: RegExp; args: RegExp; subcommands: readonly string[] } } }
/**
* Whether the owner is mid-turn. `record`: its record's `field` says (no record: it ended, so not). `tail`: the
diff --git a/cli/src/engines/kit/adoption.ts b/cli/src/engines/kit/adoption.ts
index 419b4c295..03fa6a735 100644
--- a/cli/src/engines/kit/adoption.ts
+++ b/cli/src/engines/kit/adoption.ts
@@ -9,9 +9,9 @@ import { externalEvidenceActive, externalReadFailed } from '../../lib/sessionSea
import { agentCommandOwnershipSnapshot } from '../../lib/engineBin.js'
import { absoluteFolder, entries, fileStamp, firstLine, parseLine, readHead, readJson, readTail, readText, record, text } from '../../lib/sessionSearch/externals/support.js'
-import { argvTokens, engineProcessMatch } from '../../lib/tmux.js'
+import { argvTokens, engineProcessMatch, resumeSessionId } from '../../lib/tmux.js'
import {
- type ExternalEngine, type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type ProcessView,
+ type ExternalEngine, type ExternalOrigin, type ExternalProvider, type ExternalSession, type OwnerClaim, type Ownership, type ProcessView,
type RunningProcess, type ScanContext, UNSETTLED,
} from '../../lib/sessionSearch/externals/types.js'
import type { AdoptionContract } from '../facets/adoption.js'
@@ -148,7 +148,20 @@ export async function turnOpen(path: string, tail: Tail, unknown: boolean | null
return unknown
}
-async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { records: unknown }>['records'], pattern: RegExp, dirs: string[], view: ProcessView): Promise<OwnerClaim[]> {
+/** The conversation a process's arguments say it started on: a resume of it, or one of `flags` naming it. */
+function namedSession(engine: ExternalEngine, args: string, flags: readonly string[], pattern: RegExp): string | null {
+ const resumed = resumeSessionId(engine as never, args)
+ if (resumed) return resumed
+ const tokens = argvTokens(args)
+ for (const [i, token] of tokens.entries()) {
+ const flag = flags.find(name => token === name || token.startsWith(`${name}=`))
+ const value = flag && (token === flag ? tokens[i + 1] : token.slice(flag.length + 1))
+ if (value && pattern.test(value)) return value
+ }
+ return null
+}
+
+async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { records: unknown }>['records'], pattern: RegExp, dirs: string[], view: ProcessView): Promise<Ownership> {
const claims: OwnerClaim[] = []
for (const dir of dirs) {
const records = (await entries(dir)).filter((file) => file.isFile() && file.name.endsWith(owners.suffix))
@@ -178,15 +191,28 @@ async function recordOwners(engine: ExternalEngine, owners: Extract<Owners, { re
claims.push({ sessionId: text(row?.[owners.id]), pid, record: path })
}
}
+ const unresolved: Array<{ pid: number; named?: string }> = []
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')
+ if (ids.size === 1) continue
+ // Records that disagree about one live process are a store nobody can read: nothing is admitted on it.
+ if (ids.size > 1) { externalReadFailed(new Error('no unambiguous current process record'), 'current owner'); continue }
+ // No record. This used to fail every conversation: one long-running `claude` started before it kept
+ // records (two such TUIs on a developer's Mac, days old) held every adoption on the machine forever,
+ // "The conversation's current owner could not be verified" (CLI 0.3.70). Such a process can hold only
+ // the conversation its arguments name and, moved on with `/resume` or `/clear`, one its folder's picker
+ // lists. The first is a claim never stopped on; for the rest it stays unplaced, and admission judges it
+ // against each conversation's folder. A name alone is not enough: it is where it started, not where it is.
+ const named = namedSession(engine, process.args, owners.sessionFlags ?? [], pattern)
+ if (named) claims.push({ sessionId: named, pid: process.pid, record: '', fromArgs: true })
+ unresolved.push({ pid: process.pid, ...(named ? { named } : {}) })
}
}
- return claims
+ const cwds = unresolved.length ? await view.cwds(unresolved.map(row => row.pid)) : new Map<number, string>()
+ return { claims, unresolved: unresolved.map(row => ({ ...row, cwd: cwds.get(row.pid) ?? null })) }
}
async function openFileOwners(engine: ExternalEngine, open: Extract<Owners, { open: unknown }>['open'], view: ProcessView): Promise<OwnerClaim[]> {
@@ -228,6 +254,9 @@ export function adoptionProvider(engine: ExternalEngine, contract: AdoptionContr
}
const owners = contract.owners
const busy = contract.busy
+ const ownership = async (view: ProcessView): Promise<Ownership> => 'records' in owners
+ ? recordOwners(engine, owners.records, head.id.pattern, places.records?.() ?? places.roots().map((root) => join(root, '..', owners.records.folder)), view)
+ : { claims: await openFileOwners(engine, owners.open, view), unresolved: [] }
return {
engine,
async scan(ctx: ScanContext): Promise<ExternalSession[]> {
@@ -260,11 +289,12 @@ export function adoptionProvider(engine: ExternalEngine, contract: AdoptionContr
}
return found
},
- owners: (view: ProcessView) => 'records' in owners
- ? recordOwners(engine, owners.records, head.id.pattern, places.records?.() ?? places.roots().map((root) => join(root, '..', owners.records.folder)), view)
- : openFileOwners(engine, owners.open, view),
+ ownership,
+ owners: async (view: ProcessView) => (await ownership(view)).claims,
async confirmOwner(owner, process) {
- if (!('records' in owners) || !('record' in busy)) return null
+ // Only its arguments name it (no record): nothing says whether it is still there or mid-turn, and it is
+ // never stopped on that, so its activity stays unknown.
+ if (!('records' in owners) || !('record' in busy) || owner.fromArgs) 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
@@ -277,6 +307,8 @@ export function adoptionProvider(engine: ExternalEngine, contract: AdoptionContr
},
async busy(owner): Promise<boolean | null> {
if ('tail' in busy) return turnOpen(owner.record, busy.tail, null)
+ // A process placed by its arguments has no record to read; that absence says nothing here.
+ if (!owner.record) return null
const row = record(await readJson(owner.record))
// No record: the process ended with it, so it is not mid-turn.
if (!row) return false
diff --git a/cli/src/engines/otherAdoption.golden.spec.ts b/cli/src/engines/otherAdoption.golden.spec.ts
index 96ff474d9..9273b4774 100644
--- a/cli/src/engines/otherAdoption.golden.spec.ts
+++ b/cli/src/engines/otherAdoption.golden.spec.ts
@@ -293,7 +293,7 @@ describe('what the core\'s adoption finds of the other engines\' conversations',
const view = {
list: async () => rows,
openFiles: async (pids: readonly number[]) => new Map(pids.flatMap((pid) => files.has(pid) ? [[pid, files.get(pid)!] as [number, string[]]] : [])),
- openFilesOf: async () => new Map<number, string[]>(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map<number, string[]>(),
alive: () => true,
}
const scanned = new m.external.ExternalSessions({ providers, excluded: [join(root, 'data')], log: () => {} })
@@ -321,7 +321,7 @@ describe('what the core\'s adoption finds of the other engines\' conversations',
{ pid: 105, ppid: 1, executable: 'kilo', args: `kilo -s ${ID.kilo}` },
{ pid: 104, ppid: 1, executable: 'opencode', args: `opencode -s ${ID.opencode}` },
],
- openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
+ openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
})
check('Kilo alone', {
sessions: await Promise.all(sessions.map(async session => ({ ...session, readHistory: await session.readHistory?.() }))),
diff --git a/cli/src/engines/transcriptReads.golden.spec.ts b/cli/src/engines/transcriptReads.golden.spec.ts
index fbe093753..075342610 100644
--- a/cli/src/engines/transcriptReads.golden.spec.ts
+++ b/cli/src/engines/transcriptReads.golden.spec.ts
@@ -240,7 +240,7 @@ async function adoptionCases(): Promise<Record<string, unknown>> {
{ pid: 201, ppid: 1, executable: 'claude', args: 'claude' },
]
const alive = new Set([101, 102, 106, 107, 108, 109, 110, 111, 112, 113, 201])
- const claudeView: ProcessView = { list: async () => running, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: (pid) => alive.has(pid) }
+ const claudeView: ProcessView = { list: async () => running, openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: (pid) => alive.has(pid) }
for (const moved of [false, true]) {
if (moved) adoptMoved(); else forgetMoved()
const claims = await providerOf('claude').owners!(claudeView)
@@ -273,7 +273,7 @@ async function adoptionCases(): Promise<Record<string, unknown>> {
{ pid: 313, ppid: 1, executable: 'codex-acp-wrapper', args: 'codex-acp-wrapper --stdio' },
],
openFiles: async () => new Map(), alive: () => true,
- openFilesOf: async (commands) => {
+ cwds: async () => new Map(), openFilesOf: async (commands) => {
cases['owners · codex · asked for'] = commands
return new Map([
held(301, [C1, '/dev/ttys003', join(root, 'tmp', 'rollout-notes.txt')]), held(302, ['/x/rollout-2026-not-an-id.jsonl']),
diff --git a/cli/src/lib/sessionSearch/external.spec.ts b/cli/src/lib/sessionSearch/external.spec.ts
index d6150addf..ae418e752 100644
--- a/cli/src/lib/sessionSearch/external.spec.ts
+++ b/cli/src/lib/sessionSearch/external.spec.ts
@@ -58,7 +58,7 @@ describe('ExternalSessions', () => {
})
})
-const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
+const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
describe('OpenSessions', () => {
function open(providers: ExternalProvider[], extra: Partial<ConstructorParameters<typeof OpenSessions>[0]> = {}) {
diff --git a/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts b/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts
index f0c0af836..5eaec4871 100644
--- a/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts
+++ b/cli/src/lib/sessionSearch/externalShapes.golden.spec.ts
@@ -8,7 +8,7 @@ import type { ExternalProvider, ExternalSession, OwnerClaim, ProcessView } from
process.env.TZ = 'UTC'
const golden = fileURLToPath(new URL('./__fixtures__/external-shapes.golden.json', import.meta.url))
-const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
+const quiet: ProcessView = { list: async () => [], openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
it('preserves external lists, exact ownership, conservative busy answers and core admission on both platforms', async () => {
const root = mkdtempSync(join(tmpdir(), 'external-shapes-'))
diff --git a/cli/src/lib/sessionSearch/externals/agy.spec.ts b/cli/src/lib/sessionSearch/externals/agy.spec.ts
index b3b8b8e67..1f6a625c8 100644
--- a/cli/src/lib/sessionSearch/externals/agy.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/agy.spec.ts
@@ -165,7 +165,7 @@ describe('agyProvider', () => {
[91702, [join(real, 'presence', `${ID2}.lock`), join(real, 'presence', 'not-an-id.lock'), join(real, 'elsewhere', `${ID3}.lock`), join(real, 'presence', `${ID3}.pid`)]],
])
},
- openFilesOf: async () => { throw new Error('not used') },
+ cwds: async () => new Map(), openFilesOf: async () => { throw new Error('not used') },
alive: () => true,
}
const claims = await provider.owners!(view)
@@ -184,7 +184,7 @@ describe('agyProvider', () => {
const view = (rows: RunningProcess[]): ProcessView => ({
list: async () => rows,
openFiles: async () => { asked++; return new Map([[5, [join(home, 'presence', `${ID}.lock`)]]]) },
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive: () => true,
})
expect(await provider.owners!(view([row(1, 'zsh', '-zsh')]))).toEqual([])
diff --git a/cli/src/lib/sessionSearch/externals/claude.spec.ts b/cli/src/lib/sessionSearch/externals/claude.spec.ts
index 6f59c530d..f07012e9b 100644
--- a/cli/src/lib/sessionSearch/externals/claude.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/claude.spec.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
+import { externalEvidence } from '../evidence.js'
import { claudeProvider, readClaudeHead } from './claude.js'
import { scanMemo } from './support.js'
import { type ProcessView, UNSETTLED } from './types.js'
@@ -27,7 +28,7 @@ const line = (sessionId: string, entrypoint: string, extra: Record<string, unkno
message: { role: 'user', content: 'fix the dial scroll' }, ...extra,
})
const view = (alive: (pid: number) => boolean): ProcessView => ({
- list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive,
+ list: async () => [], openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive,
})
describe('readClaudeHead', () => {
@@ -127,4 +128,36 @@ describe('claudeProvider', () => {
// The record gone is the process gone: not mid-turn.
expect(await provider.busy!({ pid: 9, record: join(root, 'sessions', 'gone.json') })).toBe(false)
})
+
+ it('places a live Claude with no record by its arguments, or leaves it unplaced with its folder, for admission only', async () => {
+ const root = home()
+ const started = Date.parse('2026-09-27T10:00:00Z')
+ write(join(root, 'sessions', '101.json'), [{ pid: 101, sessionId: A, status: 'idle', startedAt: started + 400 }])
+ const provider = claudeProvider({ projectsDir: join(root, 'projects'), home: root })
+ const running = [
+ { pid: 101, ppid: 1, executable: 'claude', args: 'claude', started },
+ { pid: 201, ppid: 1, executable: 'claude', args: `claude --resume ${B}`, started },
+ { pid: 202, ppid: 1, executable: 'claude', args: 'claude --append-system-prompt "be brief"', started },
+ { pid: 203, ppid: 1, executable: 'claude', args: 'claude --session-id not!an!id', started },
+ { pid: 204, ppid: 1, executable: '-zsh', args: `-zsh --resume ${B}`, started },
+ ]
+ const asked: number[][] = []
+ const machine: ProcessView = { ...view(() => true), list: async () => running,
+ cwds: async (pids) => { asked.push([...pids]); return new Map([[202, '/work/other']]) } }
+ expect(await externalEvidence(() => provider.ownership!(machine))).toEqual({ ok: true, value: {
+ claims: [
+ { sessionId: A, pid: 101, record: join(root, 'sessions', '101.json') },
+ { sessionId: B, pid: 201, record: '', fromArgs: true },
+ ],
+ // Named or not, a record-less process may have moved on: it stays unplaced beside its claim.
+ unresolved: [{ pid: 201, cwd: null, named: B }, { pid: 202, cwd: '/work/other' }, { pid: 203, cwd: null }],
+ } })
+ expect(asked).toEqual([[201, 202, 203]])
+ // The display reader is as it was: exact records only, and no folder is read.
+ expect(await provider.ownership!(machine)).toEqual({ claims: [{ sessionId: A, pid: 101, record: join(root, 'sessions', '101.json') }], unresolved: [] })
+ expect(asked).toHaveLength(1)
+ // Placed by its arguments alone: no record says whether it is mid-turn, so nobody can say.
+ expect(await provider.busy!({ pid: 201, record: '' })).toBeNull()
+ expect(await provider.confirmOwner!({ sessionId: B, pid: 201, record: '', fromArgs: true }, running[1])).toBeNull()
+ })
})
diff --git a/cli/src/lib/sessionSearch/externals/codex.spec.ts b/cli/src/lib/sessionSearch/externals/codex.spec.ts
index f866e1ac6..d9e7ab887 100644
--- a/cli/src/lib/sessionSearch/externals/codex.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/codex.spec.ts
@@ -132,7 +132,7 @@ describe('codexProvider', () => {
{ pid: 203, ppid: 1, executable: 'codex', args: '/opt/codex/bin/codex app-server --listen stdio' },
],
openFiles: async () => new Map(), alive: () => true,
- openFilesOf: async (commands) => {
+ cwds: async () => new Map(), openFilesOf: async (commands) => {
expect(commands).toEqual(['codex', 'Codex'])
return new Map([[201, [path, '/dev/ttys003', '/tmp/rollout-notes.txt']], [202, ['/x/rollout-2026-not-an-id.jsonl']], [203, [served]]])
},
diff --git a/cli/src/lib/sessionSearch/externals/commandcode.spec.ts b/cli/src/lib/sessionSearch/externals/commandcode.spec.ts
index 421264a14..6ac7a48e0 100644
--- a/cli/src/lib/sessionSearch/externals/commandcode.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/commandcode.spec.ts
@@ -52,7 +52,7 @@ function scanner(provider: ExternalProvider, excluded: string[] = []) {
const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })
const view = (rows: RunningProcess[]): ProcessView => ({
- list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
+ list: async () => rows, openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
})
describe('readCommandCodeHead', () => {
diff --git a/cli/src/lib/sessionSearch/externals/copilot.spec.ts b/cli/src/lib/sessionSearch/externals/copilot.spec.ts
index c5e8449ad..e3ff8e9ae 100644
--- a/cli/src/lib/sessionSearch/externals/copilot.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/copilot.spec.ts
@@ -69,7 +69,7 @@ function view(rows: RunningProcess[], alive: (pid: number) => boolean = () => tr
return {
list: async () => { listed++; return rows },
openFiles: async () => new Map(),
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive,
listed: () => listed,
}
diff --git a/cli/src/lib/sessionSearch/externals/cursor.spec.ts b/cli/src/lib/sessionSearch/externals/cursor.spec.ts
index 1cbaa6338..1aba06957 100644
--- a/cli/src/lib/sessionSearch/externals/cursor.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/cursor.spec.ts
@@ -355,7 +355,7 @@ describe('cursorProvider.owners', () => {
const processes: ProcessView = {
list: async () => rows,
openFiles: async (pids) => { asked.push([...pids]); return new Map(files ? pids.map((pid) => [pid, files[pid] ?? []]) : []) },
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive,
}
return { processes, asked }
diff --git a/cli/src/lib/sessionSearch/externals/devin.spec.ts b/cli/src/lib/sessionSearch/externals/devin.spec.ts
index 605f64173..8da3a2d38 100644
--- a/cli/src/lib/sessionSearch/externals/devin.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/devin.spec.ts
@@ -262,7 +262,7 @@ describe('Devin owners', () => {
const view = (rows: RunningProcess[], dead: number[] = []): ProcessView => ({
list: async () => rows,
openFiles: async () => new Map(),
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive: (pid) => !dead.includes(pid),
})
diff --git a/cli/src/lib/sessionSearch/externals/grok.spec.ts b/cli/src/lib/sessionSearch/externals/grok.spec.ts
index 745070ebd..1ded52522 100644
--- a/cli/src/lib/sessionSearch/externals/grok.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/grok.spec.ts
@@ -82,7 +82,7 @@ function view(rows: RunningProcess[], alive: (pid: number) => boolean = () => tr
return {
list: async () => { listed++; return rows },
openFiles: async () => new Map(),
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive,
listed: () => listed,
}
diff --git a/cli/src/lib/sessionSearch/externals/hermes.spec.ts b/cli/src/lib/sessionSearch/externals/hermes.spec.ts
index 4de91c9e6..17a69eb0d 100644
--- a/cli/src/lib/sessionSearch/externals/hermes.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/hermes.spec.ts
@@ -428,7 +428,7 @@ describe('Hermes owners', () => {
const view = (rows: RunningProcess[], dead: number[] = []): ProcessView => ({
list: async () => rows,
openFiles: async () => new Map(),
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive: (pid) => !dead.includes(pid),
})
diff --git a/cli/src/lib/sessionSearch/externals/homes.spec.ts b/cli/src/lib/sessionSearch/externals/homes.spec.ts
index d72ec66c4..d13642ac9 100644
--- a/cli/src/lib/sessionSearch/externals/homes.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/homes.spec.ts
@@ -62,7 +62,7 @@ it('search recognizes a moved Claude conversation that is still busy in another
const claims = await provider.owners!({
alive: pid => pid === 123,
list: async () => [{ pid: 123, ppid: 1, executable: 'claude', args: 'claude', started: 1000 }],
- openFiles: async () => new Map(), openFilesOf: async () => new Map(),
+ openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(),
})
expect(claims).toContainEqual({ sessionId: 'external-conversation', pid: 123, record })
expect(await provider.busy!(claims[0])).toBe(true)
diff --git a/cli/src/lib/sessionSearch/externals/index.spec.ts b/cli/src/lib/sessionSearch/externals/index.spec.ts
index ac17df6c5..b83063391 100644
--- a/cli/src/lib/sessionSearch/externals/index.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/index.spec.ts
@@ -53,7 +53,7 @@ describe('where each engine keeps its conversations', () => {
})
describe('the other engines\' readers, loaded on first use', () => {
- const none: ProcessView = { list: async () => [], openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
+ const none: ProcessView = { list: async () => [], openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true }
const missing = '/nonexistent/adoption-root'
const paths = () => externalPaths({ CURSOR_CONFIG_DIR: missing, CURSOR_DATA_DIR: missing, OPENCODE_DB: `${missing}/opencode.db`, KILO_DB: `${missing}/kilo.db`, PI_CODING_AGENT_DIR: missing })
diff --git a/cli/src/lib/sessionSearch/externals/muse.spec.ts b/cli/src/lib/sessionSearch/externals/muse.spec.ts
index 1fd74b93b..18e2126e5 100644
--- a/cli/src/lib/sessionSearch/externals/muse.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/muse.spec.ts
@@ -62,7 +62,7 @@ function scanner(provider: ExternalProvider, excluded: string[] = []) {
const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })
const view = (rows: RunningProcess[]): ProcessView => ({
- list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
+ list: async () => rows, openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
})
describe('readMuseHead', () => {
diff --git a/cli/src/lib/sessionSearch/externals/opencode.spec.ts b/cli/src/lib/sessionSearch/externals/opencode.spec.ts
index 716ef5ee4..e6392f094 100644
--- a/cli/src/lib/sessionSearch/externals/opencode.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/opencode.spec.ts
@@ -414,7 +414,7 @@ describe('OpenCode owners', () => {
const view = (rows: Array<Partial<RunningProcess> & { pid: number; args: string }>): ProcessView => ({
list: async () => rows.map((row) => ({ ppid: 1, executable: row.args.split(' ')[0], ...row })),
openFiles: async () => new Map(),
- openFilesOf: async () => new Map(),
+ cwds: async () => new Map(), openFilesOf: async () => new Map(),
alive: () => true,
})
diff --git a/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts b/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts
index 580034360..312b2dbd9 100644
--- a/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/ownershipEvidence.spec.ts
@@ -17,7 +17,7 @@ it.each(providers)('%s launch arguments cannot establish that another conversati
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() }
+ alive: () => true, openFiles: async () => new Map(), cwds: 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)
diff --git a/cli/src/lib/sessionSearch/externals/pi.spec.ts b/cli/src/lib/sessionSearch/externals/pi.spec.ts
index 348e317d7..80a4222e8 100644
--- a/cli/src/lib/sessionSearch/externals/pi.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/pi.spec.ts
@@ -54,7 +54,7 @@ function scanner(provider: ExternalProvider, excluded: string[] = []) {
const row = (pid: number, executable: string, args: string): RunningProcess => ({ pid, ppid: 1, executable, args })
const view = (rows: RunningProcess[]): ProcessView => ({
- list: async () => rows, openFiles: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
+ list: async () => rows, openFiles: async () => new Map(), cwds: async () => new Map(), openFilesOf: async () => new Map(), alive: () => true,
})
describe('readPiHead', () => {
diff --git a/cli/src/lib/sessionSearch/externals/support.spec.ts b/cli/src/lib/sessionSearch/externals/support.spec.ts
index 3643389e6..93127a9c3 100644
--- a/cli/src/lib/sessionSearch/externals/support.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/support.spec.ts
@@ -1,13 +1,13 @@
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { homedir, tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { UNSETTLED } from './types.js'
import {
- absoluteFolder, entries, epochMs, fileStamp, firstLine, harnessTtys, listProcesses, parseLine, parseLsof, parseTtys,
- processAlive, processTtys, processView, readHead, readJson, readTail, readText, record, run, scanMemo, text, UUID,
+ absoluteFolder, entries, epochMs, fileStamp, firstLine, folderKey, gitCommonDir, harnessTtys, listProcesses, parseLine, parseLsof, parseTtys,
+ processAlive, processCwds, processTtys, processView, readHead, readJson, readTail, readText, record, run, sameProject, scanMemo, text, UUID,
within,
} from './support.js'
@@ -207,6 +207,77 @@ describe('processes', () => {
expect(await processTtys([1], async () => null)).toEqual(new Map())
})
+ it("reads each process's working folder in one bounded look, and leaves out what it cannot read", async () => {
+ const calls: string[] = []
+ const exec = async (command: string, args: readonly string[]) => {
+ calls.push(`${command} ${args.join(' ')}`)
+ // lsof says nothing of a gone pid, or of one it may not look at; a pid with no name line is unknown too.
+ return 'p7\nfcwd\nn/work/dial\np8\nfcwd\n'
+ }
+ expect(await processCwds([7, 8, 9], exec, 'darwin')).toEqual(new Map([[7, '/work/dial']]))
+ expect(calls).toEqual(['lsof -n -P -a -d cwd -Fpn -p 7,8,9'])
+ expect(await processCwds([7], async () => null, 'darwin')).toEqual(new Map())
+ expect(await processCwds([], exec, 'darwin')).toEqual(new Map())
+ expect(calls).toHaveLength(1)
+ // Linux says it in /proc, one link a pid; one it may not read is unknown.
+ const links: string[] = []
+ const link = async (path: string) => {
+ links.push(path)
+ if (path === '/proc/8/cwd') throw Object.assign(new Error('denied'), { code: 'EACCES' })
+ return path === '/proc/7/cwd' ? '/work/dial' : ''
+ }
+ expect(await processCwds([7, 8, 9], exec, 'linux', link)).toEqual(new Map([[7, '/work/dial']]))
+ expect(links.sort()).toEqual(['/proc/7/cwd', '/proc/8/cwd', '/proc/9/cwd'])
+ expect(calls).toHaveLength(1)
+ })
+
+ it('keys a folder the same however it is spelled', async () => {
+ const dir = home()
+ mkdirSync(join(dir, 'project'))
+ symlinkSync(join(dir, 'project'), join(dir, 'link'))
+ const key = await folderKey(join(dir, 'project'))
+ for (const spelling of [`${join(dir, 'project')}/`, join(dir, 'link'), join(dir, 'link', '..', 'project')]) {
+ expect(await folderKey(spelling), spelling).toBe(key)
+ }
+ // A folder that is gone keeps its spelling, less a trailing slash.
+ expect(await folderKey(`${join(dir, 'gone')}/`)).toBe(join(dir, 'gone'))
+ })
+
+ it("finds a repository's shared store from any of its folders and worktrees, without running git", async () => {
+ const dir = home()
+ const main = join(dir, 'main'), tree = join(dir, 'tree'), sub = join(dir, 'sub'), odd = join(dir, 'odd')
+ mkdirSync(join(main, '.git', 'worktrees', 'tree'), { recursive: true }); mkdirSync(join(main, 'src', 'deep'), { recursive: true })
+ mkdirSync(join(tree, 'src'), { recursive: true }); mkdirSync(sub); mkdirSync(odd)
+ // A worktree names its own folder in the store, relative or absolute; a submodule its own store.
+ writeFileSync(join(tree, '.git'), 'gitdir: ../main/.git/worktrees/tree\n')
+ mkdirSync(join(main, '.git', 'modules', 'sub'), { recursive: true })
+ writeFileSync(join(sub, '.git'), `gitdir: ${join(main, '.git', 'modules', 'sub')}\n`)
+ writeFileSync(join(odd, '.git'), 'not a pointer\n')
+ const store = await folderKey(join(main, '.git'))
+ expect(await gitCommonDir(join(main, 'src', 'deep'), '/')).toBe(store)
+ expect(await gitCommonDir(join(tree, 'src'), '/')).toBe(store)
+ expect(await gitCommonDir(sub, '/')).toBe(await folderKey(join(main, '.git', 'modules', 'sub')))
+ expect(await gitCommonDir(odd, '/')).toBeNull()
+ // Not past the ceiling: a `.git` above it does not make every folder one project.
+ mkdirSync(join(dir, 'nested', 'a'), { recursive: true }); mkdirSync(join(dir, 'nested', '.git'))
+ expect(await gitCommonDir(join(dir, 'nested', 'a'), join(dir, 'nested'))).toBeNull()
+ expect(await gitCommonDir(join(dir, 'nested', 'a'), dir)).toBe(await folderKey(join(dir, 'nested', '.git')))
+ // The default ceiling is the folder holding the homes.
+ expect(await gitCommonDir(dirname(homedir()))).toBeNull()
+
+ expect(await sameProject(`${main}/`, main, '/')).toBe(true)
+ // Within one repository by its store; a folder merely above or below, outside one, is another project.
+ expect(await sameProject(main, join(main, 'src', 'deep'), '/')).toBe(true)
+ expect(await sameProject(join(main, 'src', 'deep'), main, '/')).toBe(true)
+ expect(await sameProject(dir, join(dir, 'nested', 'a'), dir)).toBe(false)
+ expect(await sameProject(join(dir, 'nested', 'a'), dir, dir)).toBe(false)
+ expect(await sameProject(join(tree, 'src'), join(main, 'src'), '/')).toBe(true)
+ expect(await sameProject(sub, main, '/')).toBe(false)
+ expect(await sameProject(odd, join(dir, 'nested', 'a'), '/')).toBe(false)
+ // A name that only starts like the other is another folder.
+ expect(await sameProject(join(dir, 'mainly'), join(dir, 'main'), dir)).toBe(false)
+ })
+
it('lists the real machine: this very process is among them, with its own open files', async () => {
const view = processView()
const me = (await view.list()).find((row) => row.pid === process.pid)
@@ -223,6 +294,7 @@ describe('processes', () => {
await handle.close()
}
expect((await processTtys([process.pid])).has(process.pid)).toBe(true)
+ expect(await folderKey((await view.cwds([process.pid])).get(process.pid) ?? '')).toBe(await folderKey(process.cwd()))
})
it('lists no processes when ps cannot be read, and each start time when it can be read', async () => {
diff --git a/cli/src/lib/sessionSearch/externals/support.ts b/cli/src/lib/sessionSearch/externals/support.ts
index a43b0ac6f..c62a198e2 100644
--- a/cli/src/lib/sessionSearch/externals/support.ts
+++ b/cli/src/lib/sessionSearch/externals/support.ts
@@ -5,8 +5,9 @@
import { execFile } from 'node:child_process'
import type { Dirent } from 'node:fs'
-import { open, readdir, readFile, stat } from 'node:fs/promises'
-import { isAbsolute, relative, resolve } from 'node:path'
+import { open, readdir, readFile, readlink, realpath, stat } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { isHarnessSession, paneOwnerFormat } from '../../harnessSessionLabel.js'
import { processRows } from '../../tmux.js'
@@ -226,11 +227,86 @@ export async function listProcesses(read: typeof processRows = processRows): Pro
})
}
+/**
+ * Each of [pids]' working folder. Linux says it in /proc; macOS only through lsof, asked once for every pid
+ * (`-a -d cwd`: that one descriptor) under the same timeout and output bound as its open files. A pid whose
+ * folder cannot be read (gone, another user's) is left out: unknown, which admission reads as "may hold any".
+ */
+export async function processCwds(
+ pids: readonly number[],
+ exec: Run = run,
+ os: NodeJS.Platform = process.platform,
+ link: (path: string) => Promise<string> = readlink,
+): Promise<Map<number, string>> {
+ const cwds = new Map<number, string>()
+ if (!pids.length) return cwds
+ if (os === 'linux') {
+ await Promise.all(pids.map(async (pid) => {
+ const cwd = await link(`/proc/${pid}/cwd`).catch(() => null)
+ if (cwd) cwds.set(pid, cwd)
+ }))
+ return cwds
+ }
+ for (const [pid, files] of parseLsof(await exec('lsof', ['-n', '-P', '-a', '-d', 'cwd', '-Fpn', '-p', pids.join(',')], 3_000) ?? '')) {
+ if (files[0]) cwds.set(pid, files[0])
+ }
+ return cwds
+}
+
+/**
+ * A folder as one key whichever way it was spelled: a trailing slash, `..`, or a link (macOS's /tmp is
+ * /private/tmp, and lsof reports the resolved one). A folder that cannot be resolved keeps its spelling.
+ */
+export async function folderKey(path: string): Promise<string> {
+ const absolute = resolve(path)
+ return realpath(absolute).catch(() => absolute)
+}
+
+/**
+ * The git store a folder's repository shares with all its worktrees, read from disk without running git: the
+ * first `.git` above it, a folder (the store itself) or a worktree's `gitdir:` file, whose
+ * `<store>/worktrees/<name>` names the store two levels up. Null outside a repository. The walk stops at the
+ * folder holding the homes, so a stray `.git` there cannot make every project one.
+ */
+export async function gitCommonDir(folder: string, stop: string = dirname(homedir())): Promise<string | null> {
+ const ceiling = await folderKey(stop)
+ let dir = await folderKey(folder)
+ for (let depth = 0; depth < 128 && dir !== ceiling; depth++) {
+ const dotgit = join(dir, '.git')
+ const found = await stat(dotgit).catch(() => null)
+ if (found?.isDirectory()) return folderKey(dotgit)
+ if (found?.isFile()) {
+ const named = /^gitdir:\s*(.+?)\s*$/m.exec(await readFile(dotgit, 'utf8').catch(() => ''))?.[1]
+ if (!named) return null
+ const gitdir = resolve(dir, named)
+ return folderKey(/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitdir) ? dirname(dirname(gitdir)) : gitdir)
+ }
+ const parent = dirname(dir)
+ if (parent === dir) break
+ dir = parent
+ }
+ return null
+}
+
+/**
+ * Whether a process working in [a] might list a conversation of [b] in its own picker: Claude Code's `/resume`
+ * lists its own folder's, and newer versions its repository's worktrees too, so the same folder or one git
+ * store. Never a folder merely above or below: a TUI left open in the home folder is common, and counting
+ * every folder below it would hold every adoption on the machine again, the bug this check replaced.
+ */
+export async function sameProject(a: string, b: string, stop?: string): Promise<boolean> {
+ const [x, y] = await Promise.all([folderKey(a), folderKey(b)])
+ if (x === y) return true
+ const [left, right] = await Promise.all([gitCommonDir(x, stop), gitCommonDir(y, stop)])
+ return left !== null && left === right
+}
+
/** The machine's processes, looked at once per view: the list is read on first use and kept. */
export function processView(
exec: Run = run,
alive: (pid: number) => boolean = processAlive,
list: () => Promise<RunningProcess[]> = listProcesses,
+ cwds: (pids: readonly number[]) => Promise<Map<number, string>> = (pids) => processCwds(pids, exec),
): ProcessView {
let listed: Promise<RunningProcess[]> | null = null
return {
@@ -241,6 +317,7 @@ export function processView(
openFilesOf: async (commands) => commands.length
? parseLsof(await exec('lsof', ['-n', '-P', '-Fpn', ...commands.flatMap((name) => ['-c', name])], 3_000) ?? '')
: new Map(),
+ cwds,
alive,
}
}
diff --git a/cli/src/lib/sessionSearch/externals/types.ts b/cli/src/lib/sessionSearch/externals/types.ts
index 1623010ee..d38204f55 100644
--- a/cli/src/lib/sessionSearch/externals/types.ts
+++ b/cli/src/lib/sessionSearch/externals/types.ts
@@ -92,6 +92,8 @@ export interface ProcessView {
openFiles(pids: readonly number[]): Promise<Map<number, string[]>>
/** The files processes with these command names have open, by pid (`lsof -c`). */
openFilesOf(commands: readonly string[]): Promise<Map<number, string[]>>
+ /** Each of [pids]' working folder, where it could be read; a pid left out is one nobody can say. */
+ cwds(pids: readonly number[]): Promise<Map<number, string>>
alive(pid: number): boolean
}
@@ -111,12 +113,36 @@ export interface OwnerClaim {
fromArgs?: boolean
}
+/**
+ * A live process of the engine that leaves no exact word of which conversation it has open: Claude Code
+ * started before it kept `sessions/<pid>.json`, with no session in its arguments. It may hold any
+ * conversation its own `/resume` lists, which are its working folder's; `cwd` is null when that folder
+ * could not be read, and then it may hold any.
+ */
+export interface UnresolvedOwner {
+ pid: number
+ cwd: string | null
+ /** The conversation its arguments name, which it started on; it may since have moved to another. */
+ named?: string
+}
+
+/** A provider's whole answer about who holds what: its exact claims, and the processes it could not place. */
+export interface Ownership {
+ claims: OwnerClaim[]
+ unresolved: UnresolvedOwner[]
+}
+
export interface ExternalProvider {
readonly engine: ExternalEngine
/** Every conversation of this engine on disk that a person started and Harness can resume. */
scan(ctx: ScanContext): Promise<ExternalSession[]>
/** Which of them a process has open right now, when the engine leaves exact evidence of it. */
owners?(view: ProcessView): Promise<OwnerClaim[]>
+ /**
+ * The same claims as `owners`, with the live processes it could not place. Only admission asks it, and
+ * only an engine whose processes can be unplaced has it; without it, every process is placed.
+ */
+ ownership?(view: ProcessView): Promise<Ownership>
/** 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.
diff --git a/cli/src/services/externalSessions.providers.spec.ts b/cli/src/services/externalSessions.providers.spec.ts
index 4ebd5dac6..2499bfe4a 100644
--- a/cli/src/services/externalSessions.providers.spec.ts
+++ b/cli/src/services/externalSessions.providers.spec.ts
@@ -1,5 +1,5 @@
/** Real provider records cross the admission service; no host processes or native homes are used. */
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
@@ -18,7 +18,7 @@ function setup(engine: 'claude' | 'grok') {
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() }
+ openFiles: async () => new Map(), cwds: 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' },
@@ -94,7 +94,7 @@ it('Codex FD claims require an actual engine process; a command-prefix helper is
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]]]) }
+ openFiles: async () => new Map(), cwds: 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 }
@@ -107,3 +107,142 @@ it('Codex FD claims require an actual engine process; a command-prefix helper is
expect(valid).toMatchObject({ ok: true, owner: { pid: 101 }, busy: true })
expect(valid).not.toHaveProperty('busyConfirmed')
})
+
+/**
+ * CLI 0.3.70: two long-running `claude` TUIs started before Claude Code kept `sessions/<pid>.json` held every
+ * adoption on the machine ("held · search · launched 0 of 4"). A process with no record may hold only what its
+ * arguments name, or what its own `/resume` lists: its project's conversations.
+ */
+function unplaced() {
+ const root = mkdtempSync(join(tmpdir(), 'adoption-unplaced-')); roots.push(root)
+ const cwd = join(root, 'project'), elsewhere = join(root, 'elsewhere'), other = '22222222-2222-4222-8222-222222222222'
+ mkdirSync(cwd); mkdirSync(elsewhere); symlinkSync(cwd, join(root, 'link'))
+ for (const session of [id, other]) json(join(root, 'projects', 'project', `${session}.jsonl`), {
+ type: 'user', sessionId: session, cwd, entrypoint: 'cli', message: { role: 'user', content: 'Fixture' },
+ })
+ const owner: RunningProcess = { pid: 101, ppid: 1, executable: 'claude', args: 'claude', started, generation: `ps:${started}` }
+ const stray: RunningProcess = { pid: 202, ppid: 1, executable: 'claude', args: 'claude --append-system-prompt "be brief"', started }
+ // `fresh` is what every look after the first sees: a process that arrives while the first look's reads wait.
+ const state = { processes: [stray], cwds: new Map<number, string>([[202, elsewhere]]), asked: [] as number[][], views: 0, fresh: null as RunningProcess[] | null }
+ const view = (): ProcessView => {
+ const processes = state.views++ && state.fresh ? state.fresh : state.processes
+ return { list: async () => processes, alive: pid => processes.some(row => row.pid === pid),
+ openFiles: async () => new Map(), openFilesOf: async () => new Map(),
+ cwds: async pids => { state.asked.push([...pids]); return new Map([...state.cwds].filter(([pid]) => pids.includes(pid))) } }
+ }
+ const provider = claudeProvider({ projectsDir: join(root, 'projects'), home: root })
+ const reader = createExternalSessions({ providers: [provider], generation: () => `ps:${started}`,
+ open: { view, ttys: async pids => new Map(pids.map(pid => [pid, `/dev/fixture-${pid}`])), harnessTtys: async () => new Set() } })
+ const inspect = (sessionId = id) => { state.views = 0; return reader.inspect({ engine: 'claude', sessionId }) }
+ const own = () => json(join(root, 'sessions', '101.json'), { pid: 101, sessionId: id, startedAt: started + 400, status: 'idle' })
+ return { root, cwd, elsewhere, other, owner, stray, state, inspect, own }
+}
+const unverified = { ok: false, error: 'SEARCH_UNAVAILABLE', detail: "The conversation's current owner could not be verified." }
+
+it('a record-less Claude in another folder holds nothing here: the conversation is free, or its own owner', async () => {
+ const test = unplaced()
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: null, busy: false })
+ // Its folder is asked once, for that process alone.
+ expect(test.state.asked).toEqual([[202]])
+ test.own(); test.state.processes = [test.owner, test.stray]
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: { pid: 101, tty: '/dev/fixture-101' }, busy: false })
+})
+
+it("a record-less Claude in the conversation's folder, or one whose folder is unknown, may hold it: nobody can say", async () => {
+ const test = unplaced()
+ for (const folder of [test.cwd, `${test.cwd}/`, join(test.root, 'link'), join(test.elsewhere, '..', 'project')]) {
+ test.state.cwds.set(202, folder)
+ expect(await test.inspect(), folder).toMatchObject(unverified)
+ }
+ test.state.cwds.clear()
+ expect(await test.inspect()).toMatchObject(unverified)
+ // Gone, it holds nothing: the same conversation is free.
+ test.state.processes = []
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: null })
+})
+
+it('a record-less Claude that arrives in the folder during the observation fails the second look', async () => {
+ const test = unplaced()
+ test.own(); test.state.processes = [test.owner]
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: { pid: 101 } })
+ test.state.fresh = [test.owner, test.stray]; test.state.cwds.set(202, test.cwd)
+ expect(await test.inspect()).toMatchObject(unverified)
+ // In another folder, its arrival changes nothing.
+ test.state.cwds.set(202, test.elsewhere)
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: { pid: 101 } })
+})
+
+it.each([
+ ['--resume', (session: string) => `claude --resume ${session}`],
+ ['-r', (session: string) => `claude -r ${session}`],
+ ['--resume=', (session: string) => `claude --resume=${session}`],
+ ['--session-id', (session: string) => `claude --session-id ${session}`],
+ ['--session-id=', (session: string) => `claude --session-id=${session}`],
+])('a record-less Claude started with %s holds that conversation, and may have moved to another of its folder', async (_flag, args) => {
+ const test = unplaced()
+ test.stray.args = args(test.other)
+ // Wherever it is, the conversation its arguments name may be open there: never stopped for it.
+ for (const folder of [test.elsewhere, test.cwd, null]) {
+ if (folder) test.state.cwds.set(202, folder); else test.state.cwds.clear()
+ expect(await test.inspect(test.other), String(folder)).toMatchObject({ ok: true, owner: { pid: 202, fromArgs: true, tty: '/dev/fixture-202' }, busy: true, generation: `ps:${started}` })
+ expect(await test.inspect(test.other)).not.toHaveProperty('busyConfirmed')
+ }
+ // `/resume` or `/clear` inside moves it to another conversation of its folder: nobody can say which.
+ test.state.cwds.set(202, test.cwd)
+ expect(await test.inspect()).toMatchObject(unverified)
+ test.state.cwds.clear()
+ expect(await test.inspect()).toMatchObject(unverified)
+ // In another folder, it cannot have this one.
+ test.state.cwds.set(202, test.elsewhere)
+ expect(await test.inspect()).toMatchObject({ ok: true, owner: null })
+ // Beside an exact owner of the same conversation, two processes may have it.
+ test.stray.args = args(id); test.own(); test.state.processes = [test.owner, test.stray]
+ expect(await test.inspect()).toMatchObject({ ok: false })
+})
+
+it('a record-less Claude elsewhere in the same repository may hold it; one merely above or below, outside one, cannot', async () => {
+ const test = unplaced()
+ // `/resume` never lists a subfolder's conversations: a TUI left open in the home folder (no repository)
+ // holds nothing in a project below it, nor one in a folder below the conversation's.
+ const below = join(test.cwd, 'packages', 'app'); mkdirSync(below, { recursive: true })
+ for (const folder of [test.root, below]) {
+ test.state.cwds.set(202, folder)
+ expect(await test.inspect(), folder).toMatchObject({ ok: true, owner: null })
+ }
+ // The conversation's folder is a worktree; the process works in the repository it was added from.
+ const main = join(test.root, 'main'); mkdirSync(join(main, '.git', 'worktrees', 'project'), { recursive: true })
+ writeFileSync(join(test.cwd, '.git'), `gitdir: ${join(main, '.git', 'worktrees', 'project')}\n`)
+ test.state.cwds.set(202, main)
+ expect(await test.inspect()).toMatchObject(unverified)
+ // Another repository, or a sibling folder outside any, is another project.
+ const unrelated = join(test.root, 'unrelated'); mkdirSync(join(unrelated, '.git'), { recursive: true })
+ for (const folder of [unrelated, test.elsewhere]) {
+ test.state.cwds.set(202, folder)
+ expect(await test.inspect(), folder).toMatchObject({ ok: true, owner: null })
+ }
+ // The conversation began in a subfolder of a repository whose root the process works in: one store.
+ rmSync(join(test.cwd, '.git')); mkdirSync(join(test.root, '.git'))
+ test.state.cwds.set(202, test.root)
+ expect(await test.inspect()).toMatchObject(unverified)
+})
+
+it('a fork names only its parent: a record-less `--fork-session` is placed by its folder', async () => {
+ const test = unplaced()
+ test.stray.args = `claude --resume ${test.other} --fork-session`
+ expect(await test.inspect(test.other)).toMatchObject({ ok: true, owner: null })
+ test.state.cwds.set(202, test.cwd)
+ expect(await test.inspect(test.other)).toMatchObject(unverified)
+})
+
+it('one live Claude named by two records still fails every conversation', async () => {
+ const test = unplaced()
+ const second = join(test.root, 'second'); mkdirSync(join(second, 'projects'), { recursive: true })
+ json(join(second, 'sessions', '101.json'), { pid: 101, sessionId: test.other, startedAt: started + 400, status: 'idle' })
+ test.own(); test.state.processes = [test.owner]
+ const reader = createExternalSessions({ providers: [claudeProvider({ projectsDir: '', home: '', roots: () => [join(test.root, 'projects'), join(second, 'projects')] })],
+ generation: () => `ps:${started}`, open: { view: () => ({ list: async () => [test.owner], alive: pid => pid === 101,
+ openFiles: async () => new Map(), openFilesOf: async () => new Map(), cwds: async () => new Map() }),
+ ttys: async () => new Map([[101, '/dev/fixture-101']]), harnessTtys: async () => new Set() } })
+ expect(await reader.inspect({ engine: 'claude', sessionId: id })).toMatchObject(unverified)
+ expect(await reader.inspect({ engine: 'claude', sessionId: test.other })).toMatchObject(unverified)
+})
diff --git a/cli/src/services/externalSessions.spec.ts b/cli/src/services/externalSessions.spec.ts
index 0340f6037..cce47f89f 100644
--- a/cli/src/services/externalSessions.spec.ts
+++ b/cli/src/services/externalSessions.spec.ts
@@ -15,7 +15,7 @@ function fixture() {
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 }
+ openFiles: async () => new Map(), cwds: 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()) } }
diff --git a/cli/src/services/externalSessions.ts b/cli/src/services/externalSessions.ts
index a007c4d52..770516728 100644
--- a/cli/src/services/externalSessions.ts
+++ b/cli/src/services/externalSessions.ts
@@ -4,9 +4,9 @@ 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'
+import { externalEvidence, externalReadFailed } from '../lib/sessionSearch/evidence.js'
+import { harnessTtys, processTtys, processView, sameProject, scanMemo } from '../lib/sessionSearch/externals/support.js'
+import type { Ownership, OwnerClaim, ProcessView, RunningProcess } from '../lib/sessionSearch/externals/types.js'
export interface ExternalReaderOptions extends ExternalSessionsOptions {
open?: Omit<OpenSessionsOptions, 'providers'>
@@ -60,7 +60,24 @@ export function createExternalSessions(options: ExternalReaderOptions) {
[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 ownership = async (view: ProcessView): Promise<Ownership> =>
+ await provider.ownership?.(view) ?? { claims: await provider.owners!(view), unresolved: [] }
+ // A process the provider could not place may hold any conversation its own picker lists: Claude Code's
+ // `/resume` lists its project's (sameProject, kept wide). One far from this folder cannot hold this one;
+ // one near it, or one whose folder could not be read, might, and then nobody can say who holds it. Before,
+ // any such process on the machine held every adoption (CLI 0.3.70: "launched 0 of 4 · 4 still waiting"
+ // behind two old TUIs). The conversation its arguments name is its fromArgs claim's to answer.
+ const ids = [session.sessionId, ...session.aliases ?? []]
+ const placed = async (found: Ownership): Promise<OwnerClaim[]> => {
+ for (const process of found.unresolved) {
+ if (process.named !== undefined && ids.includes(process.named)) continue
+ if (process.cwd !== null && !await sameProject(process.cwd, session.cwd)) continue
+ externalReadFailed(new Error('an unplaced process may hold it'), 'current owner')
+ throw new Error('an unplaced process may hold it')
+ }
+ return found.claims
+ }
+ const allClaims = await placed(await ownership(view))
const claims = matching(allClaims)
const pids = new Set(claims.map(claim => claim.pid))
if (pids.size > 1) throw new Error('conflicting owners')
@@ -86,7 +103,8 @@ export function createExternalSessions(options: ExternalReaderOptions) {
// 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')
+ // The same rule on the second look: a process that came up in this folder meanwhile may have it now.
+ if (signature(candidateClaims(await placed(await ownership(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)