The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { processLockIdentity, processStartMarker } from './processLiveness.js'
import type { AgentEngine } from '../engines/types.js'
import type { ProcessIdentity, RegisteredSession, RegisterInput } from './registry.js'
let dataDir = ''
const processIdentity = (pid: number) => ({
pid,
executable: 'claude',
startMarker: `Mon Aug 10 10:00:${String(pid % 60).padStart(2, '0')} 2026`,
})
function writeLegacyStateFile(path: string, value: string): void {
writeFileSync(path, value, { mode: 0o644 })
chmodSync(path, 0o644)
}
function registerProcess(
registry: {
byPaneEngine: (pane: string, engine: AgentEngine) => RegisteredSession | undefined
openProcessAgent: (input: {
agentId?: string
engine: AgentEngine
tmuxPane: string
cwd?: string | null
processIdentity: ProcessIdentity
}) => unknown
register: (input: RegisterInput) => {
entry: RegisteredSession
isNew: boolean
evicted: string | null
rebound: string | null
orphaned: { agentId: string; sessionId: string } | null
} | null
},
input: RegisterInput,
) {
const pane = String(input.tmuxPane ?? '')
const engine = input.engine ?? 'claude'
if (pane && !registry.byPaneEngine(pane, engine)) {
registry.openProcessAgent({
agentId: input.launcherId,
engine,
tmuxPane: pane,
cwd: input.cwd,
processIdentity: processIdentity(100 + Number(pane.slice(1) || 0)),
})
}
return registry.register(input)
}
async function loadRegistryModule() {
vi.resetModules()
process.env.ADAPTER_DATA_DIR = dataDir
process.env.CLAUDE_PROJECTS_DIR = dataDir
process.env.CODEX_HOME = dataDir
process.env.CURSOR_HOME = dataDir
return import('./registry.js')
}
/** Each pause of the registry lock's wait moves the fake clock by `taken(asked)` ms and returns at once: the wait is
* then measured on the clock alone. A real pause can take far longer than asked: on the Mac Studio, 2026-11-07, an
* agent's 20 ms `Atomics.wait` returned after ~150 ms. */
function pausesTake(taken: (asked: number) => number): void {
vi.spyOn(Atomics, 'wait').mockImplementation((_view, _index, _value, asked) => {
vi.setSystemTime(Date.now() + taken(asked ?? 0))
return 'timed-out'
})
}
describe('registry remote display names', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
})
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
// tmux takes an APC string as a pane's title, and Claude Code's kitty graphics query named a guest's harness
// "Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA" (2026-10-22). tmux.ts no longer reads one as a title; one a registry already
// stored is not a name either.
it('never names a harness with a kitty graphics query, one stored before included', async () => {
const query = 'Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA'
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
let { registry, projectDisplayName, titleDisplayName } = await loadRegistryModule()
expect(titleDisplayName(query)).toBeNull()
expect(titleDisplayName('✳ Fix the login test')).toBe('Fix the login test')
registry.load()
const registered = registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
const named = projectDisplayName(registered!.entry)
registry.updateTitle('session-1', query)
expect(projectDisplayName(registry.bySession('session-1')!)).toBe(named)
// Written by a daemon before the fix.
const file = join(dataDir, 'registry.json')
const rows = JSON.parse(readFileSync(file, 'utf-8')) as Array<Record<string, unknown>>
rows[0].title = query
writeFileSync(file, JSON.stringify(rows))
;({ registry, projectDisplayName } = await loadRegistryModule())
registry.load()
expect(projectDisplayName(registry.bySession('session-1')!)).toBe(named)
registry.updateTitle('session-1', '✳ Fix the login test')
expect(projectDisplayName(registry.bySession('session-1')!)).toBe('Fix the login test')
})
// Task #2920: the agent frame says which names a person chose, so Desktop can send those to the Swarm and never an
// engine's session title.
it('says a name was chosen by a person only for a rename, and keeps saying so after a restart', async () => {
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
let { registry, isNameChosen } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
// Nobody renamed it: its name is the engine's session title or the name it was created with.
registered!.entry.title = 'cd /Users/macbookpro/projects/lamp'
expect(isNameChosen(registered!.entry)).toBe(false)
registered!.entry.defaultName = 'Builder'
expect(isNameChosen(registered!.entry)).toBe(false)
registry.rename('session-1', 'Release notes')
expect(isNameChosen(registry.bySession('session-1')!)).toBe(true)
// A new process of the daemon reads the names file.
;({ registry, isNameChosen } = await loadRegistryModule())
registry.load()
expect(isNameChosen(registry.bySession('session-1')!)).toBe(true)
})
it('persists renamed display names independently from session removal', async () => {
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
expect(registered?.entry).toBeTruthy()
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toMatchObject([
{ sessionId: 'session-1', transcriptPath },
])
const renamed = registry.rename('session-1', 'Production API')
expect(renamed).toBeTruthy()
expect(projectDisplayName(registered!.entry)).toBe('Production API')
const persisted = JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8')) as Record<string, string>
expect(persisted).toEqual({ 'session-1': 'Production API' })
registry.remove('session-1')
expect(registry.get('session-1')).toBeUndefined()
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))).toEqual([])
expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({ 'session-1': 'Production API' })
})
it('loads persisted names for active sessions', async () => {
const transcriptPath = join(dataDir, 'session-2.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ 'session-2': 'Research box' }))
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: 'session-2',
transcriptPath,
projectDir: 'tmp-demo',
cwd: '/tmp/demo',
tmuxPane: '%2',
source: null,
title: null,
model: null,
registeredAt: 1,
updatedAt: 1,
}]))
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const session = registry.get('session-2')
expect(session).toBeTruthy()
expect(session?.engine).toBe('claude')
expect(projectDisplayName(session!)).toBe('Research box')
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({
sessionId: 'session-2',
engine: 'claude',
tmuxPane: '%2',
})
expect(statSync(dataDir).mode & 0o777).toBe(0o700)
expect(statSync(join(dataDir, 'agent-names.json')).mode & 0o777).toBe(0o600)
expect(statSync(join(dataDir, 'registry.json')).mode & 0o777).toBe(0o600)
})
it('tries a names write that failed again on the next save, so a rename survives a full disk', async () => {
const transcriptPath = join(dataDir, 'session-1.jsonl')
writeFileSync(transcriptPath, '{}\n')
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'h1', sessionId: 'session-1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo' })
// The write cannot land: a directory where the names file goes stands in for a full disk.
mkdirSync(join(dataDir, 'agent-names.json'))
expect(registry.rename('session-1', 'Named while full')).toBeTruthy()
expect(error.mock.calls.some(([line]) => String(line).includes('save names failed'))).toBe(true)
// Room again: the next save of anything writes the names too, with no second rename.
rmSync(join(dataDir, 'agent-names.json'), { recursive: true, force: true })
registry.remove('session-1')
expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({ 'session-1': 'Named while full' })
error.mockRestore()
})
it('auto-follows the tmux pane title until renamed, then the manual name stays fixed', async () => {
const transcriptPath = join(dataDir, 'session-title.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
sessionId: 'session-title',
transcriptPath,
tmuxPane: '%7',
cwd: '/tmp/demo',
title: '📋 ✳ Clarify assistant identity',
})
expect(registered?.entry).toBeTruthy()
expect(registered?.entry.title).toBe('Clarify assistant identity')
// Un-renamed: display auto-follows the tmux title.
expect(projectDisplayName(registered!.entry)).toBe('Clarify assistant identity')
const updated = registry.updateTitle('session-title', '🧪 — * Ship settings page')
expect(updated?.title).toBe('Ship settings page')
expect(projectDisplayName(updated!)).toBe('Ship settings page')
// After a manual rename the override wins and is FIXED — it must NOT drift back to the title.
registry.rename('session-title', 'Manual name')
expect(projectDisplayName(updated!)).toBe('Manual name')
// A later tmux-title change (Claude rewrites it to the latest topic) does not move the display name.
const retitled = registry.updateTitle('session-title', '⚡ New convo topic')
expect(retitled?.title).toBe('New convo topic') // internal title still tracked
expect(projectDisplayName(retitled!)).toBe('Manual name') // display stays fixed
})
it('refuses a pane title that is only the machine\'s own name', async () => {
// Hermes titles its terminal with the hostname and leaves it there. Adopted as a name, every
// hermes agent on this machine is called the same thing — which is strictly worse than the
// folder-and-session default it displaced.
const { hostname } = await import('node:os')
const transcriptPath = join(dataDir, 'session-host.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h9',
sessionId: 'session-host',
transcriptPath,
tmuxPane: '%9',
cwd: '/tmp/demo',
title: hostname(),
})
expect(registered?.entry.title).toBeNull()
expect(projectDisplayName(registered!.entry)).toBe('demo \u00b7 sess')
// The short form is the same machine wearing another name.
expect(registry.updateTitle('session-host', hostname().split('.')[0])?.title).toBeNull()
// Anything that is genuinely about the conversation still lands.
expect(registry.updateTitle('session-host', 'Ship settings page')?.title).toBe('Ship settings page')
})
it('refuses every name the machine has had while the daemon ran, not only the one it started with', async () => {
// A laptop's name follows its network, and tmux titles each new pane with the name of the moment.
// Read once at start, a pane made after the machine was renamed gave its agent the machine's name.
const hostFile = join(dataDir, 'hostname')
writeFileSync(hostFile, 'laptop-one.lan')
process.env.HARNESSD_TEST_HOSTNAME_FILE = hostFile
try {
const transcriptPath = join(dataDir, 'session-roam.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, projectDisplayName } = await loadRegistryModule()
const { machineNames } = await import('./machineNames.js')
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h8', sessionId: 'session-roam', transcriptPath, tmuxPane: '%8', cwd: '/tmp/demo', title: 'laptop-one.lan',
})
expect(registered?.entry.title).toBeNull()
// The machine joins another network; the title sweep reads its name again.
writeFileSync(hostFile, 'laptop-two.local')
machineNames.observe()
expect(registry.updateTitle('session-roam', 'laptop-two.local')?.title).toBeNull()
expect(registry.updateTitle('session-roam', 'laptop-two')?.title).toBeNull()
// A pane made under the old name keeps it.
expect(registry.updateTitle('session-roam', 'laptop-one.lan')?.title).toBeNull()
expect(registry.updateTitle('session-roam', 'Ship settings page')?.title).toBe('Ship settings page')
// A title taken before the machine had that name stops showing once it has it.
const retitled = registry.updateTitle('session-roam', 'laptop-three.lan')!
expect(projectDisplayName(retitled)).toBe('laptop-three.lan')
writeFileSync(hostFile, 'laptop-three.lan')
machineNames.observe()
expect(projectDisplayName(retitled)).toBe('demo · sess')
} finally {
delete process.env.HARNESSD_TEST_HOSTNAME_FILE
}
})
it('only adds or updates agent-names.json entries', async () => {
const transcriptPath = join(dataDir, 'session-3.jsonl')
writeFileSync(transcriptPath, '{}\n')
writeLegacyStateFile(join(dataDir, 'agent-names.json'), JSON.stringify({ old: 'Keep me' }))
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'h1', sessionId: 'session-3', transcriptPath, tmuxPane: '%3', cwd: '/tmp/demo' })
registry.rename('session-3', 'New name')
expect(JSON.parse(readFileSync(join(dataDir, 'agent-names.json'), 'utf-8'))).toEqual({
old: 'Keep me',
'session-3': 'New name',
})
})
it('persists Codex engine metadata and moves a malformed v2 row aside for operator recovery', async () => {
const sessionsDir = join(dataDir, 'sessions')
const transcriptPath = join(sessionsDir, 'codex-session.jsonl')
mkdirSync(sessionsDir)
writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id: 'codex-session', cwd: '/tmp/codex', source: 'cli' } }) + '\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
engine: 'codex',
sessionId: 'codex-session',
transcriptPath,
tmuxPane: '%4',
cwd: '/tmp/codex',
})
const valid = registry.get('codex-session')
expect(valid?.engine).toBe('codex')
const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))
persisted.push({
...persisted[0],
sessionId: 'invalid-session',
tmuxPane: 'not-a-pane',
runtimes: [{ backend: 'tmux', paneId: 'not-a-pane' }],
})
const malformed = JSON.stringify(persisted)
writeFileSync(join(dataDir, 'registry.json'), malformed)
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
registry.load()
expect(registry.list()).toEqual([])
expect(registry.get('invalid-session')).toBeUndefined()
// Kept byte for byte beside the registry, which starts empty and can be written again.
const aside = readdirSync(dataDir).filter((name) => name.startsWith('registry.json.corrupt-'))
expect(aside).toHaveLength(1)
expect(readFileSync(join(dataDir, aside[0]), 'utf-8')).toBe(malformed)
expect(existsSync(join(dataDir, 'registry.json'))).toBe(false)
error.mockRestore()
})
it('migrates legacy tmux rows additively without changing agent identity or binding', async () => {
const transcriptPath = join(dataDir, 'legacy.jsonl')
writeFileSync(transcriptPath, '{}\n')
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
agentId: 'stable-agent',
sessionId: 'legacy-session',
engine: 'claude',
transcriptPath,
projectDir: 'demo',
cwd: '/tmp/demo',
tmuxPane: '%17',
processIdentity: processIdentity(317),
registeredAt: 10,
updatedAt: 20,
}]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.get('legacy-session')).toMatchObject({
agentId: 'stable-agent',
tmuxPane: '%17',
runtimes: [{ backend: 'tmux', paneId: '%17' }],
schemaVersion: 2,
// Saved as `updatedAt` before the row's bookkeeping time was named for what it is.
touchedAt: 20,
})
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]
expect(saved).toMatchObject({
agentId: 'stable-agent',
tmuxPane: '%17',
runtimes: [{ backend: 'tmux', paneId: '%17' }],
touchedAt: 20,
})
expect(saved).not.toHaveProperty('updatedAt')
expect(JSON.parse(readFileSync(join(dataDir, 'registry.pre-v2.json'), 'utf8'))[0]).toMatchObject({
agentId: 'stable-agent', sessionId: 'legacy-session', tmuxPane: '%17',
})
expect(statSync(join(dataDir, 'registry.pre-v2.json')).mode & 0o777).toBe(0o600)
})
it.each([
['truncated JSON', '[{"agentId":'],
['non-array root', '{"schemaVersion":2}'],
['empty legacy row', JSON.stringify([{}])],
['primitive legacy row', JSON.stringify([7])],
['legacy row without runtime', JSON.stringify([{ agentId: 'legacy-agent' }])],
])('moves %s aside byte-for-byte, starts empty, and goes on starting agents', async (_label, bytes) => {
const file = join(dataDir, 'registry.json')
writeLegacyStateFile(file, bytes)
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
const { registry } = await loadRegistryModule()
registry.load()
const aside = readdirSync(dataDir).filter((name) => name.startsWith('registry.json.corrupt-'))
expect(aside).toHaveLength(1)
expect(readFileSync(join(dataDir, aside[0]), 'utf8')).toBe(bytes)
expect(statSync(join(dataDir, aside[0])).mode & 0o777).toBe(0o600)
expect(error).toHaveBeenCalledWith(expect.stringMatching(/^\[registry\] registry .*; moved it aside to .*registry\.json\.corrupt-.* and started empty$/))
registry.openProcessAgent({
agentId: 'after-the-move',
engine: 'claude',
tmuxPane: '%88',
processIdentity: processIdentity(888),
})
expect(registry.list().map((s) => s.agentId)).toEqual(['after-the-move'])
expect(JSON.parse(readFileSync(file, 'utf8')).map((row: { agentId: string }) => row.agentId)).toEqual(['after-the-move'])
error.mockRestore()
})
it.each([
['unknown row schema', JSON.stringify([{ schemaVersion: 99, agentId: 'future' }])],
['nonnumeric row schema', JSON.stringify([{ schemaVersion: '3', agentId: 'future' }])],
])('preserves a newer version\'s %s byte-for-byte and blocks later writes', async (_label, bytes) => {
const file = join(dataDir, 'registry.json')
writeLegacyStateFile(file, bytes)
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'must-not-write',
engine: 'claude',
tmuxPane: '%88',
processIdentity: processIdentity(888),
})
expect(readFileSync(file, 'utf8')).toBe(bytes)
expect(registry.list()).toEqual([])
})
it('rejects a group-writable registry without tightening or overwriting it', async () => {
const file = join(dataDir, 'registry.json')
const bytes = '[]'
writeFileSync(file, bytes, { mode: 0o600 })
chmodSync(file, 0o660)
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'must-not-write',
engine: 'claude',
tmuxPane: '%89',
processIdentity: processIdentity(889),
})
expect(readFileSync(file, 'utf8')).toBe(bytes)
expect(statSync(file).mode & 0o777).toBe(0o660)
expect(registry.list()).toEqual([])
})
it('merges a daemon-down writer committed after load instead of overwriting it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'daemon-agent', engine: 'claude', tmuxPane: '%31', processIdentity: processIdentity(831),
})
const file = join(dataDir, 'registry.json')
const [daemonRow] = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>
const external = {
...daemonRow,
agentId: 'offline-agent',
sessionId: '',
tmuxPane: '%32',
runtimes: [{ backend: 'tmux', paneId: '%32' }],
primaryRuntimeKey: 'tmux\u0000%32',
processIdentity: processIdentity(832),
}
writeFileSync(file, JSON.stringify([daemonRow, external]), { mode: 0o600 })
registry.updateTitle('daemon-agent', 'updated by daemon')
expect(JSON.parse(readFileSync(file, 'utf8'))).toHaveLength(2)
expect(registry.byAgent('offline-agent')?.processIdentity?.pid).toBe(832)
expect(registry.byAgent('daemon-agent')?.title).toBe('updated by daemon')
})
it('reclaims a crashed lock whose PID has been reused by another process generation', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const lockDir = join(dataDir, 'registry.json.lock')
mkdirSync(lockDir, { mode: 0o700 })
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({
pid: process.pid,
startMarker: '', generationMarker: `${processStartMarker(process.pid)}-earlier`,
token: 'stale-owner',
}), { mode: 0o600 })
expect(registry.openProcessAgent({
agentId: 'after-reused-pid-lock',
engine: 'claude',
tmuxPane: '%33',
processIdentity: processIdentity(833),
})?.entry.agentId).toBe('after-reused-pid-lock')
expect(registry.byAgent('after-reused-pid-lock')).toBeTruthy()
})
it.each([['no owner file', null], ['an empty owner file', ''], ['an owner file naming no one', '{}']])(
'reclaims an old lock with %s, and leaves a fresh one to its creator', async (_label, owner) => {
const { registry } = await loadRegistryModule()
registry.load()
pausesTake((asked) => asked)
const lockDir = join(dataDir, 'registry.json.lock')
const leave = (age: number) => {
mkdirSync(lockDir, { mode: 0o700 })
if (owner !== null) writeFileSync(join(lockDir, 'owner.json'), owner, { mode: 0o600 })
const at = (Date.now() - age) / 1000
if (owner !== null) utimesSync(join(lockDir, 'owner.json'), at, at)
utimesSync(lockDir, at, at)
}
leave(60_000)
expect(registry.openProcessAgent({ agentId: 'after-ownerless-lock', engine: 'claude', tmuxPane: '%34',
processIdentity: processIdentity(834) })?.entry.agentId).toBe('after-ownerless-lock')
expect(existsSync(lockDir)).toBe(false)
leave(0)
registry.openProcessAgent({ agentId: 'during-fresh-lock', engine: 'claude', tmuxPane: '%35', processIdentity: processIdentity(835) })
expect(existsSync(lockDir)).toBe(true) // its creator may be writing owner.json right now: never taken from it
expect(readFileSync(join(dataDir, 'registry.json'), 'utf8')).not.toContain('during-fresh-lock')
rmSync(lockDir, { recursive: true, force: true })
})
it('gives up on a live lock after 2 s on the clock, however long each pause really takes', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const lockDir = join(dataDir, 'registry.json.lock')
mkdirSync(lockDir, { mode: 0o700 })
writeFileSync(join(lockDir, 'owner.json'), JSON.stringify({
pid: process.pid, ...processLockIdentity(process.pid), token: 'live-holder',
}), { mode: 0o600 })
pausesTake((asked) => asked * 7.5)
const started = Date.now()
registry.openProcessAgent({ agentId: 'behind-a-live-lock', engine: 'claude', tmuxPane: '%36', processIdentity: processIdentity(836) })
expect(Date.now() - started).toBeLessThanOrEqual(2_000 + 150)
expect(readFileSync(join(lockDir, 'owner.json'), 'utf8')).toContain('live-holder')
expect(existsSync(join(dataDir, 'registry.json'))
&& readFileSync(join(dataDir, 'registry.json'), 'utf8').includes('behind-a-live-lock')).toBe(false)
rmSync(lockDir, { recursive: true, force: true })
})
it('deduplicates nested panes by process identity', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const identity = processIdentity(700)
const outer = registry.openProcessAgent({
agentId: 'nested-agent',
engine: 'claude',
tmuxPane: '%7',
processIdentity: identity,
})
const nested = registry.openProcessAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%8' }],
processIdentity: identity,
})
const other = registry.openProcessAgent({
agentId: 'other-agent',
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
processIdentity: processIdentity(701),
})
expect(nested?.entry.agentId).toBe(outer?.entry.agentId)
expect(nested?.entry.runtimes).toHaveLength(2)
expect(other?.entry.agentId).toBe('other-agent')
expect(registry.list()).toHaveLength(2)
})
it('round-trips a ptyhost row and projects its pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'windows-agent',
engine: 'claude',
runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%2' }],
processIdentity: processIdentity(702),
})
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
const saved = reloaded.byAgent('windows-agent')!
expect(saved.runtimes).toEqual([{ backend: 'ptyhost', instance: 'p1', paneId: '%2' }])
expect(saved.primaryRuntimeKey).toBe('ptyhost\u0000p1\u0000%2')
expect(saved.tmuxPane).toBe('%2')
})
it('drops a ptyhost runtime whose instance or pane is malformed', async () => {
const { validTerminalRuntime } = await loadRegistryModule()
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p3', paneId: '%0' })).toBe(true)
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p12345', paneId: '%0' })).toBe(false)
// A versioned host's: two builds of one protocol run side by side.
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-0.4.21-dev.win1', paneId: '%7' })).toBe(true)
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-h0123456789ab', paneId: '%7' })).toBe(true)
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p2-0.4.21/x', paneId: '%7' })).toBe(false)
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'default', paneId: '%0' })).toBe(false)
expect(validTerminalRuntime({ backend: 'ptyhost', paneId: '%0' })).toBe(false)
expect(validTerminalRuntime({ backend: 'ptyhost', instance: 'p3', paneId: 'w1:p1' })).toBe(false)
})
it('drops runtimes a retired Herdr backend left on disk, and agents left with none', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'mixed', engine: 'claude', tmuxPane: '%40', processIdentity: processIdentity(940) })
const [row] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
const herdr = { backend: 'herdr', endpointId: 'herdr:default:abc', sessionName: 'default', terminalId: 'terminal-1', paneId: 'w1:p1' }
const herdrKey = 'herdr\u0000herdr:default:abc\u0000w1:p1'
const { tmuxPane: _pane, ...herdrOnly } = row
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([
{ ...row, runtimes: [...row.runtimes, herdr], primaryRuntimeKey: herdrKey },
{ ...herdrOnly, agentId: 'herdr-only', sessionId: '', processIdentity: null, runtimes: [herdr], primaryRuntimeKey: herdrKey },
]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent('mixed')?.runtimes).toEqual([{ backend: 'tmux', paneId: '%40' }])
expect(reloaded.byAgent('mixed')?.primaryRuntimeKey).toBe('tmux\u0000%40')
expect(reloaded.byAgent('herdr-only')).toBeUndefined()
const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
expect(persisted.map((entry: { agentId: string }) => entry.agentId)).toEqual(['mixed'])
expect(JSON.stringify(persisted)).not.toContain('herdr')
// Still writable: nothing about the retired rows blocked the file.
reloaded.openProcessAgent({ agentId: 'after', engine: 'claude', tmuxPane: '%41', processIdentity: processIdentity(941) })
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))).toHaveLength(2)
})
// Swarm v3 (task #4215): until then Harness itself started every Swarm agent in full mode, and an older Buddy in `buddy` or
// `readOnlyAsk`; a relaunch reapplies a saved mode, so those agents kept skipping permissions after the fix.
it('clears, once, the permission modes Harness forced on saved agents, and keeps the person\'s own', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'template', engine: 'claude', tmuxPane: '%50', processIdentity: processIdentity(950) })
const [row] = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
const at = (agentId: string, pane: string, fields: Record<string, unknown>) => ({ ...row, agentId, sessionId: '', processIdentity: null,
tmuxPane: pane, runtimes: [{ backend: 'tmux', paneId: pane }], primaryRuntimeKey: `tmux\u0000${pane}`, ...fields })
const swarmSkill = { role: 'lead', key: 'swarm-lead' }
const saved = [
at('swarm-full', '%51', { swarmSkill, permissionMode: 'full', bypassPermission: true }),
at('old-buddy', '%52', { swarmSkill: { role: 'buddy', key: 'swarm-buddy' }, permissionMode: 'buddy', bypassPermission: true }),
at('old-codex-buddy', '%53', { permissionMode: 'readOnlyAsk', bypassPermission: true }),
at('own-full', '%54', { permissionMode: 'full', bypassPermission: true }),
at('swarm-ask', '%55', { swarmSkill, permissionMode: 'ask' }),
at('team-written', '%56', { swarmSkill, permissionMode: 'teamWritten', bypassPermission: true }),
]
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(saved), { mode: 0o600 })
// As a machine upgrading from a build before the sweep: no marker yet.
rmSync(join(dataDir, 'registry-own-modes'), { force: true })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
for (const id of ['swarm-full', 'old-buddy', 'old-codex-buddy']) {
expect(reloaded.byAgent(id)?.permissionMode, id).toBeUndefined()
expect(reloaded.byAgent(id)?.bypassPermission, id).toBeUndefined()
}
expect([reloaded.byAgent('own-full')?.permissionMode, reloaded.byAgent('own-full')?.bypassPermission]).toEqual(['full', true])
expect(reloaded.byAgent('swarm-ask')?.permissionMode).toBe('ask')
expect(reloaded.byAgent('team-written')?.permissionMode).toBe('teamWritten')
const persisted = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')) as Array<Record<string, unknown>>
expect(persisted.find(entry => entry.agentId === 'swarm-full')).not.toHaveProperty('permissionMode')
expect(persisted.find(entry => entry.agentId === 'swarm-full')).not.toHaveProperty('bypassPermission')
// Once: full mode a person chooses for a Swarm agent afterwards is theirs, and a later load keeps it.
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(persisted.map(entry => entry.agentId === 'swarm-full'
? { ...entry, permissionMode: 'full', bypassPermission: true } : entry)), { mode: 0o600 })
const { registry: later } = await loadRegistryModule()
later.load()
expect([later.byAgent('swarm-full')?.permissionMode, later.byAgent('swarm-full')?.bypassPermission]).toEqual(['full', true])
})
it('repairs a Codex parent registry entry overwritten with a child rollout', async () => {
const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
const sessionsDir = join(dataDir, 'sessions', '2026', '07', '23')
mkdirSync(sessionsDir, { recursive: true })
const parentPath = join(sessionsDir, `rollout-${parentId}.jsonl`)
const childPath = join(sessionsDir, `rollout-${childId}.jsonl`)
writeFileSync(parentPath, JSON.stringify({
type: 'session_meta',
payload: { id: parentId, cwd: '/fixture/work', source: 'cli' },
}) + '\n')
writeFileSync(childPath, JSON.stringify({
type: 'session_meta',
payload: {
id: childId,
source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
},
}) + '\n')
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
launcherId: 'h1',
sessionId: parentId,
engine: 'codex',
transcriptPath: childPath,
projectDir: '23',
cwd: '/tmp/codex',
tmuxPane: '%8',
source: null,
title: null,
model: null,
cliVersion: '0.144.6',
processIdentity: null,
registeredAt: 1,
updatedAt: 1,
lastHookAt: 1,
lastTranscriptAt: 1,
}]))
const { registry } = await loadRegistryModule()
registry.load()
// Other fixtures can change a shared temporary-directory ancestor while the parent pool is
// enumerated. That is a supported hold: keep the saved identity, then earn fresh evidence
// through the same retry used by discovery, without reloading or weakening the route proof.
if (registry.get(parentId)?.identityHold) {
expect(registry.get(parentId)?.identityHold).toContain('directory or ancestor changed during enumeration')
expect(registry.get(parentId)?.transcriptPath).toBe(childPath)
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0]).toMatchObject({ sessionId: parentId, transcriptPath: childPath })
await vi.waitFor(() => {
registry.revalidateBinding('h1')
expect(registry.get(parentId)?.identityHold).toBeUndefined()
}, { timeout: 1_000, interval: 20 })
}
expect(registry.get(parentId)?.identityHold).toBeUndefined()
expect(registry.get(parentId)?.transcriptPath).toBe(parentPath)
expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parentPath)
expect(registerProcess(registry, {
launcherId: 'h1',
engine: 'codex',
sessionId: parentId,
transcriptPath: childPath,
tmuxPane: '%8',
})).toBeNull()
})
it('keeps the discovered process identity when a Cursor sessionStart omits it', async () => {
const sessionId = '53d3843c-724e-47ff-ae3a-9fedfa328bba'
const transcriptPath = join(
dataDir,
'projects',
'workspace',
'agent-transcripts',
sessionId,
`${sessionId}.jsonl`,
)
mkdirSync(join(transcriptPath, '..'), { recursive: true })
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId,
transcriptPath,
tmuxPane: '%3',
processIdentity: { pid: 100, executable: 'agent', startMarker: 'old' },
hookEvent: 'beforeSubmitPrompt',
})
const resumed = registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId,
transcriptPath,
tmuxPane: '%3',
hookEvent: 'sessionStart',
})
expect(resumed?.entry.processIdentity).toEqual({ pid: 100, executable: 'agent', startMarker: 'old' })
})
it('persists a pending Cursor session and attaches its exact transcript later', async () => {
const { registry } = await loadRegistryModule()
registry.load()
expect(registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId: '12345678-1234-1234-1234-123456789abc',
tmuxPane: '%5',
cwd: '/tmp/cursor',
cliVersion: '2026.07.20-8cc9c0b',
})?.entry.transcriptPath).toBeNull()
registry.load()
expect(registry.get('12345678-1234-1234-1234-123456789abc')?.transcriptPath).toBeNull()
const transcript = join(
dataDir,
'projects',
'workspace',
'agent-transcripts',
'12345678-1234-1234-1234-123456789abc',
'12345678-1234-1234-1234-123456789abc.jsonl',
)
mkdirSync(join(transcript, '..'), { recursive: true })
writeFileSync(transcript, '{}\n')
const attached = registerProcess(registry, {
launcherId: 'h1',
engine: 'cursor',
sessionId: '12345678-1234-1234-1234-123456789abc',
transcriptPath: transcript,
tmuxPane: '%5',
})
expect(attached?.entry.transcriptPath).toBe(transcript)
})
})
describe('registry model coercion', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
// Claude Code's hooks report `model` as {id, display_name}. Persisting that object took the daemon down
// at STARTUP (runtimeProfile called .toLowerCase() on it) — and no restart could heal it, because the bad
// value was already on disk.
it('stores the id when the hook reports a model object', async () => {
const transcriptPath = join(dataDir, 'm1.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, {
launcherId: 'h1',
sessionId: 'm1', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo',
model: { id: 'claude-opus-4-8', display_name: 'Opus 4.8' } as unknown as string,
})
expect(registry.get('m1')?.model).toBe('claude-opus-4-8')
})
it('keeps a plain string and drops anything else', async () => {
const transcriptPath = join(dataDir, 'm2.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'h1', sessionId: 'm2', transcriptPath, tmuxPane: '%1', cwd: '/tmp/demo', model: 'gpt-5.6-sol' })
expect(registry.get('m2')?.model).toBe('gpt-5.6-sol')
// A SECOND launcher, not the same one: one launcher owns one pane owns one agent, so registering
// another session under 'h1' would be a rotation (which inherits the previous model) rather than the
// fresh record this coercion check needs.
registerProcess(registry, { launcherId: 'h2', sessionId: 'm3', transcriptPath, tmuxPane: '%2', cwd: '/tmp/demo', model: 42 as unknown as string })
expect(registry.get('m3')?.model).toBeNull()
})
})
/**
* A Command Code session announces itself BEFORE its transcript exists, so the path used to arrive only
* with the first Stop hook — after the first turn had already failed for want of a watcher.
*/
describe('a Command Code session without a transcript path', () => {
beforeEach(() => {
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-cc-'))
})
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.COMMANDCODE_HOME
})
it('gets the deterministic one derived from its cwd', async () => {
process.env.COMMANDCODE_HOME = dataDir
const { registry } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'commandcode',
sessionId: 'ae93cc89-0dff-452a-a875-33b1516bbc80',
tmuxPane: '%9',
cwd: '/workspace/project',
})
// The file does not exist yet — that is the whole point. The watcher opens at offset 0 and chokidar
// delivers the lines when the CLI finally writes them.
expect(registered?.entry.transcriptPath).toBe(
join(dataDir, 'projects', 'workspace-project', 'ae93cc89-0dff-452a-a875-33b1516bbc80.jsonl'),
)
})
it('keeps a path the CLI reported over the derived one', async () => {
process.env.COMMANDCODE_HOME = dataDir
const { registry } = await loadRegistryModule()
registry.load()
const reported = join(dataDir, 'projects', 'somewhere-else', 'reported.jsonl')
mkdirSync(join(dataDir, 'projects', 'somewhere-else'), { recursive: true })
writeFileSync(reported, '')
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'commandcode',
sessionId: 'reported',
tmuxPane: '%9',
cwd: '/workspace/project',
transcriptPath: reported,
})
expect(registered?.entry.transcriptPath).toBe(reported)
})
})
/** Grok's SessionStart hook can run while its updates file is still empty or absent. Register the
* deterministic ordinary layout immediately so the first remote prompt is not held waiting for a
* UserPromptSubmit hook that only that same prompt can trigger. */
describe('a Grok session before updates.jsonl exists', () => {
beforeEach(() => {
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-grok-'))
process.env.GROK_HOME = dataDir
})
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
delete process.env.GROK_HOME
})
it('derives the URL-encoded cwd path at SessionStart', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const registered = registerProcess(registry, {
launcherId: 'h1',
engine: 'grok',
sessionId: '8184b11d-175e-46cb-9cee-cf41cafe70d2',
tmuxPane: '%9',
cwd: '/workspace/project with spaces',
hookEvent: 'SessionStart',
})
expect(registered?.entry.transcriptPath).toBe(join(
dataDir,
'sessions',
encodeURIComponent('/workspace/project with spaces'),
'8184b11d-175e-46cb-9cee-cf41cafe70d2',
'updates.jsonl',
))
})
})
describe('agent identity: the process owns the agent, the session is bound to it', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-id-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
function transcript(name: string): string {
const p = join(dataDir, `${name}.jsonl`)
writeFileSync(p, '{}\n')
return p
}
it('resolves a record by EITHER id', async () => {
// Web and device address turn control with a bare sessionId (`cancel`, `question_response`) and
// everything else with the agentId; both have to land on the same record.
const { registry } = await loadRegistryModule()
registry.load()
const res = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(res?.entry.agentId).toBe('agent-1')
expect(registry.resolve('agent-1')?.sessionId).toBe('s1')
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
expect(registry.byAgent('s1')).toBeUndefined()
expect(registry.bySession('agent-1')).toBeUndefined()
})
it('a rotation rebinds the SAME agent instead of creating a second one', async () => {
// `/clear` in claude (and `/new` in opencode) ends one session id and starts another in the same pane
// under the same launcher. That is one agent with a new session underneath, not two agents.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(rot?.rebound).toBe('s1')
expect(rot?.isNew).toBe(true) // the SESSION is new — the caller still announces it
expect(registry.list()).toHaveLength(1)
expect(registry.byAgent('agent-1')?.sessionId).toBe('s2')
expect(registry.bySession('s1')).toBeUndefined() // the dead session no longer resolves
expect(registry.resolve('agent-1')?.boundAt).toBe(Date.now())
})
it('a re-register of the same session is not a rotation, and keeps the folder the row already has', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
// Claude's UserPromptSubmit carries the session's tracked SHELL directory, which follows every
// Bash `cd`; the row's folder — what a resume or restore `cd`s into — must not follow it.
const again = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })
expect(again?.isNew).toBe(false)
expect(again?.rebound).toBeNull()
expect(registry.list()).toHaveLength(1)
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo')
// A rotation is a new session and takes the folder it reports.
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo/cli' })
expect(rot?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')
})
it('a first bind whose cwd is not the transcript\'s project folder takes the folder from the transcript', async () => {
// A fork inherits its source's drifted cwd; `claude --resume` typed from a subfolder announces
// that subfolder. Claude never moves the transcript out of the project dir it was started in,
// so the file's own directory says which folder is the session's.
const { registry } = await loadRegistryModule()
registry.load()
const project = join(dataDir, 'repo')
const projectDir = join(dataDir, project.replace(/[^A-Za-z0-9]/g, '-'))
mkdirSync(projectDir, { recursive: true })
const path = join(projectDir, 's1.jsonl')
writeFileSync(path, [
JSON.stringify({ type: 'mode' }),
JSON.stringify({ type: 'user', cwd: join(project, 'cli') }),
JSON.stringify({ type: 'user', cwd: project }),
].join('\n') + '\n')
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: path, tmuxPane: '%1', cwd: join(project, 'cli') })
expect(bound?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe(project)
// The folder itself, spelled as given, is accepted as is.
const rot = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's2', transcriptPath: (() => { const p2 = join(projectDir, 's2.jsonl'); writeFileSync(p2, JSON.stringify({ cwd: project }) + '\n'); return p2 })(), tmuxPane: '%1', cwd: project })
expect(rot?.isNew).toBe(true)
expect(registry.byAgent('agent-1')?.cwd).toBe(project)
})
it('re-observing a pane follows the shell until a session is bound, then leaves the folder alone', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
registry.openProcessAgent({ engine: 'terminal', tmuxPane: '%1', cwd: '/tmp/demo/cli', processIdentity: processIdentity(101) })
expect(registry.byAgent('agent-1')?.cwd).toBe('/tmp/demo/cli')
registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })
registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo/cli', processIdentity: processIdentity(102) })
expect(registry.byAgent('agent-2')?.cwd).toBe('/tmp/demo')
})
it('one engine session cannot belong to two agents', async () => {
// `claude --resume <id>` in a second pane: the newest bind wins; both live process agents remain.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%2', cwd: '/tmp/demo' })
expect(registry.list()).toHaveLength(2)
expect(registry.resolve('s1')?.agentId).toBe('agent-2')
expect(registry.byAgent('agent-1')?.sessionId).toBe('')
})
it('ignores a legacy launcherId and binds to the discovered pane process', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'process-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
const res = registry.register({ launcherId: 'old-launcher', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(res?.entry.agentId).toBe('process-agent')
expect(registry.resolve('old-launcher')).toBeUndefined()
const rot = registry.register({ launcherId: 'different-old-launcher', sessionId: 's2', transcriptPath: transcript('s2'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(rot?.rebound).toBe('s1')
expect(registry.list()).toHaveLength(1)
})
it('creates an agent at process discovery, before any engine session exists', async () => {
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(opened?.isNew).toBe(true)
expect(opened?.entry.sessionId).toBe('')
expect(registry.unbound().map((s) => s.agentId)).toEqual(['agent-1'])
expect(registry.advertised().map((s) => s.agentId)).toEqual(['agent-1'])
expect(registry.resolve('agent-1')?.agentId).toBe('agent-1')
expect(projectDisplayName(opened!.entry)).toContain('demo') // nameable while unbound
// The engine reports its session later — same agent, now bound.
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe('agent-1')
expect(registry.list()).toHaveLength(1)
expect(registry.unbound()).toHaveLength(0)
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
})
it('restart contract: updateProcessIdentity swaps ONLY the process, keeping agentId/sessionId/runtimes', async () => {
// This is the primitive a restart handler relies on: exit the engine process, relaunch it in the
// same pane, and rebind the SAME agent to the new process — never look like delete+create.
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const before = registry.resolve('agent-1')!
// Registry entries are mutated in place (resolve() returns the live object), so the "before"
// snapshot has to be copied — not just referenced — ahead of the swap.
const beforeRuntimes = [...before.runtimes]
const beforePrimary = before.primaryRuntimeKey
const beforeIdentity = { ...before.processIdentity }
const replacement = processIdentity(999)
const ok = registry.updateProcessIdentity('agent-1', replacement)
expect(ok).toBe(true)
const after = registry.resolve('agent-1')!
expect(after.agentId).toBe('agent-1')
expect(after.sessionId).toBe('s1')
expect(after.runtimes).toEqual(beforeRuntimes)
expect(after.primaryRuntimeKey).toBe(beforePrimary)
expect(after.processIdentity).toEqual(replacement)
expect(after.processIdentity).not.toEqual(beforeIdentity)
// Both lookups still resolve to the one record — swapping the process never splits the agent.
expect(registry.resolve('s1')?.agentId).toBe('agent-1')
expect(registry.list()).toHaveLength(1)
})
it('restart contract: updateProcessIdentity also resolves by bare sessionId', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(registry.updateProcessIdentity('s1', processIdentity(999))).toBe(true)
expect(registry.byAgent('agent-1')?.processIdentity).toEqual(processIdentity(999))
})
it('does not advertise persisted terminal locators before this daemon verifies them', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(registry.advertised()).toHaveLength(1)
registry.load()
expect(registry.list()).toHaveLength(1)
expect(registry.advertised()).toHaveLength(0)
registry.setTerminalAvailable('agent-1', true)
expect(registry.advertised().map((s) => s.agentId)).toEqual(['agent-1'])
})
it('keeps the agent id when an unbound launcher becomes a new process in the same pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder',
processIdentity: processIdentity(101),
})
const replaced = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%1', cwd: '/tmp/new-folder', processIdentity: processIdentity(202),
})
expect(replaced?.entry.agentId).toBe('agent-1')
expect(replaced?.entry.sessionId).toBe('')
expect(replaced?.entry.processIdentity).toEqual(processIdentity(202))
expect(replaced?.isNew).toBe(false)
expect(registry.list()).toHaveLength(1)
})
it('does not transfer a bound session to a replacement process in the same pane', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(101),
})
registerProcess(registry, {
launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
const replacement = registry.openProcessAgent({
agentId: 'replacement-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(202),
})
expect(replacement?.entry.agentId).toBe('replacement-agent')
expect(replacement?.entry.sessionId).toBe('')
// BOTH ids, because the caller has to finish a removal the registry only
// half did: the agent is already gone from here, so the agentId is the only
// thing clients can be told to drop, and the sessionId the only thing the
// daemon's own per-session state can be cleaned by.
expect(replacement?.evicted).toEqual({
agentId: 'bound-agent',
sessionId: 's1',
})
expect(registry.resolve('s1')).toBeUndefined()
})
it('keeps a bound agent across a clock step that moved its ps start time but not its start ticks', async () => {
// machine-remote-1, 2026-10-07: the Docker VM's clock was resynced after the Mac slept, every
// `ps lstart` moved by hours, and each pane's unchanged engine got a new agent id.
const { registry } = await loadRegistryModule()
registry.load()
const before = { ...processIdentity(101), startTicks: 26385008 }
registry.openProcessAgent({ agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: before })
registerProcess(registry, {
launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo',
})
const stepped = { ...before, startMarker: 'Tue Aug 11 01:00:41 2026' }
const observed = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: stepped })
expect(observed).toMatchObject({ isNew: false, evicted: null })
expect(observed?.entry.agentId).toBe('bound-agent')
expect(observed?.entry.sessionId).toBe('s1')
expect(registry.byProcess('claude', stepped)?.agentId).toBe('bound-agent')
// Same pid, other ticks: a different process that reused the pid, whatever its marker says.
const reused = registry.openProcessAgent({
agentId: 'replacement-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: { ...stepped, startTicks: 26385009 },
})
expect(reused?.entry.agentId).toBe('replacement-agent')
expect(reused?.evicted).toEqual({ agentId: 'bound-agent', sessionId: 's1' })
})
it('matches a row saved without start ticks by its marker once, then keeps the ticks', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
registerProcess(registry, {
launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo',
})
const upgraded = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: { ...processIdentity(101), startTicks: 7 },
})
expect(upgraded).toMatchObject({ isNew: false, evicted: null })
expect(registry.byAgent('bound-agent')?.processIdentity?.startTicks).toBe(7)
const stepped = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: { ...processIdentity(101), startMarker: 'Tue Aug 11 01:00:41 2026', startTicks: 7 },
})
expect(stepped?.entry.agentId).toBe('bound-agent')
expect(stepped?.evicted).toBeNull()
})
it('removes an agent a resume left with no session and no process', async () => {
// `claude --resume` in a second pane after quitting the first: the session
// moves, and the agent it moved from has nothing left to be. Kept, it is a
// second row for the same work that can never be opened — which is exactly
// the "Terminal frozen" tile this removes.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'old-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(401),
})
registerProcess(registry, {
launcherId: 'old-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
registry.setActive('old-agent', false) // its engine was quit before the resume
registry.openProcessAgent({
agentId: 'new-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
processIdentity: processIdentity(402),
})
const bound = registerProcess(registry, {
launcherId: 'new-agent', sessionId: 's-resume', transcriptPath: transcript('s-resume'),
tmuxPane: '%2', cwd: '/tmp/demo',
})
expect(bound?.orphaned).toEqual({ agentId: 'old-agent', sessionId: 's-resume' })
expect(registry.byAgent('old-agent')).toBeUndefined()
expect(registry.byAgent('new-agent')?.sessionId).toBe('s-resume')
})
it('leaves a still-running agent alone when its session is resumed elsewhere', async () => {
// Its engine is alive, so it is a real second agent that merely became
// unbound. Removing it would take a working tile off the screen.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'live-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(501),
})
registerProcess(registry, {
launcherId: 'live-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
tmuxPane: '%1', cwd: '/tmp/demo',
})
registry.openProcessAgent({
agentId: 'other-agent', engine: 'claude', tmuxPane: '%2', cwd: '/tmp/demo',
processIdentity: processIdentity(502),
})
const bound = registerProcess(registry, {
launcherId: 'other-agent', sessionId: 's-live', transcriptPath: transcript('s-live'),
tmuxPane: '%2', cwd: '/tmp/demo',
})
expect(bound?.orphaned).toBeNull()
expect(registry.byAgent('live-agent')).toBeDefined()
expect(registry.byAgent('live-agent')?.sessionId).toBe('')
})
it('reports no eviction when the displaced agent still owns another pane', async () => {
// It lost a terminal, not its life. Announcing it as deleted would take a
// working tile off every client.
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({
agentId: 'two-panes',
engine: 'claude',
runtimes: [
{ backend: 'tmux', paneId: '%1' },
{ backend: 'tmux', paneId: '%2' },
],
cwd: '/tmp/demo',
processIdentity: processIdentity(301),
})
const replacement = registry.openProcessAgent({
agentId: 'takes-pane-1', engine: 'codex', tmuxPane: '%1', cwd: '/tmp/demo',
processIdentity: processIdentity(302),
})
expect(replacement?.evicted).toBeNull()
expect(registry.byAgent('two-panes')?.runtimes).toHaveLength(1)
})
it('re-observing the same runtime keeps the session it had already bound', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
const again = registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(again?.isNew).toBe(false)
expect(again?.entry.sessionId).toBe('s1')
expect(registry.list()).toHaveLength(1)
})
it('an unbound agent survives a daemon restart', async () => {
const { registry } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent('agent-1')?.sessionId).toBe('')
expect(reloaded.unbound()).toHaveLength(1)
})
// A row that does not leave `starting` reads as "Starting" on the desk while its engine is working,
// and the state is written from six places that cannot see each other. Each one says so, and a
// settled row says nothing — so a log from a machine where it sticks names the pair doing it.
it('names every launch change by the door it came through, and is silent when nothing changed', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const lines: string[] = []
const log = vi.spyOn(console, 'log').mockImplementation((message: unknown) => {
if (typeof message === 'string' && message.startsWith('[launch]')) lines.push(message)
})
try {
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo' })!
registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', cwd: '/tmp/demo', processIdentity: processIdentity(707) })
registry.setLaunch(pending.agentId, { state: 'ready' }) // already ready — silent
registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT' })
const id = pending.agentId.slice(0, 8)
expect(lines).toEqual([
`[launch] ${id} starting → ready · openProcessAgent re-observed`,
`[launch] ${id} ready → failed · setLaunch (START_TIMEOUT)`,
])
// A bind ends the launch without naming it: the rebuilt row carries none.
lines.length = 0
registry.setLaunch(pending.agentId, { state: 'starting' })
registerProcess(registry, { launcherId: pending.agentId, sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%7', cwd: '/tmp/demo' })
expect(lines.filter(line => line.includes('→ none'))).toHaveLength(1)
} finally {
log.mockRestore()
}
})
it('opens a route-only pending agent and adopts the engine process without changing agentId', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%7' }],
cwd: '/tmp/demo',
})
expect(pending).toMatchObject({ sessionId: '', processIdentity: null, launch: { state: 'starting' } })
expect(registry.terminalAvailable(pending!.agentId)).toBe(true)
const adopted = registry.openProcessAgent({
engine: 'claude', tmuxPane: '%7', cwd: '/tmp/demo', processIdentity: processIdentity(707),
})
expect(adopted?.entry.agentId).toBe(pending?.agentId)
expect(adopted?.entry.launch).toEqual({ state: 'ready' })
expect(registry.list()).toHaveLength(1)
})
describe('the name Harness gives an agent: who it is and when it started', () => {
afterEach(() => { vi.useRealTimers() })
const at = (y: number, mo: number, d: number, h: number, mi: number, sec = 0) => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date(y, mo - 1, d, h, mi, sec))
}
it('is the engine or DSH name and the local time, with no zero where it says nothing', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 15, 26)
const codex = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/Users/u/harnesses/codex-2026-09-17-15-26' })!
expect(registry.displayName(codex)).toBe('Codex harness 9-17 15:26')
at(2026, 9, 3, 9, 5)
const blender = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%4' }], cwd: '/tmp/b', dsh: 'autonomous/blender', label: ' Blender ' })!
expect(registry.displayName(blender)).toBe('Blender harness 9-3 9:05')
const claude = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%5' }], cwd: '/tmp/c', label: ' ' })!
expect(registry.displayName(claude)).toBe('Claude harness 9-3 9:05')
})
it('takes the seconds when the same agent already has that minute, and counts nothing', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 12, 25, 15, 26, 8)
const first = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%6' }], cwd: '/tmp/a' })!
const second = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/a' })!
const other = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/a' })!
expect([first, second, other].map((agent) => registry.displayName(agent)))
.toEqual(['Codex harness 12-25 15:26', 'Codex harness 12-25 15:26:08', 'Claude harness 12-25 15:26'])
expect(registry.agentNamesInUse()).toEqual(expect.arrayContaining(['Codex harness 12-25 15:26', 'Codex harness 12-25 15:26:08']))
})
it('gives way to the session’s title, which moves with it, until a rename fixes a name — and survives reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 15, 30)
const first = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo' })!
const second = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo' })!
expect(registry.displayName(first)).toBe('OpenCode harness 9-17 15:30')
const bound = registry.register({ engine: 'opencode', sessionId: 'session-named-by-time', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
expect(registry.displayName(bound)).toBe('Greeting')
expect(bound.defaultName).toBe('OpenCode harness 9-17 15:30')
registry.updateTitle('session-named-by-time', 'OC | Plan the launch')
expect(registry.displayName(bound)).toBe('Plan the launch')
registry.rename(second.agentId, 'My project')
registry.updateTitle(second.agentId, 'OC | Something else')
expect(registry.displayName(registry.byAgent(second.agentId)!)).toBe('My project')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.displayName(reloaded.byAgent(first.agentId)!)).toBe('Plan the launch')
expect(reloaded.displayName(reloaded.byAgent(second.agentId)!)).toBe('My project')
})
it('treats a harness-N from an earlier daemon as a name Harness gave, and a title replaces it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const legacy = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/old', defaultName: 'harness-42' })!
expect(registry.displayName(legacy)).toBe('harness-42')
registry.updateTitle(legacy.agentId, '✳ Unitree Go2 squats and wave')
expect(registry.displayName(registry.byAgent(legacy.agentId)!)).toBe('Unitree Go2 squats and wave')
})
it('keeps a name the creator asked for through titles, binding and reload; blank means Harness names it', async () => {
const { registry } = await loadRegistryModule()
registry.load()
at(2026, 9, 17, 16, 0)
const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/demo', defaultName: ' Local model ' })!
expect(named.defaultName).toBe('Local model')
expect(registry.displayName(named)).toBe('Local model')
// The engine reporting a session title does not retitle a pane that was named at creation.
const bound = registry.register({ engine: 'opencode', sessionId: 'session-named', tmuxPane: '%10', title: 'OC | Greeting' })!.entry
expect(registry.displayName(bound)).toBe('Local model')
const unnamed = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/demo', defaultName: ' ' })!
expect(registry.displayName(unnamed)).toBe('OpenCode harness 9-17 16:00')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.displayName(reloaded.byAgent(named.agentId)!)).toBe('Local model')
expect(reloaded.displayName(reloaded.byAgent(unnamed.agentId)!)).toBe('OpenCode harness 9-17 16:00')
})
})
it('keeps the named agent a pane was opened as through binding and reload, and drops one that is not an identifier', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const named = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/demo', agent: 'harness-compute', defaultName: 'Local model' })!
expect(named.agent).toBe('harness-compute')
// A hook-triggered bind carries it forward, like `dsh` and `codexHome`.
const bound = registry.register({ engine: 'opencode', sessionId: 'session-agent', tmuxPane: '%7', title: 'OC | Greeting' })!.entry
expect(bound.agent).toBe('harness-compute')
// Absent is a general session; a shape the engine could not look a file up by is not kept.
const plain = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo' })!
expect(plain.agent).toBeNull()
const odd = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo', agent: '../etc' })!
expect(odd.agent).toBeNull()
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(named.agentId)!.agent).toBe('harness-compute')
expect(reloaded.byAgent(plain.agentId)!.agent).toBeNull()
})
it('keeps the selected harness runtime through process binding and disk reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'opencode', runtimes: [{ backend: 'tmux', paneId: '%70' }],
cwd: '/tmp/drawing', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })!
expect(pending.dshRuntime).toBe('harness-opencode-original')
const bound = registry.register({ engine: 'opencode', sessionId: 'drawing-session', tmuxPane: '%70' })!.entry
expect(bound).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toMatchObject({ engine: 'opencode', dsh: 'acme/drawing', dshRuntime: 'harness-opencode-original' })
})
it('persists a failed launch for reconnect while keeping its terminal route', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo',
})!
registry.setLaunch(pending.agentId, {
state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.',
})
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toMatchObject({
active: false,
launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal output.' },
tmuxPane: '%8',
})
})
it('persists a held launch: inactive, with the service it waits for and why, never a failure', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/demo' })!
registry.setLaunch(pending.agentId, { state: 'held', service: 'models', detail: `Waiting for the models service.${'.'.repeat(600)}` })
expect(registry.byAgent(pending.agentId)).toMatchObject({ active: false, launch: { state: 'held', service: 'models' } })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
const kept = reloaded.byAgent(pending.agentId)!
expect(kept).toMatchObject({ active: false, launch: { state: 'held', service: 'models' }, tmuxPane: '%11' })
expect(kept.launch?.state === 'held' && kept.launch.detail.length).toBe(500)
// A held launch that does not say which service, or why, is no launch at all.
for (const odd of [{ service: 'Models!', detail: 'x' }, { service: 7, detail: 'x' }, { service: 'models', detail: 7 }]) {
reloaded.setLaunch(pending.agentId, { state: 'held', ...odd } as never)
expect(reloaded.byAgent(pending.agentId)!.launch).toBeUndefined()
}
})
// lib/engineHomes.ts: CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile put the engine's
// transcripts where no root reached, and no agent bound there.
it('takes a transcript beneath a home the person moved as the engine\'s own, and nothing beside it', async () => {
const { validTranscriptPath } = await loadRegistryModule()
const { adoptEngineHomes } = await import('./engineHomes.js')
const moved = mkdtempSync(join(tmpdir(), 'adapter-moved-homes-'))
try {
const claudeFile = join(moved, 'claude-work', 'projects', '-work', 's1.jsonl')
const codexFile = join(moved, 'codex-work', 'sessions', '2026', 'rollout-x.jsonl')
const beside = join(moved, 'claude-work', 'elsewhere.jsonl')
for (const file of [claudeFile, codexFile, beside]) { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, '{}\n') }
expect(validTranscriptPath('claude', claudeFile)).toBe(false)
expect(validTranscriptPath('codex', codexFile)).toBe(false)
adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(moved, 'claude-work'), CODEX_HOME: join(moved, 'codex-work') }, { claudeHome: dataDir, codexHome: dataDir })
expect(validTranscriptPath('claude', claudeFile)).toBe(true)
expect(validTranscriptPath('codex', codexFile)).toBe(true)
// Beneath the moved home but outside its transcripts, and an agent's own profile still rules alone.
expect(validTranscriptPath('claude', beside)).toBe(false)
expect(validTranscriptPath('codex', codexFile, dataDir)).toBe(false)
} finally {
rmSync(moved, { recursive: true, force: true })
}
})
it('validates a Codex transcript against the agent\'s own profile, not the daemon default', async () => {
const { validTranscriptPath } = await loadRegistryModule()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
try {
const file = join(profile, 'sessions', 'rollout-x.jsonl')
mkdirSync(join(file, '..'), { recursive: true })
writeFileSync(file, '{}\n')
expect(validTranscriptPath('codex', file, profile)).toBe(true)
// Without the override this file sits outside the (default) trusted root and must be refused.
expect(validTranscriptPath('codex', file)).toBe(false)
} finally {
rmSync(profile, { recursive: true, force: true })
}
})
it('registers a codex session against the profile it was created with', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
try {
const pending = registry.openPendingAgent({
engine: 'codex',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
codexHome: profile,
})!
expect(pending.codexHome).toBe(profile)
const transcriptFile = join(profile, 'sessions', 'rollout-x.jsonl')
mkdirSync(join(transcriptFile, '..'), { recursive: true })
writeFileSync(transcriptFile, JSON.stringify({ type: 'session_meta', payload: { id: 'sess-1', cwd: '/tmp/demo', source: 'cli' } }) + '\n')
const result = registry.register({
engine: 'codex',
sessionId: 'sess-1',
transcriptPath: transcriptFile,
tmuxPane: '%9',
cwd: '/tmp/demo',
processIdentity: processIdentity(909),
})
expect(result?.entry.sessionId).toBe('sess-1')
expect(result?.entry.codexHome).toBe(profile)
} finally {
rmSync(profile, { recursive: true, force: true })
}
})
it('never registers a delegated Codex session, agreeing with the hook server\'s admission', async () => {
const { registry } = await loadRegistryModule()
const { admitHook } = await import('../engines/hooks.js')
registry.load()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
try {
registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/demo', codexHome: profile })
const rollout = (id: string, source: unknown): string => {
const file = join(profile, 'sessions', `rollout-${id}.jsonl`)
mkdirSync(join(file, '..'), { recursive: true })
writeFileSync(file, JSON.stringify({ type: 'session_meta', payload: { id, cwd: '/tmp/demo', source } }) + '\n')
return file
}
const register = (sessionId: string, transcriptPath: string) => registry.register({
engine: 'codex', sessionId, transcriptPath, tmuxPane: '%10', cwd: '/tmp/demo', processIdentity: processIdentity(910),
})
const child = rollout('child', { subagent: { thread_spawn: { parent_thread_id: 'parent', depth: 1 } } })
expect(admitHook('codex', { transcriptPath: child })).toEqual({ accepted: false, reason: 'codex_subagent' })
expect(register('child', child)).toBeNull()
const parent = rollout('parent', 'cli')
expect(admitHook('codex', { transcriptPath: parent })).toEqual({ accepted: true })
expect(register('parent', parent)?.entry.sessionId).toBe('parent')
} finally {
rmSync(profile, { recursive: true, force: true })
}
})
it('keeps a name given before the agent had a session', async () => {
// Names live under the ENGINE session id — that is what survives the launcher and comes back on a
// resume, since the agent id is minted fresh each launch. An agent renamed while still unbound has
// its name parked under the agent id, and the bind must carry it over.
const { registry, projectDisplayName } = await loadRegistryModule()
registry.load()
registry.openProcessAgent({ agentId: 'agent-1', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
expect(registry.rename('agent-1', 'Backend fix')).toBeTruthy()
expect(projectDisplayName(registry.byAgent('agent-1')!)).toBe('Backend fix')
const bound = registerProcess(registry, { launcherId: 'agent-1', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
registry.inheritName('agent-1', 's1')
expect(projectDisplayName(bound!.entry)).toBe('Backend fix')
// …and a LATER agent that resumes the same session inherits it, because the key is the session.
registry.removeAgent('agent-1')
const resumed = registerProcess(registry, { launcherId: 'agent-2', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo' })
expect(projectDisplayName(resumed!.entry)).toBe('Backend fix')
})
it('loads a pre-agentId snapshot by reading launcherId as the agent id', async () => {
// No migration file and no version gate: every record already carried the launcher uuid, and that
// uuid IS the agent id.
const path = transcript('legacy')
const now = Date.now()
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
sessionId: 'legacy-session', engine: 'claude', launcherId: 'legacy-agent', transcriptPath: path,
projectDir: 'x', cwd: '/tmp/demo', tmuxPane: '%3', source: null, title: null, model: null,
cliVersion: null, processIdentity: null, registeredAt: now, updatedAt: now,
lastHookAt: now, lastTranscriptAt: now,
}]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.byAgent('legacy-agent')?.sessionId).toBe('legacy-session')
expect(registry.resolve('legacy-session')?.agentId).toBe('legacy-agent')
// It is immediately rewritten without legacy ownership metadata.
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ agentId: 'legacy-agent' })
expect(saved[0]).not.toHaveProperty('launcherId')
})
})
describe('registry across a reboot and pane loss', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-reboot-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
/** A row as `agent_create` + a SessionStart hook leave it: bound, with a live-looking process. */
function persistedRow(transcriptPath: string, overrides: Record<string, unknown> = {}) {
return {
schemaVersion: 2,
active: true,
launch: { state: 'ready' },
agentId: 'agent-a',
sessionId: 'session-a',
boundAt: 1,
engine: 'claude',
gateway: null,
grid: null,
codexHome: null,
bypassPermission: true,
transcriptPath,
projectDir: 'demo',
cwd: '/tmp/demo',
runtimes: [{ backend: 'tmux', paneId: '%3' }],
primaryRuntimeKey: 'tmux\u0000%3',
tmuxPane: '%3',
source: null,
title: null,
model: null,
cliVersion: null,
processIdentity: processIdentity(4242),
registeredAt: 1,
updatedAt: 1,
lastHookAt: 1,
lastTranscriptAt: 1,
...overrides,
}
}
it('keeps every agent after a reboot, clearing only what a reboot actually kills', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath, { codexHome: '/tmp/codex-work' })]))
// A boot marker from the distant past: whichever way the platform identifies a boot, this is not it.
writeLegacyStateFile(join(dataDir, 'registry-boot'), 'time:1')
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(true)
expect(registry.byAgent('agent-a')).toMatchObject({
agentId: 'agent-a',
sessionId: 'session-a',
engine: 'claude',
cwd: '/tmp/demo',
codexHome: '/tmp/codex-work',
bypassPermission: true,
runtimes: [{ backend: 'tmux', paneId: '%3' }],
active: false,
processIdentity: null,
})
// The cleared snapshot is on disk immediately: the boot marker was already refreshed, so a crash
// before this save would otherwise leave the dead pid behind with no second reboot to notice it.
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ agentId: 'agent-a', processIdentity: null, codexHome: '/tmp/codex-work', bypassPermission: true })
// The next start on the SAME boot is not a reboot, and finds the row as the previous save left it.
const again = await loadRegistryModule()
again.registry.load()
expect(again.registry.rebootedSinceLastRun).toBe(false)
expect(again.registry.byAgent('agent-a')).toMatchObject({ processIdentity: null, bypassPermission: true })
})
it('leaves the process identity alone when the machine did not reboot', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath)]))
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(false)
expect(registry.byAgent('agent-a')?.processIdentity).toEqual(processIdentity(4242))
expect(registry.byProcess('claude', processIdentity(4242))?.agentId).toBe('agent-a')
})
it('does not take a step of the wall clock for a reboot', async () => {
// A boot named by the moment it began moved with the clock: a daemon restarted after an NTP step,
// a virtual machine resumed or a long sleep marked every agent dormant (round 29). macOS has a
// per-boot id; Linux always used its own.
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath)]))
const first = await loadRegistryModule()
first.registry.load()
expect(first.registry.rebootedSinceLastRun).toBe(false)
vi.useFakeTimers({ toFake: ['Date'] })
try {
vi.setSystemTime(Date.now() + 3 * 3_600_000)
const again = await loadRegistryModule()
again.registry.load()
expect(again.registry.rebootedSinceLastRun).toBe(false)
expect(again.registry.byAgent('agent-a')?.processIdentity).toEqual(processIdentity(4242))
} finally {
vi.useRealTimers()
}
})
it('keeps the permission mode from agent_create through a bind and a reload', async () => {
const transcriptPath = join(dataDir, 'session-p.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%7' }],
cwd: '/tmp/demo',
permissionMode: 'plan',
})
expect(pending?.permissionMode).toBe('plan')
const bound = registry.register({ sessionId: 'session-p', transcriptPath, tmuxPane: '%7', cwd: '/tmp/demo' })
expect(bound?.entry.permissionMode).toBe('plan')
const again = await loadRegistryModule()
again.registry.load()
expect(again.registry.byAgent(pending!.agentId)?.permissionMode).toBe('plan')
const bogus = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%8' }],
cwd: '/tmp/demo',
permissionMode: '--dangerously-skip-permissions',
})
expect(bogus).not.toHaveProperty('permissionMode')
})
it('carries bypassPermission from agent_create through the first hook bind', async () => {
const transcriptPath = join(dataDir, 'session-b.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
bypassPermission: true,
})
expect(pending?.bypassPermission).toBe(true)
const bound = registry.register({ sessionId: 'session-b', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending!.agentId)
expect(bound?.entry.bypassPermission).toBe(true)
expect(registry.setBypassPermission(pending!.agentId, false)).toBe(true)
expect(registry.byAgent(pending!.agentId)).not.toHaveProperty('bypassPermission')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).not.toHaveProperty('bypassPermission')
})
it('fills in the permission mode discovery read off a live argv, and keeps it across a reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
bypassPermission: true,
})
expect(pending).not.toHaveProperty('permissionMode')
expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)
expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')
// Idempotent; fill-only, so the recorded mode is never re-derived into another; and a name that
// is not a mode is refused as it is on load.
expect(registry.setPermissionMode(pending!.agentId, 'full')).toBe(true)
expect(registry.setPermissionMode(pending!.agentId, 'plan')).toBe(false)
expect(registry.setPermissionMode(pending!.agentId, '--dangerously-skip-permissions')).toBe(false)
expect(registry.setPermissionMode('nope', 'full')).toBe(false)
expect(registry.byAgent(pending!.agentId)?.permissionMode).toBe('full')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending!.agentId)?.permissionMode).toBe('full')
})
const GRID_LAUNCH = {
networkId: 'grid-abc',
networkName: 'Team grid',
baseUrl: 'https://grid.example/grid-abc/relay/v1',
apiKey: 'gridkey-abc123',
model: 'gpt-5',
}
it('carries the grid — launch, key and observed assignment — through the first hook bind', async () => {
// The first SessionStart hook rebuilds the row. Before this, it rebuilt it without `grid`, so the
// agent was announced as "on no grid" until the next scan re-read the process; and without
// `gridLaunch`, so nothing could ever put it back on its grid.
const transcriptPath = join(dataDir, 'session-g.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%9' }],
cwd: '/tmp/demo',
grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },
gridLaunchRecord: { override: GRID_LAUNCH, webSearch: 'on' },
})!
expect(pending.gridLaunch).toEqual(GRID_LAUNCH)
expect(pending.gridWebSearch).toBe('on')
expect(pending.launch).toEqual({ state: 'starting' })
const bound = registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry).toMatchObject({
grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' },
gridLaunch: GRID_LAUNCH,
gridWebSearch: 'on',
gateway: null,
})
// The hook is the engine reporting in: the launch is over and the frame reads ready.
expect(bound?.entry.launch).toBeUndefined()
// Moved back to the engine's own login: the launch is gone, and a bind keeps it gone.
expect(registry.setGridLaunch(pending.agentId, null)).toBe(true)
expect(registry.register({ sessionId: 'session-g', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })?.entry.gridLaunch).toBeNull()
expect(registry.setGridLaunch('nobody', null)).toBe(false)
})
it('keeps the remembered subscription model across a reload', async () => {
// ⚠️ REGRESSION. A row is rebuilt from an explicit field list on load, so a field added to the
// type and the setter but NOT to that list is written to disk and silently dropped by the next
// load. It reads as "the setter never ran", which is where a day went — so what is pinned here
// is survival across a RELOAD, not merely that the setter returned true.
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%21' }],
cwd: '/tmp/demo',
})!
expect(registry.setSubscriptionModel(pending.agentId, 'opus')).toBe(true)
expect(registry.setSubscriptionModel('nobody', 'opus')).toBe(false)
// The reload is the whole test: a field missing from the rehydration list survives the write and
// dies here.
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.subscriptionModel).toBe('opus')
// ...and the SECOND way it was lost: a hook bind rebuilds the row from named fields, so a field
// the rebuild does not name is still on disk while memory has already forgotten it.
const transcriptPath = join(dataDir, 'session-sub.jsonl')
writeFileSync(transcriptPath, '{}\n')
const bound = reloaded.register({ sessionId: 'session-sub', transcriptPath, tmuxPane: '%21', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.subscriptionModel).toBe('opus')
})
// Task #3395 (anh Dee, 11-05): a Product Manager launched on Opus at xhigh came back on its engine's own default once
// its session was reopened, since the launch's flags were for the first launch alone.
it('keeps the launch model across a reload and a hook bind, replaced by its setter and gone with its engine', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({
engine: 'claude',
runtimes: [{ backend: 'tmux', paneId: '%31' }],
cwd: '/tmp/demo',
launchModel: { model: 'opus', effort: 'xhigh' },
})!
expect(pending.launchModel).toEqual({ model: 'opus', effort: 'xhigh' })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.launchModel).toEqual({ model: 'opus', effort: 'xhigh' })
const transcriptPath = join(dataDir, 'session-launch.jsonl')
writeFileSync(transcriptPath, '{}\n')
const bound = reloaded.register({ sessionId: 'session-launch', transcriptPath, tmuxPane: '%31', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.launchModel).toEqual({ model: 'opus', effort: 'xhigh' })
expect(reloaded.setLaunchModel(pending.agentId, { model: 'sonnet', effort: 'high' })).toBe(true)
expect(reloaded.setLaunchModel('nobody', null)).toBe(false)
const { registry: again } = await loadRegistryModule()
again.load()
expect(again.byAgent(pending.agentId)?.launchModel).toEqual({ model: 'sonnet', effort: 'high' })
// A hand-edited record is dropped, never launched with.
const plain = again.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%32' }], cwd: '/tmp/demo' })!
expect(plain.launchModel).toBeUndefined()
})
it('keeps an agent\'s launch flags across a reload, a hook bind and a stopped row, and drops an empty or malformed list', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%41' }], cwd: '/tmp/demo' })!
expect(registry.setLaunchArgs('nobody', ['--chrome'])).toBe(false)
expect(registry.setLaunchArgs(pending.agentId, ['--chrome'])).toBe(true)
const { registry: reloaded, strictPersistedRow: strict } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.launchArgs).toEqual(['--chrome'])
// A hook bind rebuilds the row from named fields; the flags must survive it.
const transcriptPath = join(dataDir, 'session-args.jsonl')
writeFileSync(transcriptPath, '{}\n')
const bound = reloaded.register({ sessionId: 'session-args', transcriptPath, tmuxPane: '%41', cwd: '/tmp/demo' })
expect(bound?.entry.launchArgs).toEqual(['--chrome'])
// A stopped row goes through the normaliser on its way back from disk.
const row = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')).find((r: { agentId: string }) => r.agentId === pending.agentId)
expect(strict(row)?.launchArgs).toEqual(['--chrome'])
expect(strict({ ...row, launchArgs: [1, '--x'] })).not.toHaveProperty('launchArgs')
expect(strict({ ...row, launchArgs: 'x' })).not.toHaveProperty('launchArgs')
expect(strict({ ...row, launchArgs: [] })).not.toHaveProperty('launchArgs')
// Empty clears the field rather than writing an empty array.
expect(reloaded.setLaunchArgs(pending.agentId, [])).toBe(true)
expect('launchArgs' in reloaded.byAgent(pending.agentId)!).toBe(false)
// A hand-edited record on disk loads without the field.
const file = join(dataDir, 'registry.json')
const rows = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>
writeFileSync(file, JSON.stringify(rows.map(r => ({ ...r, launchArgs: [1, '--x'] }))), { mode: 0o600 })
const { registry: hand } = await loadRegistryModule()
hand.load()
expect(hand.byAgent(pending.agentId)).not.toHaveProperty('launchArgs')
writeFileSync(file, JSON.stringify(rows.map(r => ({ ...r, launchArgs: 'x' }))), { mode: 0o600 })
const { registry: hand2 } = await loadRegistryModule()
hand2.load()
expect(hand2.byAgent(pending.agentId)).not.toHaveProperty('launchArgs')
void registry; void strictPersistedRow
})
// The conversation a fresh move onto a grid left (core/agents/retarget.ts): the way home reopens it.
it('keeps the remembered subscription session across a reload and the binds on the grid', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const s1 = join(dataDir, 'S1.jsonl'), s2 = join(dataDir, 'S2.jsonl')
writeFileSync(s1, '{}\n'); writeFileSync(s2, '{}\n')
registerProcess(registry, { launcherId: 'agent-1', sessionId: 'S1', transcriptPath: s1, tmuxPane: '%22', cwd: '/tmp/demo' })
expect(registry.setSubscriptionSession('agent-1', 'S1')).toBe(true)
expect(registry.setSubscriptionSession('nobody', 'S1')).toBe(false)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent('agent-1')?.subscriptionSessionId).toBe('S1')
// The fresh conversation on the grid reports in: the same agent, the left one still remembered.
const fresh = reloaded.register({ sessionId: 'S2', transcriptPath: s2, tmuxPane: '%22', cwd: '/tmp/demo' })
expect(fresh?.entry).toMatchObject({ agentId: 'agent-1', sessionId: 'S2', subscriptionSessionId: 'S1' })
// Home, the reopened conversation reports in: the same agent bound to it, not a new one.
const back = reloaded.register({ sessionId: 'S1', transcriptPath: s1, tmuxPane: '%22', cwd: '/tmp/demo' })
expect(back).toMatchObject({ rebound: 'S2', orphaned: null, entry: { agentId: 'agent-1', sessionId: 'S1' } })
expect(reloaded.list()).toHaveLength(1)
expect(reloaded.resolve('S1')?.agentId).toBe('agent-1')
expect(reloaded.setSubscriptionSession('agent-1', null)).toBe(true)
expect(reloaded.byAgent('agent-1')?.subscriptionSessionId).toBeUndefined()
})
it('fills an old supported session role once and persists it through reload', async () => {
const { registry } = await loadRegistryModule(); registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%21' }] })!
const skill = { role: 'coordinator' as const, key: pending.agentId }
expect(registry.setSwarmSkill('missing', skill)).toBe(false)
expect(registry.setSwarmSkill(pending.agentId, skill)).toBe(true)
expect(registry.setSwarmSkill(pending.agentId, { role: 'agent', key: 'replacement' })).toBe(false)
const { registry: reloaded } = await loadRegistryModule(); reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.swarmSkill).toEqual(skill)
const other = reloaded.openPendingAgent({ engine: 'opencode', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%22' }] })!
expect(reloaded.setSwarmSkill(other.agentId, skill)).toBe(false)
})
it('preserves Swarm role and runtime key across hooks and reload', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const swarmSkill = { role: 'agent' as const, key: 'harness-claude-worker' }
const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir,
runtimes: [{ backend: 'tmux', paneId: '%21' }], swarmSkill })!
const transcriptPath = join(dataDir, 'swarm.jsonl')
writeFileSync(transcriptPath, '{}\n')
expect(registry.register({ engine: 'claude', sessionId: 'swarm', transcriptPath, cwd: dataDir, tmuxPane: '%21' })?.entry.swarmSkill).toEqual(swarmSkill)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.swarmSkill).toEqual(swarmSkill)
expect(reloaded.releaseEngine(pending.agentId, true)?.swarmSkill).toBeUndefined()
})
// Project instructions, phase 4 (decision 1): a row an older CLI saved names its Swarm role in the wire's values.
it('reads a Swarm role an older CLI saved as this release keeps it, on load and from a stopped harness\'s row', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir, runtimes: [{ backend: 'tmux', paneId: '%23' }],
swarmSkill: { role: 'agent', fallback: 'review', key: 'reviewer' } })!
const file = join(dataDir, 'registry.json')
const row = (JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>).find(r => r.agentId === pending.agentId)!
expect(row.swarmSkill).toEqual({ role: 'agent', fallback: 'review', key: 'reviewer' })
const older = { ...row, swarmSkill: { role: 'review', key: 'reviewer', mode: 'default' } }
expect(strictPersistedRow(older)?.swarmSkill).toEqual({ role: 'agent', fallback: 'review', key: 'reviewer', mode: 'default' })
expect(strictPersistedRow({ ...row, swarmSkill: { role: 'lead', key: 'pm' } })?.swarmSkill).toEqual({ role: 'coordinator', key: 'pm' })
expect(strictPersistedRow({ ...row, swarmSkill: { role: 'pm', key: 'pm' } })).not.toHaveProperty('swarmSkill')
writeFileSync(file, JSON.stringify([older]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.swarmSkill).toEqual({ role: 'agent', fallback: 'review', key: 'reviewer', mode: 'default' })
})
it('keeps strict conversation resume after the engine binds and the daemon reloads', async () => {
const transcriptPath = join(dataDir, 'session-resumed.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const original = registerProcess(registry, {
engine: 'claude', sessionId: 'session-resumed', transcriptPath, tmuxPane: '%21', cwd: '/tmp/demo',
})!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
// SessionStart rebuilds the row. It must retain the policy that prevents a
// later daemon restore from silently replacing this saved conversation.
const bound = registry.register({
engine: 'claude', sessionId: original.sessionId, transcriptPath, tmuxPane: '%22', cwd: '/tmp/demo', processIdentity: processIdentity(122),
})
expect(bound?.entry.agentId).toBe(original.agentId)
expect(bound?.entry.resumeOnly).toBe(true)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(original.agentId)).toMatchObject({
sessionId: original.sessionId, tmuxPane: '%22', resumeOnly: true,
})
})
it('lets process discovery start a resumed row, and still refuses the wrong conversation', async () => {
const transcriptPath = join(dataDir, 'resume-target.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
const original = registerProcess(registry, { engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%21' })!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%22' }])
registry.openProcessAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%22' }], processIdentity: processIdentity(122) })
// The engine is running in the row's pane, so the row has started — it no longer waits for a
// hook a resume may never send. What it has NOT yet been told is which conversation reopened.
expect(registry.byAgent(original.agentId)?.launch?.state).toBe('ready')
expect(registry.byAgent(original.agentId)?.lastHookAt).toBe(0)
expect(registry.register({ engine: 'claude', sessionId: 'unexpected-new-session', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })).toBeNull()
expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: 'resume-target', launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH' } })
const confirmed = registry.register({ engine: 'claude', sessionId: 'resume-target', transcriptPath, tmuxPane: '%22', processIdentity: processIdentity(122) })
expect(confirmed?.entry).toMatchObject({ agentId: original.agentId, sessionId: 'resume-target', launch: { state: 'ready' } })
})
// The guard reads `lastHookAt`, not `launch`. A resume is now confirmed by its own live engine
// process (`resumeStoppedAgent.ts`), which marks the row ready BEFORE any hook arrives — and a
// guard keyed on `launch` would have been disarmed for exactly the resumes it protects.
it('still refuses another conversation on the first hook after the row was marked ready', async () => {
const transcriptPath = join(dataDir, 'ready-first.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
const original = registerProcess(registry, { engine: 'claude', sessionId: 'ready-first', transcriptPath, tmuxPane: '%31' })!.entry
registry.removeAgent(original.agentId)
registry.resumePendingAgent(original, [{ backend: 'tmux', paneId: '%32' }])
// What the resume service does the moment it sees the engine process in the pane.
registry.setLaunch(original.agentId, { state: 'ready' })
expect(registry.byAgent(original.agentId)?.lastHookAt).toBe(0)
expect(registry.register({ engine: 'claude', sessionId: 'somebody-elses-session', transcriptPath, tmuxPane: '%32', processIdentity: processIdentity(132) })).toBeNull()
expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: 'ready-first', launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH' } })
})
it('drops any launch state on the hook that proves the engine is up', async () => {
const transcriptPath = join(dataDir, 'session-f.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/demo' })!
registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT' })
const bound = registry.register({ sessionId: 'session-f', transcriptPath, tmuxPane: '%9', cwd: '/tmp/demo' })
expect(bound?.entry.launch).toBeUndefined()
})
it('persists the grid launch across a reboot and forgets one it cannot trust', async () => {
const transcriptPath = join(dataDir, 'session-a.jsonl')
writeFileSync(transcriptPath, '{}\n')
chmodSync(dataDir, 0o755)
writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([
persistedRow(transcriptPath, { grid: { baseUrl: GRID_LAUNCH.baseUrl, model: 'gpt-5' }, gridLaunch: GRID_LAUNCH }),
persistedRow(transcriptPath, { agentId: 'agent-b', sessionId: 'session-b', runtimes: [{ backend: 'tmux', paneId: '%4' }], primaryRuntimeKey: 'tmux\u0000%4', tmuxPane: '%4', processIdentity: processIdentity(4243), grid: { baseUrl: GRID_LAUNCH.baseUrl, model: null }, gridLaunch: { baseUrl: GRID_LAUNCH.baseUrl } }),
persistedRow(transcriptPath, { agentId: 'agent-c', sessionId: 'session-c', runtimes: [{ backend: 'tmux', paneId: '%5' }], primaryRuntimeKey: 'tmux\u0000%5', tmuxPane: '%5', processIdentity: processIdentity(4244) }),
]))
writeLegacyStateFile(join(dataDir, 'registry-boot'), 'time:1')
const { registry } = await loadRegistryModule()
registry.load()
expect(registry.rebootedSinceLastRun).toBe(true)
// Kept verbatim: this is what restore relaunches the pane with.
expect(registry.byAgent('agent-a')).toMatchObject({ processIdentity: null, gridLaunch: GRID_LAUNCH })
// A half-remembered launch is worse than none — it would look like a grid launch and fail like one.
expect(registry.byAgent('agent-b')?.gridLaunch).toBeNull()
// A row from before the field existed stays distinguishable from "vendor login".
expect(registry.byAgent('agent-c')).not.toHaveProperty('gridLaunch')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved[0]).toMatchObject({ gridLaunch: GRID_LAUNCH })
expect(saved[2]).not.toHaveProperty('gridLaunch')
})
it('a discovered Codex process fills in the profile it runs under, but never replaces one', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-work' })!
expect(opened.entry.codexHome).toBe('/tmp/codex-work')
// Discovery cannot have seen the credential: a discovered grid agent is observed, never relaunched.
expect(opened.entry.gridLaunch).toBeNull()
expect(registry.setCodexHome(opened.entry.agentId, '/tmp/codex-other')).toBe(false)
expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
registry.openProcessAgent({ engine: 'codex', tmuxPane: '%5', processIdentity: processIdentity(77), codexHome: '/tmp/codex-other' })
expect(registry.byAgent(opened.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
const bare = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%6', processIdentity: processIdentity(78) })!
expect(bare.entry.codexHome).toBeNull()
expect(registry.setCodexHome(bare.entry.agentId, '/tmp/codex-work')).toBe(true)
expect(registry.byAgent(bare.entry.agentId)?.codexHome).toBe('/tmp/codex-work')
const claude = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(79) })!
expect(registry.setCodexHome(claude.entry.agentId, '/tmp/codex-work')).toBe(false)
})
it('clearProcessIdentity forgets the pid everywhere it is indexed', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%5', processIdentity: processIdentity(77) })
const agentId = opened!.entry.agentId
expect(registry.byProcess('claude', processIdentity(77))?.agentId).toBe(agentId)
expect(registry.clearProcessIdentity(agentId)).toBe(true)
expect(registry.byAgent(agentId)?.processIdentity).toBeNull()
expect(registry.byProcess('claude', processIdentity(77))).toBeUndefined()
expect(registry.clearProcessIdentity(agentId)).toBe(true) // idempotent
expect(registry.clearProcessIdentity('nobody')).toBe(false)
})
it('survives two restored panes swapping ids when done inside one transaction', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const a = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', processIdentity: processIdentity(11) })!.entry.agentId
const b = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', processIdentity: processIdentity(12) })!.entry.agentId
// A new tmux server hands out %1/%2 again, in the other order. Saved between the two updates, A
// would claim %2 while B still lists it, and the save's route dedupe evicts one of them.
await registry.transaction(() => {
registry.updateRuntimes(a, [{ backend: 'tmux', paneId: '%2' }], 'tmux\u0000%2')
registry.updateRuntimes(b, [{ backend: 'tmux', paneId: '%1' }], 'tmux\u0000%1')
})
expect(registry.byAgent(a)?.tmuxPane).toBe('%2')
expect(registry.byAgent(b)?.tmuxPane).toBe('%1')
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
expect(saved.map((row) => row.agentId).sort()).toEqual([a, b].sort())
})
it('flushes an acknowledged binding at exit without waiting for a discovery transaction', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const transcriptPath = join(dataDir, 'just-bound.jsonl')
writeFileSync(transcriptPath, '{}\n')
const pending = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(71) })!.entry
let finish!: () => void
const batch = registry.transaction(async () => {
registry.register({ engine: 'claude', sessionId: 'just-bound', transcriptPath, tmuxPane: '%7' })
await new Promise<void>(resolve => { finish = resolve })
})
try {
// Reflect keeps this regression runnable against the former flush(), which ignored this option.
Reflect.apply(registry.flush, registry, [{ exiting: true }])
const saved = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8'))
expect(saved.find((row: any) => row.agentId === pending.agentId).sessionId).toBe('just-bound')
} finally { finish(); await batch }
})
it('never flushes an incomplete pane swap at exit or lets merge conflict resolution evict its other owner', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const a = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', processIdentity: processIdentity(11) })!.entry.agentId
const b = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%2', processIdentity: processIdentity(12) })!.entry.agentId
const file = join(dataDir, 'registry.json')
const before = readFileSync(file, 'utf8')
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
await registry.transaction(async () => {
registry.updateRuntimes(a, [{ backend: 'tmux', paneId: '%2' }], 'tmux\u0000%2')
Reflect.apply(registry.flush, registry, [{ exiting: true }])
expect(readFileSync(file, 'utf8')).toBe(before)
registry.updateRuntimes(b, [{ backend: 'tmux', paneId: '%1' }], 'tmux\u0000%1')
})
expect(JSON.parse(readFileSync(file, 'utf8')).map((row: any) => row.agentId).sort()).toEqual([a, b].sort())
error.mockRestore()
})
it('stops holding saves back for a transaction that outlives its hold, and saves what it has changed', async () => {
// A reconcile pass stuck inside its transaction held every save back for as long as it ran.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { registry } = await loadRegistryModule()
registry.load()
const saved = () => (JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>).map((row) => row.agentId)
let finish!: () => void
let inside!: string
const stuck = registry.transaction(async () => {
inside = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%7', processIdentity: processIdentity(71) })!.entry.agentId
await new Promise<void>((resolve) => { finish = resolve })
}, { holdSavesMs: 50 })
expect(existsSync(join(dataDir, 'registry.json')) ? saved() : []).not.toContain(inside)
await vi.waitFor(() => expect(saved()).toContain(inside))
expect(warn).toHaveBeenCalledWith('[registry] a transaction has held saves back for 50 ms; saving without waiting for it')
// Saved as they happen from here on, and the stuck apply finishing changes nothing about that.
const after = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%8', processIdentity: processIdentity(72) })!.entry.agentId
expect(saved()).toContain(after)
finish()
await stuck
// One that finishes in time holds its saves to the end, as before.
let during: string[] = []
await registry.transaction(() => {
registry.openProcessAgent({ engine: 'claude', tmuxPane: '%9', processIdentity: processIdentity(73) })
during = saved() as string[]
}, { holdSavesMs: 60_000 })
expect(during).toHaveLength(2)
expect(saved()).toHaveLength(3)
warn.mockRestore()
})
it('adopts a new process into an agent whose identity was cleared, keeping its id and session', async () => {
const transcriptPath = join(dataDir, 'session-c.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const bound = registerProcess(registry, { sessionId: 'session-c', transcriptPath, tmuxPane: '%4', cwd: '/tmp/demo' })
const agentId = bound!.entry.agentId
// What restore does: forget the dead pid, point the row at the recreated pane, launch pending.
registry.clearProcessIdentity(agentId)
registry.updateRuntimes(agentId, [{ backend: 'tmux', paneId: '%0' }], 'tmux\u0000%0')
registry.setLaunch(agentId, { state: 'starting' })
const adopted = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%0', processIdentity: processIdentity(500) })
expect(adopted).toMatchObject({ isNew: false, evicted: null })
expect(adopted?.entry.agentId).toBe(agentId)
expect(adopted?.entry.sessionId).toBe('session-c')
expect(registry.list()).toHaveLength(1)
})
})
describe('a terminal: a pane that becomes an engine and back', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-terminal-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
const pane = { backend: 'tmux' as const, paneId: '%9' }
it('opens as engine `terminal`, marked terminalHost, and survives a reload that way', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
expect(opened).toMatchObject({ engine: 'terminal', terminalHost: true, sessionId: '', processIdentity: null })
expect(opened.defaultName).toMatch(/^Terminal /)
expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(opened.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true })
})
it('adopts the engine started inside it — same agentId, process indexed under the engine — then a hook binds to it', async () => {
const transcriptPath = join(dataDir, 'session-t.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
const adopted = registry.adoptEngine(opened.agentId, 'claude', processIdentity(909))!
expect(adopted.agentId).toBe(opened.agentId)
expect(adopted).toMatchObject({ engine: 'claude', terminalHost: true, launch: { state: 'ready' }, active: true })
expect(registry.byProcess('claude', processIdentity(909))?.agentId).toBe(opened.agentId)
expect(registry.byRuntimeTerminal(pane)).toBeUndefined()
expect(registry.byRuntimeEngine(pane, 'claude')?.agentId).toBe(opened.agentId)
// An agent already running an engine is never re-labelled.
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(910))).toBeNull()
const bound = registry.register({ engine: 'claude', sessionId: 'session-t', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(909) })
expect(bound?.entry.agentId).toBe(opened.agentId)
expect(bound?.entry.terminalHost).toBe(true)
expect(registry.list()).toHaveLength(1)
})
it('tells the core each session\'s engine as it enters: opened, adopted, registered and loaded', async () => {
// The core starts loading what that engine's sessions read then (engines/inProcess.ts `preloadEngine`).
const transcriptPath = join(dataDir, 'session-e.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
const entered: string[] = []
registry.onEnter = (engine) => entered.push(engine)
registry.load()
// Told as often as the row is indexed: what it starts is started once (engines/inProcess.ts).
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
expect(new Set(entered)).toEqual(new Set(['terminal']))
registry.adoptEngine(opened.agentId, 'amp', processIdentity(913))
expect(entered.at(-1)).toBe('amp')
entered.length = 0
expect(registerProcess(registry, { engine: 'claude', sessionId: 'session-e', transcriptPath, tmuxPane: '%10' })).not.toBeNull()
expect(entered).toContain('claude')
registry.flush()
const { registry: reloaded } = await loadRegistryModule()
const loaded: string[] = []
reloaded.onEnter = (engine) => loaded.push(engine)
reloaded.load()
expect(new Set(loaded)).toEqual(new Set(['amp', 'claude']))
})
it('a SessionStart hook that beats the reconciler adopts the terminal at its pane rather than minting nothing', async () => {
const transcriptPath = join(dataDir, 'session-h.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
const bound = registry.register({ engine: 'claude', sessionId: 'session-h', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(911) })
expect(bound?.entry.agentId).toBe(opened.agentId)
expect(bound?.entry).toMatchObject({ engine: 'claude', terminalHost: true })
expect(registry.list()).toHaveLength(1)
})
it('releases the engine when it exits: a live terminal again, with nothing of the engine left on it', async () => {
const transcriptPath = join(dataDir, 'session-r.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const opened = registry.openPendingAgent({ engine: 'terminal', runtimes: [pane], cwd: '/tmp/work' })!
registry.adoptEngine(opened.agentId, 'claude', processIdentity(912))
registry.register({ engine: 'claude', sessionId: 'session-r', transcriptPath, tmuxPane: '%9', processIdentity: processIdentity(912) })
registry.setBypassPermission(opened.agentId, true)
const released = registry.releaseEngine(opened.agentId)!
expect(released.agentId).toBe(opened.agentId)
expect(released).toMatchObject({ engine: 'terminal', terminalHost: true, active: true, launch: { state: 'ready' }, sessionId: '', processIdentity: null, transcriptPath: null, grid: null, model: null })
// The pane's launch shape survives the engine: the same flags come back with the next launch.
expect(released.bypassPermission).toBe(true)
expect(registry.bySession('session-r')).toBeUndefined()
expect(registry.byProcess('claude', processIdentity(912))).toBeUndefined()
expect(registry.byRuntimeTerminal(pane)?.agentId).toBe(opened.agentId)
expect(registry.terminalAvailable(opened.agentId)).toBe(true)
// Already a terminal? Nothing to release. A plain agent whose engine exited? A terminal from now on.
expect(registry.releaseEngine(opened.agentId)).toBeNull()
const plain = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/x' })!
expect(plain.terminalHost).toBeUndefined()
expect(registry.releaseEngine(plain.agentId)).toMatchObject({ engine: 'terminal', terminalHost: true, active: true })
expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: '%10' })?.agentId).toBe(plain.agentId)
// And the next engine typed into the same shell is adopted just the same.
expect(registry.adoptEngine(opened.agentId, 'codex', processIdentity(913))).toMatchObject({ engine: 'codex' })
})
})
describe('lastOpenedAt: when an app last opened the agent, on the daemon clock', () => {
beforeEach(() => {
vi.useFakeTimers()
dataDir = mkdtempSync(join(tmpdir(), 'adapter-registry-opened-'))
})
afterEach(() => {
vi.useRealTimers()
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
const OPENED = Date.UTC(2026, 8, 26, 9, 30)
const onDisk = () => JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<Record<string, unknown>>
it('stamps the daemon’s own clock, persists it, and leaves the bookkeeping `touchedAt` alone', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%41' }], cwd: '/tmp/demo' })!
expect(pending.lastOpenedAt).toBeUndefined()
expect(onDisk()[0]).not.toHaveProperty('lastOpenedAt')
const touchedAt = pending.touchedAt
vi.setSystemTime(OPENED)
const opened = registry.markOpened(pending.agentId)
expect(opened?.lastOpenedAt).toBe(OPENED)
expect(opened?.touchedAt).toBe(touchedAt)
expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED, touchedAt })
expect(registry.markOpened('nobody')).toBeNull()
// The load rebuilds every row from a named list: a field missing there is written and then lost.
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)?.lastOpenedAt).toBe(OPENED)
})
it('survives the hook that rebuilds the row — the first prompt after an open must not erase it', async () => {
const transcriptPath = join(dataDir, 'session-opened.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%42' }], cwd: '/tmp/demo' })!
vi.setSystemTime(OPENED)
registry.markOpened(pending.agentId)
vi.setSystemTime(OPENED + 60_000)
const bound = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.lastOpenedAt).toBe(OPENED)
// ...and again on a re-register of the same session, then on disk.
const again = registry.register({ sessionId: 'session-opened', transcriptPath, tmuxPane: '%42', cwd: '/tmp/demo' })
expect(again?.entry.lastOpenedAt).toBe(OPENED)
expect(onDisk()[0]).toMatchObject({ agentId: pending.agentId, lastOpenedAt: OPENED })
})
it('never lets a hand-edited or nonsensical stamp reach the frame', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%43' }], cwd: '/tmp/demo' })!
const row = onDisk()[0]
expect(strictPersistedRow({ ...row, lastOpenedAt: OPENED })?.lastOpenedAt).toBe(OPENED)
for (const bad of ['yesterday', -5, 0, 1.5, Number.NaN, null]) {
expect(strictPersistedRow({ ...row, lastOpenedAt: bad })).not.toHaveProperty('lastOpenedAt')
}
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, lastOpenedAt: 'yesterday' }]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(pending.agentId)).toBeTruthy()
expect(reloaded.byAgent(pending.agentId)).not.toHaveProperty('lastOpenedAt')
})
})
describe('who started it', () => {
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'adapter-startedby-')) })
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
it('keeps a harness another agent started as one, on the row, on disk and after a reload; the person\'s has none', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const byAgent = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%5' }], cwd: '/tmp/w', startedBy: 'agent' })!
const byPerson = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%6' }], cwd: '/tmp/w', startedBy: null })!
expect(byAgent.startedBy).toBe('agent')
expect(byPerson).not.toHaveProperty('startedBy')
expect(strictPersistedRow(JSON.parse(JSON.stringify(byAgent)))?.startedBy).toBe('agent')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(byAgent.agentId)?.startedBy).toBe('agent')
expect(reloaded.byAgent(byPerson.agentId)).not.toHaveProperty('startedBy')
})
it('survives the hook that rebuilds the row, so a restart keeps the pull request line', async () => {
const transcriptPath = join(dataDir, 'session-started.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/demo', startedBy: 'agent' })!
const bound = registry.register({ sessionId: 'session-started', transcriptPath, tmuxPane: '%8', cwd: '/tmp/demo' })
expect(bound?.entry.agentId).toBe(pending.agentId)
expect(bound?.entry.startedBy).toBe('agent')
expect(registry.byAgent(pending.agentId)?.startedBy).toBe('agent')
})
it('keeps whose guest it was started for through the hook that rebuilds the row and a reload', async () => {
const transcriptPath = join(dataDir, 'session-guest.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry } = await loadRegistryModule()
registry.load()
const pending = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%31' }], cwd: '/tmp/g', guest: '[email protected]' })!
expect(pending.guest).toBe('[email protected]')
expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%32' }], cwd: '/tmp/o', guest: null })).not.toHaveProperty('guest')
registry.register({ sessionId: 'session-guest', transcriptPath, tmuxPane: '%31', cwd: '/tmp/g' })
expect(registry.byAgent(pending.agentId)?.guest).toBe('[email protected]')
registry.flush()
const reloaded = await loadRegistryModule()
reloaded.registry.load()
expect(reloaded.registry.byAgent(pending.agentId)?.guest).toBe('[email protected]')
})
it('keeps which harness here started it, beside startedBy, through a reload and the hook that rebuilds the row', async () => {
const transcriptPath = join(dataDir, 'session-child.jsonl')
writeFileSync(transcriptPath, '{}\n')
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const child = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!
expect(child.parentAgentId).toBe('lead-1')
// Only beside startedBy: the person's harness has no starter, and neither has a malformed id.
expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/w', parentAgentId: 'lead-1' })).not.toHaveProperty('parentAgentId')
expect(registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: '../x' })).not.toHaveProperty('parentAgentId')
const row = JSON.parse(JSON.stringify(child))
expect(strictPersistedRow(row)?.parentAgentId).toBe('lead-1')
expect(strictPersistedRow({ ...row, startedBy: undefined })).not.toHaveProperty('parentAgentId')
expect(strictPersistedRow({ ...row, parentAgentId: 7 })).not.toHaveProperty('parentAgentId')
const bound = registry.register({ sessionId: 'session-child', transcriptPath, tmuxPane: '%9', cwd: '/tmp/w' })
expect(bound?.entry.agentId).toBe(child.agentId)
expect(bound?.entry.parentAgentId).toBe('lead-1')
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(child.agentId)?.parentAgentId).toBe('lead-1')
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, parentAgentId: 'a b' }]), { mode: 0o600 })
const { registry: edited } = await loadRegistryModule()
edited.load()
expect(edited.byAgent(child.agentId)).toBeTruthy()
expect(edited.byAgent(child.agentId)).not.toHaveProperty('parentAgentId')
})
it('does not hand who started it to the shell its engine leaves behind under a new id', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const child = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%12' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!
// A new id with a starter is a new child to every window: it would open the person's shell beside the agent.
const shell = registry.releaseEngine(child.agentId, true)!
expect(shell.agentId).not.toBe(child.agentId)
expect(shell).not.toHaveProperty('parentAgentId')
// The same pane under its own id keeps it: that is still the harness the agent started.
const kept = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%13' }], cwd: '/tmp/w', startedBy: 'agent', parentAgentId: 'lead-1' })!
expect(registry.releaseEngine(kept.agentId)).toMatchObject({ agentId: kept.agentId, parentAgentId: 'lead-1' })
})
it('drops anything but another agent from a hand-edited row', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/w' })!
const row = JSON.parse(JSON.stringify(entry))
expect(strictPersistedRow({ ...row, startedBy: 'person' })).not.toHaveProperty('startedBy')
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, startedBy: 'someone' }]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(entry.agentId)).toBeTruthy()
expect(reloaded.byAgent(entry.agentId)).not.toHaveProperty('startedBy')
})
})
describe('fork origin record', () => {
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'adapter-forkorigin-')) })
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
async function forkRow(forkedFrom: unknown) {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({
engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/tmp/w',
forkedFrom: forkedFrom as never,
})!
const roundTrip = strictPersistedRow(JSON.parse(JSON.stringify(entry)))
return { entry, roundTrip }
}
const origin = { agentId: 'p', name: 'Parent', sessionId: 'p-sess', transcriptPath: '/x/p-sess.jsonl' }
it('R1 keeps the parent session and transcript exactly, on the entry and after a round trip', async () => {
const { entry, roundTrip } = await forkRow(origin)
expect(entry.forkedFrom).toEqual(origin)
expect(roundTrip?.forkedFrom).toEqual(origin)
})
it('R2 drops a non-string session id', async () => {
const { entry, roundTrip } = await forkRow({ agentId: 'p', name: 'P', sessionId: 42, transcriptPath: '/x/p.jsonl' })
expect(entry.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
expect(roundTrip?.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
})
it('R3 drops a relative transcript path but keeps the session', async () => {
const { entry, roundTrip } = await forkRow({ ...origin, transcriptPath: 'relative.jsonl' })
expect(entry.forkedFrom).toEqual({ agentId: 'p', name: 'Parent', sessionId: 'p-sess' })
expect(roundTrip?.forkedFrom).toEqual({ agentId: 'p', name: 'Parent', sessionId: 'p-sess' })
})
it('R4 drops an oversized session id (and the path that depends on it)', async () => {
const { entry, roundTrip } = await forkRow({ ...origin, sessionId: 's'.repeat(257) })
expect(entry.forkedFrom).toEqual({ agentId: 'p', name: 'Parent' })
expect(roundTrip?.forkedFrom).toEqual({ agentId: 'p', name: 'Parent' })
})
it('R5 drops a malformed origin altogether on a persisted row', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/tmp/w' })!
const row = strictPersistedRow({ ...JSON.parse(JSON.stringify(entry)), forkedFrom: { agentId: 7 } })
expect(row).toBeTruthy()
expect('forkedFrom' in row!).toBe(false)
})
it('R6 round-trips a legacy origin with no extra keys', async () => {
const { entry, roundTrip } = await forkRow({ agentId: 'p', name: 'P' })
expect(entry.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
expect(Object.keys(entry.forkedFrom!).sort()).toEqual(['agentId', 'name'])
expect(roundTrip?.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
expect(Object.keys(roundTrip!.forkedFrom!).sort()).toEqual(['agentId', 'name'])
})
it('R7 treats an empty session id as no session', async () => {
const { entry, roundTrip } = await forkRow({ agentId: 'p', name: 'P', sessionId: '', transcriptPath: '/x/p.jsonl' })
expect(entry.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
expect(roundTrip?.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
})
it('does not keep unknown keys from a raw persisted origin', async () => {
const { registry, strictPersistedRow } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%3' }], cwd: '/tmp/w' })!
const row = strictPersistedRow({ ...JSON.parse(JSON.stringify(entry)), forkedFrom: { ...origin, extra: 'x' } })
expect(row?.forkedFrom).toEqual(origin)
})
})
describe('fork origin record — persistence edges', () => {
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'adapter-forkorigin-v-')) })
afterEach(() => {
rmSync(dataDir, { recursive: true, force: true })
delete process.env.ADAPTER_DATA_DIR
delete process.env.CLAUDE_PROJECTS_DIR
delete process.env.CODEX_HOME
delete process.env.CURSOR_HOME
})
const origin = { agentId: 'p', name: 'Parent', sessionId: 'p-sess', transcriptPath: '/x/p-sess.jsonl' }
const onDisk = () => JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')) as Record<string, unknown>[]
async function plainRow() {
const mod = await loadRegistryModule()
mod.registry.load()
const entry = mod.registry.openPendingAgent({
engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%5' }], cwd: '/tmp/w', codexHome: '/tmp/profile',
dsh: 'autonomous/fixture', permissionMode: 'plan', bypassPermission: true, defaultName: 'My work',
})!
return { ...mod, row: JSON.parse(JSON.stringify(entry)) as Record<string, unknown> }
}
it('changes nothing but forkedFrom on an old-format persisted row', async () => {
const { strictPersistedRow, row } = await plainRow()
const base = strictPersistedRow({ ...row, title: 'Kept', lastOpenedAt: 5 })!
expect(base).toBeTruthy()
const legacy = strictPersistedRow({ ...row, title: 'Kept', lastOpenedAt: 5, forkedFrom: { agentId: 'p', name: 'P' } })
expect(legacy).toEqual({ ...base, forkedFrom: { agentId: 'p', name: 'P' } })
// Rows written before forks existed, and rows that stored an explicit null, still load.
expect(strictPersistedRow({ ...row, title: 'Kept', lastOpenedAt: 5, forkedFrom: null })).toEqual(base)
expect(strictPersistedRow({ ...row, title: 'Kept', lastOpenedAt: 5, forkedFrom: 'garbage' })).toEqual(base)
})
it('keeps a transcript path only with a valid session id, and bounds every field', async () => {
const { strictPersistedRow, row } = await plainRow()
const forked = (forkedFrom: unknown) => strictPersistedRow({ ...row, forkedFrom })?.forkedFrom
expect(forked({ agentId: 'p', name: 'P', transcriptPath: '/x/p.jsonl' })).toEqual({ agentId: 'p', name: 'P' })
expect(forked({ ...origin, transcriptPath: `/${'a'.repeat(4096)}` })).toEqual({ agentId: 'p', name: 'Parent', sessionId: 'p-sess' })
expect(forked({ ...origin, transcriptPath: `/${'a'.repeat(4095)}` })?.transcriptPath).toHaveLength(4096)
expect(forked({ ...origin, sessionId: 's'.repeat(256) })?.sessionId).toHaveLength(256)
expect(forked({ ...origin, transcriptPath: 42 })).toEqual({ agentId: 'p', name: 'Parent', sessionId: 'p-sess' })
expect(forked({ agentId: 'p', name: 7 })).toEqual({ agentId: 'p', name: '' })
expect(forked({ agentId: 'p', name: 'n'.repeat(200) })?.name).toHaveLength(120)
expect(forked({ agentId: '', name: 'P' })).toBeUndefined()
expect(forked(['p', 'P'])).toBeUndefined()
})
it('normalizes a fork origin handed to openPendingAgent the same way', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({
engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%6' }], cwd: '/tmp/w',
forkedFrom: { ...origin, extra: 'x' } as never,
})!
expect(entry.forkedFrom).toEqual(origin)
const blank = registry.openPendingAgent({
engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }], cwd: '/tmp/w', forkedFrom: { agentId: '', name: 'P' },
})!
expect(blank).toBeTruthy()
expect('forkedFrom' in blank).toBe(false)
})
it('writes the full fork origin to disk at fork time', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%8' }], cwd: '/tmp/w', forkedFrom: origin })!
expect(onDisk().find(r => r.agentId === entry.agentId)?.forkedFrom).toEqual(origin)
})
it('loads a registry whose fork row has a malformed origin instead of refusing the file', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%9' }], cwd: '/tmp/w', forkedFrom: origin })!
const [row] = onDisk()
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, forkedFrom: { agentId: 7, sessionId: {} } }]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(entry.agentId)).toBeTruthy()
expect(reloaded.byAgent(entry.agentId)?.forkedFrom ?? null).toBeNull()
// Still writable.
expect(reloaded.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%10' }], cwd: '/tmp/w' })).toBeTruthy()
})
// The real round trip for a LIVE fork: the daemon restarts while the fork is still unbound (the app
// restarts it), and inheritance needs forkedFrom exactly then.
it('keeps the fork origin of an unbound fork across a daemon restart', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%11' }], cwd: '/tmp/w', forkedFrom: origin })!
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(entry.agentId)?.forkedFrom).toEqual(origin)
})
it('keeps the full fork origin through a real load, a forced save and a re-read of the file', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%12' }], cwd: '/tmp/w', forkedFrom: origin })!
// A fresh daemon loads the file, then something rewrites it (touch / launch change / bind elsewhere).
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(entry.agentId)?.forkedFrom).toEqual(origin)
reloaded.setLaunch(entry.agentId, { state: 'failed', error: 'START_TIMEOUT' })
expect(onDisk().find(r => r.agentId === entry.agentId)?.forkedFrom).toEqual(origin)
const { registry: third } = await loadRegistryModule()
third.load()
expect(third.byAgent(entry.agentId)?.forkedFrom).toEqual(origin)
})
it('loads a legacy two-key fork origin without adding keys', async () => {
const { registry } = await loadRegistryModule()
registry.load()
const entry = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%13' }], cwd: '/tmp/w' })!
const [row] = onDisk()
writeFileSync(join(dataDir, 'registry.json'), JSON.stringify([{ ...row, forkedFrom: { agentId: 'p', name: 'P' } }]), { mode: 0o600 })
const { registry: reloaded } = await loadRegistryModule()
reloaded.load()
expect(reloaded.byAgent(entry.agentId)?.forkedFrom).toEqual({ agentId: 'p', name: 'P' })
})
})
// Filesystem durability deadlines are exercised separately from these deterministic fixture reads.
vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))