Skip to content

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

Other engines' identity, homes and launch data out of the core (o6) (#1065)

Dee8b1417520b85
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index a52279387..f23eb80f2 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -239,8 +239,6 @@ const theirs = (file: string): boolean => THEIRS.some((pattern) => pattern.test(
* reached fails the test, so remove it with the move that ends it. Empty, the core loads none of their code.
*/
const OTHER_ENGINES_CORE_MAY_REACH: Record<string, string> = {
- 'engines/cursor/pendingTasks.ts': '(o6) Cursor\'s pending tasks, read at the start and cleared on Stop and forget: a declared file, then a lazy load',
- 'lib/hermesHome.ts': '(o6) homes: which Hermes store a session\'s history is in',
'engines/copilot/normalizer.ts': '(o5) adoption\'s readers',
'engines/devin/errorLog.ts': '(o5) adoption\'s readers',
'engines/devin/normalizer.ts': '(o5) adoption\'s readers',
@@ -259,19 +257,9 @@ const OTHER_ENGINES_CORE_MAY_REACH: Record<string, string> = {
'lib/sessionSearch/externals/hermes.ts': '(o5) adoption\'s readers',
'lib/sessionSearch/externals/muse.ts': '(o5) adoption\'s readers',
'lib/sessionSearch/externals/opencode.ts': '(o5) adoption\'s readers',
- 'engines/agy/session.ts': '(o6) identity: the registry\'s layouts, bind and repair',
- 'engines/commandcode/transcript.ts': '(o6) identity: the registry\'s layouts',
- 'engines/copilot/session.ts': '(o6) identity: the registry\'s layouts, bind and repair',
- 'engines/cursor/discovery.ts': '(o6) identity: bind\'s finders',
- 'engines/cursor/home.ts': '(o6) homes: a declared home',
- 'engines/grok/session.ts': '(o6) identity: bind\'s finders',
- 'engines/hermes/home.ts': '(o6) homes: a declared home and admission',
- 'engines/hermes/homeProbe.ts': '(o6) homes: discovery\'s probe',
- 'engines/hermes/reader.ts': '(o6) homes: the hook server\'s source check',
- 'engines/muse/normalizer.ts': '(o6) identity: repair',
- 'engines/opencode/sessionModel.ts': '(o6) launch data: retarget\'s session model',
- 'engines/opencode/version.ts': '(o6) launch data: OpenCode\'s version',
- 'lib/sessionSearch/externals/pi.ts': '(o6) identity: repair',
+ 'engines/cursor/home.ts': '(o5) adoption\'s readers, through lib/sessionSearch/externals/index.ts',
+ 'engines/hermes/reader.ts': '(o5) adoption\'s readers',
+ 'lib/sessionSearch/externals/pi.ts': '(o5) adoption\'s readers',
}
/** Core's entries for each facet, and the sub-batch after which they reach none of the other engines' files. */
@@ -290,6 +278,31 @@ const FACETS_FREE_OF_THEM: Array<[string, string]> = [
// What the core reads of their model and effort, and how a switch of theirs would be driven.
['lib/runtimeProfileManager.ts', '(o4)'],
['lib/runtimeControl.ts', '(o4)'],
+ // Where their conversations are: the registry's layouts and Cursor's homes, declared; bind's finders and
+ // repair's readers, loaded; Cursor's discovery and its queued Tasks, built on first use; Hermes's store.
+ ['lib/registry.ts', '(o6)'],
+ ['core/agents/bind.ts', '(o6)'],
+ ['lib/sessionRepair.ts', '(o6)'],
+ ['core/engines/cursorDiscovery.ts', '(o6)'],
+ ['core/agents/forget.ts', '(o6)'],
+ ['core/turns/turnHooks.ts', '(o6)'],
+ ['engines/kit/notifyHooks.ts', '(o6)'],
+ ['lib/sessionCheckpoint.ts', '(o6)'],
+ ['lib/purgeAgentService.ts', '(o6)'],
+ // Hermes's admission and homes, declared and read by the kit; its home probe, loaded for a Hermes process.
+ ['hookServer.ts', '(o6)'],
+ ['core/engines/hooks.ts', '(o6)'],
+ ['lib/terminalAgentDiscovery.ts', '(o6)'],
+ // The launches: OpenCode's v2 rule declared, its version probe and session-model writer loaded for OpenCode.
+ ['core/agents/create.ts', '(o6)'],
+ ['core/agents/fork.ts', '(o6)'],
+ ['core/agents/launches.ts', '(o6)'],
+ ['core/agents/retarget.ts', '(o6)'],
+ ['core/agents/restart.ts', '(o6)'],
+ ['lib/launchOverrides.ts', '(o6)'],
+ ['lib/engineLaunch.ts', '(o6)'],
+ ['lib/gridLaunch.ts', '(o6)'],
+ ['lib/subscriptionModel.ts', '(o6)'],
]
describe('the daemon\'s shape', () => {
@@ -431,21 +444,19 @@ describe('the daemon\'s shape', () => {
const reached = [...closure.keys()].filter(theirs).sort()
expect(reached.filter((file) => !OTHER_ENGINES_CORE_MAY_REACH[file]), 'Load their code through engines/inProcess.ts (loadEngine), or declare what the core needs of it in engines/<name>/contract.ts.').toEqual([])
expect(Object.keys(OTHER_ENGINES_CORE_MAY_REACH).filter((file) => !closure.has(file)), 'No longer loaded by the core: remove it from OTHER_ENGINES_CORE_MAY_REACH').toEqual([])
- // Until (o6) gives the registry declared layouts, what it reaches of theirs is reached by whatever imports it
- // (history.ts names a session's project through it, as the frames do).
- const throughRegistry = new Set(closureOf('lib/registry.ts').keys())
for (const [entry, batch] of FACETS_FREE_OF_THEM) {
- expect([...closureOf(entry).keys()].filter((file) => theirs(file) && !throughRegistry.has(file)), `${entry}, free of their code since ${batch}`).toEqual([])
+ expect([...closureOf(entry).keys()].filter(theirs), `${entry}, free of their code since ${batch}`).toEqual([])
}
- // (o2) The start's hook step loads the other engines' installers through the loader. What else it reaches
- // of theirs (the hook server's Hermes source check, the registry's layouts) leaves in (o6).
+ // (o2) The start's hook step loads the other engines' installers through the loader; since (o6) it reaches none
+ // of their code at all (above).
expect(closureOf('core/engines/hooks.ts').has('lib/hooks.ts'), 'core/engines/hooks.ts loads lib/hooks.ts through engines/inProcess.ts').toBe(false)
// What an engine declares is data the kit reads: its own walk reaches the kit, the engines' types and the
// environment, and nothing of any engine's code.
const contracts = [...closure.keys()].filter((file) => /^engines\/\w+\/contract\.ts$/.test(file))
expect(contracts.length).toBeGreaterThan(0)
+ const environment = new Set(closureOf('config/env.ts').keys())
for (const contract of contracts) {
- expect([...closureOf(contract).keys()].filter((file) => file !== contract && !/^engines\/(kit\/|types\.ts$)|^config\/env\.ts$/.test(file)), contract).toEqual([])
+ expect([...closureOf(contract).keys()].filter((file) => file !== contract && !environment.has(file) && !/^engines\/(kit\/|types\.ts$)/.test(file)), contract).toEqual([])
}
}, WALK_TIMEOUT_MS)
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index d96981c75..e0d29c4eb 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -6,6 +6,7 @@ import { findAgyTranscript } from '../../engines/agy/session.js'
import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilot/session.js'
import { findCursorTranscript } from '../../engines/cursor/discovery.js'
import { findGrokTranscript } from '../../engines/grok/session.js'
+import { loadEngine } from '../../engines/inProcess.js'
import { continuationOf } from '../../engines/sessionFiles.js'
import { isRecentlyDeleted } from '../../lib/deletedSessions.js'
import type { RegisteredSession } from '../../lib/registry.js'
@@ -18,6 +19,11 @@ vi.mock('../../engines/copilot/session.js', () => ({ copilotSessionForPid: vi.fn
vi.mock('../../engines/cursor/discovery.js', async (real) => ({ ...await real<object>(), findCursorTranscript: vi.fn(async () => '/t/cursor.jsonl') }))
vi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>(), cursorDataDir: () => '/cursor' }))
vi.mock('../../engines/grok/session.js', () => ({ findGrokTranscript: vi.fn(async () => '/t/grok.jsonl') }))
+// The other engines' finders are their own code, loaded when asked; a test may say one could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
vi.mock('../../lib/deletedSessions.js', () => ({ isRecentlyDeleted: vi.fn(() => false) }))
vi.mock('../../engines/sessionFiles.js', () => ({ continuationOf: vi.fn(async () => null) }))
vi.mock('../../lib/sessionRepair.js', () => ({
@@ -335,6 +341,31 @@ describe('binding a running process to its session', () => {
expect(findResumedTranscript).toHaveBeenCalledWith('codex', 'codex-resumed', { codexHome: undefined })
})
+ it('finds nothing without the engine\'s code: bound without a transcript, or not at all, as when none is found', async () => {
+ const run = setup()
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))
+ vi.mocked(loadEngine).mockResolvedValue(null)
+ try {
+ for (const engine of ['cursor', 'grok', 'agy', 'copilot']) {
+ await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))
+ }
+ expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => [input.engine, input.transcriptPath])).toEqual([['agy', undefined], ['copilot', undefined]])
+ // Nor is a Copilot /resume followed.
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ engine: 'copilot' } as Partial<RegisteredSession>))
+ vi.mocked(copilotSessionForPid).mockResolvedValue('s2')
+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))
+ expect(run.deps.registry.register).toHaveBeenCalledTimes(2)
+ expect([findCursorTranscript, findGrokTranscript, findAgyTranscript, findCopilotTranscript, copilotSessionForPid].map((find) => vi.mocked(find).mock.calls.length)).toEqual([0, 0, 0, 0, 0])
+ } finally { vi.mocked(loadEngine).mockReset() }
+ // Claude Code and Codex find theirs with no engine code loaded.
+ vi.mocked(loadEngine).mockClear()
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))
+ for (const engine of ['claude', 'codex']) {
+ await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: `${engine}-resumed` } as Partial<DiscoveredTerminalAgent>))
+ }
+ expect(loadEngine).not.toHaveBeenCalled()
+ })
+
it('needs a transcript for the engines whose sessions are files, and skips a deleted session', async () => {
const run = setup()
vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex' } as Partial<RegisteredSession>))
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index 536930732..3c7337ce9 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -7,11 +7,7 @@
* Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).
*/
import { stat } from 'node:fs/promises'
-import { findAgyTranscript } from '../../engines/agy/session.js'
-import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilot/session.js'
-import { findCursorTranscript } from '../../engines/cursor/discovery.js'
-import { cursorDataDir } from '../../engines/cursor/home.js'
-import { findGrokTranscript } from '../../engines/grok/session.js'
+import { loadEngine } from '../../engines/inProcess.js'
import { continuationOf } from '../../engines/sessionFiles.js'
import { sessionStoreOf } from '../../engines/sessionStoreContracts.js'
import type { TurnRecaps } from '../turns/recaps.js'
@@ -203,6 +199,19 @@ export function createBinding({
const lastRepairAttempt = new Map<string, number>()
const repairAttempts = new Map<string, number>()
+ /**
+ * The transcript of a session the process of one of these engines names, found by that engine's own code,
+ * loaded here (engines/inProcess.ts). One whose code could not be loaded finds nothing: the process is bound as
+ * when its transcript is not there, or not at all.
+ */
+ const ownTranscript = async (engine: 'cursor' | 'grok' | 'agy' | 'copilot', sessionId: string, cwd: string): Promise<string | null> => {
+ switch (engine) {
+ case 'cursor': { const cursor = await loadEngine('cursor'); return cursor && cursor.findCursorTranscript(cursor.cursorDataDir(), sessionId) }
+ case 'grok': { const grok = await loadEngine('grok'); return grok && grok.findGrokTranscript(homes.grok, cwd, sessionId) }
+ case 'agy': { const agy = await loadEngine('agy'); return agy && agy.findAgyTranscript(homes.agy, sessionId) }
+ case 'copilot': { const copilot = await loadEngine('copilot'); return copilot && copilot.findCopilotTranscript(homes.copilot, sessionId) }
+ }
+ }
const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {
const agent = registry.byProcess(observed.engine, observed.processIdentity)
if (!agent) return
@@ -216,9 +225,12 @@ export function createBinding({
if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') return
if (agent.sessionId) {
if (observed.engine === 'copilot') {
- const current = await copilotSessionForPid(homes.copilot, observed.processIdentity.pid)
+ // Copilot's own code reads its lock (engines/inProcess.ts): without it, a /resume is not followed.
+ const copilot = await loadEngine('copilot')
+ if (!copilot) return
+ const current = await copilot.copilotSessionForPid(homes.copilot, observed.processIdentity.pid)
if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return
- const transcript = await findCopilotTranscript(homes.copilot, current)
+ const transcript = await copilot.findCopilotTranscript(homes.copilot, current)
console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)
const rotated = registry.register({
engine: 'copilot',
@@ -276,17 +288,11 @@ export function createBinding({
const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')
if (Number.isFinite(ownerStarted) && (!Number.isFinite(observedStarted) || observedStarted <= ownerStarted)) return
}
- transcriptPath = observed.engine === 'cursor'
- ? await findCursorTranscript(cursorDataDir(), sessionId) ?? undefined
- : observed.engine === 'grok'
- ? await findGrokTranscript(homes.grok, observed.cwd, sessionId) ?? undefined
- : observed.engine === 'agy'
- ? await findAgyTranscript(homes.agy, sessionId) ?? undefined
- : observed.engine === 'copilot'
- ? await findCopilotTranscript(homes.copilot, sessionId) ?? undefined
- : observed.engine === 'claude' || observed.engine === 'codex'
- ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined
- : undefined
+ transcriptPath = observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'agy' || observed.engine === 'copilot'
+ ? await ownTranscript(observed.engine, sessionId, observed.cwd) ?? undefined
+ : observed.engine === 'claude' || observed.engine === 'codex'
+ ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined
+ : undefined
// The registry refuses a claude/codex session without its file, so a resume of a transcript this
// machine does not have is not a session — the hook that follows the user's next prompt will say.
if ((observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'claude' || observed.engine === 'codex')
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index f86a03464..27062410a 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -8,11 +8,12 @@ import { materializeWorkspace } from '../../dsh/materialize.js'
import { harnessLaunchOrRefusal, incompatibleHarnessEngine } from '../../dsh/runtime.js'
import { createAndRegisterPane } from '../../lib/createAgentPane.js'
import { enginePathOverride } from '../../lib/engineBin.js'
-import { buildEngineLaunchArgv, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from '../../lib/engineLaunch.js'
+import { buildEngineLaunchArgv, namedAgentArgs, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt } from '../../lib/engineLaunch.js'
import { setUpWithin } from '../../lib/setUpWithin.js'
import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
import { buildGridEngineLaunch } from '../../lib/gridLaunch.js'
import { engineHooks } from '../../engines/hooks.js'
+import { loadEngine } from '../../engines/inProcess.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
@@ -29,6 +30,11 @@ vi.mock('../../dsh/runtime.js', async (real) => ({
prepareHarnessLaunch: vi.fn(),
}))
vi.mock('../../dsh/launch.js', async (real) => ({ ...await real<object>(), harnessEnvToClear: vi.fn(() => ['HARNESS_OLD']) }))
+// OpenCode's version probe is its own code, loaded for an OpenCode launch alone; a test may say it could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
vi.mock('../../engines/opencode/version.js', () => ({ opencodeMajorVersion: vi.fn(() => 2) }))
// The engines' folder trust (engines/launchPrep.ts), one spy per engine: never the person's own config.
const trust = vi.hoisted(() => ({
@@ -324,6 +330,27 @@ describe('creating an agent', () => {
warn.mockRestore()
})
+ it('refuses an OpenCode create whose code could not be loaded, before anything is written or any pane opens', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ const t = setup()
+ expect(await t.create(request({ engine: 'opencode', agent: 'reviewer', grid: { networkName: 'g' } }))).toEqual({ ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ expect(warn).toHaveBeenCalledWith('[agent] create opencode refused · OpenCode\'s code could not be loaded')
+ expect(t.deps.gridLaunchMachine).not.toHaveBeenCalled()
+ expect(t.deps.installOpencodePlugin).not.toHaveBeenCalled()
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ // Any other engine's launch loads nothing, and its machine facts are asked for that engine.
+ vi.mocked(loadEngine).mockClear()
+ vi.mocked(buildGridEngineLaunch).mockReturnValueOnce({ ok: false, error: 'GRID_UNSUPPORTED', detail: 'no' } as never)
+ await t.create(request({ engine: 'claude', agent: 'reviewer', grid: { networkName: 'g' } }))
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(t.deps.gridLaunchMachine).toHaveBeenCalledWith('claude')
+ // With OpenCode's code, its own probe names the version its named agent opens for.
+ await t.create(request({ engine: 'opencode', agent: 'reviewer' }))
+ expect(namedAgentArgs).toHaveBeenLastCalledWith('opencode', 'reviewer', 2)
+ warn.mockRestore()
+ })
+
it('opens as a named agent, with a first prompt, and does not install an engine with a path override', async () => {
vi.mocked(enginePathOverride).mockReturnValueOnce('/opt/claude' as never)
const { deps, create } = setup()
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 3682ccfc3..c7b4fa6d5 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -17,8 +17,8 @@ import { harnessEnvToClear, type DshAccount } from '../../dsh/launch.js'
import { dshPinnedPermissionMode } from '../../dsh/manifest.js'
import { materializeWorkspace } from '../../dsh/materialize.js'
import { harnessLaunchOrRefusal, incompatibleHarnessEngine, prepareHarnessLaunch } from '../../dsh/runtime.js'
-import { opencodeMajorVersion } from '../../engines/opencode/version.js'
-import { isTerminalEngine } from '../../engines/types.js'
+import { loadEngine } from '../../engines/inProcess.js'
+import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'
import { engineLabel } from '../../lib/agentNames.js'
import { createAndRegisterPane } from '../../lib/createAgentPane.js'
import { enginePathOverride } from '../../lib/engineBin.js'
@@ -71,7 +71,8 @@ export interface CreateAgentDeps {
/** OpenCode's plugin, installed again before an OpenCode spawn (core/engines/hooks.ts
* `installOpencodePluginBeforeSpawn`): false when the other engines' installers could not be loaded. */
installOpencodePlugin: (port: number) => Promise<boolean>
- gridLaunchMachine: () => GridLaunchMachine
+ /** The facts about this machine a launch of `engine` needs (lib/gridLaunch.ts). */
+ gridLaunchMachine: (engine: AgentEngine) => GridLaunchMachine
terminalHintMachineName: () => string
/** Whether a folder is being purged (PurgeAgentService.blocksFolder). */
blocksFolder: (cwd: string) => boolean | undefined
@@ -128,6 +129,15 @@ export function createAgentCreator({
console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)
return { ok: false, ...refusal }
}
+ // Which OpenCode is installed decides its argv: v2's TUI exits on v1's flags. Its probe is OpenCode's own code,
+ // loaded for an OpenCode launch alone (engines/inProcess.ts), here before anything is written: without it the
+ // launch is refused, never given a guessed argv.
+ const opencode = engine === 'opencode' ? await loadEngine('opencode') : null
+ if (engine === 'opencode' && !opencode) {
+ const detail = 'OpenCode\'s code could not be loaded'
+ console.warn(`[agent] create opencode refused · ${detail}`)
+ return { ok: false, error: 'ENGINE_UNAVAILABLE', detail }
+ }
// Harness-created sessions are easy to distinguish from a user's organic tmux sessions while
// retaining the engine and a collision-resistant creation suffix for diagnostics. Computed
// before the grid block because a file-configured engine keys its config directory on it.
@@ -200,7 +210,7 @@ export function createAgentCreator({
// wrong account and looks identical to one that worked.
let gridLaunch: { env: Record<string, string>; args: string[]; webSearch: GridWebSearchStatus } | undefined
if (grid) {
- const built = buildGridEngineLaunch(engine, grid, gridLaunchMachine())
+ const built = buildGridEngineLaunch(engine, grid, gridLaunchMachine(engine))
if (!built.ok) {
console.warn(`[agent] create ${engine} refused · ${built.detail}`)
return { ok: false, error: built.error, detail: built.detail }
@@ -259,7 +269,7 @@ export function createAgentCreator({
// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
// checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.
- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencodeMajorVersion()) : []), ...resumeArgs]
+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencode ? opencode.opencodeMajorVersion() : null) : []), ...resumeArgs]
// The first prompt is a launch option only — never part of `extraArgs`, which the registry row
// carries into a relaunch (engineLaunch.ts, `firstPrompt`).
// Stopped mid-turn, the resumed conversation is told to carry on — by an engine that can open
diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.ts
index cc7cd7c97..9ae4318f4 100644
--- a/cli/src/core/agents/forget.spec.ts
+++ b/cli/src/core/agents/forget.spec.ts
@@ -1,9 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import { removePendingCursorTasks } from '../engines/cursorTasks.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createForgetSession, type ForgetDeps } from './forget.js'
-vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))
+// Cursor's queued Tasks are cleared through the core's own door to them (core/engines/cursorTasks.ts).
+vi.mock('../engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
function setup() {
const agents = new Map<string, RegisteredSession>([
@@ -47,7 +48,7 @@ function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {
expect(deps.clearAgyIdleWatch).toHaveBeenCalledWith(sessionId)
expect(deps.cursorDiscovery.remove).toHaveBeenCalledWith(sessionId)
expect(deps.cursorSubagents.forget).toHaveBeenCalledWith(sessionId)
- expect(removeCursorPendingTasks).toHaveBeenCalledWith('/data', sessionId)
+ expect(removePendingCursorTasks).toHaveBeenCalledWith('/data', sessionId)
expect(deps.runtimeProfiles.forget).toHaveBeenCalledWith(sessionId)
expect(deps.watcher.removeSession).toHaveBeenCalledWith(sessionId)
expect(deps.stopHeartbeat).toHaveBeenCalledWith(sessionId)
@@ -58,7 +59,7 @@ function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {
}
describe('forgetting a session', () => {
- afterEach(() => { vi.restoreAllMocks(); vi.mocked(removeCursorPendingTasks).mockClear() })
+ afterEach(() => { vi.restoreAllMocks(); vi.mocked(removePendingCursorTasks).mockClear() })
it('releases a session and keeps its agent: everything per-session goes, the agent and its tiles stay', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.ts
index b34313d2a..eed225824 100644
--- a/cli/src/core/agents/forget.ts
+++ b/cli/src/core/agents/forget.ts
@@ -5,7 +5,7 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).
*/
-import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import { removePendingCursorTasks } from '../engines/cursorTasks.js'
import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'
import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { AutonomousDeviceInput } from '../deviceInput.js'
@@ -84,7 +84,7 @@ export function createForgetSession({
clearAgyIdleWatch(sessionId)
cursorDiscovery.remove(sessionId)
cursorSubagents.forget(sessionId)
- void removeCursorPendingTasks(dataDir, sessionId)
+ void removePendingCursorTasks(dataDir, sessionId)
runtimeProfiles.forget(sessionId)
void watcher.removeSession(sessionId)
stopHeartbeat(sessionId)
diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.ts
index f84f12863..dd27d3baa 100644
--- a/cli/src/core/agents/fork.spec.ts
+++ b/cli/src/core/agents/fork.spec.ts
@@ -8,6 +8,7 @@ import { createAndRegisterPane } from '../../lib/createAgentPane.js'
import { enginePathOverride } from '../../lib/engineBin.js'
import { buildEngineLaunchArgv, refusePermissionFlagIfUnsupported, supportsNamedAgent } from '../../lib/engineLaunch.js'
import { planFork } from '../../lib/forkAgent.js'
+import { prepareInstructionWrites } from '../../scm/scmProjects.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createAgentForker, type ForkAgentDeps } from './fork.js'
@@ -18,6 +19,11 @@ vi.mock('../../dsh/runtime.js', async (real) => ({
harnessLaunchOrRefusal: vi.fn((prepare: () => unknown) => { prepare(); return { ok: true, launch: { env: { HARNESS_DSH: 'blender' }, args: ['--dsh'] } } }),
prepareHarnessLaunch: vi.fn(),
}))
+// OpenCode's version probe is its own code, loaded for an OpenCode launch alone; a test may say it could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
vi.mock('../../engines/opencode/version.js', () => ({ opencodeMajorVersion: vi.fn(() => 2) }))
vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
vi.mock('../../lib/engineBin.js', async (real) => ({ ...await real<object>(), enginePathOverride: vi.fn(() => null) }))
@@ -30,6 +36,10 @@ vi.mock('../../lib/engineLaunch.js', async (real) => ({
refusePermissionFlagIfUnsupported: vi.fn(async () => null),
supportsNamedAgent: vi.fn(() => true),
}))
+vi.mock('../../scm/scmProjects.js', async (real) => {
+ const actual = await real<typeof import('../../scm/scmProjects.js')>()
+ return { ...actual, prepareInstructionWrites: vi.fn(actual.prepareInstructionWrites) }
+})
vi.mock('../../lib/forkAgent.js', async (real) => ({ ...await real<object>(), planFork: vi.fn(() => ({ ok: true, level: 'native', forkSessionId: 's1' })) }))
const root = mkdtempSync(join(tmpdir(), 'core-fork-'))
@@ -168,6 +178,28 @@ describe('forking an agent', () => {
expect(createAndRegisterPane).not.toHaveBeenCalled()
})
+ it('refuses to fork OpenCode when its code could not be loaded, having written nothing, and loads nothing for another engine', async () => {
+ const { loadEngine } = await import('../../engines/inProcess.js')
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)
+ const refused = setup(source({ engine: 'opencode', agent: 'reviewer', dsh: 'blender' } as Partial<RegisteredSession>))
+ expect(await refused.fork({ agentId: 'a1', name: null, prompt: null }))
+ .toEqual({ ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ // No instruction files prepared, no harness runtime folder, no relaunch overrides, no pane.
+ expect(prepareInstructionWrites).not.toHaveBeenCalled()
+ expect(harnessLaunchOrRefusal).not.toHaveBeenCalled()
+ expect(refused.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ vi.mocked(loadEngine).mockClear()
+ await setup(source({ agent: 'reviewer' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(supportsNamedAgent).toHaveBeenLastCalledWith('claude', null)
+ // With OpenCode's code, its own probe names the version the fork's named agent is checked against.
+ await setup(source({ engine: 'opencode', agent: 'reviewer' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })
+ expect(supportsNamedAgent).toHaveBeenLastCalledWith('opencode', 2)
+ })
+
it('carries the harness and the named agent over, when the engine still takes it', async () => {
vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)
vi.mocked(createAndRegisterPane).mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%3' } }, pending: { ...pending, dsh: 'blender' } } as never)
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
index 390ccacd7..b2eace1e9 100644
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@ -13,7 +13,7 @@ import type { BackendSocket } from '../../backendSocket.js'
import { installedDsh } from '../../dsh/installed.js'
import { harnessEnvToClear } from '../../dsh/launch.js'
import { forkRuntimeKey, harnessLaunchOrRefusal, prepareHarnessLaunch } from '../../dsh/runtime.js'
-import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+import { loadEngine } from '../../engines/inProcess.js'
import type { TurnRecaps } from '../turns/recaps.js'
import { createAndRegisterPane } from '../../lib/createAgentPane.js'
import { enginePathOverride } from '../../lib/engineBin.js'
@@ -74,6 +74,10 @@ export function createAgentForker({
}
const plan = planFork({ engine, sessionId: source.sessionId, name: sourceName, cwd: source.cwd }, memory, prompt)
if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
+ // Which OpenCode is installed decides a fork's named agent (below). Its probe is OpenCode's own code, loaded for
+ // OpenCode alone (engines/inProcess.ts), here before anything is written: without it, no fork.
+ const opencode = engine === 'opencode' ? await loadEngine('opencode') : null
+ if (engine === 'opencode' && !opencode) return { ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' }
const label = buildHarnessSessionLabel(engine)
await prepareInstructionWrites(source.cwd)
@@ -105,7 +109,7 @@ export function createAgentForker({
const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
// Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2
// as a general session rather than handing the v2 TUI an `--agent` it exits on.
- const forkMajor = opencodeMajorVersion()
+ const forkMajor = opencode ? opencode.opencodeMajorVersion() : null
const extraArgs = [...built.overrides.extraArgs, ...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]
const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt
const launchOptions = {
diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.ts
index 67966556c..641d2a3df 100644
--- a/cli/src/core/agents/launch.spec.ts
+++ b/cli/src/core/agents/launch.spec.ts
@@ -4,12 +4,23 @@ import { ApiConnectionError, type ApiConnections } from '../../lib/apiConnection
import { refreshApiLaunch } from '../../lib/apiModels.js'
import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps } from '../../lib/launchOverrides.js'
+import { loadEngine } from '../../engines/inProcess.js'
+import { prepareInstructionWrites } from '../../scm/scmProjects.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createLaunchHelpers, type LaunchHelperDeps } from './launch.js'
vi.mock('../../engines/launchPrep.js', async (real) => ({ ...await real<object>(), prepareResume: vi.fn(() => ({ repairedItems: 0 })) }))
vi.mock('../../lib/apiModels.js', async (real) => ({ ...await real<object>(), refreshApiLaunch: vi.fn((_apis: unknown, launch: object) => ({ ...launch, refreshed: true })) }))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), dropPermissionFlagIfUnsupported: vi.fn() }))
+// OpenCode's version is its own code, loaded for an OpenCode relaunch alone; a test may say it could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
+vi.mock('../../scm/scmProjects.js', async (real) => {
+ const actual = await real<typeof import('../../scm/scmProjects.js')>()
+ return { ...actual, prepareInstructionWrites: vi.fn(async () => {}) }
+})
vi.mock('../../lib/launchOverrides.js', async (real) => ({ ...await real<object>(), buildLaunchOverrides: vi.fn(async () => ({ ok: true })) }))
const session = (over: Partial<RegisteredSession> = {}): RegisteredSession =>
@@ -29,6 +40,23 @@ function setup() {
describe('relaunch helpers', () => {
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it('refuses an OpenCode relaunch whose code could not be loaded, having written nothing, and loads nothing for another engine', async () => {
+ const { deps, helpers } = setup()
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ expect(await helpers.relaunchOverrides(session({ engine: 'opencode' }))).toEqual({ ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ // No instruction files prepared, no API notes, no overrides built.
+ expect(prepareInstructionWrites).not.toHaveBeenCalled()
+ expect(deps.prepareApiTools).not.toHaveBeenCalled()
+ expect(buildLaunchOverrides).not.toHaveBeenCalled()
+ vi.mocked(loadEngine).mockClear()
+ expect(await helpers.relaunchOverrides(session())).toEqual({ ok: true })
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(prepareInstructionWrites).toHaveBeenCalledWith('/work')
+ // With OpenCode's code, an OpenCode relaunch is built.
+ expect(await helpers.relaunchOverrides(session({ engine: 'opencode' }))).toEqual({ ok: true })
+ expect(loadEngine).toHaveBeenCalledWith('opencode')
+ })
+
it('rebuilds a launch from the row: its DSH, folder and named agent, whatever the source adds', async () => {
const { deps, helpers } = setup()
expect(await helpers.relaunchOverrides(session())).toEqual({ ok: true })
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index 71f8d750d..850eae415 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -6,6 +6,7 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).
*/
+import { loadEngine } from '../../engines/inProcess.js'
import { prepareResume, repairedItemsName } from '../../engines/launchPrep.js'
import { ApiConnectionError, type ApiConnections } from '../../lib/apiConnections.js'
import { refreshApiLaunch } from '../../lib/apiModels.js'
@@ -33,6 +34,11 @@ export function createLaunchHelpers({ prepareApiTools, savedApis, launchOverride
// An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key
// pasted since takes effect, and a removed API is refused rather than kept on its old key.
const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {
+ // OpenCode's version decides its relaunch's argv, read by OpenCode's own code (lib/launchOverrides.ts): loaded
+ // here, before anything is written, and the relaunch refused without it.
+ if (session.engine === 'opencode' && !await loadEngine('opencode')) {
+ return { ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' }
+ }
await prepareInstructionWrites(session.cwd)
prepareApiTools(session.cwd, session.engine)
let gridLaunch = source.gridLaunch ?? null
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 89f97f98f..4ae431ef2 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -4,6 +4,7 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { installedDsh } from '../../dsh/installed.js'
import { dshSupportedEngines } from '../../dsh/manifest.js'
+import { loadEngine } from '../../engines/inProcess.js'
import { opencodeMajorVersion } from '../../engines/opencode/version.js'
import { AgentCreationReceiptError, AgentCreationReceipts, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
@@ -30,6 +31,11 @@ const { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject }
vi.mock('../../engines/launchPrep.js', () => ({ folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
? { trusts: (path: string) => trust.claudeTrusts(path), record: (path: string) => trust.preTrustClaudeProject(path) }
: engine === 'codex' ? { trusts: (path: string) => trust.codexTrusts(path, profile), record: (path: string) => trust.preTrustCodexProject(path, profile) } : null }))
+// OpenCode's version probe is its own code, loaded for an OpenCode launch alone; a test may say it could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
vi.mock('../../engines/opencode/version.js', async (real) => ({ ...await real<object>(), opencodeMajorVersion: vi.fn(() => 1) }))
vi.mock('../../lib/newAgentModel.js', async (real) => ({
...await real<object>(), parseNewAgentModel: vi.fn(() => ({ state: 'absent' })),
@@ -167,6 +173,16 @@ describe('agent_create, refused before any pane exists', () => {
expect(create).not.toHaveBeenCalled()
})
+ it('an OpenCode named agent when OpenCode\'s code could not be loaded, and loads nothing for another engine\'s', async () => {
+ const { ask, create } = setup()
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ expect(await ask({ engine: 'opencode', cwd: '/w', agent: 'reviewer' })).toStrictEqual({ error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ expect(create).not.toHaveBeenCalled()
+ vi.mocked(loadEngine).mockClear()
+ await ask({ engine: 'claude', cwd: '/w', agent: 'reviewer' })
+ expect(loadEngine).not.toHaveBeenCalled()
+ })
+
it('a permission mode the engine does not have, and a conversation to resume that is not one or comes with new-conversation choices', async () => {
const { ask, create } = setup()
vi.mocked(permissionModeFlags).mockReturnValueOnce(null as never)
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 86aa50402..d5d1ed5c0 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -15,7 +15,7 @@ import type { BackendSocket } from '../../backendSocket.js'
import { installedDsh } from '../../dsh/installed.js'
import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'
import { folderTrust } from '../../engines/launchPrep.js'
-import { opencodeMajorVersion } from '../../engines/opencode/version.js'
+import { loadEngine } from '../../engines/inProcess.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'
import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
@@ -184,8 +184,13 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA
if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {
reply({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return
}
- // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts).
- if (!supportsNamedAgent(engine, engine === 'opencode' ? opencodeMajorVersion() : null)) {
+ // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts). Which one is installed is
+ // read by OpenCode's own probe, loaded for OpenCode alone (engines/inProcess.ts); without it, no launch.
+ const opencode = engine === 'opencode' ? await loadEngine('opencode') : null
+ if (engine === 'opencode' && !opencode) {
+ reply({ error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' }); return
+ }
+ if (!supportsNamedAgent(engine, opencode ? opencode.opencodeMajorVersion() : null)) {
reply({ error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return
}
agent = payload.agent
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index ef00cffa6..c1c227590 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -17,6 +17,11 @@ vi.mock('../../engines/opencode/sessionModel.js', async (real) => ({
applyOpencodeSessionModel: vi.fn(async () => ({ ok: true })),
parseOpencodeModelId: vi.fn((id: string) => ({ providerID: id.split('/')[0], modelID: id.split('/')[1] })),
}))
+// OpenCode's version probe is its own code, loaded for an OpenCode launch alone; a test may say it could not be.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
vi.mock('../../engines/opencode/version.js', () => ({ isOpencodeV2: vi.fn(() => false), opencodeMajorVersion: vi.fn(() => 1) }))
vi.mock('../../lib/binaryOnPath.js', () => ({ binaryOnPath: vi.fn(() => true) }))
vi.mock('../../lib/gatewayRuntime.js', async (real) => ({ ...await real<object>(), probeGatewayRuntime: vi.fn(async () => ({ kind: 'none' })) }))
@@ -207,6 +212,15 @@ describe('retargeting an agent', () => {
vi.mocked(binaryOnPath).mockReturnValue(true)
})
+ it('refuses to move OpenCode when its code could not be loaded, before the pane is touched', async () => {
+ const { loadEngine } = await import('../../engines/inProcess.js')
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ const run = setup(agent({ engine: 'opencode' } as Partial<RegisteredSession>))
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ expect(restartAgent).not.toHaveBeenCalled()
+ expect(applyOpencodeSessionModel).not.toHaveBeenCalled()
+ })
+
it('reads the live bypass flag only when the row recorded none, and announces nothing for a row gone meanwhile', async () => {
const run = setup()
vi.mocked(run.deps.registry.byAgent).mockReturnValue(undefined)
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 8c2270a25..ab6a679f0 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -12,8 +12,7 @@
* Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
*/
import type { BackendSocket } from '../../backendSocket.js'
-import { applyOpencodeSessionModel, parseOpencodeModelId } from '../../engines/opencode/sessionModel.js'
-import { isOpencodeV2, opencodeMajorVersion } from '../../engines/opencode/version.js'
+import { loadEngine } from '../../engines/inProcess.js'
import { binaryOnPath } from '../../lib/binaryOnPath.js'
import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
import { probeGridAssignment } from '../../lib/gridAssignment.js'
@@ -127,8 +126,12 @@ export function createAgentRetargeter({
// sqlite3 (`applyOpencodeSessionModel`).
const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId
&& (!!grid || !!remembered?.includes('/'))
- const opencodeMajor = session.engine === 'opencode' ? opencodeMajorVersion() : null
- if (rewritesOpencodeSession && !isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {
+ // OpenCode's version and its session's model are OpenCode's own code, loaded for OpenCode alone
+ // (engines/inProcess.ts), as the launch overrides above loaded it: without it, the move is refused.
+ const opencode = session.engine === 'opencode' ? await loadEngine('opencode') : null
+ if (session.engine === 'opencode' && !opencode) return { ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' }
+ const opencodeMajor = opencode ? opencode.opencodeMajorVersion() : null
+ if (rewritesOpencodeSession && opencode && !opencode.isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {
return {
ok: false,
error: 'OPENCODE_SQLITE_MISSING',
@@ -200,10 +203,10 @@ export function createAgentRetargeter({
// `Unrecognized flag: -m` and a dead pane), and ships its own writer: the service's
// `session.switchModel`. `applyOpencodeSessionModel` picks per version, and on v2 every
// failure refuses the move — with the live process still untouched.
- if (rewritesOpencodeSession) {
- const model = built.overrides.sessionModel ? parseOpencodeModelId(built.overrides.sessionModel) : null
+ if (rewritesOpencodeSession && opencode) {
+ const model = built.overrides.sessionModel ? opencode.parseOpencodeModelId(built.overrides.sessionModel) : null
if (model) {
- const written = await applyOpencodeSessionModel({
+ const written = await opencode.applyOpencodeSessionModel({
opencodeMajor, dbPath: opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,
// (A model of opencode's own is looked for in its catalogue; a grid's provider lives in
// the pane's own config, which the service never reads.)
diff --git a/cli/src/core/engines/cursorDiscovery.spec.ts b/cli/src/core/engines/cursorDiscovery.spec.ts
new file mode 100644
index 000000000..3d22c96a6
--- /dev/null
+++ b/cli/src/core/engines/cursorDiscovery.spec.ts
@@ -0,0 +1,81 @@
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { engineNow, loadEngine } from '../../engines/inProcess.js'
+import { createCursorDiscovery } from './cursorDiscovery.js'
+
+const made = vi.hoisted(() => ({ discoveries: [] as unknown[] }))
+vi.mock('../../engines/cursor/discovery.js', () => ({
+ CursorTranscriptDiscovery: class {
+ readonly args: unknown[]
+ start = vi.fn(async () => {})
+ add = vi.fn(async () => {})
+ remove = vi.fn()
+ stop = vi.fn(async () => {})
+ constructor(...args: unknown[]) { this.args = args; made.discoveries.push(this) }
+ },
+ findCursorTranscript: vi.fn(),
+}))
+// Cursor's code is loaded by its session's attach before that attach hands the session here; a test may say it
+// could not be, or that it is not loaded at all.
+vi.mock('../../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../../engines/inProcess.js')>()
+ return { ...actual, engineNow: vi.fn(actual.engineNow) }
+})
+beforeAll(async () => { await loadEngine('cursor') })
+
+type Discovery = { args: unknown[]; start: ReturnType<typeof vi.fn>; add: ReturnType<typeof vi.fn>; remove: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn> }
+const built = () => made.discoveries as Discovery[]
+
+describe('Cursor\'s transcript discovery', () => {
+ afterEach(() => { made.discoveries.length = 0; vi.clearAllMocks() })
+
+ it('builds nothing, and loads nothing, until an attach hands it a Cursor session', async () => {
+ const discovery = createCursorDiscovery('/cursor/data', vi.fn())
+ await discovery.start()
+ discovery.remove('s1')
+ await discovery.stop()
+ expect(built()).toEqual([])
+ expect(engineNow).not.toHaveBeenCalled()
+ })
+
+ it('looks in the data folder named at the start, with the core\'s callback, once loaded', async () => {
+ const onFound = vi.fn()
+ const discovery = createCursorDiscovery('/cursor/data', onFound)
+ await discovery.start()
+ await discovery.add('s1')
+ const [one] = built()
+ expect(one.args).toEqual(['/cursor/data', onFound])
+ // Started as the core started it, before the session it was built for.
+ expect(one.start).toHaveBeenCalledOnce()
+ expect(one.start.mock.invocationCallOrder[0]).toBeLessThan(one.add.mock.invocationCallOrder[0])
+ expect(one.add).toHaveBeenCalledWith('s1')
+ await discovery.add('s2')
+ discovery.remove('s1')
+ await discovery.stop()
+ expect(built()).toHaveLength(1)
+ expect(one.add).toHaveBeenLastCalledWith('s2')
+ expect(one.remove).toHaveBeenCalledWith('s1')
+ expect(one.stop).toHaveBeenCalledOnce()
+ })
+
+ it('builds stopped when the core has not started it, and starts with the core', async () => {
+ const discovery = createCursorDiscovery('/cursor/data', vi.fn())
+ await discovery.add('s1')
+ const [one] = built()
+ expect(one.start).not.toHaveBeenCalled()
+ await discovery.start()
+ expect(one.start).toHaveBeenCalledOnce()
+ // A stop, then a session: built already, so nothing is started again until the core does.
+ await discovery.stop()
+ await discovery.add('s2')
+ expect(one.start).toHaveBeenCalledOnce()
+ })
+
+ it('looks for nothing when Cursor\'s code could not be loaded', async () => {
+ vi.mocked(engineNow).mockReturnValueOnce(null)
+ const discovery = createCursorDiscovery('/cursor/data', vi.fn())
+ await discovery.start()
+ await expect(discovery.add('s1')).resolves.toBeUndefined()
+ expect(built()).toEqual([])
+ expect(engineNow).toHaveBeenCalledWith('cursor', 'a session\'s transcript was looked for')
+ })
+})
diff --git a/cli/src/core/engines/cursorDiscovery.ts b/cli/src/core/engines/cursorDiscovery.ts
new file mode 100644
index 000000000..a432da808
--- /dev/null
+++ b/cli/src/core/engines/cursorDiscovery.ts
@@ -0,0 +1,34 @@
+/**
+ * Finding the transcript of a Cursor session that has not written one yet (engines/cursor/discovery.ts).
+ *
+ * Built on the first Cursor session an attach hands it, from Cursor's own code (engines/inProcess.ts), loaded by
+ * that attach before it gets here: no other engine's daemon ever builds it. Until then nothing is pending, so a
+ * start, a remove or a stop has nothing to act on but whether it is started. Without Cursor's code a session's
+ * transcript is not looked for, as for any session whose engine's code could not be loaded.
+ */
+import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'
+import { engineNow } from '../../engines/inProcess.js'
+
+export type CursorDiscovery = Pick<CursorTranscriptDiscovery, 'start' | 'add' | 'remove' | 'stop'>
+
+/** `cursorHome` is named when the core starts, as it always was: the folder does not move with Cursor's load. */
+export function createCursorDiscovery(cursorHome: string, onFound: (sessionId: string, transcriptPath: string) => void): CursorDiscovery {
+ let built: CursorTranscriptDiscovery | null = null
+ let started = false
+ const build = (): CursorTranscriptDiscovery | null => {
+ if (built) return built
+ const cursor = engineNow('cursor', 'a session\'s transcript was looked for')
+ if (!cursor) return null
+ built = new cursor.CursorTranscriptDiscovery(cursorHome, onFound)
+ // Started already, as the core starts it once at boot: the same state, then this session.
+ if (started) void built.start()
+ return built
+ }
+ return {
+ start: async () => { started = true; await built?.start() },
+ // Synchronously into Cursor's own `add`, so nothing changes about what a stop() in flight discards.
+ add: async (sessionId) => { await build()?.add(sessionId) },
+ remove: (sessionId) => built?.remove(sessionId),
+ stop: async () => { started = false; await built?.stop() },
+ }
+}
diff --git a/cli/src/core/engines/cursorTasks.spec.ts b/cli/src/core/engines/cursorTasks.spec.ts
index 62b2fc872..f0874bcb7 100644
--- a/cli/src/core/engines/cursorTasks.spec.ts
+++ b/cli/src/core/engines/cursorTasks.spec.ts
@@ -1,8 +1,11 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { CursorNormalizer } from '../../engines/cursor/normalizer.js'
import { engineNow, loadEngine } from '../../engines/inProcess.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import { createCursorTaskHooks, type CursorTaskDeps } from './cursorTasks.js'
+import { createCursorTaskHooks, loadPendingCursorTasks, removePendingCursorTasks, type CursorTaskDeps } from './cursorTasks.js'
const made = vi.hoisted(() => ({ managers: [] as unknown[], queues: [] as unknown[] }))
vi.mock('../../engines/cursor/home.js', () => ({ cursorConfigDir: () => '/cursor/config', cursorDataDir: () => '/cursor/data' }))
@@ -27,7 +30,7 @@ vi.mock('../../engines/cursor/taskHookQueue.js', () => ({
// could not be.
vi.mock('../../engines/inProcess.js', async (real) => {
const actual = await real<typeof import('../../engines/inProcess.js')>()
- return { ...actual, engineNow: vi.fn(actual.engineNow) }
+ return { ...actual, engineNow: vi.fn(actual.engineNow), loadEngine: vi.fn(actual.loadEngine) }
})
beforeAll(async () => { await loadEngine('cursor') })
@@ -138,3 +141,52 @@ describe('Cursor\'s Task hooks', () => {
expect(deps.cursorNormalizers.size).toBe(0)
})
})
+
+describe('Cursor\'s queued Tasks', () => {
+ const dirs: string[] = []
+ const dataDir = () => { const dir = mkdtempSync(join(tmpdir(), 'cursor-pending-')); dirs.push(dir); return dir }
+ const now = Date.now()
+ const task = (sessionId: string, toolUseId: string) => ({ sessionId, toolUseId, input: { prompt: toolUseId }, createdAt: now })
+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); vi.clearAllMocks() })
+
+ it('load none of Cursor\'s code where its hook never queued one: the start, a Stop and a forget find nothing', async () => {
+ const dir = dataDir()
+ expect(await loadPendingCursorTasks(dir)).toEqual([])
+ await removePendingCursorTasks(dir, 's1')
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(existsSync(join(dir, 'cursor-pending-tasks.json'))).toBe(false)
+ })
+
+ it('are taken at the start by Cursor\'s own code, and a session\'s dropped on its Stop or its forget', async () => {
+ const dir = dataDir()
+ const file = join(dir, 'cursor-pending-tasks.json')
+ writeFileSync(file, JSON.stringify([task('s1', 't1'), task('s2', 't2')]))
+ expect(await loadPendingCursorTasks(dir)).toEqual([task('s1', 't1'), task('s2', 't2')])
+ expect(loadEngine).toHaveBeenCalledWith('cursor')
+ await removePendingCursorTasks(dir, 's1')
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual([task('s2', 't2')])
+ await removePendingCursorTasks(dir, 's2')
+ expect(existsSync(file)).toBe(false)
+ })
+
+ it('are read once the hook that holds the queue\'s lock lets go, as Cursor\'s code always waited', async () => {
+ const dir = dataDir()
+ const file = join(dir, 'cursor-pending-tasks.json')
+ mkdirSync(`${file}.lock`)
+ setTimeout(() => {
+ writeFileSync(file, JSON.stringify([task('s1', 't1')]))
+ rmSync(`${file}.lock`, { recursive: true, force: true })
+ }, 60)
+ expect(await loadPendingCursorTasks(dir)).toEqual([task('s1', 't1')])
+ })
+
+ it('are none, and stay queued, when Cursor\'s code could not be loaded', async () => {
+ const dir = dataDir()
+ const file = join(dir, 'cursor-pending-tasks.json')
+ writeFileSync(file, JSON.stringify([task('s1', 't1')]))
+ vi.mocked(loadEngine).mockResolvedValueOnce(null).mockResolvedValueOnce(null)
+ expect(await loadPendingCursorTasks(dir)).toEqual([])
+ await removePendingCursorTasks(dir, 's1')
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual([task('s1', 't1')])
+ })
+})
diff --git a/cli/src/core/engines/cursorTasks.ts b/cli/src/core/engines/cursorTasks.ts
index e933a1ea4..0a836e851 100644
--- a/cli/src/core/engines/cursorTasks.ts
+++ b/cli/src/core/engines/cursorTasks.ts
@@ -8,10 +8,14 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).
*/
+import { access } from 'node:fs/promises'
+import { join } from 'node:path'
+import { PENDING_TASKS_FILE } from '../../engines/cursor/contract.js'
+import type { PendingCursorTask } from '../../engines/cursor/pendingTasks.js'
import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'
-import { engineNow } from '../../engines/inProcess.js'
+import { engineNow, loadEngine } from '../../engines/inProcess.js'
import type { LiveEvent } from '../../engines/kit/events.js'
import type { registry } from '../../lib/registry.js'
import type { Watcher } from '../../watcher/watcher.js'
@@ -66,3 +70,31 @@ export function createCursorTaskHooks({ emitSessionEvents, watcher, registry, cu
}
return { cursorSubagents, cursorTaskHooks, onCursorTaskStart }
}
+
+/**
+ * Whether Cursor's hook queued Tasks while no daemon ran, or is queueing one now: the lock it takes to write the
+ * queue, or the queue (engines/cursor/contract.ts). Neither is there on a machine whose Cursor never did, and
+ * Cursor's code is loaded only when one is: its own read and write of the queue then run as they always did. The
+ * lock is looked for first: a hook that takes it, writes the queue and lets go between the two looks leaves the
+ * queue for the second.
+ */
+async function queued(dataDir: string): Promise<boolean> {
+ const file = join(dataDir, PENDING_TASKS_FILE)
+ for (const path of [`${file}.lock`, file]) {
+ try { await access(path); return true } catch { /* not this one */ }
+ }
+ return false
+}
+
+/** The Tasks Cursor's hook queued while no daemon ran, taken at the start. None without Cursor's code. */
+export async function loadPendingCursorTasks(dataDir: string): Promise<PendingCursorTask[]> {
+ if (!await queued(dataDir)) return []
+ const cursor = await loadEngine('cursor')
+ return cursor ? cursor.loadCursorPendingTasks(dataDir) : []
+}
+
+/** A session's queued Tasks, dropped on its Stop and when it is forgotten. */
+export async function removePendingCursorTasks(dataDir: string, sessionId: string): Promise<void> {
+ if (!await queued(dataDir)) return
+ await (await loadEngine('cursor'))?.removeCursorPendingTasks(dataDir, sessionId)
+}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 73711919a..16711a42b 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -4,7 +4,7 @@ import { createModelControls } from './engines/modelControls.js'
import { masterRunsEngineModelControl } from '../harnessd/services.js'
import { createScreens } from './engines/screens.js'
import { createScreenTransport } from './engines/screenTransport.js'
-import { inProcessScreen, preloadEngine } from '../engines/inProcess.js'
+import { engineNow, inProcessScreen, preloadEngine } from '../engines/inProcess.js'
import { masterRunsEngineScreen } from '../harnessd/services.js'
import { createSubmissions } from './engines/submissions.js'
import { createNativeControls } from './engines/nativeControls.js'
@@ -49,7 +49,7 @@ import { removePidFileIf, onError } from '../lib/daemonLaunch.js'
import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'
import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'
import { ENGINES, enginePathOverride } from '../lib/engineBin.js'
-import { isTerminalEngine } from '../engines/types.js'
+import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { engineInstallRecipe } from '../lib/engineInstall.js'
import { buildEngineLaunchArgv } from '../lib/engineLaunch.js'
import { workspaceMissing } from '../lib/workspaceCheck.js'
@@ -140,8 +140,9 @@ import { createLaunchRequests } from './agents/launches.js'
import { createAgentList } from './agents/list.js'
import { createAgentUpdate } from './agents/update.js'
import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn } from './engines/hooks.js'
-import { createCursorTaskHooks } from './engines/cursorTasks.js'
-import { databaseHistory } from './transcripts/databaseHistory.js'
+import { createCursorDiscovery } from './engines/cursorDiscovery.js'
+import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'
+import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
import { startStalls } from './stall.js'
@@ -185,11 +186,7 @@ import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'
import { isInstalledCopy } from '../lib/installedCopy.js'
import { managedNodePath } from '../lib/nodeRuntime.js'
import { type ActivityFrame } from '../lib/turnActivity.js'
-import { CursorTranscriptDiscovery } from '../engines/cursor/discovery.js'
-import { cursorDataDir } from '../engines/cursor/home.js'
-import { loadCursorPendingTasks } from '../engines/cursor/pendingTasks.js'
-import { opencodeMajorVersion } from '../engines/opencode/version.js'
-import { hermesDbForSession } from '../lib/hermesHome.js'
+import { cursorDataDir } from '../engines/cursor/contract.js'
import { TranscriptPager } from '../lib/transcriptPages.js'
import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'
import { agentFrame, lastActivityAt, type AgentFrame } from '../lib/agentFrame.js'
@@ -1013,7 +1010,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
const emitSessionEvents = funnel.emit
const announceTurnAborted = funnel.announceTurnAborted
- const cursorDiscovery = new CursorTranscriptDiscovery(cursorDataDir(), (sessionId, transcriptPath) => {
+ const cursorDiscovery = createCursorDiscovery(cursorDataDir(), (sessionId, transcriptPath) => {
const existing = registry.bySession(sessionId)
if (!existing || existing.engine !== 'cursor' || existing.transcriptPath === transcriptPath) return
const result = registry.register({
@@ -1062,7 +1059,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
terminalLabel: primaryTerminalLabel,
dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
devinHome: env.DEVIN_HOME,
- hermesDb: (s) => hermesDbForSession(s),
+ hermesDb,
concurrency: ATTACH_CONCURRENCY,
relaunchMarks,
// Built further down: told when an attach finds its last turn already over, never now.
@@ -1075,7 +1072,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// A conversation's history, a page at a time, and how long it is (core/transcripts/history.ts).
const history = createHistory({ readerFor: engineReaders.forEngine, resolve: (id) => registry.resolve(id), stopped: () => stoppedAgents.list(),
pages: new TranscriptPager(), dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
- hermesDb: (s) => hermesDbForSession(s) })
+ hermesDb })
backend.historyProvider = history.sessionGet
backend.sessionsProvider = history.sessionsList
// Everything the core writes into a pane, and the device's pane lock (core/input.ts).
@@ -1150,7 +1147,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
readerFor: engineReaders.forEngine,
bySession: (sessionId) => registry.bySession(sessionId),
dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
- hermesDb: (s) => hermesDbForSession(s),
+ hermesDb,
})
// Recaps: turn cards, notifications, cut by the recaps (services/recaps.ts) from the lifecycle the core tells (core/turns/recaps.ts).
const recaps = createRecaps({
@@ -1896,11 +1893,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
* cannot disagree about it.
*
* The other is which OpenCode is installed: v2's TUI exits 1 on v1's `-m` / `--agent`. Cached per
- * installed file (`engines/opencode/version.ts`), so this costs a `stat` after the first read.
+ * installed file (`engines/opencode/version.ts`), so this costs a `stat` after the first read. Read for an
+ * OpenCode launch alone, by OpenCode's own code: every launch of OpenCode loads it before asking, and is refused
+ * without it (core/agents/create.ts, lib/launchOverrides.ts).
*/
- const gridLaunchMachine = (): GridLaunchMachine => ({
+ const gridLaunchMachine = (engine: AgentEngine): GridLaunchMachine => ({
hermesSystemManaged: existsSync(HERMES_SYSTEM_MANAGED_DIR),
- opencodeMajor: opencodeMajorVersion(),
+ opencodeMajor: engine === 'opencode' ? engineNow('opencode', 'an OpenCode launch was built')?.opencodeMajorVersion() ?? null : null,
})
/**
@@ -2065,7 +2064,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
await agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)
// A file lock and a JSON parse, neither of which is worth the daemon: an unreadable queue means no
// pending Cursor tasks this boot, not no daemon.
- const pendingCursorTasks = await loadCursorPendingTasks(env.ADAPTER_DATA_DIR).catch((error) => {
+ const pendingCursorTasks = await loadPendingCursorTasks(env.ADAPTER_DATA_DIR).catch((error) => {
console.warn(`[cursor] pending tasks skipped · ${error instanceof Error ? error.message : error}`)
return []
})
diff --git a/cli/src/core/transcripts/databaseHistory.spec.ts b/cli/src/core/transcripts/databaseHistory.spec.ts
index 1ab4caaa9..b3e904f91 100644
--- a/cli/src/core/transcripts/databaseHistory.spec.ts
+++ b/cli/src/core/transcripts/databaseHistory.spec.ts
@@ -7,7 +7,7 @@ import { readKiloMessages } from '../../engines/kilo/reader.js'
import { readOpencodeMessages } from '../../engines/opencode/reader.js'
import { hermesDbForSession } from '../../lib/hermesHome.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import { databaseHistory } from './databaseHistory.js'
+import { databaseHistory, hermesDb } from './databaseHistory.js'
vi.mock('../../engines/opencode/reader.js', () => ({ readOpencodeMessages: vi.fn(async () => ['opencode rows']) }))
vi.mock('../../engines/opencode/normalizer.js', () => ({ opencodeMessagesToEvents: vi.fn((rows: unknown[]) => [{ from: 'opencode', rows }]) }))
@@ -49,6 +49,20 @@ describe('reading a conversation its engine keeps in a database', () => {
error.mockRestore()
})
+ it('a Hermes session\'s store is its home\'s, found by Hermes\'s code; the default home\'s without it', async () => {
+ const hermes = session('hermes')
+ expect(await hermesDb(hermes)).toBe('/profiles/work/state.db')
+ expect(hermesDbForSession).toHaveBeenLastCalledWith(hermes)
+ vi.resetModules()
+ vi.doMock('../../engines/hermes/inProcess.js', () => { throw new Error('Hermes is gone') })
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { hermesDb: lazily } = await import('./databaseHistory.js')
+ expect(await lazily(hermes)).toBe(join(env.HERMES_HOME, 'state.db'))
+ expect(error).toHaveBeenCalledWith(expect.stringMatching(/^\[engine hermes\] unavailable · /))
+ vi.doUnmock('../../engines/hermes/inProcess.js')
+ error.mockRestore()
+ })
+
it('nothing to read for an engine with a transcript file, and nothing read until asked', () => {
expect(databaseHistory(session('claude'))).toBeUndefined()
databaseHistory(session('opencode'))
diff --git a/cli/src/core/transcripts/databaseHistory.ts b/cli/src/core/transcripts/databaseHistory.ts
index 88a44b73d..36606af2b 100644
--- a/cli/src/core/transcripts/databaseHistory.ts
+++ b/cli/src/core/transcripts/databaseHistory.ts
@@ -1,3 +1,5 @@
+import { env } from '../../config/env.js'
+import { hermesDbPath } from '../../engines/hermes/contract.js'
import { loadEngine } from '../../engines/inProcess.js'
import type { LiveEvent } from '../../engines/kit/events.js'
import type { RegisteredSession } from '../../lib/registry.js'
@@ -12,3 +14,11 @@ const STORES: ReadonlySet<string> = new Set(SQLITE_BACKED_ENGINES)
*/
export const databaseHistory = (s: RegisteredSession): (() => Promise<readonly LiveEvent[]>) | undefined =>
STORES.has(s.engine) ? async () => await (await loadEngine('databaseHistory'))?.databaseHistory(s)?.() ?? [] : undefined
+
+/**
+ * The store a Hermes session's history is in: its own home's, found by Hermes's code and kept on its row
+ * (lib/hermesHome.ts), which is loaded with Hermes's. Read only once that code is there, for a Hermes session;
+ * without it, the default home's, as when no home claims the session.
+ */
+export const hermesDb = async (s: RegisteredSession): Promise<string> =>
+ await (await loadEngine('hermes'))?.hermesDbForSession(s) ?? hermesDbPath(env.HERMES_HOME)
diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.ts
index 77fa88223..898808eb6 100644
--- a/cli/src/core/turns/turnHooks.spec.ts
+++ b/cli/src/core/turns/turnHooks.spec.ts
@@ -1,6 +1,6 @@
import type { LiveParser } from '../../engines/facets/live.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import { removePendingCursorTasks } from '../engines/cursorTasks.js'
import type { TurnState } from '../../lib/normalize.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createSessionNormalizers } from '../transcripts/normalizers.js'
@@ -8,7 +8,8 @@ import { createTurnHooks, STOP_HOOK_GRACE_MS, type TurnHookDeps } from './turnHo
import { engineHooks } from '../../engines/hooks.js'
import type { HookTurnContext } from '../../engines/facets/hooks.js'
-vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))
+// Cursor's queued Tasks are cleared through the core's own door to them (core/engines/cursorTasks.ts).
+vi.mock('../engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
const END = [{ type: 'turn_ended', payload: {} }]
const ABORT = [{ type: 'turn_ended', payload: { aborted: true } }]
@@ -412,7 +413,7 @@ describe('turn hooks', () => {
expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
expect(run.deps.announceTurnAborted).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(2_500)
- expect(removeCursorPendingTasks).toHaveBeenCalledWith('/data', 's1')
+ expect(removePendingCursorTasks).toHaveBeenCalledWith('/data', 's1')
})
it('announces a turn that failed before writing anything, and leaves a session with no normalizer', async () => {
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
index febd88420..40aa742f0 100644
--- a/cli/src/core/turns/turnHooks.ts
+++ b/cli/src/core/turns/turnHooks.ts
@@ -9,7 +9,7 @@
*/
import { hooksFor } from '../../engines/hooks.js'
import type { HookTurnContext } from '../../engines/facets/hooks.js'
-import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import { removePendingCursorTasks } from '../engines/cursorTasks.js'
import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
import type { TurnRecaps } from './recaps.js'
@@ -119,7 +119,7 @@ export function createTurnHooks({
if (status === 'error' && closing.length === 0) {
announceTurnAborted(sessionId, 'cursor', 'Cursor ended the turn with an error before producing any output')
}
- setTimeout(() => void removeCursorPendingTasks(dataDir, sessionId), 2_500)
+ setTimeout(() => void removePendingCursorTasks(dataDir, sessionId), 2_500)
})().catch((err) => {
console.error('[cursor] stop hook failed:', err instanceof Error ? err.message : err)
})
diff --git a/cli/src/engines/__fixtures__/other-admission.golden.json b/cli/src/engines/__fixtures__/other-admission.golden.json
new file mode 100644
index 000000000..6fe5d0f0e
--- /dev/null
+++ b/cli/src/engines/__fixtures__/other-admission.golden.json
@@ -0,0 +1,186 @@
+{
+ "admission": [
+ [
+ "the default home's CLI session",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "20261008_100000_aaaaaa",
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check"
+ ]
+ ],
+ [
+ "a session one delegated to",
+ 200,
+ {
+ "pending": true
+ },
+ [],
+ [
+ "[hooks] 20261008 SessionStart ignored · hermes_subagent"
+ ]
+ ],
+ [
+ "a profile's TUI session",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "20261008_100003_cccccc",
+ "engine": "hermes",
+ "hermesHome": "<root>/home/.hermes/profiles/work"
+ }
+ ],
+ [
+ "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check · home=<root>/home/.hermes/profiles/work"
+ ]
+ ],
+ [
+ "a profile's session with no source",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "20261008_100004_eeeeee",
+ "engine": "hermes",
+ "hermesHome": "<root>/home/.hermes/profiles/work"
+ }
+ ],
+ [
+ "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check · home=<root>/home/.hermes/profiles/work"
+ ]
+ ],
+ [
+ "a profile's delegated session",
+ 200,
+ {
+ "pending": true
+ },
+ [],
+ [
+ "[hooks] 20261008 SessionStart ignored · hermes_subagent"
+ ]
+ ],
+ [
+ "one in both homes: the default asked first",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "20261008_100002_dddddd",
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check"
+ ]
+ ],
+ [
+ "an editor's session, whose id is a uuid",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "[hooks] 0b6f4f2e SessionStart · engine=hermes · isNew=true · after a source check"
+ ]
+ ],
+ [
+ "one no store holds yet",
+ 200,
+ {
+ "pending": true
+ },
+ [
+ {
+ "sessionId": "20261008_100009_999999",
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check"
+ ]
+ ]
+ ],
+ "home probe": [
+ [
+ "a profile",
+ {
+ "engine": "hermes",
+ "hermesHome": "<root>/home/.hermes/profiles/work"
+ }
+ ],
+ [
+ "the default",
+ {
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "the default, with a trailing slash",
+ {
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "a relative path",
+ {
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "a path with a control character",
+ {
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "none",
+ {
+ "engine": "hermes",
+ "hermesHome": null
+ }
+ ],
+ [
+ "an environment that could not be read",
+ {
+ "engine": "hermes",
+ "hermesHome": "undefined"
+ }
+ ],
+ [
+ "claude",
+ {
+ "engine": "claude",
+ "hermesHome": null
+ }
+ ]
+ ]
+}
diff --git a/cli/src/engines/__fixtures__/other-identity.golden.json b/cli/src/engines/__fixtures__/other-identity.golden.json
new file mode 100644
index 000000000..bbe2d1c73
--- /dev/null
+++ b/cli/src/engines/__fixtures__/other-identity.golden.json
@@ -0,0 +1,2225 @@
+{
+ "register": [
+ [
+ "commandcode",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-my-project/0b6f4f2e-6c1a-4c55-9a51-000000000001.jsonl",
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/My Project",
+ "not-a-uuid",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-my-project/not-a-uuid.jsonl",
+ "cwd": "/work/My Project",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/My Project",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/My Project",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-camel-case-repo/0b6f4f2e-6c1a-4c55-9a51-000000000002.jsonl",
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-camel-case-repo/not-a-uuid.jsonl",
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/camelCaseRepo",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/camelCaseRepo",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-ueber-uenicode/0b6f4f2e-6c1a-4c55-9a51-000000000003.jsonl",
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-ueber-uenicode/not-a-uuid.jsonl",
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/über-ünïcødé",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/über-ünïcødé",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "commandcode",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/root/0b6f4f2e-6c1a-4c55-9a51-000000000004.jsonl",
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "commandcode",
+ "/",
+ "not-a-uuid",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/root/not-a-uuid.jsonl",
+ "cwd": "/",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "commandcode",
+ "/",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "commandcode",
+ "/",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-a-b/0b6f4f2e-6c1a-4c55-9a51-000000000005.jsonl",
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/a/../b",
+ "not-a-uuid",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-a-b/not-a-uuid.jsonl",
+ "cwd": "/work/a/../b",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/a/../b",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "commandcode",
+ "/work/a/../b",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "commandcode",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.commandcode/projects/work-x/0b6f4f2e-6c1a-4c55-9a51-000000000090.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "commandcode",
+ "named outside",
+ null
+ ],
+ [
+ "grok",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2FMy%20Project/0b6f4f2e-6c1a-4c55-9a51-000000000001/updates.jsonl",
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "grok",
+ "/work/My Project",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "grok",
+ "/work/My Project",
+ "../escape",
+ null
+ ],
+ [
+ "grok",
+ "/work/My Project",
+ "with space",
+ null
+ ],
+ [
+ "grok",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2FcamelCaseRepo/0b6f4f2e-6c1a-4c55-9a51-000000000002/updates.jsonl",
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "grok",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "grok",
+ "/work/camelCaseRepo",
+ "../escape",
+ null
+ ],
+ [
+ "grok",
+ "/work/camelCaseRepo",
+ "with space",
+ null
+ ],
+ [
+ "grok",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2F%C3%BCber-%C3%BCn%C3%AFc%C3%B8d%C3%A9/0b6f4f2e-6c1a-4c55-9a51-000000000003/updates.jsonl",
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "grok",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "grok",
+ "/work/über-ünïcødé",
+ "../escape",
+ null
+ ],
+ [
+ "grok",
+ "/work/über-ünïcødé",
+ "with space",
+ null
+ ],
+ [
+ "grok",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2F/0b6f4f2e-6c1a-4c55-9a51-000000000004/updates.jsonl",
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "grok",
+ "/",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "grok",
+ "/",
+ "../escape",
+ null
+ ],
+ [
+ "grok",
+ "/",
+ "with space",
+ null
+ ],
+ [
+ "grok",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fa%2F..%2Fb/0b6f4f2e-6c1a-4c55-9a51-000000000005/updates.jsonl",
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "grok",
+ "/work/a/../b",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "grok",
+ "/work/a/../b",
+ "../escape",
+ null
+ ],
+ [
+ "grok",
+ "/work/a/../b",
+ "with space",
+ null
+ ],
+ [
+ "grok",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fx/0b6f4f2e-6c1a-4c55-9a51-000000000090/updates.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "grok",
+ "named outside",
+ null
+ ],
+ [
+ "agy",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000001/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "agy",
+ "/work/My Project",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "agy",
+ "/work/My Project",
+ "../escape",
+ null
+ ],
+ [
+ "agy",
+ "/work/My Project",
+ "with space",
+ null
+ ],
+ [
+ "agy",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000002/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "agy",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "agy",
+ "/work/camelCaseRepo",
+ "../escape",
+ null
+ ],
+ [
+ "agy",
+ "/work/camelCaseRepo",
+ "with space",
+ null
+ ],
+ [
+ "agy",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000003/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "agy",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "agy",
+ "/work/über-ünïcødé",
+ "../escape",
+ null
+ ],
+ [
+ "agy",
+ "/work/über-ünïcødé",
+ "with space",
+ null
+ ],
+ [
+ "agy",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000004/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "agy",
+ "/",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "agy",
+ "/",
+ "../escape",
+ null
+ ],
+ [
+ "agy",
+ "/",
+ "with space",
+ null
+ ],
+ [
+ "agy",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000005/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "agy",
+ "/work/a/../b",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "agy",
+ "/work/a/../b",
+ "../escape",
+ null
+ ],
+ [
+ "agy",
+ "/work/a/../b",
+ "with space",
+ null
+ ],
+ [
+ "agy",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000090/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "agy",
+ "named outside",
+ null
+ ],
+ [
+ "copilot",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000001/events.jsonl",
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "copilot",
+ "/work/My Project",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "copilot",
+ "/work/My Project",
+ "../escape",
+ null
+ ],
+ [
+ "copilot",
+ "/work/My Project",
+ "with space",
+ null
+ ],
+ [
+ "copilot",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000002/events.jsonl",
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "copilot",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "copilot",
+ "/work/camelCaseRepo",
+ "../escape",
+ null
+ ],
+ [
+ "copilot",
+ "/work/camelCaseRepo",
+ "with space",
+ null
+ ],
+ [
+ "copilot",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000003/events.jsonl",
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "copilot",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "copilot",
+ "/work/über-ünïcødé",
+ "../escape",
+ null
+ ],
+ [
+ "copilot",
+ "/work/über-ünïcødé",
+ "with space",
+ null
+ ],
+ [
+ "copilot",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000004/events.jsonl",
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "copilot",
+ "/",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "copilot",
+ "/",
+ "../escape",
+ null
+ ],
+ [
+ "copilot",
+ "/",
+ "with space",
+ null
+ ],
+ [
+ "copilot",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000005/events.jsonl",
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "copilot",
+ "/work/a/../b",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "copilot",
+ "/work/a/../b",
+ "../escape",
+ null
+ ],
+ [
+ "copilot",
+ "/work/a/../b",
+ "with space",
+ null
+ ],
+ [
+ "copilot",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000090/events.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "copilot",
+ "named outside",
+ null
+ ],
+ [
+ "cursor",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "cursor",
+ "/work/My Project",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "cursor",
+ "/work/My Project",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "cursor",
+ "/work/My Project",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "cursor",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "cursor",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "cursor",
+ "/work/camelCaseRepo",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "cursor",
+ "/work/camelCaseRepo",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "cursor",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "cursor",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "cursor",
+ "/work/über-ünïcødé",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "cursor",
+ "/work/über-ünïcødé",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "cursor",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "cursor",
+ "/",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "cursor",
+ "/",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "cursor",
+ "/",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "cursor",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "cursor",
+ "/work/a/../b",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "cursor",
+ "/work/a/../b",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "cursor",
+ "/work/a/../b",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "cursor",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.cursor/projects/work-x/agent-transcripts/0b6f4f2e-6c1a-4c55-9a51-000000000090/0b6f4f2e-6c1a-4c55-9a51-000000000090.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "cursor",
+ "named outside",
+ null
+ ],
+ [
+ "pi",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000001"
+ }
+ ],
+ [
+ "pi",
+ "/work/My Project",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "pi",
+ "/work/My Project",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "pi",
+ "/work/My Project",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/My Project",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "pi",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000002"
+ }
+ ],
+ [
+ "pi",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "pi",
+ "/work/camelCaseRepo",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "pi",
+ "/work/camelCaseRepo",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/camelCaseRepo",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "pi",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000003"
+ }
+ ],
+ [
+ "pi",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "pi",
+ "/work/über-ünïcødé",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "pi",
+ "/work/über-ünïcødé",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/über-ünïcødé",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "pi",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000004"
+ }
+ ],
+ [
+ "pi",
+ "/",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "pi",
+ "/",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "pi",
+ "/",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "pi",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000005"
+ }
+ ],
+ [
+ "pi",
+ "/work/a/../b",
+ "not-a-uuid",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "not-a-uuid"
+ }
+ ],
+ [
+ "pi",
+ "/work/a/../b",
+ "../escape",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "../escape"
+ }
+ ],
+ [
+ "pi",
+ "/work/a/../b",
+ "with space",
+ {
+ "transcriptPath": null,
+ "cwd": "/work/a/../b",
+ "sessionId": "with space"
+ }
+ ],
+ [
+ "pi",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.pi/agent/sessions/--work-x--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000090.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "pi",
+ "named outside",
+ null
+ ],
+ [
+ "muse",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ null
+ ],
+ [
+ "muse",
+ "/work/My Project",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "muse",
+ "/work/My Project",
+ "../escape",
+ null
+ ],
+ [
+ "muse",
+ "/work/My Project",
+ "with space",
+ null
+ ],
+ [
+ "muse",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ null
+ ],
+ [
+ "muse",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "muse",
+ "/work/camelCaseRepo",
+ "../escape",
+ null
+ ],
+ [
+ "muse",
+ "/work/camelCaseRepo",
+ "with space",
+ null
+ ],
+ [
+ "muse",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ null
+ ],
+ [
+ "muse",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "muse",
+ "/work/über-ünïcødé",
+ "../escape",
+ null
+ ],
+ [
+ "muse",
+ "/work/über-ünïcødé",
+ "with space",
+ null
+ ],
+ [
+ "muse",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ null
+ ],
+ [
+ "muse",
+ "/",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "muse",
+ "/",
+ "../escape",
+ null
+ ],
+ [
+ "muse",
+ "/",
+ "with space",
+ null
+ ],
+ [
+ "muse",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ null
+ ],
+ [
+ "muse",
+ "/work/a/../b",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "muse",
+ "/work/a/../b",
+ "../escape",
+ null
+ ],
+ [
+ "muse",
+ "/work/a/../b",
+ "with space",
+ null
+ ],
+ [
+ "muse",
+ "named inside",
+ {
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/08/0b6f4f2e-6c1a-4c55-9a51-000000000090/session.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "muse",
+ "named outside",
+ null
+ ],
+ [
+ "amp",
+ "/work/My Project",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ null
+ ],
+ [
+ "amp",
+ "/work/My Project",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "amp",
+ "/work/My Project",
+ "../escape",
+ null
+ ],
+ [
+ "amp",
+ "/work/My Project",
+ "with space",
+ null
+ ],
+ [
+ "amp",
+ "/work/camelCaseRepo",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000002",
+ null
+ ],
+ [
+ "amp",
+ "/work/camelCaseRepo",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "amp",
+ "/work/camelCaseRepo",
+ "../escape",
+ null
+ ],
+ [
+ "amp",
+ "/work/camelCaseRepo",
+ "with space",
+ null
+ ],
+ [
+ "amp",
+ "/work/über-ünïcødé",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000003",
+ null
+ ],
+ [
+ "amp",
+ "/work/über-ünïcødé",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "amp",
+ "/work/über-ünïcødé",
+ "../escape",
+ null
+ ],
+ [
+ "amp",
+ "/work/über-ünïcødé",
+ "with space",
+ null
+ ],
+ [
+ "amp",
+ "/",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000004",
+ null
+ ],
+ [
+ "amp",
+ "/",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "amp",
+ "/",
+ "../escape",
+ null
+ ],
+ [
+ "amp",
+ "/",
+ "with space",
+ null
+ ],
+ [
+ "amp",
+ "/work/a/../b",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000005",
+ null
+ ],
+ [
+ "amp",
+ "/work/a/../b",
+ "not-a-uuid",
+ null
+ ],
+ [
+ "amp",
+ "/work/a/../b",
+ "../escape",
+ null
+ ],
+ [
+ "amp",
+ "/work/a/../b",
+ "with space",
+ null
+ ],
+ [
+ "amp",
+ "named inside",
+ {
+ "transcriptPath": "<root>/data/amp-sessions/T-0b6f4f2e-6c1a-4c55-9a51-000000000090.jsonl",
+ "cwd": "/work/x",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000090"
+ }
+ ],
+ [
+ "amp",
+ "named outside",
+ null
+ ]
+ ],
+ "valid transcripts": [
+ [
+ "claude",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "codex",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "cursor",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "opencode",
+ false,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "pi",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "hermes",
+ false,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "commandcode",
+ true,
+ [
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "devin",
+ false,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "muse",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "amp",
+ true,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ],
+ false
+ ],
+ [
+ "kilo",
+ false,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "grok",
+ true,
+ [
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "agy",
+ true,
+ [
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ],
+ [
+ "copilot",
+ true,
+ [
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ true
+ ],
+ [
+ "terminal",
+ false,
+ [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ],
+ false
+ ]
+ ],
+ "cursor homes": [
+ [
+ {},
+ "<root>/home/.cursor",
+ "<root>/home/.cursor"
+ ],
+ [
+ {
+ "CURSOR_DATA_DIR": "/data/cursor"
+ },
+ "<root>/home/.cursor",
+ "/data/cursor"
+ ],
+ [
+ {
+ "CURSOR_CONFIG_DIR": "/config/cursor"
+ },
+ "/config/cursor",
+ "<root>/home/.cursor"
+ ],
+ [
+ {
+ "XDG_CONFIG_HOME": "/xdg"
+ },
+ "/xdg/cursor",
+ "<root>/home/.cursor"
+ ],
+ [
+ {
+ "CURSOR_CONFIG_DIR": " ",
+ "XDG_CONFIG_HOME": " /xdg2 ",
+ "CURSOR_DATA_DIR": " "
+ },
+ "/xdg2/cursor",
+ "<root>/home/.cursor"
+ ]
+ ],
+ "hook command": "'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor",
+ "bind": [
+ [
+ "cursor",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000031",
+ [
+ {
+ "engine": "cursor",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000031",
+ "transcriptPath": "<root>/home/.cursor/projects/p/agent-transcripts/0b6f4f2e-6c1a-4c55-9a51-000000000031/0b6f4f2e-6c1a-4c55-9a51-000000000031.jsonl",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "cursor"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "cursor",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ []
+ ],
+ [
+ "grok",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000032",
+ [
+ {
+ "engine": "grok",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000032",
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fg/0b6f4f2e-6c1a-4c55-9a51-000000000032/updates.jsonl",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "grok"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "grok",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ []
+ ],
+ [
+ "agy",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000033",
+ [
+ {
+ "engine": "agy",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000033",
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000033/.system_generated/logs/transcript_full.jsonl",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "agy"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "agy",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ [
+ {
+ "engine": "agy",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "agy"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "copilot",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000034",
+ [
+ {
+ "engine": "copilot",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000034",
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000034/events.jsonl",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "copilot"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "copilot",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ [
+ {
+ "engine": "copilot",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000039",
+ "cwd": "/work/g",
+ "source": "terminal-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "copilot"
+ },
+ "hookEvent": "TerminalResumeDiscovery"
+ }
+ ]
+ ],
+ [
+ "copilot /resume",
+ [
+ {
+ "engine": "copilot",
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000035",
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000035/events.jsonl",
+ "cwd": "/work/g",
+ "source": "copilot-resume",
+ "runtimes": [
+ {
+ "backend": "tmux",
+ "paneId": "%1"
+ }
+ ],
+ "primaryRuntimeKey": "tmux:%1",
+ "processIdentity": {
+ "pid": 4242,
+ "startMarker": "Mon Oct 8 10:00:00 2026",
+ "executable": "copilot"
+ },
+ "hookEvent": "CopilotResume"
+ }
+ ]
+ ]
+ ],
+ "repair": [
+ [
+ "pi",
+ null,
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "transcriptPath": "<root>/home/.pi/agent/sessions/--work-r--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000041.jsonl"
+ }
+ ],
+ [
+ "pi",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "transcriptPath": "<root>/home/.pi/agent/sessions/--work-r--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000041.jsonl"
+ }
+ ],
+ [
+ "pi",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "transcriptPath": "<root>/home/.pi/agent/sessions/--work-r--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000041.jsonl"
+ }
+ ],
+ [
+ "pi",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "transcriptPath": "<root>/home/.pi/agent/sessions/--work-r--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000041.jsonl"
+ }
+ ],
+ [
+ "commandcode",
+ null,
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000042",
+ "transcriptPath": "<root>/home/.commandcode/projects/work-r/0b6f4f2e-6c1a-4c55-9a51-000000000042.jsonl"
+ }
+ ],
+ [
+ "commandcode",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000042",
+ "transcriptPath": "<root>/home/.commandcode/projects/work-r/0b6f4f2e-6c1a-4c55-9a51-000000000042.jsonl"
+ }
+ ],
+ [
+ "commandcode",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000042",
+ "transcriptPath": "<root>/home/.commandcode/projects/work-r/0b6f4f2e-6c1a-4c55-9a51-000000000042.jsonl"
+ }
+ ],
+ [
+ "commandcode",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000042",
+ "transcriptPath": "<root>/home/.commandcode/projects/work-r/0b6f4f2e-6c1a-4c55-9a51-000000000042.jsonl"
+ }
+ ],
+ [
+ "amp",
+ null,
+ {
+ "sessionId": "T-0b6f4f2e-6c1a-4c55-9a51-000000000043",
+ "transcriptPath": "<root>/data/amp-sessions/T-0b6f4f2e-6c1a-4c55-9a51-000000000043.jsonl"
+ }
+ ],
+ [
+ "amp",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "T-0b6f4f2e-6c1a-4c55-9a51-000000000043",
+ "transcriptPath": "<root>/data/amp-sessions/T-0b6f4f2e-6c1a-4c55-9a51-000000000043.jsonl"
+ }
+ ],
+ [
+ "amp",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "T-0b6f4f2e-6c1a-4c55-9a51-000000000043",
+ "transcriptPath": "<root>/data/amp-sessions/T-0b6f4f2e-6c1a-4c55-9a51-000000000043.jsonl"
+ }
+ ],
+ [
+ "amp",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "T-0b6f4f2e-6c1a-4c55-9a51-000000000043",
+ "transcriptPath": "<root>/data/amp-sessions/T-0b6f4f2e-6c1a-4c55-9a51-000000000043.jsonl"
+ }
+ ],
+ [
+ "muse",
+ null,
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000044",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/08/0b6f4f2e-6c1a-4c55-9a51-000000000044/session.jsonl"
+ }
+ ],
+ [
+ "muse",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000044",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/08/0b6f4f2e-6c1a-4c55-9a51-000000000044/session.jsonl"
+ }
+ ],
+ [
+ "muse",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000044",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/08/0b6f4f2e-6c1a-4c55-9a51-000000000044/session.jsonl"
+ }
+ ],
+ [
+ "muse",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000044",
+ "transcriptPath": "<root>/home/.muse/sessions/2026/10/08/0b6f4f2e-6c1a-4c55-9a51-000000000044/session.jsonl"
+ }
+ ],
+ [
+ "grok",
+ null,
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000046",
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fr/0b6f4f2e-6c1a-4c55-9a51-000000000046/updates.jsonl"
+ }
+ ],
+ [
+ "grok",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000046",
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fr/0b6f4f2e-6c1a-4c55-9a51-000000000046/updates.jsonl"
+ }
+ ],
+ [
+ "grok",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000046",
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fr/0b6f4f2e-6c1a-4c55-9a51-000000000046/updates.jsonl"
+ }
+ ],
+ [
+ "grok",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000046",
+ "transcriptPath": "<root>/home/.grok/sessions/%2Fwork%2Fr/0b6f4f2e-6c1a-4c55-9a51-000000000046/updates.jsonl"
+ }
+ ],
+ [
+ "copilot",
+ null,
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000047",
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000047/events.jsonl"
+ }
+ ],
+ [
+ "copilot",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000047",
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000047/events.jsonl"
+ }
+ ],
+ [
+ "copilot",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000048"
+ }
+ ],
+ [
+ "copilot",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000047",
+ "transcriptPath": "<root>/home/.copilot/session-state/0b6f4f2e-6c1a-4c55-9a51-000000000047/events.jsonl"
+ }
+ ],
+ [
+ "hermes",
+ null,
+ {
+ "sessionId": "20261008_110000_a1b2",
+ "hermesHome": "<root>/home/.hermes"
+ }
+ ],
+ [
+ "hermes",
+ {
+ "bornOnly": true
+ },
+ {
+ "sessionId": "20261008_110000_a1b2",
+ "hermesHome": "<root>/home/.hermes"
+ }
+ ],
+ [
+ "hermes",
+ {
+ "pid": 5151
+ },
+ {
+ "sessionId": "20261008_110000_a1b2",
+ "hermesHome": "<root>/home/.hermes"
+ }
+ ],
+ [
+ "hermes",
+ {
+ "pid": 99999999
+ },
+ {
+ "sessionId": "20261008_110000_a1b2",
+ "hermesHome": "<root>/home/.hermes"
+ }
+ ],
+ [
+ "agy",
+ null,
+ null
+ ],
+ [
+ "agy",
+ {
+ "bornOnly": true
+ },
+ null
+ ],
+ [
+ "agy",
+ {
+ "pid": 5151
+ },
+ null
+ ],
+ [
+ "agy",
+ {
+ "pid": 99999999
+ },
+ null
+ ],
+ [
+ "hermes",
+ "/work/p",
+ {
+ "sessionId": "20261008_110500_c3d4",
+ "hermesHome": "<root>/home/.hermes/profiles/work"
+ }
+ ],
+ [
+ "hermes",
+ "/work/both",
+ null
+ ],
+ [
+ "hermes",
+ "/work/none",
+ null
+ ],
+ [
+ "pi resumed",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "/work/r",
+ "<root>/home/.pi/agent/sessions/--work-r--/2026_0b6f4f2e-6c1a-4c55-9a51-000000000041.jsonl"
+ ],
+ [
+ "pi resumed",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000041",
+ "/work/other",
+ null
+ ],
+ [
+ "pi resumed",
+ "0b6f4f2e-6c1a-4c55-9a51-000000000049",
+ "/work/r",
+ null
+ ],
+ [
+ "pi resumed",
+ "bad id",
+ "/work/r",
+ "threw The Pi conversation location is unavailable."
+ ]
+ ],
+ "repair agy lock": [
+ [
+ "held",
+ {
+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000050",
+ "transcriptPath": "<root>/home/.gemini/antigravity-cli/brain/0b6f4f2e-6c1a-4c55-9a51-000000000050/.system_generated/logs/transcript_full.jsonl"
+ }
+ ],
+ [
+ "let go",
+ null
+ ]
+ ]
+}
diff --git a/cli/src/engines/__fixtures__/other-launch.golden.json b/cli/src/engines/__fixtures__/other-launch.golden.json
new file mode 100644
index 000000000..0817b4023
--- /dev/null
+++ b/cli/src/engines/__fixtures__/other-launch.golden.json
@@ -0,0 +1,294 @@
+{
+ "agent_create · OpenCode v1": [
+ [
+ "opencode",
+ "harness-compute",
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "opencode",
+ "agent": "harness-compute",
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "opencode",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "opencode",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "claude",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "claude has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "claude",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "claude",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "pi",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "pi has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "pi",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "pi",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "cursor",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "cursor has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "cursor",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "cursor",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ]
+ ],
+ "agent_create · OpenCode v2": [
+ [
+ "opencode",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "opencode has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "opencode",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "opencode",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "claude",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "claude has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "claude",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "claude",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "pi",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "pi has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "pi",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "pi",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "cursor",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "cursor has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "cursor",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "cursor",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ]
+ ],
+ "agent_create · OpenCode none": [
+ [
+ "opencode",
+ "harness-compute",
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "opencode",
+ "agent": "harness-compute",
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "opencode",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "opencode",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "claude",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "claude has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "claude",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "claude",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "pi",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "pi has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "pi",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "pi",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ],
+ [
+ "cursor",
+ "harness-compute",
+ {
+ "error": "AGENT_UNSUPPORTED",
+ "detail": "cursor has no documented way to open as a named agent, so the agent was not created."
+ },
+ []
+ ],
+ [
+ "cursor",
+ null,
+ {
+ "error": "RECORDED"
+ },
+ [
+ {
+ "engine": "cursor",
+ "agent": null,
+ "name": "Named"
+ }
+ ]
+ ]
+ ]
+}
diff --git a/cli/src/engines/agy/contract.ts b/cli/src/engines/agy/contract.ts
new file mode 100644
index 000000000..2a32029f6
--- /dev/null
+++ b/cli/src/engines/agy/contract.ts
@@ -0,0 +1,14 @@
+/**
+ * What the core knows of agy without loading its code: declared data, read in line on the hook path
+ * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of agy's code.
+ */
+import { join } from 'node:path'
+
+/** A conversation id: its folder's name. */
+export const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** `<AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`. */
+export function agyTranscriptPath(agyHome: string, conversationId: string): string | null {
+ if (!CONVERSATION_ID.test(conversationId)) return null
+ return join(agyHome, 'brain', conversationId, '.system_generated', 'logs', 'transcript_full.jsonl')
+}
diff --git a/cli/src/engines/agy/inProcess.ts b/cli/src/engines/agy/inProcess.ts
index fc5374a28..d3f9f6458 100644
--- a/cli/src/engines/agy/inProcess.ts
+++ b/cli/src/engines/agy/inProcess.ts
@@ -5,3 +5,4 @@
*/
export { AgyNormalizer, agyMessagesToEvents, lastAgyTurnText } from './normalizer.js'
export { agyPaneIdle, parseAgyFooterProfile } from './runtimeProfile.js'
+export { agyConversationForPid, findAgyTranscript } from './session.js'
diff --git a/cli/src/engines/agy/session.ts b/cli/src/engines/agy/session.ts
index 45e45642a..f70ccaba1 100644
--- a/cli/src/engines/agy/session.ts
+++ b/cli/src/engines/agy/session.ts
@@ -5,13 +5,8 @@ import { promisify } from 'util'
const execFileAsync = promisify(execFile)
-const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
-
-/** `<AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`. */
-export function agyTranscriptPath(agyHome: string, conversationId: string): string | null {
- if (!CONVERSATION_ID.test(conversationId)) return null
- return join(agyHome, 'brain', conversationId, '.system_generated', 'logs', 'transcript_full.jsonl')
-}
+import { agyTranscriptPath, CONVERSATION_ID } from './contract.js'
+export { agyTranscriptPath } from './contract.js'
async function isFile(path: string): Promise<boolean> {
try { return (await stat(path)).isFile() } catch { return false }
diff --git a/cli/src/engines/commandcode/contract.ts b/cli/src/engines/commandcode/contract.ts
new file mode 100644
index 000000000..e7956ff24
--- /dev/null
+++ b/cli/src/engines/commandcode/contract.ts
@@ -0,0 +1,36 @@
+/**
+ * What the core knows of Command Code without loading its code: declared data, read in line on the hook path
+ * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Command Code's code.
+ */
+import { join } from 'path'
+import slugify from '@sindresorhus/slugify'
+import { env } from '../../config/env.js'
+
+/**
+ * Command Code lays its transcripts out deterministically:
+ *
+ * <COMMANDCODE_HOME>/projects/<cwd slug>/<sessionId>.jsonl
+ *
+ * Command Code 1.66.0 uses @sindresorhus/slugify with its defaults and falls back to "root". This
+ * splits camelCase and acronyms and transliterates Unicode; simply replacing punctuation loses paths.
+ *
+ * Deriving it matters because the CLI fires SessionStart BEFORE the file exists, and a path that is not on
+ * disk fails the registry's realpath check — so the path used to arrive only with the first Stop hook, i.e.
+ * AFTER the first turn. Nothing tailed the transcript for that turn, which is the only signal Command Code
+ * has that a message was accepted, so the first message of every new session reported "the agent did not
+ * accept this message" and produced no recap.
+ */
+export function commandcodeProjectSlug(cwd: string): string {
+ return slugify(cwd) || 'root'
+}
+
+/** null when there is not enough to build a path, or when either part could escape the projects root. */
+export function commandcodeTranscriptPath(cwd: string | null | undefined, sessionId: string): string | null {
+ if (!cwd || !sessionId) return null
+ // The session id becomes a FILENAME, so anything that could climb out of the directory disqualifies it.
+ // Command Code uses uuids; this is here so a malformed hook payload cannot point the watcher elsewhere.
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === '.' || sessionId === '..') return null
+ const slug = commandcodeProjectSlug(cwd)
+ if (!slug) return null
+ return join(env.COMMANDCODE_HOME, 'projects', slug, `${sessionId}.jsonl`)
+}
diff --git a/cli/src/engines/commandcode/transcript.ts b/cli/src/engines/commandcode/transcript.ts
index 66e882ecc..fc671eebf 100644
--- a/cli/src/engines/commandcode/transcript.ts
+++ b/cli/src/engines/commandcode/transcript.ts
@@ -1,32 +1,2 @@
-import { join } from 'path'
-import slugify from '@sindresorhus/slugify'
-import { env } from '../../config/env.js'
-
-/**
- * Command Code lays its transcripts out deterministically:
- *
- * <COMMANDCODE_HOME>/projects/<cwd slug>/<sessionId>.jsonl
- *
- * Command Code 1.66.0 uses @sindresorhus/slugify with its defaults and falls back to "root". This
- * splits camelCase and acronyms and transliterates Unicode; simply replacing punctuation loses paths.
- *
- * Deriving it matters because the CLI fires SessionStart BEFORE the file exists, and a path that is not on
- * disk fails the registry's realpath check — so the path used to arrive only with the first Stop hook, i.e.
- * AFTER the first turn. Nothing tailed the transcript for that turn, which is the only signal Command Code
- * has that a message was accepted, so the first message of every new session reported "the agent did not
- * accept this message" and produced no recap.
- */
-export function commandcodeProjectSlug(cwd: string): string {
- return slugify(cwd) || 'root'
-}
-
-/** null when there is not enough to build a path, or when either part could escape the projects root. */
-export function commandcodeTranscriptPath(cwd: string | null | undefined, sessionId: string): string | null {
- if (!cwd || !sessionId) return null
- // The session id becomes a FILENAME, so anything that could climb out of the directory disqualifies it.
- // Command Code uses uuids; this is here so a malformed hook payload cannot point the watcher elsewhere.
- if (!/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === '.' || sessionId === '..') return null
- const slug = commandcodeProjectSlug(cwd)
- if (!slug) return null
- return join(env.COMMANDCODE_HOME, 'projects', slug, `${sessionId}.jsonl`)
-}
+// Command Code's transcript layout is declared (contract.ts), so that the registry derives a path without its code.
+export { commandcodeProjectSlug, commandcodeTranscriptPath } from './contract.js'
diff --git a/cli/src/engines/copilot/contract.ts b/cli/src/engines/copilot/contract.ts
new file mode 100644
index 000000000..e4354a558
--- /dev/null
+++ b/cli/src/engines/copilot/contract.ts
@@ -0,0 +1,19 @@
+/**
+ * What the core knows of Copilot without loading its code: declared data, read in line on the hook path
+ * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Copilot's code.
+ */
+import { join } from 'node:path'
+
+/** A session id: its folder's name. */
+export const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/**
+ * `<COPILOT_HOME>/session-state/<sessionId>/events.jsonl`.
+ *
+ * Deterministic from the session id alone, and confirmed by Copilot itself: the `agentStop` hook
+ * reports this exact path in `transcriptPath`.
+ */
+export function copilotTranscriptPath(copilotHome: string, sessionId: string): string | null {
+ if (!SESSION_ID.test(sessionId)) return null
+ return join(copilotHome, 'session-state', sessionId, 'events.jsonl')
+}
diff --git a/cli/src/engines/copilot/inProcess.ts b/cli/src/engines/copilot/inProcess.ts
index 1b4e8e845..f318ad0bd 100644
--- a/cli/src/engines/copilot/inProcess.ts
+++ b/cli/src/engines/copilot/inProcess.ts
@@ -4,3 +4,4 @@
* its own: what the core calls is the engine's own, unchanged.
*/
export { CopilotNormalizer, copilotHistoryTurnOpen, copilotMessagesToEvents, lastCopilotTurnText } from './normalizer.js'
+export { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from './session.js'
diff --git a/cli/src/engines/copilot/session.ts b/cli/src/engines/copilot/session.ts
index 985b91bbf..33963d304 100644
--- a/cli/src/engines/copilot/session.ts
+++ b/cli/src/engines/copilot/session.ts
@@ -1,18 +1,8 @@
import { readdir, stat } from 'fs/promises'
import { join } from 'path'
-const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
-
-/**
- * `<COPILOT_HOME>/session-state/<sessionId>/events.jsonl`.
- *
- * Deterministic from the session id alone, and confirmed by Copilot itself: the `agentStop` hook
- * reports this exact path in `transcriptPath`.
- */
-export function copilotTranscriptPath(copilotHome: string, sessionId: string): string | null {
- if (!SESSION_ID.test(sessionId)) return null
- return join(copilotHome, 'session-state', sessionId, 'events.jsonl')
-}
+import { copilotTranscriptPath, SESSION_ID } from './contract.js'
+export { copilotTranscriptPath } from './contract.js'
async function isFile(path: string): Promise<boolean> {
try { return (await stat(path)).isFile() } catch { return false }
diff --git a/cli/src/engines/cursor/contract.ts b/cli/src/engines/cursor/contract.ts
new file mode 100644
index 000000000..03b7de90f
--- /dev/null
+++ b/cli/src/engines/cursor/contract.ts
@@ -0,0 +1,20 @@
+/**
+ * What the core knows of Cursor without loading its code: declared data, read in line on the hook path and in
+ * the hook command (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Cursor's code.
+ */
+import { join } from 'node:path'
+import { env } from '../../config/env.js'
+
+/** Cursor's hooks and chat databases follow its config root, which can differ from its data root. */
+export function cursorConfigDir(vars: NodeJS.ProcessEnv = process.env): string {
+ return vars.CURSOR_CONFIG_DIR?.trim()
+ || (vars.XDG_CONFIG_HOME?.trim() ? join(vars.XDG_CONFIG_HOME.trim(), 'cursor') : env.CURSOR_HOME)
+}
+
+/** Agent transcripts live under projects in Cursor's data root. */
+export function cursorDataDir(vars: NodeJS.ProcessEnv = process.env): string {
+ return vars.CURSOR_DATA_DIR?.trim() || env.CURSOR_HOME
+}
+
+/** Cursor's Task hooks a hook queued while no daemon ran (hook/notify.mjs writes it), in the data folder. */
+export const PENDING_TASKS_FILE = 'cursor-pending-tasks.json'
diff --git a/cli/src/engines/cursor/home.ts b/cli/src/engines/cursor/home.ts
index dda2c02e2..ff6980949 100644
--- a/cli/src/engines/cursor/home.ts
+++ b/cli/src/engines/cursor/home.ts
@@ -1,13 +1,2 @@
-import { join } from 'node:path'
-import { env } from '../../config/env.js'
-
-/** Cursor's hooks and chat databases follow its config root, which can differ from its data root. */
-export function cursorConfigDir(vars: NodeJS.ProcessEnv = process.env): string {
- return vars.CURSOR_CONFIG_DIR?.trim()
- || (vars.XDG_CONFIG_HOME?.trim() ? join(vars.XDG_CONFIG_HOME.trim(), 'cursor') : env.CURSOR_HOME)
-}
-
-/** Agent transcripts live under projects in Cursor's data root. */
-export function cursorDataDir(vars: NodeJS.ProcessEnv = process.env): string {
- return vars.CURSOR_DATA_DIR?.trim() || env.CURSOR_HOME
-}
+// Cursor's homes are declared (contract.ts), so that the registry and the hook command name them without its code.
+export { cursorConfigDir, cursorDataDir } from './contract.js'
diff --git a/cli/src/engines/cursor/inProcess.ts b/cli/src/engines/cursor/inProcess.ts
index e4549bce6..e3da14c97 100644
--- a/cli/src/engines/cursor/inProcess.ts
+++ b/cli/src/engines/cursor/inProcess.ts
@@ -7,3 +7,5 @@ export { CursorNormalizer, cursorMessagesToEvents, lastCursorTurnText, windowCur
export { CursorSubagentManager, loadCursorReplayTaskLinks } from './subagent.js'
export { CursorTaskHookQueue } from './taskHookQueue.js'
export { cursorConfigDir, cursorDataDir } from './home.js'
+export { CursorTranscriptDiscovery, findCursorTranscript } from './discovery.js'
+export { loadCursorPendingTasks, removeCursorPendingTasks } from './pendingTasks.js'
diff --git a/cli/src/engines/cursor/pendingTasks.ts b/cli/src/engines/cursor/pendingTasks.ts
index 0828e20f5..bd359b9c7 100644
--- a/cli/src/engines/cursor/pendingTasks.ts
+++ b/cli/src/engines/cursor/pendingTasks.ts
@@ -1,5 +1,6 @@
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
+import { PENDING_TASKS_FILE } from './contract.js'
export interface PendingCursorTask {
sessionId: string
@@ -8,7 +9,7 @@ export interface PendingCursorTask {
createdAt: number
}
-const FILE_NAME = 'cursor-pending-tasks.json'
+const FILE_NAME = PENDING_TASKS_FILE
const MAX_AGE_MS = 10 * 60_000
const LOCK_RETRIES = 20
const LOCK_RETRY_MS = 25
diff --git a/cli/src/engines/grok/inProcess.ts b/cli/src/engines/grok/inProcess.ts
index 23034562c..6c7ff9663 100644
--- a/cli/src/engines/grok/inProcess.ts
+++ b/cli/src/engines/grok/inProcess.ts
@@ -5,3 +5,4 @@
*/
export { GrokNormalizer, grokMessagesToEvents, lastGrokTurnText } from './normalizer.js'
export { parseGrokFooterProfile } from './runtimeProfile.js'
+export { findGrokTranscript } from './session.js'
diff --git a/cli/src/engines/hermes/contract.ts b/cli/src/engines/hermes/contract.ts
new file mode 100644
index 000000000..3c1dfb203
--- /dev/null
+++ b/cli/src/engines/hermes/contract.ts
@@ -0,0 +1,47 @@
+/**
+ * What the core knows of Hermes without loading its code: declared data (docs/design/2026-10-08-other-engines-out-of-
+ * core.md). It imports nothing of Hermes's code.
+ */
+import { join } from 'node:path'
+import type { StoreHomes } from '../kit/storeHomes.js'
+import type { StoreSourceRule } from '../kit/storeSource.js'
+
+/** The store a Hermes home keeps its sessions in. */
+export function hermesDbPath(home: string): string {
+ return join(home, 'state.db')
+}
+
+/**
+ * Every id a Hermes store keeps a conversation under: the CLI's and the gateway's (`YYYYMMDD_HHMMSS_<hex>`), and
+ * an editor's. The ACP adapter names its sessions with a uuid4 (`acp_adapter/session.py`; all six ACP rows on the
+ * machine measured were uuids), so their history is readable too. `hermesSessionSource` keeps the narrower shape:
+ * it decides whether a hook's session is a pane's own, and editors' sessions never are.
+ */
+export const HERMES_HISTORY_ID_RE =
+ /^(?:[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/
+
+/**
+ * Hermes keeps one store per home: `hermes -p <name>` runs against `~/.hermes/profiles/<name>`, with its own
+ * `state.db` (engines/hermes/home.ts). Listed by the kit (kit/storeHomes.ts) for the hook server, repair and the
+ * readers alike.
+ */
+export const HERMES_HOMES: StoreHomes = { profiles: 'profiles', store: hermesDbPath, max: 64, ttlMs: 30_000 }
+
+/**
+ * A Hermes sub-agent is a full Hermes session of its own and runs the same shell hooks, so it announces itself to
+ * the adapter from the parent's pane. Measured live: dispatching two sub-agents fired `on_session_start` for
+ * `20260805_111618_8e3027` / `…_0777bc` 0.2s after the parent's rows appeared, the pane re-bound to them, and the
+ * parent was `forgotten` mid-turn — taking its delegation bookkeeping and its sub-agent list with it.
+ * `sessions.source` separates them: 'cli'/'tui' for the real one, 'subagent'/'tool' for the children (`cwd` also
+ * points into `/tmp`, but source is the explicit marker). Read by the kit (kit/storeSource.ts) in the hook server.
+ *
+ * The ids are the CLI's and the gateway's, `YYYYMMDD_HHMMSS_<hex>` (6 hex chars for the CLI and the TUI, 8 for the
+ * gateway): an editor's sessions, never a pane's own, read as one.
+ */
+export const HERMES_SOURCE: StoreSourceRule = {
+ id: /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/,
+ query: 'SELECT source FROM sessions WHERE id = ?;',
+ column: 'source',
+ interactive: ['', 'cli', 'tui'],
+ maxBuffer: 1 << 20,
+}
diff --git a/cli/src/engines/hermes/home.ts b/cli/src/engines/hermes/home.ts
index 8543adde4..8aa04b7a6 100644
--- a/cli/src/engines/hermes/home.ts
+++ b/cli/src/engines/hermes/home.ts
@@ -22,23 +22,19 @@
*/
import { readdirSync, realpathSync, statSync } from 'node:fs'
-import { readdir, stat } from 'node:fs/promises'
import { isAbsolute, join } from 'node:path'
import { env } from '../../config/env.js'
+import { HERMES_HISTORY_ID_RE, HERMES_HOMES, hermesDbPath } from './contract.js'
+import { forgetStoreHomes, listStoreHomes } from '../kit/storeHomes.js'
import { sqliteReadAll } from '../../lib/sqliteRead.js'
import type { AgentEngine } from '../types.js'
-import { HERMES_HISTORY_ID_RE } from './reader.js'
/** `YYYYMMDD_HHMMSS_<hex>`, or an editor's (ACP) uuid — the shapes `reader.ts` reads history for. */
const SESSION_ID_RE = HERMES_HISTORY_ID_RE
-/** How long a homes listing is reused. A profile is created by hand, minutes apart; this is a `readdir`. */
-const HOMES_TTL_MS = 30_000
/** A person with hundreds of profile folders has a different problem; this keeps the scan bounded. */
const MAX_PROFILES = 64
-export function hermesDbPath(home: string): string {
- return join(home, 'state.db')
-}
+export { hermesDbPath } from './contract.js'
function canonical(path: string): string {
try { return realpathSync(path) } catch { return path }
@@ -49,30 +45,15 @@ export function sameHermesHome(a: string, b: string): boolean {
return canonical(a.replace(/\/+$/, '')) === canonical(b.replace(/\/+$/, ''))
}
-let homesCache: { at: number; homes: string[] } | null = null
-
/**
* Every home this machine has, the default first.
*
* A profile counts only once it has a `state.db`: before that there is nothing to read and nothing to
- * match a session against, and listing it would cost a failed query on every lookup.
+ * match a session against, and listing it would cost a failed query on every lookup. Declared (contract.ts) and
+ * listed by the kit, whose one listing the hook server's admission shares.
*/
export async function listHermesHomes(defaultHome = env.HERMES_HOME): Promise<string[]> {
- const now = Date.now()
- if (homesCache && now - homesCache.at < HOMES_TTL_MS) return homesCache.homes
- const homes = [defaultHome]
- try {
- const entries = await readdir(join(defaultHome, 'profiles'), { withFileTypes: true })
- for (const entry of entries.slice(0, MAX_PROFILES)) {
- if (!entry.isDirectory()) continue
- const home = join(defaultHome, 'profiles', entry.name)
- try {
- if ((await stat(hermesDbPath(home))).isFile()) homes.push(home)
- } catch { /* a profile whose first session has not started */ }
- }
- } catch { /* no profiles folder — the single-home machine, which is most of them */ }
- homesCache = { at: now, homes }
- return homes
+ return listStoreHomes(HERMES_HOMES, defaultHome)
}
/**
@@ -97,7 +78,7 @@ export function hermesConfigHomes(defaultHome = env.HERMES_HOME): string[] {
/** Forget the listing — for a test, and for an installer that has just made a profile. */
export function forgetHermesHomes(): void {
- homesCache = null
+ forgetStoreHomes(HERMES_HOMES)
}
/**
diff --git a/cli/src/engines/hermes/inProcess.ts b/cli/src/engines/hermes/inProcess.ts
index b10bf4427..7d41312b1 100644
--- a/cli/src/engines/hermes/inProcess.ts
+++ b/cli/src/engines/hermes/inProcess.ts
@@ -6,3 +6,6 @@
export { HermesReader, readHermesMessages } from './reader.js'
export { hermesMessagesToEvents, lastHermesTurnText, windowHermesMessages } from './normalizer.js'
export { HERMES_EFFORTS, hermesStatusModel, parseHermesConfig, parseHermesModelsCache, parseHermesPickerPage } from './runtimeProfile.js'
+// The half of Hermes's homes that fills the registry's row: Hermes's own lookup, run only for Hermes.
+export { hermesDbForSession } from '../../lib/hermesHome.js'
+export { probeHermesHome } from './homeProbe.js'
diff --git a/cli/src/engines/hermes/reader.ts b/cli/src/engines/hermes/reader.ts
index ad9fcdb99..7f30bcc80 100644
--- a/cli/src/engines/hermes/reader.ts
+++ b/cli/src/engines/hermes/reader.ts
@@ -13,21 +13,15 @@
import type { LiveEvent } from '../../lib/normalize.js'
import { sqliteReadAll } from '../../lib/sqliteRead.js'
+import { HERMES_HISTORY_ID_RE, HERMES_SOURCE } from './contract.js'
+import { isInteractiveSource, storeSessionSource } from '../kit/storeSource.js'
import {
messageToEvents, newHermesTurnState, isTerminalFinish,
type HermesTurnState, type HmMessage,
} from './normalizer.js'
-// `YYYYMMDD_HHMMSS_<hex>` — CLI/TUI use 6 hex chars, the gateway 8.
-const SESSION_ID_RE = /^[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}$/
-/**
- * Every id a Hermes store keeps a conversation under: the ones above, and an editor's. The ACP adapter
- * names its sessions with a uuid4 (`acp_adapter/session.py`; all six ACP rows on the machine measured
- * were uuids), so their history is readable too. `hermesSessionSource` keeps the narrower shape: it
- * decides whether a hook's session is a pane's own, and editors' sessions never are.
- */
-export const HERMES_HISTORY_ID_RE =
- /^(?:[0-9]{8}_[0-9]{6}_[0-9a-fA-F]{4,16}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/
+// Every id a Hermes store keeps a conversation under, declared (contract.ts): homes are found by it too.
+export { HERMES_HISTORY_ID_RE } from './contract.js'
const POLL_MS = 1_000
const MAX_BUFFER = 32 * 1024 * 1024
@@ -75,18 +69,11 @@ export async function readHermesMessages(
}
/**
- * True when this session id belongs to a DELEGATION CHILD rather than to the CLI the user is looking at.
- *
- * A hermes sub-agent is a full hermes session of its own and runs the same shell hooks, so it announces
- * itself to the adapter from the parent's pane. Measured live: dispatching two sub-agents fired
- * `on_session_start` for `20260805_111618_8e3027` / `…_0777bc` 0.2s after the parent's rows appeared, the
- * pane re-bound to them, and the parent was `forgotten` mid-turn — taking its delegation bookkeeping and
- * its sub-agent list with it. `sessions.source` separates them: 'cli'/'tui' for the real one, 'subagent'/'tool'
- * for the children (`cwd` also points into `/tmp`, but source is the explicit marker).
- *
+ * Whether a session's source is the CLI's the user is looking at rather than a DELEGATION CHILD's. Declared
+ * (contract.ts `HERMES_SOURCE`, which says why), read by the kit.
*/
export function isHermesInteractiveSource(source: string): boolean {
- return source === '' || source === 'cli' || source === 'tui'
+ return isInteractiveSource(HERMES_SOURCE, source)
}
export async function isHermesSubagentSession(dbPath: string, sessionId: string): Promise<boolean> {
@@ -95,21 +82,10 @@ export async function isHermesSubagentSession(dbPath: string, sessionId: string)
}
/**
- * `sessions.source` for one id, or null when the row is not there YET — which is a real state, not an
- * error: measured, a delegation child's `on_session_start` hook reached the adapter 110ms BEFORE hermes
- * inserted its row, so an immediate lookup said "not a sub-agent" and the child took over the pane.
- * Callers that can afford to wait should treat null as "ask again shortly".
- *
- * Read through `lib/sqliteRead` like every other query against this store: hermes writes to this DB
- * constantly, and the read's busy wait is bounded there so a contended lookup cannot park the daemon.
+ * `sessions.source` for one id, or null when the row is not there YET: ask again shortly (kit/storeSource.ts).
*/
export async function hermesSessionSource(dbPath: string, sessionId: string): Promise<string | null> {
- if (!SESSION_ID_RE.test(sessionId)) return ''
- const result = await sqliteReadAll(dbPath, 'SELECT source FROM sessions WHERE id = ?;', [sessionId], { maxBuffer: 1 << 20 })
- if (!result.ok) return '' // no reader / db locked — treat as a normal session, exactly as before
- if (result.rows.length === 0) return null
- const source = result.rows[0]?.source
- return typeof source === 'string' ? source : ''
+ return storeSessionSource(HERMES_SOURCE, dbPath, sessionId)
}
export interface HermesReaderDeps {
diff --git a/cli/src/engines/kit/notifyHooks.ts b/cli/src/engines/kit/notifyHooks.ts
index 0f1d18b8e..3ecd360e4 100644
--- a/cli/src/engines/kit/notifyHooks.ts
+++ b/cli/src/engines/kit/notifyHooks.ts
@@ -4,7 +4,7 @@ import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { env } from '../../config/env.js'
import { managedNodePath } from '../../lib/nodeRuntime.js'
-import { cursorDataDir } from '../cursor/home.js'
+import { cursorDataDir } from '../cursor/contract.js'
// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):
// - packaged/bundled: cli.js at ~/.harness/cli/cli.js → notify.mjs is a SIBLING (dist/ bundle too).
diff --git a/cli/src/engines/kit/storeHomes.ts b/cli/src/engines/kit/storeHomes.ts
new file mode 100644
index 000000000..f21507efb
--- /dev/null
+++ b/cli/src/engines/kit/storeHomes.ts
@@ -0,0 +1,48 @@
+/**
+ * The homes of an engine that keeps one store per home, as its contract declares them: the default, then each
+ * profile folder below it that has a store (Hermes: `~/.hermes` and `~/.hermes/profiles/<name>`). Listed for
+ * whoever reads those stores: the hook server's admission, repair and the readers share one listing per
+ * declaration, reused for its `ttlMs`.
+ *
+ * Moved from engines/hermes/home.ts (`listHermesHomes`), unchanged but for the declaration it reads.
+ */
+import { readdir, stat } from 'node:fs/promises'
+import { join } from 'node:path'
+
+export interface StoreHomes {
+ /** The folder below the default home whose folders are the other homes. */
+ profiles: string
+ /** A home's store. A profile counts as a home only once it has one: before that there is nothing to read. */
+ store: (home: string) => string
+ /** How many profile folders are looked at, at most: hundreds would be a different problem. */
+ max: number
+ /** How long a listing is reused. A profile is made by hand, minutes apart; this is a `readdir`. */
+ ttlMs: number
+}
+
+const listings = new WeakMap<StoreHomes, { at: number; homes: string[] }>()
+
+/** Every home, the default first. */
+export async function listStoreHomes(declared: StoreHomes, defaultHome: string): Promise<string[]> {
+ const now = Date.now()
+ const listed = listings.get(declared)
+ if (listed && now - listed.at < declared.ttlMs) return listed.homes
+ const homes = [defaultHome]
+ try {
+ const entries = await readdir(join(defaultHome, declared.profiles), { withFileTypes: true })
+ for (const entry of entries.slice(0, declared.max)) {
+ if (!entry.isDirectory()) continue
+ const home = join(defaultHome, declared.profiles, entry.name)
+ try {
+ if ((await stat(declared.store(home))).isFile()) homes.push(home)
+ } catch { /* a profile whose first session has not started */ }
+ }
+ } catch { /* no profiles folder — the single-home machine, which is most of them */ }
+ listings.set(declared, { at: now, homes })
+ return homes
+}
+
+/** Forget the listing — for a test, and for an installer that has just made a profile. */
+export function forgetStoreHomes(declared: StoreHomes): void {
+ listings.delete(declared)
+}
diff --git a/cli/src/engines/kit/storeSource.ts b/cli/src/engines/kit/storeSource.ts
new file mode 100644
index 000000000..d6324f261
--- /dev/null
+++ b/cli/src/engines/kit/storeSource.ts
@@ -0,0 +1,43 @@
+/**
+ * Whether a hook's session is a pane's own or one a session delegated to, read from the engine's store as its
+ * contract declares (Hermes: `sessions.source`). A delegated session runs its hooks from the parent's pane, so the
+ * hook server settles this before the session may take the pane (hookServer.ts `awaitHermesKind`).
+ *
+ * Moved from engines/hermes/reader.ts (`hermesSessionSource`, `isHermesInteractiveSource`), unchanged but for the
+ * declaration it reads. Read through `lib/sqliteRead` like every other query against such a store: the engine
+ * writes to it constantly, and the read's busy wait is bounded there so a contended lookup cannot park the daemon.
+ */
+import { sqliteReadAll } from '../../lib/sqliteRead.js'
+
+export interface StoreSourceRule {
+ /** The ids a pane's own session has. Any other (an editor's) reads as a pane's own: `''`. */
+ id: RegExp
+ /** The query for one id's row, with the id as its one parameter. */
+ query: string
+ /** The row's column that names its source. */
+ column: string
+ /** The sources of a pane's own session; any other is a delegated one's. */
+ interactive: readonly string[]
+ /** The most the read may return. */
+ maxBuffer: number
+}
+
+/**
+ * The source of one id's row, or null when the row is not there YET — which is a real state, not an error:
+ * measured, a Hermes delegation child's `on_session_start` hook reached the adapter 110ms BEFORE Hermes inserted
+ * its row, so an immediate lookup said "not a sub-agent" and the child took over the pane. Callers that can afford
+ * to wait should treat null as "ask again shortly".
+ */
+export async function storeSessionSource(rule: StoreSourceRule, dbPath: string, sessionId: string): Promise<string | null> {
+ if (!rule.id.test(sessionId)) return ''
+ const result = await sqliteReadAll(dbPath, rule.query, [sessionId], { maxBuffer: rule.maxBuffer })
+ if (!result.ok) return '' // no reader / db locked — treat as a normal session, exactly as before
+ if (result.rows.length === 0) return null
+ const source = result.rows[0]?.[rule.column]
+ return typeof source === 'string' ? source : ''
+}
+
+/** Whether a source is a pane's own session's. */
+export function isInteractiveSource(rule: StoreSourceRule, source: string): boolean {
+ return rule.interactive.includes(source)
+}
diff --git a/cli/src/engines/muse/inProcess.ts b/cli/src/engines/muse/inProcess.ts
index 215fe8687..447202fb7 100644
--- a/cli/src/engines/muse/inProcess.ts
+++ b/cli/src/engines/muse/inProcess.ts
@@ -5,3 +5,4 @@
*/
export { MuseNormalizer, lastMuseTurnText, museMessagesToEvents } from './normalizer.js'
export { parseMuseSettings } from './runtimeProfile.js'
+export { museEvent, museWorkspaceRoot } from './normalizer.js'
diff --git a/cli/src/engines/opencode/contract.ts b/cli/src/engines/opencode/contract.ts
new file mode 100644
index 000000000..4dc613107
--- /dev/null
+++ b/cli/src/engines/opencode/contract.ts
@@ -0,0 +1,12 @@
+/**
+ * What the core knows of OpenCode without loading its code: declared data, read in line where a launch is built
+ * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of OpenCode's code.
+ */
+
+/** The first major whose TUI rejects `-m` / `--agent` and whose sessions live behind its API. */
+const OPENCODE_V2_MAJOR = 2
+
+/** Whether a major version (`engines/opencode/version.ts` reads it) is v2 or later; unknown reads as v1. */
+export function isOpencodeV2(major: number | null | undefined): boolean {
+ return (major ?? 0) >= OPENCODE_V2_MAJOR
+}
diff --git a/cli/src/engines/opencode/inProcess.ts b/cli/src/engines/opencode/inProcess.ts
index db27f26dd..6a1c0317c 100644
--- a/cli/src/engines/opencode/inProcess.ts
+++ b/cli/src/engines/opencode/inProcess.ts
@@ -1,8 +1,11 @@
/**
* OpenCode's code the core runs in its own process, loaded only once one of OpenCode's sessions needs it
* (engines/inProcess.ts; docs/design/2026-10-08-other-engines-out-of-core.md). It re-exports, and holds no code of
- * its own: what the core calls is the engine's own, unchanged: its transcripts' readers, and its runtime profile's.
+ * its own: what the core calls is the engine's own, unchanged: its transcripts' readers, its runtime profile's, the
+ * probe of the installed version its launches are built for, and the writer of a session's model.
*/
export { OpencodeReader, readOpencodeMessages } from './reader.js'
export { lastOpencodeTurnText, opencodeMessagesToEvents, windowOpencodeMessages } from './normalizer.js'
export { countOpencodePickers, opencodeFooterModelId, opencodeRowMatches, opencodeRowNamesModel, parseOpencodeFooter, parseOpencodeModelsOutput, parseOpencodePickerRows } from './runtimeProfile.js'
+export { isOpencodeV2, opencodeMajorVersion } from './version.js'
+export { applyOpencodeSessionModel, parseOpencodeModelId } from './sessionModel.js'
diff --git a/cli/src/engines/opencode/version.ts b/cli/src/engines/opencode/version.ts
index aae865e2e..87af57f01 100644
--- a/cli/src/engines/opencode/version.ts
+++ b/cli/src/engines/opencode/version.ts
@@ -19,18 +19,13 @@ import { statSync } from 'node:fs'
import { opencodeBin } from '../../lib/engineBin.js'
import { resolveBinaryOnPath } from '../../lib/binaryOnPath.js'
-/** The first major whose TUI rejects `-m` / `--agent` and whose sessions live behind its API. */
-const OPENCODE_V2_MAJOR = 2
-
/** The major in what `opencode --version` prints: `opencode v2.0.18` on v2, a bare `1.18.31` on v1. */
export function parseOpencodeMajor(output: string): number | null {
const match = /(\d+)\.\d+\.\d+/.exec(output)
return match ? Number(match[1]) : null
}
-export function isOpencodeV2(major: number | null | undefined): boolean {
- return (major ?? 0) >= OPENCODE_V2_MAJOR
-}
+export { isOpencodeV2 } from './contract.js'
/** How the version is read. A seam so the cache can be specified without a binary. */
export interface OpencodeVersionProbe {
diff --git a/cli/src/engines/otherAdmission.golden.spec.ts b/cli/src/engines/otherAdmission.golden.spec.ts
new file mode 100644
index 000000000..f0235e628
--- /dev/null
+++ b/cli/src/engines/otherAdmission.golden.spec.ts
@@ -0,0 +1,187 @@
+/**
+ * How the core admits a Hermes session and learns its home, recorded from main before Hermes's admission and home
+ * probe left the core's static imports (docs/design/2026-10-08-other-engines-out-of-core.md, (o6)). Through the
+ * core's own entries:
+ *
+ * - the hook server: a Hermes hook is answered at once and settled off the HTTP path, by the `source` of its
+ * session's row in whichever home's store holds it: a pane's own session is registered (with its home, when that
+ * is not the default), a delegated one ignored, and one no store has yet registered after a bounded wait;
+ * - discovery (`probeTerminalAgents`): the home a live Hermes process names in its environment, and nothing for
+ * any other engine's.
+ *
+ * Every home is under a throwaway root named through the environment, pinned whatever the host sets; the process
+ * table and each process's environment are given, `TZ` is UTC, and no path's length matters. Results name the root
+ * `<root>`. `RECORD_OTHER_ENGINES_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter
+ * how Hermes's sessions are admitted or homed, and say so in that change.
+ */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import type { Server } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-admission.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'
+const START = 'Thu Oct 8 10:00:00 2026'
+
+// The process table and each process's environment, as the host would report them.
+const host = vi.hoisted(() => ({ rows: null as unknown[] | null, envs: new Map<number, Record<string, string> | null>() }))
+vi.mock('../lib/tmux.js', async (real) => ({
+ ...await real<object>(),
+ processRows: vi.fn(async () => host.rows),
+ enrichProcessRows: vi.fn(async (rows: unknown[]) => rows),
+}))
+vi.mock('../lib/processEnv.js', async (real) => ({
+ ...await real<object>(),
+ readProcessEnv: vi.fn(async (identity: { pid: number }) => host.envs.get(identity.pid) ?? null),
+}))
+
+let root = ''
+let golden: Record<string, unknown> = {}
+const recorded: Record<string, unknown> = {}
+const normalize = (value: unknown): unknown => JSON.parse(JSON.stringify(value ?? null).split(root).join('<root>'))
+function check(key: string, value: unknown): void {
+ const result = normalize(value)
+ recorded[key] = result
+ if (!RECORD) expect({ key, result }).toEqual({ key, result: golden[key] })
+}
+
+const saved: Record<string, string | undefined> = {}
+type Modules = {
+ registry: typeof import('../lib/registry.js')
+ hookServer: typeof import('../hookServer.js')
+ hookAuth: typeof import('../lib/hookAuth.js')
+ discovery: typeof import('../lib/terminalAgentDiscovery.js')
+}
+let m: Modules
+const home = (...parts: string[]) => join(root, 'home', ...parts)
+
+beforeAll(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'other-admission-golden-')))
+ const env: Record<string, string | undefined> = {
+ HOME: home(), ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'), HERMES_HOME: home('.hermes'),
+ CLAUDE_PROJECTS_DIR: home('.claude', 'projects'), CODEX_HOME: home('.codex'), CLAUDE_CONFIG_DIR: undefined, TZ: 'UTC',
+ }
+ for (const [name, value] of Object.entries(env)) {
+ saved[name] = process.env[name]
+ if (value === undefined) delete process.env[name]; else process.env[name] = value
+ }
+ for (const dir of ['data', 'runtime', join('home', '.claude', 'projects'), join('home', '.codex')]) mkdirSync(join(root, dir), { recursive: true })
+ vi.resetModules()
+ m = {
+ registry: await import('../lib/registry.js'),
+ hookServer: await import('../hookServer.js'),
+ hookAuth: await import('../lib/hookAuth.js'),
+ discovery: await import('../lib/terminalAgentDiscovery.js'),
+ }
+ m.registry.registry.load()
+ golden = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, unknown>
+})
+
+afterAll(() => {
+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value
+ if (root) rmSync(root, { recursive: true, force: true })
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(recorded, null, 1) + '\n')
+})
+
+describe('how the core admits a Hermes session and learns its home', () => {
+ it('admits a Hermes hook by its session\'s source, in whichever home\'s store holds it', async () => {
+ const { DatabaseSync } = (process as unknown as { getBuiltinModule(name: string): unknown }).getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; close(): void }
+ }
+ const store = (dir: string, rows: Array<[string, string]>) => {
+ mkdirSync(dir, { recursive: true })
+ const db = new DatabaseSync(join(dir, 'state.db'))
+ db.exec(`CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, cwd TEXT, started_at REAL);
+ ${rows.map(([id, source]) => `INSERT INTO sessions VALUES ('${id}', '${source}', '/work/h', 0);`).join('\n')}`)
+ db.close()
+ }
+ // The default home, a profile with a store, and one without: a profile is a home once a session has run in it.
+ store(home('.hermes'), [['20261008_100000_aaaaaa', 'cli'], ['20261008_100001_bbbbbb', 'tool'], ['20261008_100002_dddddd', 'cli']])
+ store(home('.hermes', 'profiles', 'work'), [['20261008_100003_cccccc', 'tui'], ['20261008_100004_eeeeee', ''], ['20261008_100002_dddddd', 'tool'], ['20261008_100005_ffffff', 'delegate']])
+ mkdirSync(home('.hermes', 'profiles', 'empty'), { recursive: true })
+ writeFileSync(home('.hermes', 'profiles', 'empty', 'config.yaml'), '')
+
+ const registered: unknown[] = []
+ const logs: string[] = []
+ const log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(' ')) })
+ let server: Server | null = null
+ try {
+ const started = await m.hookServer.startHookServer(0, {
+ onRegistered: (entry) => { registered.push({ sessionId: entry.sessionId, engine: entry.engine, hermesHome: entry.hermesHome ?? null }) },
+ onSessionEnd: () => {},
+ })
+ server = started.server
+ const headers = { 'content-type': 'application/json', 'x-harness-hook-token': m.hookAuth.readHookCredential(join(root, 'data'))! }
+ const results: unknown[] = []
+ const cases = [
+ ['the default home\'s CLI session', '20261008_100000_aaaaaa'],
+ ['a session one delegated to', '20261008_100001_bbbbbb'],
+ ['a profile\'s TUI session', '20261008_100003_cccccc'],
+ ['a profile\'s session with no source', '20261008_100004_eeeeee'],
+ ['a profile\'s delegated session', '20261008_100005_ffffff'],
+ ['one in both homes: the default asked first', '20261008_100002_dddddd'],
+ ['an editor\'s session, whose id is a uuid', '0b6f4f2e-6c1a-4c55-9a51-000000000001'],
+ ['one no store holds yet', '20261008_100009_999999'],
+ ] as const
+ let pane = 0
+ for (const [label, sessionId] of cases) {
+ const tmuxPane = `%${++pane}`
+ m.registry.registry.openProcessAgent({ engine: 'hermes', tmuxPane, cwd: '/work/h', processIdentity: { pid: 20_000 + pane, startMarker: START, executable: 'python3' } })
+ registered.length = 0
+ logs.length = 0
+ const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/session-start`, {
+ method: 'POST', headers, body: JSON.stringify({ engine: 'hermes', tmuxPane, sessionId, cwd: '/work/h', hookEvent: 'SessionStart' }),
+ })
+ const answer = await response.json()
+ // Settled off the HTTP path: registered, or ignored, within the bounded wait for a row.
+ const deadline = Date.now() + 10_000
+ while (!registered.length && !logs.some((line) => line.includes('ignored')) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))
+ results.push([label, response.status, answer, [...registered], logs.filter((line) => line.startsWith('[hooks]'))])
+ }
+ check('admission', results)
+ } finally {
+ log.mockRestore()
+ if (server) await new Promise<void>((resolve) => server!.close(() => resolve()))
+ }
+ }, 120_000)
+
+ it('reads a Hermes process\'s home off its environment, and nothing for another engine\'s', async () => {
+ const row = (pid: number, parentPid: number, executable: string, args = executable) => ({ pid, parentPid, executable, args, startMarker: START })
+ const panes = [
+ ['a profile', { HERMES_HOME: home('.hermes', 'profiles', 'work') }],
+ ['the default', { HERMES_HOME: home('.hermes') }],
+ ['the default, with a trailing slash', { HERMES_HOME: `${home('.hermes')}/` }],
+ ['a relative path', { HERMES_HOME: 'profiles/work' }],
+ ['a path with a control character', { HERMES_HOME: `${home('.hermes')}\u0007x` }],
+ ['none', {}],
+ ['an environment that could not be read', null],
+ ] as const
+ host.rows = []
+ host.envs.clear()
+ const roots: Array<{ runtime: { backend: 'tmux'; paneId: string }; rootPid: number; cwd: string }> = []
+ panes.forEach(([, processEnv], i) => {
+ const shell = 100 + i * 10
+ host.rows!.push(row(shell, 1, 'zsh'), row(shell + 1, shell, 'python3', '/opt/hermes-agent/hermes'))
+ host.envs.set(shell + 1, processEnv as Record<string, string> | null)
+ roots.push({ runtime: { backend: 'tmux', paneId: `%${50 + i}` }, rootPid: shell, cwd: '/work/h' })
+ })
+ // Another engine's process, under a Hermes variable it does not read.
+ host.rows.push(row(900, 1, 'zsh'), row(901, 900, 'claude'))
+ host.envs.set(901, { HERMES_HOME: home('.hermes', 'profiles', 'work') })
+ roots.push({ runtime: { backend: 'tmux', paneId: '%90' }, rootPid: 900, cwd: '/work/h' })
+ const backend = { name: 'tmux', instanceId: 'tmux', inventory: async () => ({ state: 'available', roots }) }
+ const probe = await m.discovery.probeTerminalAgents([backend as never], ['tmux'], 999_999)
+ const byPane = new Map(probe.agents.map((agent) => [agent.primaryRuntimeKey, agent]))
+ check('home probe', [...panes.map(([label], i) => [label, `%${50 + i}`] as const), ['claude', '%90'] as const].map(([label, paneId]) => {
+ const agent = [...byPane.values()].find((one) => one.runtimes.some((runtime) => runtime.paneId === paneId))
+ return [label, agent ? { engine: agent.engine, hermesHome: agent.hermesHome === undefined ? 'undefined' : agent.hermesHome } : 'no agent']
+ }))
+ }, 60_000)
+
+ it('has a recorded outcome for every case, and no other', () => {
+ if (RECORD) return
+ expect(Object.keys(recorded).sort()).toEqual(Object.keys(golden).sort())
+ })
+})
diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.ts
new file mode 100644
index 000000000..ec9f4fcc6
--- /dev/null
+++ b/cli/src/engines/otherIdentity.golden.spec.ts
@@ -0,0 +1,272 @@
+/**
+ * Where the core finds the twelve other engines' conversations, recorded from main before their layouts, homes
+ * and finders left the core's static imports (docs/design/2026-10-08-other-engines-out-of-core.md, (o6)). Through
+ * the core's own entries:
+ *
+ * - the registry: the transcript a hook's session is bound to (`register`, derived from each layout when the hook
+ * names none), which transcripts it accepts (`validTranscriptPath`) and which engines keep one;
+ * - binding a process that names its session on its command line, and Copilot's `/resume` (`createBinding`);
+ * - repair: the session a live process is running, found by its folder, its store or its lock (`findLiveSession`),
+ * and a resumed Pi conversation (`findResumedTranscript`);
+ * - Cursor's homes, and the hook command that names them.
+ *
+ * Every home is under a throwaway root named through the environment, which is pinned whatever the host sets;
+ * file times are set, the clock and `process.platform` pinned (agy is asked about a process that does not exist,
+ * through /proc, on every host), `TZ` is UTC, and no path's length matters. Results name the root `<root>`. One case
+ * runs on the host's own platform: agy's lock, held open by this very process, read as each platform reads it.
+ *
+ * `RECORD_OTHER_ENGINES_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter where these
+ * engines' conversations are found, and say so in that change.
+ */
+import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import type { AgentEngine } from './types.js'
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-identity.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'
+const NOW = Date.parse('2026-10-08T12:00:00.000Z')
+const T0 = NOW - 60 * 60_000
+const UUID = (n: number) => `0b6f4f2e-6c1a-4c55-9a51-${String(n).padStart(12, '0')}`
+const ENGINES = ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok', 'agy', 'copilot', 'terminal'] as const
+
+let root = ''
+let golden: Record<string, unknown> = {}
+const recorded: Record<string, unknown> = {}
+const normalize = (value: unknown): unknown => JSON.parse(JSON.stringify(value ?? null).split(root).join('<root>'))
+function check(key: string, value: unknown): void {
+ const result = normalize(value)
+ recorded[key] = result
+ if (!RECORD) expect({ key, result }).toEqual({ key, result: golden[key] })
+}
+let fileTime = T0
+/** A file, written, whose modification time is the next tick of a fixed clock: a scan's newest-first order is set. */
+function file(path: string, text = ''): string {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, text)
+ fileTime += 1000
+ utimesSync(path, fileTime / 1000, fileTime / 1000)
+ return path
+}
+
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const saved: Record<string, string | undefined> = {}
+type Modules = {
+ registry: typeof import('../lib/registry.js')
+ repair: typeof import('../lib/sessionRepair.js')
+ bind: typeof import('../core/agents/bind.js')
+ notify: typeof import('./kit/notifyHooks.js')
+ home: typeof import('./cursor/home.js')
+}
+let m: Modules
+
+beforeAll(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'other-identity-golden-')))
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.useFakeTimers({ toFake: ['Date'], now: NOW })
+ const home = join(root, 'home')
+ const env: Record<string, string | undefined> = {
+ HOME: home, XDG_CONFIG_HOME: undefined, XDG_DATA_HOME: undefined, ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'),
+ CLAUDE_PROJECTS_DIR: join(home, '.claude', 'projects'), CODEX_HOME: join(home, '.codex'), CLAUDE_CONFIG_DIR: undefined,
+ AGY_HOME: join(home, '.gemini', 'antigravity-cli'), AGY_CONFIG_DIR: undefined, COPILOT_HOME: join(home, '.copilot'),
+ GROK_HOME: join(home, '.grok'), CURSOR_HOME: join(home, '.cursor'), CURSOR_DATA_DIR: undefined, CURSOR_CONFIG_DIR: undefined,
+ COMMANDCODE_HOME: join(home, '.commandcode'), MUSE_HOME: join(home, '.muse'), PI_HOME: join(home, '.pi'), HERMES_HOME: join(home, '.hermes'),
+ AMP_SESSIONS_DIR: join(root, 'data', 'amp-sessions'), OPENCODE_DATA_DIR: join(home, '.local', 'share', 'opencode'),
+ KILO_DATA_DIR: join(home, '.local', 'share', 'kilo'), DEVIN_HOME: join(home, '.local', 'share', 'devin', 'cli'), TZ: 'UTC',
+ }
+ for (const [name, value] of Object.entries(env)) {
+ saved[name] = process.env[name]
+ if (value === undefined) delete process.env[name]; else process.env[name] = value
+ }
+ for (const dir of ['data', 'runtime', join('home', '.claude', 'projects'), join('home', '.codex')]) mkdirSync(join(root, dir), { recursive: true })
+ vi.resetModules()
+ m = {
+ registry: await import('../lib/registry.js'),
+ repair: await import('../lib/sessionRepair.js'),
+ bind: await import('../core/agents/bind.js'),
+ notify: await import('./kit/notifyHooks.js'),
+ home: await import('./cursor/home.js'),
+ }
+ m.registry.registry.load()
+ golden = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, unknown>
+})
+
+afterAll(() => {
+ vi.useRealTimers()
+ Object.defineProperty(process, 'platform', platform)
+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value
+ if (root) rmSync(root, { recursive: true, force: true })
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(recorded, null, 1) + '\n')
+})
+
+const home = (...parts: string[]) => join(root, 'home', ...parts)
+let pane = 0
+/** A hook's session, registered as the registry takes it: its process opened on a pane first. */
+function register(engine: AgentEngine, input: { sessionId: string; cwd?: string; transcriptPath?: string }) {
+ const tmuxPane = `%${++pane}`
+ const processIdentity = { pid: 10_000 + pane, startMarker: `Mon Oct 8 10:00:${String(pane % 60).padStart(2, '0')} 2026`, executable: engine }
+ m.registry.registry.openProcessAgent({ engine, tmuxPane, cwd: input.cwd ?? null, processIdentity })
+ const result = m.registry.registry.register({ engine, tmuxPane, processIdentity, ...input })
+ return result && { transcriptPath: result.entry.transcriptPath, cwd: result.entry.cwd, sessionId: result.entry.sessionId }
+}
+
+describe('where the core finds the other engines\' conversations', () => {
+ it('derives each layout\'s transcript for a hook that names none, and takes one it names only in its own folder', () => {
+ const cwds = ['/work/My Project', '/work/camelCaseRepo', '/work/über-ünïcødé', '/', '/work/a/../b']
+ const results: unknown[] = []
+ for (const engine of ['commandcode', 'grok', 'agy', 'copilot', 'cursor', 'pi', 'muse', 'amp'] as const) {
+ for (const [i, cwd] of cwds.entries()) {
+ for (const sessionId of [UUID(i + 1), 'not-a-uuid', '../escape', 'with space']) {
+ results.push([engine, cwd, sessionId, register(engine, { sessionId, cwd })])
+ }
+ }
+ // A transcript the hook names: inside each engine's folder, and outside it.
+ const inside: Record<string, string> = {
+ commandcode: home('.commandcode', 'projects', 'work-x', `${UUID(90)}.jsonl`),
+ grok: home('.grok', 'sessions', encodeURIComponent('/work/x'), UUID(90), 'updates.jsonl'),
+ agy: home('.gemini', 'antigravity-cli', 'brain', UUID(90), '.system_generated', 'logs', 'transcript_full.jsonl'),
+ copilot: home('.copilot', 'session-state', UUID(90), 'events.jsonl'),
+ cursor: home('.cursor', 'projects', 'work-x', 'agent-transcripts', UUID(90), `${UUID(90)}.jsonl`),
+ pi: home('.pi', 'agent', 'sessions', '--work-x--', `2026_${UUID(90)}.jsonl`),
+ muse: home('.muse', 'sessions', '2026', '10', '08', UUID(90), 'session.jsonl'),
+ amp: join(root, 'data', 'amp-sessions', `T-${UUID(90)}.jsonl`),
+ }
+ file(inside[engine]!, '{}\n')
+ const outside = file(join(root, 'elsewhere', `${engine}.jsonl`), '{}\n')
+ results.push([engine, 'named inside', register(engine, { sessionId: UUID(90), cwd: '/work/x', transcriptPath: inside[engine] })])
+ results.push([engine, 'named outside', register(engine, { sessionId: UUID(91), cwd: '/work/x', transcriptPath: outside })])
+ }
+ check('register', results)
+ }, 120_000)
+
+ it('accepts a transcript only in its engine\'s folders, and says which engines keep one', () => {
+ const paths = [
+ home('.commandcode', 'projects', 'p', `${UUID(1)}.jsonl`),
+ home('.grok', 'sessions', 'x', UUID(1), 'updates.jsonl'),
+ home('.gemini', 'antigravity-cli', 'brain', UUID(1), '.system_generated', 'logs', 'transcript_full.jsonl'),
+ home('.copilot', 'session-state', UUID(1), 'events.jsonl'),
+ home('.cursor', 'projects', 'p', 'agent-transcripts', UUID(1), `${UUID(1)}.jsonl`),
+ home('.cursor', 'projects', 'p', 'agent-transcripts', UUID(1), `${UUID(2)}.jsonl`),
+ home('.cursor', 'projects', 'p', 'transcripts', UUID(1), `${UUID(1)}.jsonl`),
+ home('.pi', 'agent', 'sessions', 'p', 'x.jsonl'),
+ home('.muse', 'sessions', 's.jsonl'),
+ join(root, 'data', 'amp-sessions', 'T-1.jsonl'),
+ ].map((path) => file(path, '{}\n'))
+ const missing = home('.copilot', 'session-state', UUID(5), 'events.jsonl')
+ mkdirSync(join(missing, '..'), { recursive: true })
+ check('valid transcripts', ENGINES.map((engine) => [engine, m.registry.engineKeepsTranscriptFile(engine),
+ [...paths, missing].map((path) => m.registry.validTranscriptPath(engine, path)),
+ m.registry.validTranscriptPath(engine, missing, undefined, true)]))
+ })
+
+ it('names Cursor\'s homes as its environment does, and the hook command with them', () => {
+ const variants: NodeJS.ProcessEnv[] = [{}, { CURSOR_DATA_DIR: '/data/cursor' }, { CURSOR_CONFIG_DIR: '/config/cursor' }, { XDG_CONFIG_HOME: '/xdg' },
+ { CURSOR_CONFIG_DIR: ' ', XDG_CONFIG_HOME: ' /xdg2 ', CURSOR_DATA_DIR: ' ' }]
+ check('cursor homes', variants.map((vars) => [vars, m.home.cursorConfigDir(vars), m.home.cursorDataDir(vars)]))
+ check('hook command', m.notify.command(19473, 'cursor').split(m.notify.HOOK_SCRIPT).join('<script>').split(process.execPath).join('<node>'))
+ })
+
+ it('binds a process that names its session, and follows Copilot\'s /resume', async () => {
+ file(home('.cursor', 'projects', 'p', 'agent-transcripts', UUID(31), `${UUID(31)}.jsonl`), '{}\n')
+ file(home('.grok', 'sessions', encodeURIComponent('/work/g'), UUID(32), 'updates.jsonl'), '{}\n')
+ file(home('.gemini', 'antigravity-cli', 'brain', UUID(33), '.system_generated', 'logs', 'transcript_full.jsonl'), '{}\n')
+ file(home('.copilot', 'session-state', UUID(34), 'events.jsonl'), '{}\n')
+ file(home('.copilot', 'session-state', UUID(35), 'inuse.4242.lock'))
+ file(home('.copilot', 'session-state', UUID(35), 'events.jsonl'), '{}\n')
+ const registered: unknown[] = []
+ const agents = new Map<string, Record<string, unknown>>()
+ const binding = m.bind.createBinding({
+ registry: {
+ inheritName: () => {}, unbindSession: () => true, byAgent: (id: string) => agents.get(id),
+ byProcess: (engine: string) => agents.get(engine), has: () => false, bySession: () => undefined,
+ register: (input: unknown) => { registered.push(input); return null },
+ } as never,
+ mirror: { inheritSummary: () => {} }, forgetSession: () => {}, clients: { send: () => {} }, attachSession: async () => true,
+ announceSession: () => {}, stoppedAgents: { save: () => {}, finishResume: () => {}, get: () => null } as never, syncRecapPool: () => {},
+ teams: { forget: () => {} } as never, input: { forget: () => {} } as never, deviceInput: { forget: () => {} } as never,
+ homes: { copilot: home('.copilot'), grok: home('.grok'), agy: home('.gemini', 'antigravity-cli') },
+ })
+ const observed = (engine: string, over: Record<string, unknown>) => ({
+ engine, cwd: '/work/g', runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux:%1',
+ processIdentity: { pid: 4242, startMarker: 'Mon Oct 8 10:00:00 2026', executable: engine }, ...over,
+ })
+ const results: unknown[] = []
+ const ids: Record<string, string[]> = { cursor: [UUID(31), UUID(39)], grok: [UUID(32), UUID(39)], agy: [UUID(33), UUID(39)], copilot: [UUID(34), UUID(39)] }
+ for (const [engine, sessions] of Object.entries(ids)) {
+ for (const resumeSessionId of sessions) {
+ agents.clear(); agents.set(engine, { agentId: `agent-${engine}`, engine, sessionId: '', registeredAt: 0 })
+ registered.length = 0
+ await binding.bindObservedAgent(observed(engine, { resumeSessionId }) as never)
+ results.push([engine, resumeSessionId, [...registered]])
+ }
+ }
+ agents.clear(); agents.set('copilot', { agentId: 'agent-copilot', engine: 'copilot', sessionId: UUID(34), registeredAt: 0 })
+ registered.length = 0
+ await binding.bindObservedAgent(observed('copilot', {}) as never)
+ results.push(['copilot /resume', [...registered]])
+ check('bind', results)
+ }, 60_000)
+
+ it('repairs a live process\'s session: by folder, by store, by its lock, and a resumed Pi conversation', async () => {
+ const since = T0
+ // Pi, Command Code and Amp name the folder on their first line; Muse its workspace, once a run has opened.
+ file(home('.pi', 'agent', 'sessions', '--work-r--', `2026_${UUID(41)}.jsonl`), `${JSON.stringify({ type: 'session', id: UUID(41), cwd: '/work/r' })}\n`)
+ file(home('.commandcode', 'projects', 'work-r', `${UUID(42)}.jsonl`), `${JSON.stringify({ cwd: '/work/r', sessionId: UUID(42) })}\n`)
+ file(join(root, 'data', 'amp-sessions', `T-${UUID(43)}.jsonl`), `${JSON.stringify({ t: 'session', threadId: `T-${UUID(43)}`, cwd: '/work/r' })}\n`)
+ const museRun = [JSON.stringify({ payload: { kind: 'session', record: { workspace_root: '/work/r' } } }), JSON.stringify({ payload: { kind: 'run', event: { kind: 'started' } } })]
+ file(home('.muse', 'sessions', '2026', '10', '08', UUID(44), 'session.jsonl'), `${museRun.join('\n')}\n`)
+ file(home('.muse', 'sessions', '2026', '10', '08', UUID(45), 'session.jsonl'), `${museRun[0]}\n`)
+ file(home('.grok', 'sessions', encodeURIComponent('/work/r'), UUID(46), 'updates.jsonl'), '{}\n')
+ file(home('.copilot', 'session-state', UUID(47), 'events.jsonl'), `${JSON.stringify({ type: 'session.start', data: { context: { cwd: '/work/r' } } })}\n`)
+ file(home('.copilot', 'session-state', UUID(48), 'inuse.5151.lock'))
+ // Hermes: a store per home, the default and a profile's.
+ const { DatabaseSync } = (process as unknown as { getBuiltinModule(name: string): unknown }).getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; close(): void }
+ }
+ // Both claim /work/both, which is ambiguous; each has one of its own.
+ for (const [store, id, cwd] of [[home('.hermes', 'state.db'), '20261008_110000_a1b2', '/work/r'], [home('.hermes', 'profiles', 'work', 'state.db'), '20261008_110500_c3d4', '/work/p']] as const) {
+ mkdirSync(join(store, '..'), { recursive: true })
+ const db = new DatabaseSync(store)
+ db.exec(`CREATE TABLE sessions (id TEXT PRIMARY KEY, cwd TEXT, started_at REAL, source TEXT);
+ INSERT INTO sessions VALUES ('${id}', '${cwd}', ${(since + 120_000) / 1000}, 'cli'), ('${id}0', '/work/both', ${(since + 120_000) / 1000}, 'cli');`)
+ db.close()
+ }
+ const results: unknown[] = []
+ for (const engine of ['pi', 'commandcode', 'amp', 'muse', 'grok', 'copilot', 'hermes', 'agy'] as const) {
+ for (const opts of [undefined, { bornOnly: true }, { pid: 5151 }, { pid: 99_999_999 }]) {
+ results.push([engine, opts ?? null, await m.repair.findLiveSession(engine, '/work/r', since, opts).catch((error: Error) => `threw ${error.message}`)])
+ }
+ }
+ for (const cwd of ['/work/p', '/work/both', '/work/none']) {
+ results.push(['hermes', cwd, await m.repair.findLiveSession('hermes', cwd, since).catch((error: Error) => `threw ${error.message}`)])
+ }
+ for (const [sessionId, cwd] of [[UUID(41), '/work/r'], [UUID(41), '/work/other'], [UUID(49), '/work/r'], ['bad id', '/work/r']] as const) {
+ results.push(['pi resumed', sessionId, cwd, await m.repair.findResumedTranscript('pi', sessionId, { cwd }).catch((error: Error) => `threw ${error.message}`)])
+ }
+ check('repair', results)
+ }, 60_000)
+
+ it('repairs agy\'s session from the lock its live process holds open, read as the host reads it', async () => {
+ const id = UUID(50)
+ file(home('.gemini', 'antigravity-cli', 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl'), '{}\n')
+ const lock = file(home('.gemini', 'antigravity-cli', 'presence', `${id}.lock`))
+ const results: unknown[] = []
+ // Linux reads /proc, any other host lsof: this process's own descriptors, the same on both.
+ Object.defineProperty(process, 'platform', platform)
+ try {
+ const held = openSync(lock, 'r')
+ try {
+ results.push(['held', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: process.pid })])
+ } finally { closeSync(held) }
+ results.push(['let go', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: process.pid })])
+ } finally { Object.defineProperty(process, 'platform', { ...platform, value: 'linux' }) }
+ check('repair agy lock', results)
+ }, 60_000)
+
+ it('has a recorded outcome for every case, and no other', () => {
+ if (RECORD) return
+ expect(Object.keys(recorded).sort()).toEqual(Object.keys(golden).sort())
+ })
+})
diff --git a/cli/src/engines/otherLaunch.golden.spec.ts b/cli/src/engines/otherLaunch.golden.spec.ts
new file mode 100644
index 000000000..3d705d3ca
--- /dev/null
+++ b/cli/src/engines/otherLaunch.golden.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * How the core asks which OpenCode is installed when an agent is asked for as a named agent, recorded from main
+ * before OpenCode's version probe left the core's static imports (docs/design/2026-10-08-other-engines-out-of-
+ * core.md, (o6)). Through the core's own entry for `agent_create` (`createLaunchRequests`), with OpenCode's real
+ * probe run against an installed v1, an installed v2 and none at all: v2's TUI exits on `--agent`, so it is
+ * refused before any pane exists, and every other engine is answered without asking.
+ *
+ * The OpenCode binaries are scripts under a throwaway root (`OPENCODE_PATH`), every home is pinned through the
+ * environment, `TZ` is UTC, and no path's length matters. Results name the root `<root>`. The argv each launch
+ * is built with is (c1)'s launchArgv.golden.spec.ts. `RECORD_OTHER_ENGINES_GOLDEN=1` writes the fixture.
+ */
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-launch.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'
+
+let root = ''
+let golden: Record<string, unknown> = {}
+const recorded: Record<string, unknown> = {}
+const normalize = (value: unknown): unknown => JSON.parse(JSON.stringify(value ?? null).split(root).join('<root>'))
+function check(key: string, value: unknown): void {
+ const result = normalize(value)
+ recorded[key] = result
+ if (!RECORD) expect({ key, result }).toEqual({ key, result: golden[key] })
+}
+
+const saved: Record<string, string | undefined> = {}
+function setEnv(values: Record<string, string | undefined>): void {
+ for (const [name, value] of Object.entries(values)) {
+ if (!(name in saved)) saved[name] = process.env[name]
+ if (value === undefined) delete process.env[name]; else process.env[name] = value
+ }
+}
+
+beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'other-launch-golden-')))
+ const home = join(root, 'home')
+ setEnv({
+ HOME: home, ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'), CLAUDE_CONFIG_DIR: join(home, '.claude'),
+ CLAUDE_PROJECTS_DIR: join(home, '.claude', 'projects'), CODEX_HOME: join(home, '.codex'), TZ: 'UTC',
+ })
+ for (const dir of ['data', 'runtime', 'work', join('home', '.claude', 'projects'), join('home', '.codex')]) mkdirSync(join(root, dir), { recursive: true })
+ for (const [version, prints] of [['v1', '1.18.31'], ['v2', 'opencode v2.0.18']]) {
+ mkdirSync(join(root, 'bin', version), { recursive: true })
+ writeFileSync(join(root, 'bin', version, 'opencode'), `#!/bin/sh\necho "${prints}"\n`)
+ chmodSync(join(root, 'bin', version, 'opencode'), 0o755)
+ }
+ golden = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, unknown>
+})
+
+afterAll(() => {
+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value
+ if (root) rmSync(root, { recursive: true, force: true })
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(recorded, null, 1) + '\n')
+})
+
+describe('which OpenCode the core asks for, for a named agent', () => {
+ it('refuses a named agent on OpenCode v2 before any pane exists, and asks nothing for any other engine', async () => {
+ let receipts = 0
+ for (const [installed, path] of [['v1', join(root, 'bin', 'v1', 'opencode')], ['v2', join(root, 'bin', 'v2', 'opencode')], ['none', join(root, 'bin', 'none', 'opencode')]] as const) {
+ setEnv({ OPENCODE_PATH: path })
+ vi.resetModules()
+ const { createLaunchRequests } = await import('../core/agents/launches.js')
+ const { AgentCreationReceipts } = await import('../lib/agentCreationReceipt.js')
+ const asked: unknown[] = []
+ const requests = createLaunchRequests({
+ receipts: new AgentCreationReceipts(join(root, 'data', `receipts-${++receipts}`)),
+ createAgent: () => async (request) => {
+ asked.push({ engine: request.engine, agent: request.agent, name: request.name })
+ return { ok: false, error: 'RECORDED' }
+ },
+ forkAgent: () => null, resumeAgent: () => null, restartAgent: () => null,
+ byAgent: () => undefined, toProject: async () => ({}) as never, modelTarget: async () => null as never,
+ })
+ const results: unknown[] = []
+ for (const engine of ['opencode', 'claude', 'pi', 'cursor'] as const) {
+ for (const agent of ['harness-compute', null] as const) {
+ asked.length = 0
+ let answer: unknown = null
+ await requests.create({ engine, cwd: join(root, 'work'), agent, name: 'Named' }, { local: true }, (result) => { answer = result })
+ results.push([engine, agent, answer, [...asked]])
+ }
+ }
+ check(`agent_create · OpenCode ${installed}`, results)
+ }
+ }, 120_000)
+
+ it('has a recorded outcome for every case, and no other', () => {
+ if (RECORD) return
+ expect(Object.keys(recorded).sort()).toEqual(Object.keys(golden).sort())
+ })
+})
diff --git a/cli/src/engines/pi/inProcess.ts b/cli/src/engines/pi/inProcess.ts
index 284fb0a32..9717ac333 100644
--- a/cli/src/engines/pi/inProcess.ts
+++ b/cli/src/engines/pi/inProcess.ts
@@ -5,3 +5,4 @@
*/
export { PiNormalizer, lastPiTurnText, piMessagesToEvents, windowPiLines } from './normalizer.js'
export { PI_EFFORTS, PI_THINKING_LEVELS, parsePiFooterProfile, parsePiModelsOutput, parsePiThinkingSelection, piThinkingSteps } from './runtimeProfile.js'
+export { piSessionFolder, readPiHead } from '../../lib/sessionSearch/externals/pi.js'
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index ef5666cbc..4daa4f7d0 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -9,8 +9,9 @@ import { join } from 'node:path'
import http from 'node:http'
import type { AddressInfo } from 'node:net'
import { admitHook, hooksFor } from './engines/hooks.js'
-import { hermesSessionSource, isHermesInteractiveSource } from './engines/hermes/reader.js'
-import { hermesDbPath, listHermesHomes } from './engines/hermes/home.js'
+import { HERMES_HOMES, HERMES_SOURCE, hermesDbPath } from './engines/hermes/contract.js'
+import { listStoreHomes } from './engines/kit/storeHomes.js'
+import { isInteractiveSource, storeSessionSource } from './engines/kit/storeSource.js'
import { isRecentlyDeleted } from './lib/deletedSessions.js'
import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'
import { sid } from './lib/log.js'
@@ -365,8 +366,10 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
// EVERY home, not just the default. A `hermes -p <name>` session's row lives in that profile's own
// store, so asking the default one answered `null` (unknown) six times and fell through — and, worse,
- // the home found here is the one the whole row then reads its history from (openharness#191).
- const homes = await listHermesHomes()
+ // the home found here is the one the whole row then reads its history from (openharness#191). Hermes's homes
+ // and the source that tells a delegated session are declared (engines/hermes/contract.ts) and read by the kit:
+ // admission never waits for Hermes's code.
+ const homes = await listStoreHomes(HERMES_HOMES, env.HERMES_HOME)
let hermesHome: string | undefined
for (let i = 0; i < HERMES_KIND_TRIES; i++) {
if (i > 0) await new Promise((resolve) => { const t = setTimeout(resolve, HERMES_KIND_WAIT_MS); t.unref?.() })
@@ -374,14 +377,14 @@ async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers
if (isRecentlyDeleted(body.sessionId)) return
let source: string | null = null
for (const home of homes) {
- const answer = await hermesSessionSource(hermesDbPath(home), body.sessionId ?? '')
+ const answer = await storeSessionSource(HERMES_SOURCE, hermesDbPath(home), body.sessionId ?? '')
if (answer === null) continue // not in this store — try the next home
source = answer
if (home !== env.HERMES_HOME) hermesHome = home
break
}
if (source === null) continue
- if (!isHermesInteractiveSource(source)) {
+ if (!isInteractiveSource(HERMES_SOURCE, source)) {
console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · hermes_subagent`)
return
}
diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.ts
index addf490c8..ce38d355a 100644
--- a/cli/src/leanEntry.spec.ts
+++ b/cli/src/leanEntry.spec.ts
@@ -90,13 +90,16 @@ describe('the lean bundle a release carries', () => {
it.each([
// Each a string its module alone holds: lib/questionPane.ts's, lib/hooks.ts's (its Amp plugin's), Amp's thread
// export's (engines/amp/threadExport.ts), and the name the bundle keeps for Cursor's sub-agents' reader
- // (engines/cursor/subagent.ts) and Devin's switch reader (engines/devin/runtimeProfile.ts), which the core's
- // own files only call.
+ // (engines/cursor/subagent.ts), Devin's switch reader (engines/devin/runtimeProfile.ts), agy's lock reader
+ // (engines/agy/session.ts) and Cursor's discovery (engines/cursor/discovery.ts), which the core's own files only
+ // call.
['pane readers', 'Native screen reader must be injected'],
['hook installers', 'Mirrors this Amp thread to the machine adapter'],
['own code: Amp\'s', 'AMP_DISABLE_PLUGINS'],
['own code: Cursor\'s', '"loadCursorReplayTaskLinks"'],
['runtime profiles: Devin\'s', '"devinModelCommandResult"'],
+ ['identity: agy\'s', '"agyConversationForPid"'],
+ ['identity: Cursor\'s discovery', '"CursorTranscriptDiscovery"'],
])('leaves the other engines\' %s out of the core until it needs them', (_, marker) => {
// engines/inProcess.ts imports them (docs/design/2026-10-08-other-engines-out-of-core.md): a file of the
// core's own, which Node reads only then.
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 9aab87380..95c85cd97 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -8,7 +8,7 @@ import { env } from '../config/env.js'
import { launchContract, launchField } from '../engines/launches.js'
import { startupFunctions, startupNeedsScript, startupRuns } from '../engines/kit/launchStartup.js'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
-import { isOpencodeV2 } from '../engines/opencode/version.js'
+import { isOpencodeV2 } from '../engines/opencode/contract.js'
import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
import { engineInstallPaths, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index a3d598936..7c64749e4 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -45,7 +45,7 @@
import { homedir } from 'node:os'
import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
-import { isOpencodeV2 } from '../engines/opencode/version.js'
+import { isOpencodeV2 } from '../engines/opencode/contract.js'
import {
CLAUDE_ALLOW_WEB_TOOLS_ARG,
CLAUDE_DISALLOW_WEB_TOOLS_ARG,
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 5143d766e..f02c60171 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
+import { loadEngine } from '../engines/inProcess.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps } from './launchOverrides.js'
import { DSH_SESSION_ENV } from '../dsh/launch.js'
import { GRID_CONFLICTING_ENV_VARS, type GridLaunchOverride } from './gridLaunch.js'
@@ -11,6 +12,12 @@ const GRID: GridLaunchOverride = {
model: 'gpt-5',
}
+// OpenCode's version probe is its own code, loaded for an OpenCode launch alone; a test may say it could not be.
+vi.mock('../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
+
function deps(overrides: Partial<LaunchOverridesDeps> = {}) {
const calls: string[] = []
const d: LaunchOverridesDeps = {
@@ -93,6 +100,19 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
expect(calls).toEqual([])
})
+ it('refuses an OpenCode launch whose code could not be loaded, and asks the machine for the engine it launches', async () => {
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ expect(await buildLaunchOverrides(deps().d, 'opencode', {}, 'agent-1')).toEqual({ ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' })
+ vi.mocked(loadEngine).mockClear()
+ const machine = vi.fn((_engine: string) => ({ hermesSystemManaged: false }))
+ await buildLaunchOverrides(deps({ machine }).d, 'claude', { gridLaunch: GRID, subscriptionModel: 'opus' }, 'agent-1')
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(machine.mock.calls.every(([engine]) => engine === 'claude')).toBe(true)
+ await buildLaunchOverrides(deps({ machine }).d, 'opencode', { agent: 'reviewer' }, 'agent-1')
+ expect(loadEngine).toHaveBeenCalledWith('opencode')
+ expect(machine).toHaveBeenLastCalledWith('opencode')
+ })
+
it('never lets the key into argv', async () => {
for (const engine of ['claude', 'codex', 'opencode', 'hermes', 'grok', 'pi', 'copilot'] as const) {
const result = await buildLaunchOverrides(deps().d, engine, { gridLaunch: { ...GRID, model: 'm' } }, 'a')
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index 0bc759e9c..32e0179f5 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -13,6 +13,7 @@
*/
import { join } from 'node:path'
+import { loadEngine } from '../engines/inProcess.js'
import type { AgentEngine } from '../engines/types.js'
import { subscriptionModelLaunch } from './subscriptionModel.js'
import { ownLoginProviderArgs } from '../engines/launches.js'
@@ -59,7 +60,7 @@ export type LaunchOverridesResult =
export interface LaunchOverridesDeps {
/** The facts about THIS machine a contract needs and cannot read for itself — see `GridLaunchMachine`. */
- machine: () => GridLaunchMachine
+ machine: (engine: AgentEngine) => GridLaunchMachine
writeGridConfigDir: (
key: string,
files: NonNullable<GridEngineLaunch['configDir']>['files'],
@@ -135,8 +136,11 @@ export async function validateLaunchOverrides(
engine: AgentEngine,
source: LaunchSource,
): Promise<{ ok: true } | { ok: false; error: string; detail: string }> {
+ // Which OpenCode is installed decides its argv (`machine`), read by OpenCode's own probe: loaded here for an
+ // OpenCode launch alone (engines/inProcess.ts), and the launch refused without it rather than given a guess.
+ if (engine === 'opencode' && !await loadEngine('opencode')) return { ok: false, error: 'ENGINE_UNAVAILABLE', detail: 'OpenCode\'s code could not be loaded' }
if (!source.gridLaunch) return { ok: true }
- const built = buildGridEngineLaunch(engine, source.gridLaunch, deps.machine())
+ const built = buildGridEngineLaunch(engine, source.gridLaunch, deps.machine(engine))
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
// Only a launch that SETS variables needs the tmux that can set them.
if (!(await deps.tmuxSupportsSessionEnv())) {
@@ -188,7 +192,7 @@ export async function buildLaunchOverrides(
// handing the engine a flag it does not know. The same guard covers an opencode agent created on
// v1 and relaunched on v2, whose TUI has no `--agent`: a resumed v2 session keeps the agent it
// stored (`session_v2.agent`), so nothing is lost by not naming it.
- const opencodeMajor = deps.machine().opencodeMajor ?? null
+ const opencodeMajor = deps.machine(engine).opencodeMajor ?? null
if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {
overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }
}
@@ -218,7 +222,7 @@ async function buildBaseLaunchOverrides(
// back on the DEFAULT profile, reading hooks from a folder that was not the one it writes to.
let ownLogin: LaunchOverrides | null = null
if (!source.gridLaunch) {
- const restored = subscriptionModelLaunch(engine, source.subscriptionModel, deps.machine().opencodeMajor ?? null)
+ const restored = subscriptionModelLaunch(engine, source.subscriptionModel, deps.machine(engine).opencodeMajor ?? null)
// Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the
// model against the provider it has been given.
const provider = ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })
@@ -232,7 +236,7 @@ async function buildBaseLaunchOverrides(
}
}
if (source.gridLaunch) {
- const built = buildGridEngineLaunch(engine, source.gridLaunch, deps.machine())
+ const built = buildGridEngineLaunch(engine, source.gridLaunch, deps.machine(engine))
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
const env: Record<string, string> = { ...built.launch.env }
if (built.launch.configDir) {
diff --git a/cli/src/lib/purgeAgentService.ts b/cli/src/lib/purgeAgentService.ts
index 7b581b1cd..d721187b4 100644
--- a/cli/src/lib/purgeAgentService.ts
+++ b/cli/src/lib/purgeAgentService.ts
@@ -5,7 +5,7 @@ import { promisify } from 'node:util'
import { existsSync, lstatSync, realpathSync, unlinkSync } from 'node:fs'
import { basename, dirname, join, resolve, sep } from 'node:path'
import { env } from '../config/env.js'
-import { hermesDbPath } from '../engines/hermes/home.js'
+import { hermesDbPath } from '../engines/hermes/contract.js'
import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
import { sqliteReadAll } from './sqliteRead.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index fcb3de902..cda39ebd4 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -38,7 +38,7 @@ import {
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative, isAbsolute } from 'path'
import { machineNames } from './machineNames.js'
-import { cursorDataDir } from '../engines/cursor/home.js'
+import { cursorDataDir } from '../engines/cursor/contract.js'
import { env } from '../config/env.js'
import { sessionFolderOf, sessionRoots } from './engineHomes.js'
import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'
@@ -48,9 +48,9 @@ import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js
import type { GridAssignment } from './gridAssignment.js'
import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord, type GridWebSearchStatus } from './gridLaunch.js'
import { parseScmLaunchRecord, type ScmLaunchRecord } from '../scm/types.js'
-import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
-import { agyTranscriptPath } from '../engines/agy/session.js'
-import { copilotTranscriptPath } from '../engines/copilot/session.js'
+import { commandcodeTranscriptPath } from '../engines/commandcode/contract.js'
+import { agyTranscriptPath } from '../engines/agy/contract.js'
+import { copilotTranscriptPath } from '../engines/copilot/contract.js'
import { bootChanged, currentBootId } from './bootId.js'
import { lockOwnerAlive, lockStartMarker, processLockIdentity } from './processLiveness.js'
import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.ts
index 80bd0afdd..f1eb9250d 100644
--- a/cli/src/lib/sessionCheckpoint.ts
+++ b/cli/src/lib/sessionCheckpoint.ts
@@ -7,7 +7,7 @@ import { env } from '../config/env.js'
import { atomicWriteJson, engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
import { sqliteReadAll } from './sqliteRead.js'
-import { hermesDbPath } from '../engines/hermes/home.js'
+import { hermesDbPath } from '../engines/hermes/contract.js'
import { findResumedTranscript } from './sessionRepair.js'
export class SessionCheckpointError extends Error {
diff --git a/cli/src/lib/sessionRepair.lazy.spec.ts b/cli/src/lib/sessionRepair.lazy.spec.ts
new file mode 100644
index 000000000..0a6479b51
--- /dev/null
+++ b/cli/src/lib/sessionRepair.lazy.spec.ts
@@ -0,0 +1,83 @@
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+/**
+ * Repair reads the other engines' files with their own code, loaded when it is asked (engines/inProcess.ts). An
+ * engine whose code could not be loaded has no repair answer, as when nothing is found; Claude Code's and Codex's
+ * repair loads nothing. `sessionRepair.spec.ts` and `engines/otherIdentity.golden.spec.ts` pin the answers.
+ */
+const loader = vi.hoisted(() => ({ refused: new Set<string>(), asked: [] as string[] }))
+vi.mock('../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../engines/inProcess.js')>()
+ return {
+ ...actual,
+ loadEngine: vi.fn(async (name: Parameters<typeof actual.loadEngine>[0]) => {
+ loader.asked.push(name)
+ return loader.refused.has(name) ? null : actual.loadEngine(name)
+ }),
+ }
+})
+
+const STARTED_AT = Date.parse('2026-10-08T09:00:00Z')
+const CWD = '/work/project'
+const UUID = '0b6f4f2e-6c1a-4c55-9a51-000000000001'
+let root = ''
+const saved: Record<string, string | undefined> = {}
+let repair: typeof import('./sessionRepair.js')
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'repair-lazy-'))
+ const env = {
+ MUSE_HOME: join(root, 'muse'), COPILOT_HOME: join(root, 'copilot'), HERMES_HOME: join(root, 'hermes'),
+ AGY_HOME: join(root, 'agy'), PI_HOME: join(root, 'pi'), GROK_HOME: join(root, 'grok'), CLAUDE_PROJECTS_DIR: join(root, 'claude'), CODEX_HOME: join(root, 'codex'),
+ }
+ for (const [name, value] of Object.entries(env)) { saved[name] = process.env[name]; process.env[name] = value }
+ // A muse conversation that repair binds when muse's code is there.
+ const museDir = join(root, 'muse', 'sessions', '2026', '10', '08', UUID)
+ mkdirSync(museDir, { recursive: true })
+ const museFile = join(museDir, 'session.jsonl')
+ writeFileSync(museFile, [
+ JSON.stringify({ payload: { record: { workspace_root: CWD } } }),
+ JSON.stringify({ payload: { kind: 'run', event: { kind: 'started', prompt: 'hi' } } }),
+ ].join('\n') + '\n')
+ utimesSync(museFile, new Date(STARTED_AT + 5_000), new Date(STARTED_AT + 5_000))
+ vi.resetModules()
+ repair = await import('./sessionRepair.js')
+})
+
+afterAll(() => {
+ for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value
+ rmSync(root, { recursive: true, force: true })
+})
+
+describe('session repair, with the other engines\' code loaded when asked', () => {
+ it('binds by the engine\'s own reader, loaded for that engine alone', async () => {
+ loader.asked.length = 0
+ expect(await repair.findLiveSession('muse', CWD, STARTED_AT)).toMatchObject({ sessionId: UUID })
+ expect(loader.asked).toEqual(['muse'])
+ })
+
+ it('has no answer for an engine whose code could not be loaded', async () => {
+ loader.refused = new Set(['muse', 'copilot', 'agy', 'pi'])
+ try {
+ expect(await repair.findLiveSession('muse', CWD, STARTED_AT)).toBeNull()
+ expect(await repair.findLiveSession('copilot', CWD, STARTED_AT, { pid: 4242 })).toBeNull()
+ expect(await repair.findLiveSession('agy', CWD, STARTED_AT, { pid: 4242 })).toBeNull()
+ await expect(repair.findResumedTranscript('pi', 'abc123', { cwd: CWD })).rejects.toThrow('The Pi conversation location is unavailable.')
+ } finally { loader.refused = new Set() }
+ })
+
+ it('loads nothing for Claude Code, Codex, or an engine whose files or stores it reads itself', async () => {
+ loader.asked.length = 0
+ await repair.findLiveSession('claude', CWD, STARTED_AT)
+ await repair.findLiveSession('codex', CWD, STARTED_AT)
+ await repair.findResumedTranscript('claude', UUID)
+ await repair.findLiveSession('grok', CWD, STARTED_AT)
+ await repair.findLiveSession('pi', CWD, STARTED_AT)
+ // Hermes's homes are declared: its stores are read without its code.
+ await repair.findLiveSession('hermes', CWD, STARTED_AT)
+ expect(loader.asked).toEqual([])
+ })
+})
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index c0f92e6fb..7cafce0a9 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -20,15 +20,13 @@ import { basename, dirname, join, relative, sep } from 'path'
import { env } from '../config/env.js'
import type { SessionStoreContract } from '../engines/facets/sessionStore.js'
import { headBytes } from '../engines/kit/continuation.js'
-import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'
import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'
import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
import type { AgentEngine } from '../engines/types.js'
-import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'
-import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'
-import { hermesDbPath, listHermesHomes } from '../engines/hermes/home.js'
+import { HERMES_HOMES, hermesDbPath } from '../engines/hermes/contract.js'
+import { listStoreHomes } from '../engines/kit/storeHomes.js'
+import { loadEngine, type InProcessModules } from '../engines/inProcess.js'
import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'
-import { piSessionFolder, readPiHead } from './sessionSearch/externals/pi.js'
import { sessionRoots } from './engineHomes.js'
import { argvTokens, engineProcessMatchScore, processRows, type ProcessRow } from './tmux.js'
@@ -190,7 +188,7 @@ const str = (v: unknown): string => (typeof v === 'string' ? v : '')
* triggered it rather than a person. `payload.kind` is what separates the two lifecycles that share the
* name `started`; a `task` one is scheduler bookkeeping and several fire inside a single run.
*/
-function hasRun(lines: string[]): boolean {
+function hasRun(lines: string[], museEvent: InProcessModules['muse']['museEvent']): boolean {
for (const line of lines) {
const record = museEvent(line)
if (record?.scope === 'run' && str(record.event.kind) === 'started') return true
@@ -277,7 +275,8 @@ function placeholders(count: number): string {
async function copilotDirectoryScan(
cwd: string,
startedAtMs: number,
- opts?: { bornOnly?: boolean },
+ opts: { bornOnly?: boolean } | undefined,
+ copilotSessionCwd: InProcessModules['copilot']['copilotSessionCwd'],
): Promise<RepairedSession | null> {
return fileEngineSession(join(env.COPILOT_HOME, 'session-state'), cwd, startedAtMs, async (path) => {
if (basename(path) !== 'events.jsonl') return null
@@ -329,12 +328,17 @@ export async function findLiveSession(
const real = await realpath(cwd).catch(() => cwd)
const dirs = real === cwd ? [cwd] : [cwd, real]
const dirList = placeholders(dirs.length)
+ // Muse's, Copilot's and agy's readers of their own files are their code, loaded where they are read
+ // (engines/inProcess.ts); Hermes's homes are declared (engines/hermes/contract.ts). An engine whose code could not be loaded has no repair answer: its process stays
+ // unbound, as when nothing is found.
switch (engine) {
case 'pi':
return fileEngineSession(join(env.PI_HOME, 'agent', 'sessions'), cwd, startedAtMs, readTranscriptMeta, opts)
case 'commandcode':
return fileEngineSession(join(env.COMMANDCODE_HOME, 'projects'), cwd, startedAtMs, readTranscriptMeta, opts)
- case 'muse':
+ case 'muse': {
+ const muse = await loadEngine('muse')
+ if (!muse) return null
// Muse's hooks never fire, so this scan is the ONLY way a muse pane is ever bound. The tree is
// `sessions/YYYY/MM/DD/<session-uuid>/session.jsonl` (4 levels — exactly MAX_DEPTH) and nothing in
// the path names the project: `workspace_root` in the first record is the only link. Sub-agent
@@ -342,7 +346,7 @@ export async function findLiveSession(
return fileEngineSession(join(env.MUSE_HOME, 'sessions'), cwd, startedAtMs, async (path) => {
if (path.includes(`${sep}subagent${sep}`)) return null
const lines = (await readFile(path, 'utf-8').catch(() => '')).split('\n')
- const root = museWorkspaceRoot(lines[0] ?? '')
+ const root = muse.museWorkspaceRoot(lines[0] ?? '')
if (!root) return null
// Muse opens sessions of its OWN under the same workspace_root — memory reminders
// (`memory_reminder_child_session_linked`) are the ones seen live. They are indistinguishable from
@@ -350,9 +354,10 @@ export async function findLiveSession(
// measured, the daemon tailed an 11-line reminder session while the real conversation ran on in
// another file, so web and device received nothing at all. What separates them is that a session
// being conversed in has opened a RUN.
- if (!hasRun(lines)) return null
+ if (!hasRun(lines, muse.museEvent)) return null
return { cwd: root, sessionId: basename(dirname(path)) }
}, opts)
+ }
case 'amp':
// The transcripts scanned here are the adapter's own — Amp keeps no conversation on disk, so its
// plugin writes one per thread as `<AMP_SESSIONS_DIR>/<threadId>.jsonl` with `cwd` on the first
@@ -402,7 +407,7 @@ export async function findLiveSession(
// never rebind a profile agent after a restart (openharness#191). Each store is asked on its
// own and the answers are pooled, so two homes claiming the same cwd is ambiguous — exactly as
// two rows in one store already are — rather than "whichever home was listed first".
- const homes = await listHermesHomes()
+ const homes = await listStoreHomes(HERMES_HOMES, env.HERMES_HOME)
const found: RepairedSession[] = []
for (const home of homes) {
const one = await dbEngineSession(
@@ -431,12 +436,14 @@ export async function findLiveSession(
// The lock the process holds is the only thing a `/resume` leaves behind, and it is exact.
// Fall through to the directory scan when there is no pid or no lock yet (a brand-new session
// takes its lock only once Copilot creates it).
- const locked = opts?.pid ? await copilotSessionForPid(env.COPILOT_HOME, opts.pid) : null
+ const copilot = await loadEngine('copilot')
+ if (!copilot) return null
+ const locked = opts?.pid ? await copilot.copilotSessionForPid(env.COPILOT_HOME, opts.pid) : null
if (locked) {
- const transcriptPath = await findCopilotTranscript(env.COPILOT_HOME, locked)
+ const transcriptPath = await copilot.findCopilotTranscript(env.COPILOT_HOME, locked)
return { sessionId: locked, transcriptPath: transcriptPath ?? undefined }
}
- return copilotDirectoryScan(cwd, startedAtMs, opts)
+ return copilotDirectoryScan(cwd, startedAtMs, opts, copilot.copilotSessionCwd)
}
case 'agy':
@@ -455,9 +462,11 @@ export async function findLiveSession(
/** The conversation the given `agy` pid is holding, if its transcript exists yet. */
async function agySession(pid: number): Promise<RepairedSession | null> {
- const conversationId = await agyConversationForPid(env.AGY_HOME, pid)
+ const agy = await loadEngine('agy')
+ if (!agy) return null
+ const conversationId = await agy.agyConversationForPid(env.AGY_HOME, pid)
if (!conversationId) return null
- const transcriptPath = await findAgyTranscript(env.AGY_HOME, conversationId)
+ const transcriptPath = await agy.findAgyTranscript(env.AGY_HOME, conversationId)
// A conversation with no transcript is one agy has opened but not written to; registry derives the
// path anyway, so bind it and let the watcher pick the file up when it appears.
return { sessionId: conversationId, transcriptPath: transcriptPath ?? undefined }
@@ -481,6 +490,10 @@ export async function findResumedTranscript(
// exact ID again at Close, including after exit, without guessing by mtime.
if (!opts?.cwd || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/.test(sessionId)
|| sessionId.endsWith('.jsonl')) throw new Error('The Pi conversation location is unavailable.')
+ // Pi's own code names its folders and reads its files (engines/inProcess.ts): without it, the location is not known.
+ const pi = await loadEngine('pi')
+ if (!pi) throw new Error('The Pi conversation location is unavailable.')
+ const { piSessionFolder, readPiHead } = pi
const directory = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(opts.cwd))
let files: string[]
try { files = await readdir(directory) } catch (error) {
diff --git a/cli/src/lib/sessionSearch/externals/agy.ts b/cli/src/lib/sessionSearch/externals/agy.ts
index 88d1d9fe9..d244808a6 100644
--- a/cli/src/lib/sessionSearch/externals/agy.ts
+++ b/cli/src/lib/sessionSearch/externals/agy.ts
@@ -16,7 +16,7 @@
import { realpath, stat } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
-import { agyTranscriptPath } from '../../../engines/agy/session.js'
+import { agyTranscriptPath } from '../../../engines/agy/contract.js'
import type { AgentCommandOwnershipSnapshot } from '../../engineBin.js'
import { engineProcessMatch } from '../../tmux.js'
import { absoluteFolder, entries, fileStamp, parseLine, readJson, readText, record, text, UUID } from './support.js'
diff --git a/cli/src/lib/subscriptionModel.ts b/cli/src/lib/subscriptionModel.ts
index 40c62ceff..8adaef054 100644
--- a/cli/src/lib/subscriptionModel.ts
+++ b/cli/src/lib/subscriptionModel.ts
@@ -30,7 +30,7 @@
* a regression, and it is recoverable by hand in the pane.
*/
import type { AgentEngine } from '../engines/types.js'
-import { isOpencodeV2 } from '../engines/opencode/version.js'
+import { isOpencodeV2 } from '../engines/opencode/contract.js'
export interface SubscriptionModelLaunch {
env: Record<string, string>
diff --git a/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts b/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts
new file mode 100644
index 000000000..9aa81aa9b
--- /dev/null
+++ b/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ProcessRow } from './tmux.js'
+import type { TerminalBackend } from './terminalBackend.js'
+
+/**
+ * The Hermes home a process runs under rides the live discovery path, read by Hermes's own probe
+ * (engines/hermes/homeProbe.ts), loaded for a Hermes process alone (engines/inProcess.ts).
+ * `engines/otherAdmission.golden.spec.ts` pins what it reads; this pins when it is asked.
+ */
+const processRows = vi.hoisted(() => vi.fn())
+const readProcessEnv = vi.hoisted(() => vi.fn())
+vi.mock('./gatewayRuntime.js', () => ({ probeGatewayRuntime: vi.fn(async () => ({ kind: null })) }))
+vi.mock('./gridAssignment.js', () => ({ probeGridAssignment: vi.fn(async () => null) }))
+vi.mock('./processEnv.js', async (real) => ({ ...await real<object>(), readProcessEnv }))
+vi.mock('./tmux.js', async (real) => ({ ...await real<typeof import('./tmux.js')>(), processRows, enrichProcessRows: vi.fn(async (rows: unknown) => rows) }))
+vi.mock('../engines/inProcess.js', async (real) => {
+ const actual = await real<typeof import('../engines/inProcess.js')>()
+ return { ...actual, loadEngine: vi.fn(actual.loadEngine) }
+})
+
+const { loadEngine } = await import('../engines/inProcess.js')
+const { probeTerminalAgents } = await import('./terminalAgentDiscovery.js')
+
+const START = 'Thu Oct 8 10:00:00 2026'
+const row = (pid: number, parentPid: number, executable: string, args = executable): ProcessRow => ({ pid, parentPid, executable, startMarker: START, args })
+const backend = {
+ name: 'tmux', instanceId: 'tmux',
+ inventory: async () => ({ state: 'available', roots: [{ runtime: { backend: 'tmux', paneId: '%1' }, rootPid: 10, cwd: '/work' }, { runtime: { backend: 'tmux', paneId: '%2' }, rootPid: 20, cwd: '/work' }] }),
+} as unknown as TerminalBackend
+const homes = async () => {
+ const probe = await probeTerminalAgents([backend], ['tmux'], 999)
+ return Object.fromEntries(probe.agents.map((agent) => [agent.engine, agent.hermesHome]))
+}
+
+beforeEach(() => {
+ vi.mocked(loadEngine).mockClear()
+ processRows.mockResolvedValue([row(10, 1, 'zsh'), row(11, 10, 'python3', '/opt/hermes-agent/hermes'), row(20, 1, 'zsh'), row(21, 20, 'claude')])
+ readProcessEnv.mockResolvedValue({ HERMES_HOME: '/home/u/.hermes/profiles/work' })
+})
+
+describe('Hermes\'s home on the live terminal discovery path', () => {
+ it('is read by Hermes\'s code, loaded for its process alone', async () => {
+ expect(await homes()).toEqual({ hermes: '/home/u/.hermes/profiles/work', claude: null })
+ expect(vi.mocked(loadEngine).mock.calls).toEqual([['hermes']])
+ })
+
+ it('is unknown without Hermes\'s code, which never overwrites what the registry knows', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ vi.mocked(loadEngine).mockResolvedValueOnce(null)
+ expect(await homes()).toEqual({ hermes: undefined, claude: null })
+ error.mockRestore()
+ })
+
+ it('is not asked of a pane with no Hermes in it', async () => {
+ processRows.mockResolvedValue([row(20, 1, 'zsh'), row(21, 20, 'claude')])
+ expect(await homes()).toEqual({ claude: null })
+ expect(loadEngine).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index 6220f7aa3..cc312cc65 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -8,7 +8,7 @@ import {
import { probeGatewayRuntime } from './gatewayRuntime.js'
import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'
import { probeProfileHome } from '../engines/discoveries.js'
-import { probeHermesHome } from '../engines/hermes/homeProbe.js'
+import { loadEngine } from '../engines/inProcess.js'
import { probeDsh } from '../dsh/probe.js'
import type { TerminalBackend } from './terminalBackend.js'
import {
@@ -264,8 +264,12 @@ export async function probeTerminalAgents(
agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)
// And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.
agent.codexHome = await probeProfileHome(agent.processIdentity, agent.engine)
- // …and, for Hermes, the home — same cached read, and it beats looking the session up in every store.
- agent.hermesHome = await probeHermesHome(agent.processIdentity, agent.engine)
+ // …and, for Hermes, the home — same cached read, and it beats looking the session up in every store. Read by
+ // Hermes's own code, loaded for a Hermes process alone (engines/inProcess.ts); without it the process could
+ // not be read, which never overwrites what the registry knows.
+ agent.hermesHome = agent.engine === 'hermes'
+ ? await (await loadEngine('hermes'))?.probeHermesHome(agent.processIdentity, agent.engine)
+ : null
// And the DSH it was created as — same read, so a pane the daemon did not create is labelled too.
agent.dsh = await probeDsh(agent.processIdentity)
}))
diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.ts
index 6afe07965..fb50d3dfc 100644
--- a/cli/src/testing/socketCore.ts
+++ b/cli/src/testing/socketCore.ts
@@ -23,7 +23,7 @@ import { createCancelRequest } from '../core/turns/cancel.js'
import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'
import { createHarnessResourcesReader } from '../lib/harnessResources.js'
import { createHarnessStorageReader } from '../lib/harnessTelemetry.js'
-import { hermesDbForSession } from '../lib/hermesHome.js'
+import { hermesDb } from '../core/transcripts/databaseHistory.js'
import { registry } from '../lib/registry.js'
import { stoppedAgents } from '../lib/stoppedAgents.js'
import { TranscriptPager } from '../lib/transcriptPages.js'
@@ -38,7 +38,7 @@ export function bindHistory(socket: BackendSocket): void {
stopped: () => stoppedAgents.list(),
pages: new TranscriptPager(),
dbs: { opencode: join(env.OPENCODE_DATA_DIR, 'opencode.db'), kilo: join(env.KILO_DATA_DIR, 'kilo.db'), devin: join(env.DEVIN_HOME, 'sessions.db') },
- hermesDb: (s) => hermesDbForSession(s),
+ hermesDb,
})
socket.historyProvider = history.sessionGet
socket.sessionsProvider = history.sessionsList