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.

One owner per conversation, stopped harnesses included (#1150)

Deecdb6b0312547
diff --git a/cli/e2e/conversationOwners.e2e.ts b/cli/e2e/conversationOwners.e2e.ts
new file mode 100644
index 000000000..0713e3834
--- /dev/null
+++ b/cli/e2e/conversationOwners.e2e.ts
@@ -0,0 +1,96 @@
+/**
+ * One owner per conversation, stopped harnesses included (core/agents/conversationOwners.ts), on the real
+ * daemon with the fake Claude Code.
+ *
+ * How the duplicates formed on a real Mac (2026-10-10, docs/research/2026-10-10-harness-data-audit.md): a
+ * harness is stopped with its conversation, then the person picks that conversation up somewhere else, here
+ * `claude --resume <id>` typed into a terminal tile. The registry gave the conversation to the tile, as it
+ * does between running harnesses, but the stopped harness's record still claimed it, and Cmd-P listed both.
+ *
+ * What must happen: the stopped record is set aside (moved under `superseded/`, never deleted) the moment
+ * the tile binds, the apps are told with the tile as its successor, and the conversation has one row, still
+ * one after the tile is stopped too. A duplicate an older daemon left on disk is set aside as the core starts.
+ */
+import { copyFileSync, existsSync, mkdirSync, rmSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Row = Record<string, any>
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+const holders = async (client: LocalClient, sessionId: string) =>
+ (await rows(client)).filter((agent) => agent.sessionId === sessionId).map((agent) => agent.id)
+
+describe('one owner per conversation, stopped harnesses included', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it('a conversation resumed in a terminal leaves the stopped harness it came from: now, after a stop, and at start', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-200).join('\n')}`) })
+ const cwd = join(d.projectsDir, 'owners')
+ mkdirSync(cwd, { recursive: true })
+ await d.start()
+ let client = await LocalClient.connect(d)
+
+ // A Claude Code harness with a conversation, stopped: its record keeps the conversation.
+ const created = await client.request('agent_create', { engine: 'claude', cwd }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const first = await until('the first harness to bind its conversation', async () => {
+ const now = await row(client, created.agent.id)
+ return now?.status === 'active' && now.sessionId ? now : null
+ }, 60_000, 250)
+ const conversation: string = first.sessionId
+ // A turn, as a person has before stopping: what the conversation's identity is confirmed from.
+ const ended = client.next((frame) => frame.type === 'turn_ended' && frame.agentId === first.id, 45_000, 'the first turn to end')
+ client.send('message', { agentId: first.id, content: 'remember this conversation' })
+ await ended
+ expect((await client.request('agent_delete', { agentId: first.id }, 60_000)).error).toBeUndefined()
+ await until('the first harness listed as stopped with its conversation', async () => {
+ const now = await row(client, first.id)
+ return now?.status === 'stopped' && now.sessionId === conversation ? now : null
+ }, 60_000, 250)
+
+ // The person picks the conversation up in a terminal tile.
+ const opened = await client.request('agent_create', { engine: 'terminal', cwd }, 60_000)
+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()
+ const tile = await until('the terminal tile to be up', async () => {
+ const now = await row(client, opened.agent.id)
+ return now?.status === 'active' && now.tmuxPane ? now : null
+ }, 60_000, 250)
+ // Only what is said from here on: the stop above announced its own agent_deleted (retained).
+ const told = client.next((frame) => frame.type === 'agent_deleted' && frame.payload?.agentId === first.id, 60_000, 'the stopped harness set aside')
+ await d.tmux.run('send-keys', '-t', tile.tmuxPane, '-l', `claude --resume ${conversation}`)
+ await d.tmux.run('send-keys', '-t', tile.tmuxPane, 'Enter')
+ await until('the tile to bind the conversation', async () => (await row(client, tile.id))?.sessionId === conversation || null, 45_000, 500)
+ expect((await told).payload).toMatchObject({ agentId: first.id, retained: false, successor: tile.id })
+ expect(await holders(client, conversation)).toEqual([tile.id])
+ const aside = join(d.env.ADAPTER_DATA_DIR!, 'stopped-agents', 'superseded', `${first.id}.json`)
+ expect(existsSync(aside), 'set aside, not deleted').toBe(true)
+ expect(existsSync(join(d.env.ADAPTER_DATA_DIR!, 'stopped-agents', `${first.id}.json`))).toBe(false)
+
+ // Stopped too, the tile is the conversation's one row.
+ expect((await client.request('agent_delete', { agentId: tile.id }, 60_000)).error).toBeUndefined()
+ await until('the tile listed as stopped with the conversation', async () => {
+ const now = await row(client, tile.id)
+ return now?.status === 'stopped' && now.sessionId === conversation ? now : null
+ }, 60_000, 250)
+ expect(await holders(client, conversation)).toEqual([tile.id])
+
+ // The duplicate as an older daemon left it: put the first record back, and start again.
+ client.close()
+ await d.stop()
+ copyFileSync(aside, join(d.env.ADAPTER_DATA_DIR!, 'stopped-agents', `${first.id}.json`))
+ rmSync(aside)
+ await d.start()
+ client = await LocalClient.connect(d)
+ expect(await holders(client, conversation)).toEqual([tile.id])
+ expect(existsSync(aside), 'set aside again as the core started').toBe(true)
+ expect(d.log()).toMatch(new RegExp(`${first.id.slice(0, 8)} set aside: ${tile.id.slice(0, 8)} owns conversation`))
+ client.close()
+ }, 300_000)
+})
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index 594f51d7b..9c420cac6 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -113,6 +113,26 @@ describe('binding a registered session to its agent', () => {
})
})
+ // A conversation new to this harness takes it from any stopped harness it came from (conversationOwners.ts).
+ it('settles who owns a newly bound conversation, and only a newly bound one; a failure never stops the bind', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const owners = { settle: vi.fn(() => []) }
+ const run = setup({ owners })
+ const entry = agent({ boundAt: Date.parse('2026-10-04T10:00:00Z') })
+ await registered(run, entry, meta({ isNew: true }))
+ expect(owners.settle).toHaveBeenCalledWith(['claude\u0000\u0000\u0000s1'])
+ await registered(run, entry, meta({ isNew: false }))
+ expect(owners.settle).toHaveBeenCalledTimes(1)
+ owners.settle.mockImplementationOnce(() => { throw new Error('stopped store unreadable') })
+ await registered(run, entry, meta({ isNew: true }))
+ owners.settle.mockImplementationOnce(() => { throw 'plain' })
+ await registered(run, entry, meta({ isNew: true }))
+ expect(warn).toHaveBeenCalledWith('[agent] a1 could not settle who owns s1: stopped store unreadable')
+ expect(warn).toHaveBeenCalledWith('[agent] a1 could not settle who owns s1: plain')
+ // Each new binding is still announced after a failed settle (the one that was not new announces nothing).
+ expect(run.deps.announceSession).toHaveBeenCalledTimes(3)
+ })
+
it('still tells the app of a binding when the record it resumes from cannot be saved, as on a full disk', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const run = setup()
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index 78c87cdff..af179e7cd 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -22,6 +22,7 @@ import { projectDisplayName, type registry, type RegisteredSession } from '../..
import type { SessionInputController } from '../../lib/sessionInput.js'
import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
+import { conversationKey, type ConversationOwners } from './conversationOwners.js'
import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
import type { SwarmPromptScopes } from '../../teams/promptScope.js'
@@ -69,11 +70,13 @@ export interface BindDeps {
deviceInput: Pick<AutonomousDeviceInput, 'forget'>
/** Where Copilot, Grok and agy keep their sessions. */
homes: { copilot: string; grok: string; agy: string }
+ /** One owner per conversation, stopped harnesses included (conversationOwners.ts). */
+ owners?: Pick<ConversationOwners, 'settle'>
}
export function createBinding({
registry, mirror, forgetSession, clients, attachSession, announceSession, stoppedAgents, syncRecapPool, teams,
- input, deviceInput, homes,
+ input, deviceInput, homes, owners,
}: BindDeps) {
/**
* Forks whose engine session has not reported in yet, agentId → the SOURCE's sessionId. A fork's tile
@@ -128,6 +131,12 @@ export function createBinding({
console.error(`[agent] ${sid(entry.agentId)} could not save the record it resumes from: ${error instanceof Error ? error.message : error}`)
}
if (entry.resumeOnly) stoppedAgents.finishResume(entry.agentId)
+ // A conversation new to this harness has one owner from now on: a stopped harness it came from (a
+ // `/resume`, `claude --resume` in a terminal, a compaction) lets it go, as a running one already has.
+ if (meta.isNew) {
+ try { owners?.settle([conversationKey(entry)]) }
+ catch (error) { console.warn(`[agent] ${sid(entry.agentId)} could not settle who owns ${sid(entry.sessionId)}: ${error instanceof Error ? error.message : error}`) }
+ }
syncRecapPool()
if (meta.isNew) {
registry.inheritName(entry.agentId, entry.sessionId)
diff --git a/cli/src/core/agents/conversationOwners.spec.ts b/cli/src/core/agents/conversationOwners.spec.ts
new file mode 100644
index 000000000..8b6c0cb3f
--- /dev/null
+++ b/cli/src/core/agents/conversationOwners.spec.ts
@@ -0,0 +1,126 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { conversationKey, createConversationOwners, type ConversationOwnersDeps } from './conversationOwners.js'
+
+const row = (agentId: string, sessionId: string, extra: Partial<RegisteredSession> = {}): RegisteredSession => ({
+ agentId, sessionId, engine: 'claude', codexHome: null, hermesHome: null, boundAt: 1000, registeredAt: 500, touchedAt: 2000,
+ ...extra,
+} as RegisteredSession)
+
+/** A stopped store holding [stopped], live harnesses [live], and what was said to the apps. */
+function setup(stopped: RegisteredSession[], live: RegisteredSession[] = [], extra: Partial<ConversationOwnersDeps> = {}) {
+ const records = new Map(stopped.map((saved) => [saved.agentId, saved]))
+ const reservations = new Map<string, number>()
+ const sent: unknown[] = []
+ const commander: unknown[] = []
+ const stoppedAgents = {
+ list: vi.fn(() => [...records.values()]),
+ get: vi.fn((id: string) => records.get(id) ?? null),
+ supersede: vi.fn((id: string) => { const saved = records.get(id) ?? null; records.delete(id); return saved }),
+ resumeReservedAt: vi.fn((id: string) => reservations.get(id) ?? null),
+ }
+ const owners = createConversationOwners({
+ stoppedAgents, live: () => live, clients: { send: (frame) => sent.push(frame), sendCommander: (frame) => commander.push(frame) },
+ reservationMs: 600_000, now: () => 10_000_000, ...extra,
+ })
+ return { owners, records, reservations, sent, commander, stoppedAgents }
+}
+
+describe('a conversation', () => {
+ it('is its engine, profile, home and id; a record without one, or a terminal, holds none', () => {
+ expect(conversationKey(row('a', 'c1'))).toBe('claude\u0000\u0000\u0000c1')
+ expect(conversationKey(row('a', 'c1', { engine: 'codex', codexHome: '/p' }))).not.toBe(conversationKey(row('a', 'c1', { engine: 'codex' })))
+ expect(conversationKey(row('a', 'c1', { engine: 'hermes', hermesHome: '/h' }))).not.toBe(conversationKey(row('a', 'c1', { engine: 'hermes' })))
+ expect(conversationKey(row('a', ''))).toBeNull()
+ expect(conversationKey(row('a', 'c1', { engine: 'terminal' }))).toBeNull()
+ })
+})
+
+describe('one owner per conversation, stopped harnesses included', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('a running harness wins: every stopped record of another harness holding it is set aside and announced', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { owners, records, sent, commander } = setup([row('old', 'c1', { boundAt: 9_000 }), row('older', 'c1')], [row('new', 'c1', { boundAt: 1 })])
+ expect(owners.settle().sort()).toEqual(['old', 'older'])
+ expect([...records.keys()]).toEqual([])
+ expect(sent).toContainEqual({ type: 'agent_deleted', payload: { agentId: 'old', retained: false, successor: 'new' } })
+ expect(commander).toContainEqual({ type: 'agent_deleted', payload: { agentId: 'old' } })
+ })
+
+ it('among stopped records the newest binding wins, then the newest record, then the id', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const bound = setup([row('a', 'c1', { boundAt: 3000 }), row('b', 'c1', { boundAt: 5000 }), row('c', 'c1', { boundAt: null })])
+ expect(bound.owners.settle().sort()).toEqual(['a', 'c'])
+ expect([...bound.records.keys()]).toEqual(['b'])
+ const touched = setup([row('a', 'c1', { touchedAt: 9 }), row('b', 'c1', { touchedAt: 7 })])
+ expect(touched.owners.settle()).toEqual(['b'])
+ const named = setup([row('b', 'c1'), row('a', 'c1')])
+ expect(named.owners.settle()).toEqual(['b'])
+ // A record bound before its fields existed dates from its registration.
+ const legacy = setup([row('a', 'c1', { boundAt: null, registeredAt: 7000 }), row('b', 'c1', { boundAt: 6000 })])
+ expect(legacy.owners.settle()).toEqual(['b'])
+ })
+
+ it('leaves alone what has one owner: a lone record, a running harness\'s own record, other conversations', () => {
+ const { owners, records } = setup([row('a', 'c1'), row('b', 'c2'), row('live', 'c3'), row('t', '', { engine: 'terminal' })], [row('live', 'c3'), row('other', 'c4')])
+ expect(owners.settle()).toEqual([])
+ expect([...records.keys()]).toEqual(['a', 'b', 'live', 't'])
+ })
+
+ it('never sets aside a record whose resume is in flight; an older reservation protects nothing', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { owners, records, reservations } = setup([row('a', 'c1', { boundAt: 1 }), row('b', 'c1', { boundAt: 2 }), row('c', 'c1', { boundAt: 3 })])
+ reservations.set('a', 10_000_000 - 1000)
+ reservations.set('b', 10_000_000 - 600_001)
+ expect(owners.settle()).toEqual(['b'])
+ expect([...records.keys()].sort()).toEqual(['a', 'c'])
+ })
+
+ it('settles only the conversations named, and nothing for none', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { owners, stoppedAgents } = setup([row('a', 'c1'), row('b', 'c1', { boundAt: 2000 }), row('x', 'c2'), row('y', 'c2', { boundAt: 2000 })])
+ expect(owners.settle([null])).toEqual([])
+ expect(stoppedAgents.list).not.toHaveBeenCalled()
+ expect(owners.settle([conversationKey(row('?', 'c1'))])).toEqual(['a'])
+ expect(owners.settle()).toEqual(['x'])
+ })
+
+ it('a record that vanished or cannot be moved stays, said, and the others still settle', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { owners, stoppedAgents, sent } = setup([row('gone', 'c1'), row('stuck', 'c1'), row('ok', 'c1'), row('owner', 'c1', { boundAt: 9000 })])
+ stoppedAgents.supersede.mockImplementation((id: string) => {
+ if (id === 'gone') return null
+ if (id === 'stuck') throw new Error('disk full')
+ if (id === 'ok') return row('ok', 'c1')
+ throw 'not a record'
+ })
+ expect(owners.settle()).toEqual(['ok'])
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('disk full'))
+ expect(sent).toHaveLength(1)
+ })
+
+ it('a non-Error failure is said in words too', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { owners, stoppedAgents } = setup([row('a', 'c1'), row('b', 'c1', { boundAt: 9000 })])
+ stoppedAgents.supersede.mockImplementation(() => { throw 'plain' })
+ expect(owners.settle()).toEqual([])
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('plain'))
+ })
+
+ it('settles the conversation a stopped record holds as saved, or nothing when there is no record', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { owners } = setup([row('stopped-now', 'c1', { boundAt: 1000 }), row('took-it', 'c1', { boundAt: 5000 })])
+ expect(owners.settleSaved('nobody')).toEqual([])
+ expect(owners.settleSaved('stopped-now')).toEqual(['stopped-now'])
+ })
+
+ it('reads the clock it is given, or the real one', () => {
+ const { stoppedAgents } = setup([])
+ const owners = createConversationOwners({ stoppedAgents, live: () => [], clients: { send: () => {}, sendCommander: () => {} }, reservationMs: 1 })
+ stoppedAgents.list.mockReturnValue([row('a', 'c1'), row('b', 'c1', { boundAt: 9000 })])
+ stoppedAgents.resumeReservedAt.mockReturnValue(Date.now() + 60_000)
+ expect(owners.settle()).toEqual([])
+ })
+})
diff --git a/cli/src/core/agents/conversationOwners.ts b/cli/src/core/agents/conversationOwners.ts
new file mode 100644
index 000000000..98f55dd51
--- /dev/null
+++ b/cli/src/core/agents/conversationOwners.ts
@@ -0,0 +1,114 @@
+/**
+ * One owner per conversation, stopped harnesses included.
+ *
+ * The registry already gives a running conversation one owner: "the newest bind wins", and an agent left with
+ * neither a session nor a process is removed, because it can only sit in the list as a second row for the
+ * same work (lib/registry.ts `register`, its `orphaned`). Stopped records were never held to that rule. A
+ * conversation another harness picked up (`/resume`, `claude --resume` in a terminal, a compaction) stayed
+ * claimed by the stopped harness it came from. One Mac had 18 conversations listed two or three times in Cmd-P
+ * (2026-10-10, docs/research/2026-10-10-harness-data-audit.md): opening one's history read whichever record the
+ * folder listed first (transcripts/history.ts), and its history could not be deleted, since another harness
+ * "used" it (lib/purgeAgentService.ts).
+ *
+ * The same rule, applied to them: a running owner wins, else the newest binding. Every other stopped record
+ * holding the conversation is set aside (moved, never deleted: `StoppedAgentStore.supersede`) and the apps
+ * are told, with the owner as its successor. The transcript is untouched, and the name follows the
+ * conversation (names are kept by session id, `registry.rename`). A harness that is running is never set
+ * aside (its record follows it), nor one whose resume is in flight.
+ */
+import { isTerminalEngine } from '../../engines/types.js'
+import { sid } from '../../lib/log.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
+
+type Frame = { type: string; payload: Record<string, unknown> }
+
+export interface ConversationOwnersDeps {
+ stoppedAgents: Pick<StoppedAgentStore, 'list' | 'get' | 'supersede' | 'resumeReservedAt'>
+ /** The running harnesses (`registry.list()`). */
+ live: () => readonly RegisteredSession[]
+ /** The app (`send`) and the dial (`sendCommander`). */
+ clients: { send(frame: Frame): void; sendCommander(frame: Frame): void }
+ /** How long a resume may hold its reservation (lib/resumeStoppedAgent.ts): an older one protects nothing. */
+ reservationMs: number
+ now?: () => number
+}
+
+type Owned = Pick<RegisteredSession, 'engine' | 'sessionId' | 'codexHome' | 'hermesHome'>
+
+/**
+ * A conversation, or null for a record that holds none. The same id under another Codex profile or Hermes
+ * home is another conversation; a terminal holds none of its own.
+ */
+export function conversationKey(row: Owned): string | null {
+ if (!row.sessionId || isTerminalEngine(row.engine)) return null
+ return [row.engine, row.codexHome ?? '', row.hermesHome ?? '', row.sessionId].join('\u0000')
+}
+
+/** Newest binding first; then the newest record, then the id, so every daemon picks the same one. */
+const newestFirst = (a: RegisteredSession, b: RegisteredSession): number =>
+ (b.boundAt ?? b.registeredAt) - (a.boundAt ?? a.registeredAt)
+ || b.touchedAt - a.touchedAt
+ || a.agentId.localeCompare(b.agentId)
+
+export function createConversationOwners(deps: ConversationOwnersDeps) {
+ const now = deps.now ?? Date.now
+
+ /**
+ * Gives each named conversation (or every one) a single owner, and returns the ids set aside. Called as the
+ * core starts, after a harness binds a conversation new to it, and after a stopped harness's last record is
+ * saved: a stop can keep a conversation another harness has since taken (lib/stoppedAgents.ts `save`).
+ */
+ const settle = (keys?: ReadonlyArray<string | null>): string[] => {
+ const wanted = keys ? new Set(keys.filter((key): key is string => !!key)) : null
+ if (wanted?.size === 0) return []
+ const live = deps.live()
+ const running = new Set(live.map((row) => row.agentId))
+ const groups = new Map<string, { live: RegisteredSession[]; stopped: RegisteredSession[] }>()
+ const add = (row: RegisteredSession, side: 'live' | 'stopped'): void => {
+ const key = conversationKey(row)
+ if (!key || (wanted && !wanted.has(key))) return
+ const group = groups.get(key) ?? { live: [], stopped: [] }
+ group[side].push(row)
+ groups.set(key, group)
+ }
+ for (const row of live) add(row, 'live')
+ // A running harness's own record follows it and is never a second owner.
+ for (const row of deps.stoppedAgents.list()) if (!running.has(row.agentId)) add(row, 'stopped')
+ const setAside: string[] = []
+ for (const group of groups.values()) {
+ if (!group.stopped.length || group.live.length + group.stopped.length < 2) continue
+ // The registry keeps one running owner per conversation; a stopped record never outranks it.
+ const owner = group.live[0] ?? [...group.stopped].sort(newestFirst)[0]
+ for (const row of group.stopped) {
+ if (row.agentId === owner.agentId) continue
+ const reserved = deps.stoppedAgents.resumeReservedAt(row.agentId)
+ if (reserved !== null && now() - reserved <= deps.reservationMs) continue
+ try {
+ if (!deps.stoppedAgents.supersede(row.agentId)) continue
+ } catch (error) {
+ console.warn(`[agent] ${sid(row.agentId)} could not be set aside for ${sid(owner.agentId)} · ${error instanceof Error ? error.message : error}`)
+ continue
+ }
+ setAside.push(row.agentId)
+ console.log(`[agent] ${sid(row.agentId)} set aside: ${sid(owner.agentId)} owns conversation ${sid(row.sessionId)} now`)
+ deps.clients.send({ type: 'agent_deleted', payload: { agentId: row.agentId, retained: false, successor: owner.agentId } })
+ deps.clients.sendCommander({ type: 'agent_deleted', payload: { agentId: row.agentId } })
+ }
+ }
+ return setAside
+ }
+
+ /**
+ * Settles the conversation a stopped harness's record holds as saved, which can be one the row given to the
+ * save no longer named (`StoppedAgentStore.save` keeps a known conversation through an unbound observation).
+ */
+ const settleSaved = (agentId: string): string[] => {
+ const saved = deps.stoppedAgents.get(agentId)
+ return saved ? settle([conversationKey(saved)]) : []
+ }
+
+ return { settle, settleSaved }
+}
+
+export type ConversationOwners = ReturnType<typeof createConversationOwners>
diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.ts
index b9b1cd267..146bb28e4 100644
--- a/cli/src/core/agents/forget.spec.ts
+++ b/cli/src/core/agents/forget.spec.ts
@@ -139,6 +139,30 @@ describe('forgetting a session', () => {
expect(String(log.mock.calls[0][0])).toContain('forgotten')
})
+ // Its last record may hold a conversation another harness took meanwhile (conversationOwners.ts).
+ it('settles who owns the conversation its last record holds, once it is no longer running; never on a release', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { deps } = setup()
+ const order: string[] = []
+ vi.mocked(deps.registry.removeAgent).mockImplementation(() => { order.push('removed'); return true })
+ const owners = { settleSaved: vi.fn(() => { order.push('settled'); return [] }) }
+ const forget = createForgetSession({ ...deps, owners })
+ forget('s1')
+ expect(owners.settleSaved).toHaveBeenCalledWith('a1')
+ expect(order).toEqual(['removed', 'settled'])
+ forget('s1', { keepAgent: true })
+ forget('unknown-session')
+ expect(owners.settleSaved).toHaveBeenCalledTimes(1)
+ owners.settleSaved.mockImplementationOnce(() => { throw new Error('stopped store unreadable') })
+ forget('s1')
+ owners.settleSaved.mockImplementationOnce(() => { throw 'plain' })
+ forget('s1')
+ expect(warn).toHaveBeenCalledWith('[agent] a1 could not settle who owns its conversation: stopped store unreadable')
+ expect(warn).toHaveBeenCalledWith('[agent] a1 could not settle who owns its conversation: plain')
+ expect(deps.clients.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a1', retained: true } })
+ })
+
it('removes a session the registry no longer knows, announced by the agent id the caller names', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const named = setup()
diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.ts
index fff022a9b..d62d584ac 100644
--- a/cli/src/core/agents/forget.ts
+++ b/cli/src/core/agents/forget.ts
@@ -20,11 +20,14 @@ import type { SwarmPromptScopes } from '../../teams/promptScope.js'
import type { Watcher } from '../../watcher/watcher.js'
import type { SessionNormalizers } from '../transcripts/normalizers.js'
import type { RelaunchMarks } from '../transcripts/relaunch.js'
+import type { ConversationOwners } from './conversationOwners.js'
type Frame = { type: string; payload: Record<string, unknown> }
export interface ForgetDeps {
onRemoved?: (agentId: string) => void
+ /** One owner per conversation, stopped harnesses included (conversationOwners.ts). */
+ owners?: Pick<ConversationOwners, 'settleSaved'>
registry: Pick<typeof registry, 'resolve' | 'unbindSession' | 'removeAgent' | 'remove'>
stoppedAgents: Pick<StoppedAgentStore, 'save'>
syncRecapPool: () => void
@@ -54,7 +57,7 @@ export interface ForgetDeps {
export function createForgetSession({
registry, stoppedAgents, syncRecapPool, normalizers, forgetAttach, turnStartedAt, neverFoldedHistory, replayedFirstTurn, relaunchMarks,
clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, teams, input,
- deviceInput, detachDsh, mirror, clients, dataDir, onRemoved,
+ deviceInput, detachDsh, mirror, clients, dataDir, onRemoved, owners,
}: ForgetDeps) {
/** Release a mutable session binding, or remove the process-owned agent everywhere. */
const forgetSession = (
@@ -90,6 +93,12 @@ export function createForgetSession({
if (opts.keepAgent) registry.unbindSession(sessionId)
else if (doomed) registry.removeAgent(doomed.agentId)
else registry.remove(sessionId)
+ // No longer running, its last record may still hold a conversation another harness took meanwhile: the
+ // save keeps a known one through an unbound row (StoppedAgentStore.save). One owner each from here on.
+ if (!opts.keepAgent && doomed) {
+ try { owners?.settleSaved(doomed.agentId) }
+ catch (error) { console.warn(`[agent] ${sid(doomed.agentId)} could not settle who owns its conversation: ${error instanceof Error ? error.message : error}`) }
+ }
syncRecapPool()
normalizers.forget(sessionId)
forgetAttach(sessionId)
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index b82c86ac7..5fbb3b310 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -67,6 +67,8 @@ import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from
import { restoreAgents, tmuxSurvey, type RestoreAgentsDeps, type RestoreSummary } from '../lib/restoreAgents.js'
import { createRetainExitedSession } from '../lib/retainExitedSession.js'
import { createKeepAbandonedConversation } from '../lib/keepAbandonedConversation.js'
+import { RESUME_READINESS_BUDGET_MS } from '../lib/resumeStoppedAgent.js'
+import { createConversationOwners } from './agents/conversationOwners.js'
import { OpenTabProtection } from '../lib/openTabProtection.js'
import { sessionCheckpoints } from '../lib/sessionCheckpoint.js'
import { repairProjectCwds } from '../lib/cwdRepair.js'
@@ -1484,7 +1486,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const onCursorTaskStart = cursorTasks.onCursorTaskStart
// Release a session's binding, or remove a process-owned agent everywhere (core/agents/forget.ts).
+ // One owner per conversation, stopped harnesses included; the conversations claimed twice so far settle now.
+ const conversationOwners = createConversationOwners({ stoppedAgents, live: () => registry.list(), clients: backend, reservationMs: RESUME_READINESS_BUDGET_MS })
+ conversationOwners.settle()
const forgetSession = createForgetSession({
+ owners: conversationOwners,
forgetAttach: attach.forget,
onRemoved: (agentId) => forgetRestartRevision(agentId),
relaunchMarks,
@@ -1530,6 +1536,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Binding a session to its agent, and a running process to its session (core/agents/bind.ts).
const binding = createBinding({
+ owners: conversationOwners,
registry,
mirror,
forgetSession,
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index efdcf19dc..3670eee74 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -267,6 +267,27 @@ describe('stopped harness persistence', () => {
expect(fresh().list().find(row => row.agentId === fork.agentId)).toBeTruthy()
})
+ // Another harness took its conversation (core/agents/conversationOwners.ts): moved aside, never deleted.
+ it('sets a record aside, with its reservation, and lists it no more', async () => {
+ const { StoppedAgentStore, saved, store } = await fixture()
+ store.save(saved)
+ expect(store.beginResume(saved.agentId)).toBeTruthy()
+ const before = readFileSync(join(directory, 'stopped-agents', `${saved.agentId}.json`), 'utf8')
+ expect(store.list()).toHaveLength(1)
+ expect(store.supersede(saved.agentId)).toMatchObject({ agentId: saved.agentId, sessionId: 'conversation-123' })
+ expect(readFileSync(join(directory, 'stopped-agents', 'superseded', `${saved.agentId}.json`), 'utf8')).toBe(before)
+ expect(statSync(join(directory, 'stopped-agents', 'superseded')).mode & 0o777).toBe(0o700)
+ expect(store.resumeReservedAt(saved.agentId)).toBeNull()
+ expect(store.get(saved.agentId)).toBeNull()
+ expect(store.list()).toEqual([])
+ expect(store.ids()).toEqual([])
+ expect(new StoppedAgentStore(join(directory, 'stopped-agents')).list()).toEqual([])
+ // Nothing to set aside: an unsafe id, an absent record, one already set aside.
+ expect(store.supersede('../escape')).toBeNull()
+ expect(store.supersede('never-saved')).toBeNull()
+ expect(store.supersede(saved.agentId)).toBeNull()
+ })
+
it('hides a running identity or conversation, without discarding its archive', async () => {
const { saved, store } = await fixture()
store.save(saved)
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 682a0b1bc..3adec833c 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -1,5 +1,5 @@
/** Stopped work is durable history, separate from the registry of live terminal routes. */
-import { closeSync, constants, fsyncSync, lstatSync, openSync, readdirSync, statSync, unlinkSync, writeFileSync, type BigIntStats } from 'node:fs'
+import { closeSync, constants, fsyncSync, lstatSync, openSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, type BigIntStats } from 'node:fs'
import { randomUUID } from 'node:crypto'
import { dirname, join } from 'node:path'
import { env } from '../config/env.js'
@@ -236,6 +236,24 @@ export class StoppedAgentStore {
this.syncDirectory()
}
+ /**
+ * Sets a record aside because another harness owns its conversation now (core/agents/conversationOwners.ts).
+ * Moved into `superseded/`, never deleted, so a wrong owner can be put back by hand; a reservation it left
+ * goes with it, since nothing can resume a record that is not listed. Null when there is no such record.
+ */
+ supersede(agentId: string): RegisteredSession | null {
+ if (!SAFE_ID.test(agentId)) return null
+ const saved = this.get(agentId)
+ if (!saved) return null
+ const aside = join(this.directory, 'superseded')
+ secureStateDirectory(aside)
+ renameSync(join(this.directory, `${agentId}.json`), join(aside, `${agentId}.json`))
+ this.forgetCatalogRecord(agentId)
+ this.finishResume(agentId)
+ this.syncDirectory()
+ return saved
+ }
+
/** Suppress archives whose identity or conversation is already running. */
available(live: readonly RegisteredSession[]): RegisteredSession[] {
const ids = new Set(live.map(session => session.agentId))
diff --git a/docs/research/2026-10-10-harness-data-audit.md b/docs/research/2026-10-10-harness-data-audit.md
new file mode 100644
index 000000000..f1a7c7126
--- /dev/null
+++ b/docs/research/2026-10-10-harness-data-audit.md
@@ -0,0 +1,128 @@
+# How Harness stores harnesses and sessions: an audit
+
+2026-10-10. Read from the code on `main` (0b2dd18f) and checked against one real Mac's data folder
+(`~/.harness/cli/data`), read only. Every number below was measured, not estimated.
+
+## The stores
+
+| Store | What it holds | Written by | Read by |
+|---|---|---|---|
+| `registry.json` | Live harnesses: id, engine, folder, conversation id, transcript path, pane | `lib/registry.ts` | everything live |
+| `stopped-agents/<id>.json` | Stopped harnesses: the same record, kept as durable history | `lib/stoppedAgents.ts`: Stop (`stopAgentService.ts:99`), forget (`core/agents/forget.ts:76`), exited and abandoned sessions | resume, Cmd-P (`agents_list` with `includeStopped`), search sources |
+| `stopped-agents/<id>.resume` | A resume in progress (crash guard) | `beginResume` | resume; one older than the readiness budget is taken over (`resumeAgentService.ts:65`) |
+| `session-search.db` | Every conversation's turns, full-text indexed | search service (`services/search.ts`, `lib/sessionSearch/`) | Cmd-P content search, `hn` session picker, previews, Memories |
+| engine transcripts | The conversations themselves (`~/.claude/projects`, `~/.codex/sessions`, …) | the engines | resume, the index |
+
+A harness's life: created → `registry.json`; Stop → record saved to `stopped-agents/` (kept forever);
+Resume → back in `registry.json` (the archive stays, hidden while live by `available()`,
+`stoppedAgents.ts:239`); Delete with session data → transcript, checkpoints, index rows and the archive
+removed (`purgeAgentService.ts:318-329`, `core/agents/lifecycle.ts:65`).
+
+The search index follows the records: its sources are `core.agents.all()` = live **and** stopped
+(`core/api.ts:1409`, `services/search.ts:80`), and each sweep drops rows whose harness no longer exists
+(`indexer.ts:234-243`). On this Mac every one of 165 indexed Harness conversations has a record
+(17 live, 148 stopped). Cmd-P, resume and the `hn` picker read folders from those records, never from
+the index.
+
+## What is wrong
+
+### 1. A test run can write into the real data folder (fix)
+
+`vitest.setup.ts` gives every spec a throwaway home and data folder, but only when vitest runs from
+`cli/`. Run from the repository root it finds no config, skips the setup, and every spec uses the real
+`~/.harness`, `~/.claude` and `~/.codex`. Proved with the repo's own isolation spec and a fake `HOME`:
+from `cli/`, 6 of 6 pass; from the root, 5 of 6 fail. Nothing in `config/env.ts` refuses.
+
+On this Mac, 19 records in `stopped-agents/` carry `stopAgentService.spec.ts`'s exact fixture (pid 77,
+`startMarker: 'fixture'`, folder `/tmp`, session id `saved` or `latest`), all written at 15:37:22 on
+2026-09-26. Cmd-P lists 17 of them as stopped "Codex harness 9-26 15:37" rows. Which command wrote them
+is not recorded; running a spec from the root is the one path found that would.
+
+**Fix:** `config/env.ts` refuses to load under Vitest unless `vitest.setup.ts` marked the run isolated,
+so a mistaken run fails at once instead of writing. Then remove the 19 fixture files (with the owner's
+yes: it is their data folder).
+
+### 2. One conversation, two or three stopped rows (fix)
+
+The daemon answers Cmd-P with 414 rows. Apart from the fixtures, 18 conversations appear in more than one
+stopped record. The app keys rows by harness id (`app_state.dart:9683`), so each shows. They come from a
+conversation bound by a second harness: `source` is `terminal-resume`, `resume`, `compact` or
+`process-repair` on the later record. While one copy runs the other is hidden (`available()`); when both
+are stopped both show, and neither copy's history can be deleted, because delete refuses a conversation
+another harness uses (`purgeAgentService.ts:240`, which is the right guard).
+
+**Fix:** apply the registry's own newest-bind-wins rule to stopped records (see Decision below).
+
+### 3. The index keeps no folder or title for Harness conversations (fix, for Memories)
+
+`externalFields` (`indexer.ts:76`) writes `cwd` and `title` only for conversations Harness did not start.
+All 165 Harness rows have both empty; outside rows have them. That is 5,072 of 9,928 indexed messages on
+this Mac (and 3,940 of the 4,000 most recent). Cmd-P does not need them (it joins to the records), but
+Memories reads the index directly, so it cannot place half of a person's messages in a project.
+
+**Fix:** the search service already has `s.cwd` and `s.title` for every Harness source
+(`services/search.ts:80-92`); the indexer writes them for Harness rows too. The header stays as it is.
+
+## Checked and fine
+
+- **Leftover resume reservations** (8, 13 to 19 days old): a later resume takes them over
+ (`resumeAgentService.ts:65-71`). Harmless files.
+- **The same harness in both stores** (14): by design; the archive is hidden while the harness is live.
+- **Index rows without a record:** none. Delete removes rows at once; sweeps remove the rest.
+- **Deleting shared history:** refused while another harness holds the conversation.
+
+## Watch, no change now
+
+- `stopped-agents/` only grows: 399 records (490 KB) in about three weeks. Each Cmd-P open lists them all;
+ the parse cache holds 2,048 records (`stoppedAgents.ts:12`). At this rate that is reached in about
+ three months; measure `agents_list` then.
+- 186 stopped harnesses never had a conversation (113 terminals, 73 agents). Cmd-P lists them; whether a
+ never-used harness belongs in history is a product call.
+
+## Decision (after a full study of the code)
+
+**Keep the layout. Apply the registry's own ownership rule to stopped records. Nothing else changes now.**
+
+### Why the layout stays
+
+`registry.json` is the process table: "one per supported top-level engine process in a tmux pane … lives
+exactly as long as that process", persisted only so a live agent survives an update restart
+(`lib/registry.ts:1-13`). `stopped-agents/` is durable history (`lib/stoppedAgents.ts:1`). The process
+table must change several rows in one atomic write — a pane taken from one agent by another
+(`openProcessAgent`), a conversation moved with its displaced owner (`save`'s `bindingCommit.displaced`),
+checked after every write so no two rows own a process, pane or conversation (`validatedRows`) — while three
+writers share it: the daemon, the engine hook (`cli/hook/notify.mjs` `writeRegistry`) and a peer daemon on the
+same data folder (`reconcileUnconfirmed`). History has one writer and never changes rows together.
+
+| Alternative | Verdict |
+|---|---|
+| One file per harness | Loses the atomic multi-row write: a crash between two files leaves a pane or conversation with two owners or none. Needs a journal. Rejected. |
+| Stopped rows inside `registry.json` | Keeps atomicity, but every process-table write and every hook read would carry all history (13× today's bytes, growing). Rejected. |
+| SQLite | Transactions and per-row writes, but brings a native module into the core and the hook, which the architecture keeps out (search runs in its own process for that reason). No user-visible gain now. Rejected. |
+| One read API over both stores | Every consumer already compares by harness id, so a harness in both stores (live plus its own record) is handled correctly everywhere (`available()`, the search indexer's fresher-record rule, delete's `agentId !==` checks, `worktreeDeletion.ts:93`). A refactor with no bug behind it, in the busiest code. Not now. |
+
+### The fix
+
+For running harnesses the registry already enforces one owner per conversation: "The same engine session
+cannot belong to two agents … The newest bind wins", and an agent left with no session and no process is
+removed because it "can only sit in the list as a second row for the same work" (`registry.ts:1818`,
+`register`'s `orphaned`). Stopped records were never held to that rule, which is the whole source of the 18
+duplicated conversations. Every new binding — engine hook or process scan — lands in one place,
+`handleRegistered` (`core/agents/bind.ts:88`), which already saves the binding harness's own record. There:
+
+- a stopped record of **another** harness holding the same conversation (engine, Codex home, Hermes home,
+ session id) is removed and the apps are told (`agent_deleted`), as the registry does for a live orphan;
+- not when that harness is running (its record follows it on its next bind or stop), not while it has a resume
+ in flight (its reservation), not for terminals, not for a record without a conversation;
+- the conversation's name follows it (names are keyed by session id on purpose, `registry.ts:2488`), its
+ transcript is untouched, and the new owner's row resumes it.
+
+A one-time pass at start clears the duplicates that exist (newest binding wins; a running owner always wins),
+backing up every removed record first. That also makes `session_get`'s lookup by conversation
+deterministic (`core/transcripts/history.ts:130`) and lets delete erase a conversation's history again.
+
+### Not now, with the numbers
+
+The stopped store grows ~20 records a day. Measured on this Mac: listing 400 records takes 21 ms warm; at
+4,000 it takes 144 ms, because the parse cache holds 2,048 (`stoppedAgents.ts:12`). That is about three months
+away. Retention (or an index) is decided then, with the measurement, not now.