The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
refactor(cli): move Claude Code and Codex hooks behind engine facets (#1013)
Deee144fde4364a
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 3afed8db6..f585629f0 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -13,7 +13,8 @@ import { buildEngineLaunchArgv, permissionModeFlags, refusePermissionFlagIfUnsupimport { setUpWithin } from '../../lib/setUpWithin.js'import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { buildGridEngineLaunch } from '../../lib/gridLaunch.js'-import { installCodexHooks, installOpencodePlugin } from '../../lib/hooks.js'+import { engineHooks } from '../../engines/hooks.js'+import { installOpencodePlugin } from '../../lib/hooks.js'import type { RegisteredSession } from '../../lib/registry.js'import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'import { clearPaneRemainOnExit } from '../../lib/tmux.js'@@ -53,7 +54,11 @@ vi.mock('../../lib/gridLaunch.js', async (real) => ({describeGridLaunch: vi.fn(() => '[grid] claude on Home'),gridConflictingEnvToClear: vi.fn(() => ['ANTHROPIC_API_KEY']),}))-vi.mock('../../lib/hooks.js', async (real) => ({ ...await real<object>(), installCodexHooks: vi.fn(), installOpencodePlugin: vi.fn() }))+vi.mock('../../engines/hooks.js', async (real) => {+ const actual = await real<typeof import('../../engines/hooks.js')>()+ return { ...actual, engineHooks: { ...actual.engineHooks, codex: { ...actual.engineHooks.codex, installIn: vi.fn() } } }+})+vi.mock('../../lib/hooks.js', async (real) => ({ ...await real<object>(), installOpencodePlugin: vi.fn() }))vi.mock('../../lib/sessionSearch/external.js', async (real) => ({ ...await real<object>(), stopSessionOwner: vi.fn(async () => true) }))vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))vi.mock('../../lib/tmuxVersion.js', async (real) => ({ ...await real<object>(), tmuxSupportsSessionEnv: vi.fn(async () => true) }))@@ -294,13 +299,13 @@ describe('creating an agent', () => {const on = setup()await on.create(request({ engine: 'codex', codexHome: '/codex-work' }))await on.create(request({ engine: 'opencode' }))- expect(installCodexHooks).toHaveBeenCalledWith(4242, '/codex-work')+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/codex-work')expect(installOpencodePlugin).toHaveBeenCalledWith(4242)expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ env: { CODEX_HOME: '/codex-work' }, codexHome: '/codex-work' })const off = setup({ hooksDisabled: true })await off.create(request({ engine: 'codex', codexHome: '/codex-work' }))await off.create(request({ engine: 'opencode' }))- expect(installCodexHooks).toHaveBeenCalledTimes(1)+ expect(engineHooks.codex.installIn).toHaveBeenCalledTimes(1)expect(installOpencodePlugin).toHaveBeenCalledTimes(1)})diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex f53b3525e..45a7520ff 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -33,7 +33,8 @@ import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, type GridLaunchMachine, type GridWebSearchStatus } from '../../lib/gridLaunch.js'import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'-import { installCodexHooks, installOpencodePlugin } from '../../lib/hooks.js'+import { engineHooks } from '../../engines/hooks.js'+import { installOpencodePlugin } from '../../lib/hooks.js'import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import { stopSessionOwner, type SessionOwner } from '../../lib/sessionSearch/external.js'@@ -233,7 +234,7 @@ export function createAgentCreator({// THAT folder, not the one `harness login` already installed into — without this, such an agent// fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.// Idempotent, so paying this on every create against an already-set-up profile is free.- if (codexHome && !hooksDisabled) installCodexHooks(hookPort, codexHome)+ if (codexHome && !hooksDisabled) engineHooks.codex.installIn(hookPort, codexHome)// OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must// not discover our old server plugin; the cached version probe changes with the executable.if (engine === 'opencode' && !hooksDisabled) installOpencodePlugin(hookPort)diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsindex c1863f847..1bf1f3745 100644--- a/cli/src/core/engines/hooks.spec.ts+++ b/cli/src/core/engines/hooks.spec.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import * as hooks from '../../lib/hooks.js'+import { engineHooks } from '../../engines/hooks.js'import type { RegisteredSession } from '../../lib/registry.js'import { processRows } from '../../lib/terminalAgentDiscovery.js'import { dirname } from 'node:path'@@ -7,6 +8,13 @@ import { env } from '../../config/env.js'import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'import { createEngineHooks, installEngineHooks, PROCESS_RECORD_WAIT_MS, type EngineHookDeps } from './hooks.js'+vi.mock('../../engines/hooks.js', async (real) => {+ const actual = await real<typeof import('../../engines/hooks.js')>()+ return { ...actual, engineHooks: {+ claude: { ...actual.engineHooks.claude, install: vi.fn(), installIn: vi.fn() },+ codex: { ...actual.engineHooks.codex, install: vi.fn(), installIn: vi.fn() },+ } }+})vi.mock('../../lib/engineHomes.js', () => ({adoptEngineHomes: vi.fn(() => ({ claude: null, codex: null })),movedEngineHomes: vi.fn(() => ({ claude: [], codex: [] })),@@ -14,8 +22,6 @@ vi.mock('../../lib/engineHomes.js', () => ({vi.mock('../../lib/terminalAgentDiscovery.js', async (real) => ({ ...await real<object>(), processRows: vi.fn(async () => []) }))vi.mock('../../lib/hooks.js', async (real) => ({...await real<object>(),- installSessionHooks: vi.fn(),- installCodexHooks: vi.fn(),installCursorHooks: vi.fn(),installOpencodePlugin: vi.fn(),installKiloPlugin: vi.fn(),@@ -295,7 +301,7 @@ describe('which agent a hook belongs to', () => {describe('installing every engine\'s hooks', () => {const installs = [- hooks.installSessionHooks, hooks.installCodexHooks, hooks.installCursorHooks, hooks.installOpencodePlugin,+ engineHooks.claude.install, engineHooks.codex.install, hooks.installCursorHooks, hooks.installOpencodePlugin,hooks.installKiloPlugin, hooks.installPiExtension, hooks.installAmpPlugin, hooks.installHermesHooks,hooks.installDevinHooks, hooks.installCommandCodeHooks, hooks.installGrokHooks, hooks.installAgyHooks,hooks.installCopilotHooks,@@ -312,17 +318,18 @@ describe('installing every engine\'s hooks', () => {it('only the engines asked for (HOOK_INSTALL_ENGINES), the homes they moved included', () => {vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })installEngineHooks(4242, { only: new Set(['codex']), environment: {} })- expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242)- expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/w/codex')- for (const install of installs.filter((one) => one !== hooks.installCodexHooks)) expect(install).not.toHaveBeenCalled()+ expect(engineHooks.codex.install).toHaveBeenCalledWith(4242)+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')+ for (const install of installs.filter((one) => one !== engineHooks.codex.install)) expect(install).not.toHaveBeenCalled()+ expect(engineHooks.claude.installIn).not.toHaveBeenCalled()})// lib/engineHomes.ts: with CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile, no agent ever bound.it('puts the hooks in every home adopted on an earlier boot, at every start', () => {vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })installEngineHooks(4242, { environment: {} })- expect(hooks.installSessionHooks).toHaveBeenCalledWith(4242, '/w/claude/settings.json')- expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/w/codex')+ expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/w/claude')+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')})it('adopts the homes its own environment moves, then the login shell\'s once that is read, and installs there', async () => {@@ -334,11 +341,11 @@ describe('installing every engine\'s hooks', () => {.mockReturnValueOnce({ claude: null, codex: '/s/codex' })installEngineHooks(4242, { environment: own, loginShell: Promise.resolve(shell) })expect(adoptEngineHomes).toHaveBeenCalledWith(own, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })- expect(hooks.installSessionHooks).toHaveBeenCalledWith(4242, '/m/claude/settings.json')+ expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/m/claude')expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Claude Code in /m/claude')await Promise.resolve()expect(adoptEngineHomes).toHaveBeenLastCalledWith(shell, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })- expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/s/codex')+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/s/codex')expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Codex in /s/codex')})@@ -350,7 +357,7 @@ describe('installing every engine\'s hooks', () => {})it('one at a time: a vendor whose install throws is skipped and named, and the rest still install', () => {- vi.mocked(hooks.installCodexHooks).mockImplementationOnce(() => { throw new Error('config.toml is read-only') })+ vi.mocked(engineHooks.codex.install).mockImplementationOnce(() => { throw new Error('config.toml is read-only') })vi.mocked(hooks.installGrokHooks).mockImplementationOnce(() => { throw 'settings mid-write' })installEngineHooks(4242)expect(console.warn).toHaveBeenCalledWith('[hooks] codex install skipped · config.toml is read-only')diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsindex 36cc5bf33..f4b5a58d4 100644--- a/cli/src/core/engines/hooks.ts+++ b/cli/src/core/engines/hooks.ts@@ -4,14 +4,14 @@** Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).*/-import { dirname, join } from 'node:path'+import { dirname } from 'node:path'+import { engineHooks } from '../../engines/hooks.js'import { env } from '../../config/env.js'import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'import {- installAgyHooks, installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCopilotHooks, installCursorHooks,+ installAgyHooks, installAmpPlugin, installCommandCodeHooks, installCopilotHooks, installCursorHooks,installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension,- installSessionHooks,} from '../../lib/hooks.js'import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'@@ -202,8 +202,9 @@ export function installEngineHooks(port: number, options: InstallEngineHooksOpti// once it has been read. That read is never waited on (cli.ts), so an engine started in the first// seconds of a daemon's very first start with a moved home may miss its first hook.const installIn = (homes: { claude: Array<string | null>; codex: Array<string | null> }): void => {- for (const home of homes.claude) if (home) hookStep('claude', () => installSessionHooks(port, join(home, 'settings.json')))- for (const home of homes.codex) if (home) hookStep('codex', () => installCodexHooks(port, home))+ for (const engine of Object.keys(homes) as Array<keyof typeof homes>) {+ for (const home of homes[engine]) if (home) hookStep(engine, () => engineHooks[engine].installIn(port, home))+ }}const adopt = (environment: NodeJS.ProcessEnv): void => {const moved = adoptEngineHomes(environment, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })@@ -214,8 +215,7 @@ export function installEngineHooks(port: number, options: InstallEngineHooksOptiinstallIn(movedEngineHomes())adopt(options.environment ?? process.env)void options.loginShell?.then(adopt)- hookStep('claude', () => installSessionHooks(port))- hookStep('codex', () => installCodexHooks(port))+ for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port))hookStep('cursor', () => installCursorHooks(port))hookStep('opencode', () => installOpencodePlugin(port))hookStep('kilo', () => installKiloPlugin(port))diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 70cd56c70..21fc22e97 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -24,7 +24,7 @@ import { terminalActivity } from '../lib/terminalActivity.js'import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'import { engineSessionTitle } from '../lib/sessionTitle.js'import { machineNames } from '../lib/machineNames.js'-import { installCodexHooks } from '../lib/hooks.js'+import { engineHooks as engineHookFacets } from '../engines/hooks.js'import { DAEMON_LOG_FILE, PID_FILE, daemonPort, isAlive, readPid, LEGACY_LOG_FILE, MACHINE_NAME_FILE, tildify, computerId, thisDeviceLabel } from '../lib/daemonState.js'import { clearSafeModeMarker, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from '../lib/daemonSafeMode.js'import { awakeTimeout } from '../lib/sleepAware.js'@@ -1789,7 +1789,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {machine: gridLaunchMachine,writeGridConfigDir,tmuxSupportsSessionEnv,- installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome) },+ installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) engineHookFacets.codex.installIn(hookPort, codexHome) },dshLaunch: (id, workspace, engine, runtimeKey) => {const installed = installedDsh(id)if (!installed) {diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.tsindex e97d16efb..840c06fa9 100644--- a/cli/src/core/turns/turnHooks.spec.ts+++ b/cli/src/core/turns/turnHooks.spec.ts@@ -4,6 +4,7 @@ import type { TurnState } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'import { createSessionNormalizers } from '../transcripts/normalizers.js'import { createTurnHooks, STOP_HOOK_GRACE_MS, type TurnHookDeps } from './turnHooks.js'+import { engineHooks } from '../../engines/hooks.js'vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))@@ -72,9 +73,26 @@ describe('turn hooks', () => {unknown.hooks.onTurnStop({ sessionId: 'nobody' })const pi = setup('pi')pi.hooks.onTurnStop({ sessionId: 's1' })+ const codex = setup('codex')+ codex.hooks.onTurnStop({ sessionId: 's1', status: 'error' })await vi.runAllTimersAsync()expect(unknown.deps.drain).not.toHaveBeenCalled()expect(pi.deps.drain).not.toHaveBeenCalled()+ expect(codex.deps.drain).not.toHaveBeenCalled()+ expect(codex.deps.emit).not.toHaveBeenCalled()+ })++ it('contains a synchronous engine failure and still handles another engine', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.spyOn(engineHooks.claude, 'onStop').mockImplementationOnce(() => { throw new Error('engine failed') })+ expect(() => setup('claude').hooks.onTurnStop({ sessionId: 's1' })).not.toThrow()+ const other = setup('commandcode')+ const state = engineState()+ put(other.normalizers.commandcodeNormalizers, state)+ other.hooks.onTurnStop({ sessionId: 's1' })+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)+ expect(other.deps.emit).toHaveBeenCalledWith('s1', END)+ expect(error).toHaveBeenCalledWith('[hooks] claude stop hook failed:', 'engine failed')})describe('Claude Code', () => {diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.tsindex f636a460b..39434b88e 100644--- a/cli/src/core/turns/turnHooks.ts+++ b/cli/src/core/turns/turnHooks.ts@@ -7,12 +7,14 @@* Moved verbatim out of the hook server's options in `runForeground` (the core boundary, step 9:* docs/design/2026-10-03-harnessd.md).*/+import { hooksFor } from '../../engines/hooks.js'+import type { HookTurnContext } from '../../engines/facets/hooks.js'import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'import type { TurnRecaps } from './recaps.js'import { sid } from '../../lib/log.js'-import type { LiveEvent, TurnState } from '../../lib/normalize.js'+import type { LiveEvent } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'import type { SessionNormalizers } from '../transcripts/normalizers.js'@@ -65,12 +67,29 @@ export function createTurnHooks({promptFiredAt.set(sessionId, firedAt)if (promptFiredAt.size > PROMPT_HOOKS_KEPT) promptFiredAt.delete(promptFiredAt.keys().next().value!)}+ const hookTurns: HookTurnContext = {+ turnState: (sessionId) => turnStates.get(sessionId),+ latestPromptAt: (sessionId) => promptFiredAt.get(sessionId),+ drain,+ noteEngineStopped: (sessionId) => mirror.noteEngineStopped(sessionId),+ emit,+ graceMs: STOP_HOOK_GRACE_MS,+ }const onToolStart = ({ sessionId, toolUseId, toolName, input: toolInput }: { sessionId: string; toolUseId: string; toolName: string; input: unknown }): void => {if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)}const onTurnStop = ({ sessionId, status, firedAt }: { sessionId: string; status?: string; firedAt?: number }): void => {const session = resolve(sessionId)if (!session) return+ const hooks = hooksFor(session.engine)+ if (hooks) {+ // Invoke synchronously: the engine snapshots which turn the hook arrived about before draining.+ const failed = (error: unknown): void => {+ console.error(`[hooks] ${session.engine} stop hook failed:`, error instanceof Error ? error.message : error)+ }+ try { void Promise.resolve(hooks.onStop?.(hookTurns, { sessionId, status, firedAt })).catch(failed) } catch (error) { failed(error) }+ return+ }if (session.engine === 'cursor') {void (async () => {await cursorTaskHooks.wait(sessionId)@@ -97,10 +116,6 @@ export function createTurnHooks({})return}- // claude: authoritative turn-close from the Stop/StopFailure hook. Drain any un-read JSONL FIRST- // (may emit the real turn_ended → st.turnOpen already false); only force-close if still open. A- // later real end_turn line is then a no-op (lineToEvents guards on state.turnOpen). This closes- // the B1/B2 cases (max_tokens/refusal/API-error/wedged tool) the JSONL parse would otherwise miss.// Command Code has no UserPromptSubmit and commits records per turn, so Stop is its authoritative// close: drain the transcript first (the natural close usually wins), then force-close what's left.if (session.engine === 'commandcode') {@@ -201,46 +216,6 @@ export function createTurnHooks({})return}- if (session.engine !== 'claude') return- // A pass a blocking Stop hook continued (a /goal loop) is the transcript's to close, by its end_turn or- // turn_duration: the Stop of the pass before it reached the daemon 520 ms after it began (end to end,- // under load) and force-closed it while it ran. Only a StopFailure still closes one here.- const leftToTranscript = (st: TurnState): boolean => st.continued === true && status !== 'error'- // A Stop closes only the turn it is about. Found by the soak run (e2e/endurance.e2e.ts): under load a turn's- // Stop reached the daemon 6 s late, after the next prompt's turn had opened, and force-closed that turn- // with a question open in it, which was then never shown. So:- // - a Stop its engine ran before the session's latest prompt hook is about an earlier turn, and closes- // nothing (the time each hook was run comes with it, hook/notify.mjs);- // - otherwise it is about the turn open as it arrives, and not one opened after that (read in the drain- // below), whose prompt hook has not come in yet; a StopFailure closes whichever turn is open.- // A turn left open with no end of its own is closed by the next prompt (lib/normalize.ts).- const stale = firedAt !== undefined && (promptFiredAt.get(sessionId) ?? 0) > firedAt- const arrived = turnStates.get(sessionId)- const about = arrived?.turnOpen ? arrived.opened ?? 0 : null- const itsTurn = (st: TurnState): boolean => !stale && (status === 'error' || (st === arrived && about !== null && (st.opened ?? 0) === about))- void (async () => {- await drain(sessionId)- // A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is- // HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is- // on disk — without it the recap fires on its settle timer and can beat claude's closing summary- // to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).- mirror.noteEngineStopped(sessionId)- const open = turnStates.get(sessionId)- if (!open?.turnOpen || leftToTranscript(open) || !itsTurn(open)) return // natural JSONL close already won → nothing to do- // Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close- // if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))- await drain(sessionId)- const st = turnStates.get(sessionId)- if (st?.turnOpen && !leftToTranscript(st) && itsTurn(st)) {- st.turnOpen = false- st.pendingTools.clear()- console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)- emit(sessionId, [{ type: 'turn_ended', payload: {} }])- }- })().catch((err) => {- console.error('[hooks] claude stop hook failed:', err instanceof Error ? err.message : err)- })}return { onTurnStart, onToolStart, onTurnStop, onPromptHook }}diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 8bfb4d6d9..ae9548ad8 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -15,8 +15,10 @@ sub-agents, questions, completion. An engine is the translator between your agenthat stream.**The engine interface is being migrated in small batches.** Claude Code and Codex now own their-launch contracts and the history/last-turn readers behind `Engine` (`engine.ts`). `registry.ts` selects-those engines; `launches.ts` exposes their launch metadata without loading transcript readers. The+launch contracts, history/last-turn readers and hook behavior behind `Engine` (`engine.ts`). `registry.ts`+selects those engines; `launches.ts` and `hooks.ts` expose their respective facets without loading history+readers. Hook transport, process binding and event delivery stay with core. These adapters still run in+the core process: the interface is a code boundary, not a separate worker process. Theremaining facets and engines still use the shared paths below. This is an internal interface, not anexternal plugin API. When extending a migrated facet, put engine behavior in its folder and sharedmechanics in `kit/`. See the [migration design](../../../docs/design/2026-10-05-engine-interface.md)diff --git a/cli/src/engines/claude/hooks.ts b/cli/src/engines/claude/hooks.tsnew file mode 100644index 000000000..ad23b79a1--- /dev/null+++ b/cli/src/engines/claude/hooks.ts@@ -0,0 +1,72 @@+import { existsSync } from 'node:fs'+import { basename, join } from 'node:path'+import { sid } from '../../lib/log.js'+import type { TurnState } from '../../lib/normalize.js'+import type { EngineHooks, HookSession, HookStop, HookTurnContext } from '../facets/hooks.js'+import { installSessionHooks } from './installHooks.js'++/**+ * `claude --resume` from a folder other than the conversation's own: Claude Code announces a transcript+ * under the CURRENT cwd's project dir, then keeps writing the original file (measured: a resume of+ * 73f090ca from `cli/` announced `…-openharness-cli/73f090ca.jsonl`, and every later turn still landed+ * in `…-openharness/73f090ca.jsonl`). The announced file never appears, the hook is dropped, and the+ * resume is never confirmed — "Start failed" over a pane that is working. The row being resumed already+ * knows the real file; take it when it names this very conversation.+ */+export function transcriptFor(body: HookSession, agent: HookSession | undefined): string | undefined {+ const announced = body.transcriptPath ?? undefined+ if (!announced || existsSync(announced)) return announced+ const known = agent?.transcriptPath+ if (!known || !body.sessionId || agent.sessionId !== body.sessionId) return announced+ if (basename(known) !== `${body.sessionId}.jsonl` || !existsSync(known)) return announced+ return known+}++/** Capture the arrival's turn before the first await: a drain can open the next turn. */+async function onStop(+ { turnState, latestPromptAt, drain, noteEngineStopped, emit, graceMs }: HookTurnContext,+ { sessionId, status, firedAt }: HookStop,+): Promise<void> {+ // A pass a blocking Stop hook continued (a /goal loop) is the transcript's to close, by its end_turn or+ // turn_duration: the Stop of the pass before it reached the daemon 520 ms after it began (end to end,+ // under load) and force-closed it while it ran. Only a StopFailure still closes one here.+ const leftToTranscript = (st: TurnState): boolean => st.continued === true && status !== 'error'+ // A Stop closes only the turn it is about. Found by the soak run (e2e/endurance.e2e.ts): under load a turn's+ // Stop reached the daemon 6 s late, after the next prompt's turn had opened, and force-closed that turn+ // with a question open in it, which was then never shown. So:+ // - a Stop its engine ran before the session's latest prompt hook is about an earlier turn, and closes+ // nothing (the time each hook was run comes with it, hook/notify.mjs);+ // - otherwise it is about the turn open as it arrives, and not one opened after that (read in the drain+ // below), whose prompt hook has not come in yet; a StopFailure closes whichever turn is open.+ // A turn left open with no end of its own is closed by the next prompt (lib/normalize.ts).+ const stale = firedAt !== undefined && (latestPromptAt(sessionId) ?? 0) > firedAt+ const arrived = turnState(sessionId)+ const about = arrived?.turnOpen ? arrived.opened ?? 0 : null+ const itsTurn = (st: TurnState): boolean => !stale && (status === 'error' || (st === arrived && about !== null && (st.opened ?? 0) === about))+ await drain(sessionId)+ // A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is+ // HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is+ // on disk — without it the recap fires on its settle timer and can beat claude's closing summary+ // to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).+ noteEngineStopped(sessionId)+ const open = turnState(sessionId)+ if (!open?.turnOpen || leftToTranscript(open) || !itsTurn(open)) return // natural JSONL close already won → nothing to do+ // Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close+ // if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.+ await new Promise((r) => setTimeout(r, graceMs))+ await drain(sessionId)+ const st = turnState(sessionId)+ if (st?.turnOpen && !leftToTranscript(st) && itsTurn(st)) {+ st.turnOpen = false+ st.pendingTools.clear()+ console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)+ emit(sessionId, [{ type: 'turn_ended', payload: {} }])+ }+}++export const hooks: EngineHooks = {+ install: installSessionHooks,+ installIn: (port, home) => installSessionHooks(port, join(home, 'settings.json')),+ transcriptFor,+ onStop,+}diff --git a/cli/src/engines/claude/installHooks.ts b/cli/src/engines/claude/installHooks.tsnew file mode 100644index 000000000..89ef51310--- /dev/null+++ b/cli/src/engines/claude/installHooks.ts@@ -0,0 +1,67 @@+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { homedir } from 'node:os'+import { command, HOOK_SCRIPT, isOurs, type Settings } from '../kit/notifyHooks.js'++const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')++// SessionStart/UserPromptSubmit bind mutable engine-session metadata to the process agent. SessionEnd+// only asks discovery to reconcile: the process, not the hook, owns the tile lifetime. UserPromptSubmit+// is the CATCH hook, so a SessionStart missed because the adapter started late is repaired on first input.+// Stop/StopFailure are the authoritative turn-close signals (Stop = normal finish incl. max_tokens/+// refusal; StopFailure = turn ended on an API error, where Stop does NOT fire) — they close a turn even+// when the JSONL-derived turn_ended is missed. Neither supports a matcher (silently ignored).+const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'Stop', 'StopFailure'] as const++/** `settingsPath`: another Claude Code home's settings, for a home the person moved (lib/engineHomes.ts). */+export function installSessionHooks(port: number, settingsPath: string = SETTINGS_PATH): void {+ let settings: Settings = {}+ try {+ settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Settings+ } catch {+ // missing / unreadable → start from empty settings+ }++ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}+ const cmd = command(port, 'claude')+ let changed = false+ let updated = false // true when an EXISTING block's command changed (path/port drift)++ for (const event of EVENTS) {+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []+ // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and+ // keep every non-ours block untouched.+ const foreign = blocks.filter((b) => !isOurs(b))+ const oursBlocks = blocks.filter(isOurs)+ if (oursBlocks.length > 1) changed = true // dropping duplicates is a change++ // The one canonical block for this event with the CURRENT command (path + port). If a prior+ // block existed with a different command (moved checkout / dev↔dist / changed port), this+ // overwrites it in place.+ const existingCmd = oursBlocks[0]?.hooks?.find((h) => isOurs({ hooks: [h] }))?.command+ if (oursBlocks.length === 0) changed = true+ else if (existingCmd !== cmd) { changed = true; updated = true }++ settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]+ }++ if (!changed) {+ console.log('[hooks] Claude session + turn (Stop/StopFailure) hooks already installed')+ return+ }++ try {+ mkdirSync(dirname(settingsPath), { recursive: true })+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n')+ // Both name the file written: a daemon can write several (every moved home gets its own), and the+ // end-to-end harness checks each one it names is inside its throwaway root.+ console.log(+ updated+ ? `[hooks] updated (path/port changed) → ${HOOK_SCRIPT} --port ${port} in ${settingsPath}`+ : `[hooks] installed Claude session + turn (Stop/StopFailure) hooks → ${settingsPath}`,+ )+ console.log('[hooks] (takes effect on the next claude session start)')+ } catch (err) {+ console.error('[hooks] failed to write settings.json:', err)+ }+}diff --git a/cli/src/engines/codex/hooks.ts b/cli/src/engines/codex/hooks.tsnew file mode 100644index 000000000..fde7c76b2--- /dev/null+++ b/cli/src/engines/codex/hooks.ts@@ -0,0 +1,12 @@+import type { EngineHooks } from '../facets/hooks.js'+import { readCodexRolloutMeta } from './rollout.js'+import { installCodexHooks } from './installHooks.js'++export const hooks: EngineHooks = {+ install: installCodexHooks,+ installIn: installCodexHooks,+ admit: (body) => body.transcriptPath && readCodexRolloutMeta(body.transcriptPath)?.isSubagent+ ? { accepted: false, reason: 'codex_subagent' }+ : { accepted: true },+ // Codex closes turns through its transcript, never a Stop hook.+}diff --git a/cli/src/engines/codex/installHooks.ts b/cli/src/engines/codex/installHooks.tsnew file mode 100644index 000000000..88d7f6f13--- /dev/null+++ b/cli/src/engines/codex/installHooks.ts@@ -0,0 +1,59 @@+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../../config/env.js'+import { command, isOurs, writeJsonAtomic, type HookBlock, type Settings } from '../kit/notifyHooks.js'++/**+ * Merge Machine's user-level Codex hooks without replacing unrelated hooks. A malformed existing+ * file is left untouched: silently replacing it could disable user security/automation hooks.+ *+ * `codexHome` defaults to this machine's own default profile, but a Codex agent launched against a+ * different CODEX_HOME profile (see `Agent.codexHome`/`agent_create`) reads hooks.json from THAT+ * folder, not this one — so `onCreateAgent` calls this again with the chosen profile before+ * spawning such an agent. Idempotent either way.+ */+export function installCodexHooks(port: number, codexHome: string = env.CODEX_HOME): void {+ const hooksPath = join(codexHome, 'hooks.json')+ let settings: Settings = {}+ if (existsSync(hooksPath)) {+ try {+ settings = JSON.parse(readFileSync(hooksPath, 'utf-8')) as Settings+ } catch (err) {+ console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${hooksPath}`)+ console.error('[hooks] fix the file, then restart harness login')+ return+ }+ }+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}++ const cmd = command(port, 'codex', codexHome)+ const required: Array<{ event: 'SessionStart' | 'UserPromptSubmit'; matcher?: string }> = [+ { event: 'SessionStart', matcher: 'startup|resume|clear|compact' },+ { event: 'UserPromptSubmit' },+ ]+ let changed = false+ for (const { event, matcher } of required) {+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []+ const foreign = blocks.filter((b) => !isOurs(b))+ const ours = blocks.filter(isOurs)+ const canonical: HookBlock = {+ ...(matcher ? { matcher } : {}),+ hooks: [{ type: 'command', command: cmd, timeout: 5 }],+ }+ const current = ours[0]+ if (ours.length !== 1 || current?.matcher !== matcher || current?.hooks?.[0]?.command !== cmd) changed = true+ settings.hooks[event] = [...foreign, canonical]+ }++ if (!changed) {+ console.log(`[hooks] Codex SessionStart/UserPromptSubmit hooks already installed → ${hooksPath}`)+ return+ }+ try {+ writeJsonAtomic(hooksPath, settings)+ console.log(`[hooks] installed Codex SessionStart/UserPromptSubmit hooks → ${hooksPath}`)+ console.log('[hooks] Codex requires reviewing these user hooks with /hooks before normal use')+ } catch (err) {+ console.error('[hooks] failed to write Codex hooks.json:', err)+ }+}diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.tsindex b227b79f3..19b6f87c9 100644--- a/cli/src/engines/engine.ts+++ b/cli/src/engines/engine.ts@@ -1,10 +1,12 @@import type { ProcessEngine } from './types.js'import type { EngineTranscript } from './facets/transcript.js'import type { EngineLaunch } from './facets/launch.js'+import type { EngineHooks } from './facets/hooks.js'-/** The engine's own contracts. Migration begins with Claude Code and Codex, two facets at a time. */+/** The engine's own contracts. Claude Code and Codex migrate one small batch at a time. */export interface Engine {readonly name: ProcessEnginereadonly transcript: EngineTranscriptreadonly launch: EngineLaunch+ readonly hooks: EngineHooks}diff --git a/cli/src/engines/facets/hooks.ts b/cli/src/engines/facets/hooks.tsnew file mode 100644index 000000000..9a349e765--- /dev/null+++ b/cli/src/engines/facets/hooks.ts@@ -0,0 +1,29 @@+import type { LiveEvent, TurnState } from '../../lib/normalize.js'++/** Only the session facts a hook needs; transport authentication and process binding stay in core. */+export interface HookSession {+ sessionId?: string | null+ transcriptPath?: string | null+}++export interface HookStop { sessionId: string; status?: string; firedAt?: number }++/** Core owns the state and event funnel. The engine decides what its Stop means. */+export interface HookTurnContext {+ turnState(sessionId: string): TurnState | undefined+ latestPromptAt(sessionId: string): number | undefined+ drain(sessionId: string): Promise<void>+ noteEngineStopped(sessionId: string): void+ emit(sessionId: string, events: LiveEvent[]): void+ graceMs: number+}++export type HookAdmission = { accepted: true } | { accepted: false; reason: string }++export interface EngineHooks {+ install(port: number): void+ installIn(port: number, home: string): void+ transcriptFor?(body: HookSession, agent: HookSession | undefined): string | undefined+ admit?(body: HookSession): HookAdmission+ onStop?(context: HookTurnContext, body: HookStop): void | Promise<void>+}diff --git a/cli/src/engines/hooks.spec.ts b/cli/src/engines/hooks.spec.tsnew file mode 100644index 000000000..898533807--- /dev/null+++ b/cli/src/engines/hooks.spec.ts@@ -0,0 +1,57 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterEach, expect, it, vi } from 'vitest'+import { admitHook, engineHooks, hooksFor } from './hooks.js'+import { engineFor } from './registry.js'++afterEach(() => vi.restoreAllMocks())++it('exposes the same hooks through the full and hook-only engine interfaces', () => {+ for (const name of ['claude', 'codex']) expect(engineFor(name)!.hooks).toBe(hooksFor(name))+ for (const name of [null, undefined, '', 'future', 'constructor', '__proto__']) expect(hooksFor(name)).toBeUndefined()+ expect(admitHook('future', {})).toEqual({ accepted: true })+ expect(admitHook('claude', {})).toEqual({ accepted: true })+})++it('installs Claude hooks into the requested home through its facet', () => {+ const home = mkdtempSync(join(tmpdir(), 'claude-hook-facet-'))+ try {+ engineHooks.claude.installIn(19473, home)+ const file = join(home, 'settings.json')+ const first = readFileSync(file, 'utf8')+ const settings = JSON.parse(first)+ expect(Object.keys(settings.hooks)).toEqual(['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'Stop', 'StopFailure'])+ const command = settings.hooks.Stop[0].hooks[0].command as string+ expect(command).toContain('--port 19473')+ expect(command).toContain(fileURLToPath(new URL('../../hook/notify.mjs', import.meta.url)))+ expect(command).not.toContain('--engine')+ engineHooks.claude.installIn(19473, home)+ expect(readFileSync(file, 'utf8')).toBe(first)+ } finally { rmSync(home, { recursive: true, force: true }) }+})++it('rejects Codex delegated rollouts without rejecting a main session or an unwritten transcript', () => {+ const root = mkdtempSync(join(tmpdir(), 'codex-hook-admission-'))+ const transcriptPath = join(root, 'rollout.jsonl')+ try {+ expect(admitHook('codex', {})).toEqual({ accepted: true })+ expect(admitHook('codex', { transcriptPath })).toEqual({ accepted: true })+ writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id: 'child', source: { subagent: { thread_spawn: { parent_thread_id: 'parent' } } } } }) + '\n')+ expect(admitHook('codex', { transcriptPath })).toEqual({ accepted: false, reason: 'codex_subagent' })+ writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id: 'parent', source: 'cli' } }) + '\n')+ expect(admitHook('codex', { transcriptPath })).toEqual({ accepted: true })+ } finally { rmSync(root, { recursive: true, force: true }) }+})++it('rejects a hook when its engine admission check throws, and leaves other engines available', () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(engineHooks.codex, 'admit')+ .mockImplementationOnce(() => { throw new Error('reader failed') })+ .mockImplementationOnce(() => { throw 'reader failed again' })+ expect(admitHook('codex', {})).toEqual({ accepted: false, reason: 'engine_hook_failed' })+ expect(admitHook('codex', {})).toEqual({ accepted: false, reason: 'engine_hook_failed' })+ expect(admitHook('claude', {})).toEqual({ accepted: true })+ expect(console.warn).toHaveBeenCalledWith('[hooks] codex admission failed:', 'reader failed')+})diff --git a/cli/src/engines/hooks.ts b/cli/src/engines/hooks.tsnew file mode 100644index 000000000..5eae149ed--- /dev/null+++ b/cli/src/engines/hooks.ts@@ -0,0 +1,18 @@+import type { EngineHooks, HookAdmission, HookSession } from './facets/hooks.js'+import { hooks as claude } from './claude/hooks.js'+import { hooks as codex } from './codex/hooks.js'++/** Hook-only lookup: installation and the HTTP door do not need history readers or launch code. */+export const engineHooks = { claude, codex }++export function hooksFor(name: string | null | undefined): EngineHooks | undefined {+ return name && Object.hasOwn(engineHooks, name) ? engineHooks[name as keyof typeof engineHooks] : undefined+}++/** A broken admission check must never let a delegated session claim its parent's pane. */+export function admitHook(engine: string, body: HookSession): HookAdmission {+ try { return hooksFor(engine)?.admit?.(body) ?? { accepted: true } } catch (error) {+ console.warn(`[hooks] ${engine} admission failed:`, error instanceof Error ? error.message : error)+ return { accepted: false, reason: 'engine_hook_failed' }+ }+}diff --git a/cli/src/engines/kit/notifyHooks.ts b/cli/src/engines/kit/notifyHooks.tsnew file mode 100644index 000000000..0f1d18b8e--- /dev/null+++ b/cli/src/engines/kit/notifyHooks.ts@@ -0,0 +1,78 @@+/** The notify.mjs command and JSON merge primitives shared by shell-hook engines. */+import { existsSync, mkdirSync, writeFileSync, renameSync } from 'node:fs'+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'++// 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).+// - a core started from the lean bundle (leanEntry.ts): its file is lean/<sha>/ in the data folder, which+// holds no notify.mjs, and its script (process.argv[1]) is the cli.js it was read from: the sibling of that.+// - dev/per-file: notifyHooks.js at <appRoot>/{src,dist}/engines/kit/ → ../../../hook/notify.mjs.+// Prefer the sibling, fall back to the dev path.+const cliDir = dirname(fileURLToPath(import.meta.url))+export const HOOK_SCRIPT =+ [join(cliDir, 'notify.mjs'), ...(process.argv[1] ? [join(dirname(process.argv[1]), 'notify.mjs')] : []), join(cliDir, '..', '..', '..', 'hook', 'notify.mjs')].find(existsSync) ??+ join(cliDir, '..', '..', '..', 'hook', 'notify.mjs')++interface CommandHook {+ type: string+ command: string+ timeout?: number+}+export interface HookBlock {+ matcher?: string+ hooks: CommandHook[]+}+export type Settings = { hooks?: Record<string, HookBlock[]> } & Record<string, unknown>++function shellQuote(value: string): string {+ return `'${value.replace(/'/g, `'\\''`)}'`+}++export function command(+ port: number,+ engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy' | 'copilot',+ // Only ever non-default for 'codex': a per-agent CODEX_HOME profile gets its OWN hooks.json, and+ // that file's baked --codex-home must match where it actually lives (see installCodexHooks).+ codexHome: string = env.CODEX_HOME,+ // Same rule for Hermes, and it was broken the same way: a `hermes -p <name>` profile has its own+ // config.yaml, and the block in it carried the DEFAULT home — so the hook looked the session up in+ // a store it was not in (openharness#191). See installHermesHooks.+ hermesHome: string = env.HERMES_HOME,+): string {+ return [+ // Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell+ // whose PATH is none of our business — and since the product ships its own Node, a computer with+ // no `node` on PATH is normal. See managedNodePath(); a changed interpreter is picked up by the+ // same drift comparison each installer already does for a changed path or port.+ shellQuote(managedNodePath()),+ shellQuote(HOOK_SCRIPT),+ '--port', String(port),+ '--data-dir', shellQuote(env.ADAPTER_DATA_DIR),+ '--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),+ '--codex-home', shellQuote(codexHome),+ '--grok-home', shellQuote(env.GROK_HOME),+ '--cursor-home', shellQuote(cursorDataDir()),+ '--hermes-home', shellQuote(hermesHome),+ '--commandcode-home', shellQuote(env.COMMANDCODE_HOME),+ '--devin-home', shellQuote(env.DEVIN_HOME),+ '--agy-home', shellQuote(env.AGY_HOME),+ '--copilot-home', shellQuote(env.COPILOT_HOME),+ ...(engine !== 'claude' ? ['--engine', engine] : []),+ ].join(' ')+}++/** True if a block already points at our notify.mjs script (any path — robust across layout/version). */+export function isOurs(block: HookBlock): boolean {+ return Array.isArray(block?.hooks) && block.hooks.some((h) => h?.command?.includes('notify.mjs'))+}++export function writeJsonAtomic(file: string, value: unknown): void {+ mkdirSync(dirname(file), { recursive: true })+ const tmp = `${file}.${process.pid}.tmp`+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')+ renameSync(tmp, file)+}diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.tsindex 7e7c0fbb6..820bf4ab5 100644--- a/cli/src/engines/registry.ts+++ b/cli/src/engines/registry.ts@@ -1,15 +1,15 @@import type { Engine } from './engine.js'import { engineLaunches } from './launches.js'+import { engineHooks } from './hooks.js'import { transcript as claudeTranscript } from './claude/transcript.js'import { transcript as codexTranscript } from './codex/transcript.js'/** Only the migrated engines. Others keep their existing handlers until their own small batch. */const engines = {- claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript },- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript },+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude },+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex },} satisfies Record<string, Engine>type MigratedEngine = keyof typeof enginesexport function engineFor(name: string | null | undefined): Engine | undefined {return name && Object.hasOwn(engines, name) ? engines[name as MigratedEngine] : undefined}-diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex f1df2732f..f03815c4a 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -14,6 +14,7 @@ import { createServiceHost } from './core/serviceHost.js'import { startCommandBar, type Commands } from './services/commandBar.js'import { fakeCore } from './testing/fakeCore.js'import { ENGINES } from './engines/types.js'+import { engineHooks } from './engines/hooks.js'let server: Server | null = null@@ -76,6 +77,28 @@ async function start(overrides: Partial<HookServerHandlers> = {}) {describe('process-owned hook server', () => {+ it('honors engine admission before registering or announcing a prompt, including a failed check', async () => {+ const admit = vi.spyOn(engineHooks.codex, 'admit')+ .mockReturnValueOnce({ accepted: false, reason: 'codex_subagent' })+ .mockImplementationOnce(() => { throw new Error('rollout unavailable') })+ try {+ const onPromptSubmitted = vi.fn()+ const { handlers, base, headers } = await start({+ resolveHookAgent: async () => ({ engine: 'codex', agentId: 'parent' }) as RegisteredSession,+ onPromptSubmitted,+ })+ for (const reason of ['codex_subagent', 'engine_hook_failed']) {+ const response = await fetch(`${base}/api/hook/session-start`, {+ method: 'POST', headers,+ body: JSON.stringify({ engine: 'codex', tmuxPane: '%41', sessionId: 'child', hookEvent: 'UserPromptSubmit' }),+ })+ expect(await response.json()).toEqual({ ignored: true, reason })+ }+ expect(handlers.onRegistered).not.toHaveBeenCalled()+ expect(onPromptSubmitted).not.toHaveBeenCalled()+ } finally { admit.mockRestore() }+ })+it('runs targeted resolution and rejects a hook without a matching pane engine process', async () => {const resolveHookAgent = vi.fn(async () => null)const { handlers, base, headers } = await start({ resolveHookAgent })@@ -406,6 +429,16 @@ describe('knownTranscriptFor', () => {expect(knownTranscriptFor({ engine: 'claude', sessionId, transcriptPath: known }, { ...row, transcriptPath: join(root, 'other.jsonl') })).toBe(known)})+ it('keeps the announcement if the engine lookup fails', () => {+ const lookup = vi.spyOn(engineHooks.claude, 'transcriptFor')+ .mockImplementationOnce(() => { throw new Error('lookup failed') })+ .mockImplementationOnce(() => { throw 'lookup failed again' })+ try {+ expect(knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toBe(announced)+ expect(knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toBe(announced)+ } finally { lookup.mockRestore() }+ })+it.each<[string, Parameters<typeof knownTranscriptFor>[0], RegisteredSession | undefined]>([['another conversation', { engine: 'claude', sessionId: 'other-conversation', transcriptPath: announced }, row],['another engine', { engine: 'codex', sessionId, transcriptPath: announced }, row],@@ -413,6 +446,7 @@ describe('knownTranscriptFor', () => {['a row whose file is gone', { engine: 'claude', sessionId, transcriptPath: announced }, { ...row, transcriptPath: join(root, 'gone', `${sessionId}.jsonl`) }],['no row', { engine: 'claude', sessionId, transcriptPath: announced }, undefined],['no announcement', { engine: 'claude', sessionId }, row],+ ['no conversation id', { engine: 'claude', transcriptPath: announced }, row],])('leaves the announcement alone for %s', (_case, body, agent) => {expect(knownTranscriptFor(body, agent)).toBe(body.transcriptPath)})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 1da265692..ef5666cbc 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -5,10 +5,10 @@*/import { existsSync } from 'node:fs'-import { basename, join } from 'node:path'+import { join } from 'node:path'import http from 'node:http'import type { AddressInfo } from 'node:net'-import { readCodexRolloutMeta } from './engines/codex/rollout.js'+import { admitHook, hooksFor } from './engines/hooks.js'import { hermesSessionSource, isHermesInteractiveSource } from './engines/hermes/reader.js'import { hermesDbPath, listHermesHomes } from './engines/hermes/home.js'import { isRecentlyDeleted } from './lib/deletedSessions.js'@@ -322,21 +322,13 @@ function registeredHookProcess(body: RegisterInput, engine: AgentEngine): Registreturn body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) : undefined}-/**- * `claude --resume` from a folder other than the conversation's own: Claude Code announces a transcript- * under the CURRENT cwd's project dir, then keeps writing the original file (measured: a resume of- * 73f090ca from `cli/` announced `…-openharness-cli/73f090ca.jsonl`, and every later turn still landed- * in `…-openharness/73f090ca.jsonl`). The announced file never appears, the hook is dropped, and the- * resume is never confirmed — "Start failed" over a pane that is working. The row being resumed already- * knows the real file; take it when it names this very conversation.- */+/** The engine may correct an announcement; a failed correction leaves registration's checks intact. */export function knownTranscriptFor(body: RegisterInput, agent: RegisteredSession | undefined): string | undefined {- const announced = body.transcriptPath- if (!announced || existsSync(announced) || (body.engine ?? 'claude') !== 'claude') return announced- const known = agent?.transcriptPath- if (!known || !body.sessionId || agent.sessionId !== body.sessionId) return announced- if (basename(known) !== `${body.sessionId}.jsonl` || !existsSync(known)) return announced- return known+ const engine = body.engine ?? 'claude'+ try { return hooksFor(engine)?.transcriptFor?.(body, agent) ?? body.transcriptPath } catch (error) {+ console.warn(`[hooks] ${engine} transcript lookup failed:`, error instanceof Error ? error.message : error)+ return body.transcriptPath+ }}/**@@ -547,10 +539,8 @@ export function startHookServer(// hook still fires — and the exact process may remain alive during SIGTERM grace. Without// this the tile the user just deleted re-registers itself and comes back.if (isRecentlyDeleted(body.sessionId)) { ignore('deleted'); return }- if (body.engine === 'codex' && body.transcriptPath && readCodexRolloutMeta(body.transcriptPath)?.isSubagent) {- ignore('codex_subagent')- return- }+ const admission = admitHook(engine, body)+ if (!admission.accepted) { ignore(admission.reason); return }// Same story for hermes, which reaches here through its own hooks rather than a transcript file:// every delegated sub-agent is a hermes session that runs those hooks from the parent's pane.if (body.engine === 'hermes' && body.sessionId) {diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex f7fc59aba..8fec3f352 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -1,22 +1,16 @@-/**- * Idempotently install the machine-adapter SessionStart / SessionEnd hooks into- * ~/.claude/settings.json so claude notifies us when tmux sessions start/end.- *- * Changes to settings.json take effect on the NEXT claude session start.- */+/** Hook installers for engines still awaiting migration to their hooks facet. */import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync } from 'fs'import { basename, join, dirname } from 'path'-import { homedir } from 'os'-import { fileURLToPath } from 'url'import { cursorConfigDir, cursorDataDir } from '../engines/cursor/home.js'import { env } from '../config/env.js'import { VERSION } from '../version.js'import { hermesConfigHomes } from '../engines/hermes/home.js'import { opencodeMajorVersion } from '../engines/opencode/version.js'-import { managedNodePath } from './nodeRuntime.js'+import { command, isOurs, writeJsonAtomic, type HookBlock, type Settings } from '../engines/kit/notifyHooks.js'+export { installSessionHooks } from '../engines/claude/installHooks.js'+export { installCodexHooks } from '../engines/codex/installHooks.js'-const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')const CURSOR_HOOKS_PATH = join(cursorConfigDir(), 'hooks.json')// agy reads hooks from its SHARED customization root (~/.gemini/config), not from its own state dir —@@ -27,193 +21,6 @@ const AGY_HOOKS_PATH = join(env.AGY_CONFIG_DIR, 'hooks.json')// user's. Measured: a file dropped here fires without any further opt-in.const COPILOT_HOOKS_PATH = join(env.COPILOT_HOME, 'hooks', 'harness.json')-// 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).-// - a core started from the lean bundle (leanEntry.ts): its file is lean/<sha>/ in the data folder, which-// holds no notify.mjs, and its script (process.argv[1]) is the cli.js it was read from: the sibling of that.-// - dev/per-file: hooks.js at <appRoot>/{src,dist}/lib/ → notify.mjs at ../../hook/notify.mjs.-// Prefer the sibling, fall back to the dev path.-const cliDir = dirname(fileURLToPath(import.meta.url))-const HOOK_SCRIPT =- [join(cliDir, 'notify.mjs'), ...(process.argv[1] ? [join(dirname(process.argv[1]), 'notify.mjs')] : []), join(cliDir, '..', '..', 'hook', 'notify.mjs')].find(existsSync) ??- join(cliDir, '..', '..', 'hook', 'notify.mjs')--// SessionStart/UserPromptSubmit bind mutable engine-session metadata to the process agent. SessionEnd-// only asks discovery to reconcile: the process, not the hook, owns the tile lifetime. UserPromptSubmit-// is the CATCH hook, so a SessionStart missed because the adapter started late is repaired on first input.-// Stop/StopFailure are the authoritative turn-close signals (Stop = normal finish incl. max_tokens/-// refusal; StopFailure = turn ended on an API error, where Stop does NOT fire) — they close a turn even-// when the JSONL-derived turn_ended is missed. Neither supports a matcher (silently ignored).-const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'Stop', 'StopFailure'] as const--interface CommandHook {- type: string- command: string- timeout?: number-}-interface HookBlock {- matcher?: string- hooks: CommandHook[]-}-type Settings = { hooks?: Record<string, HookBlock[]> } & Record<string, unknown>--function shellQuote(value: string): string {- return `'${value.replace(/'/g, `'\\''`)}'`-}--function command(- port: number,- engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy' | 'copilot',- // Only ever non-default for 'codex': a per-agent CODEX_HOME profile gets its OWN hooks.json, and- // that file's baked --codex-home must match where it actually lives (see installCodexHooks).- codexHome: string = env.CODEX_HOME,- // Same rule for Hermes, and it was broken the same way: a `hermes -p <name>` profile has its own- // config.yaml, and the block in it carried the DEFAULT home — so the hook looked the session up in- // a store it was not in (openharness#191). See installHermesHooks.- hermesHome: string = env.HERMES_HOME,-): string {- return [- // Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell- // whose PATH is none of our business — and since the product ships its own Node, a computer with- // no `node` on PATH is normal. See managedNodePath(); a changed interpreter is picked up by the- // same drift comparison each installer already does for a changed path or port.- shellQuote(managedNodePath()),- shellQuote(HOOK_SCRIPT),- '--port', String(port),- '--data-dir', shellQuote(env.ADAPTER_DATA_DIR),- '--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),- '--codex-home', shellQuote(codexHome),- '--grok-home', shellQuote(env.GROK_HOME),- '--cursor-home', shellQuote(cursorDataDir()),- '--hermes-home', shellQuote(hermesHome),- '--commandcode-home', shellQuote(env.COMMANDCODE_HOME),- '--devin-home', shellQuote(env.DEVIN_HOME),- '--agy-home', shellQuote(env.AGY_HOME),- '--copilot-home', shellQuote(env.COPILOT_HOME),- ...(engine !== 'claude' ? ['--engine', engine] : []),- ].join(' ')-}--/** True if a block already points at our notify.mjs script (any path — robust across layout/version). */-function isOurs(block: HookBlock): boolean {- return Array.isArray(block?.hooks) && block.hooks.some((h) => h?.command?.includes('notify.mjs'))-}--/** `settingsPath`: another Claude Code home's settings, for a home the person moved (lib/engineHomes.ts). */-export function installSessionHooks(port: number, settingsPath: string = SETTINGS_PATH): void {- let settings: Settings = {}- try {- settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Settings- } catch {- // missing / unreadable → start from empty settings- }-- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}- const cmd = command(port, 'claude')- let changed = false- let updated = false // true when an EXISTING block's command changed (path/port drift)-- for (const event of EVENTS) {- const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []- // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and- // keep every non-ours block untouched.- const foreign = blocks.filter((b) => !isOurs(b))- const oursBlocks = blocks.filter(isOurs)- if (oursBlocks.length > 1) changed = true // dropping duplicates is a change-- // The one canonical block for this event with the CURRENT command (path + port). If a prior- // block existed with a different command (moved checkout / dev↔dist / changed port), this- // overwrites it in place.- const existingCmd = oursBlocks[0]?.hooks?.find((h) => isOurs({ hooks: [h] }))?.command- if (oursBlocks.length === 0) changed = true- else if (existingCmd !== cmd) { changed = true; updated = true }-- settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]- }-- if (!changed) {- console.log('[hooks] Claude session + turn (Stop/StopFailure) hooks already installed')- return- }-- try {- mkdirSync(dirname(settingsPath), { recursive: true })- writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n')- // Both name the file written: a daemon can write several (every moved home gets its own), and the- // end-to-end harness checks each one it names is inside its throwaway root.- console.log(- updated- ? `[hooks] updated (path/port changed) → ${HOOK_SCRIPT} --port ${port} in ${settingsPath}`- : `[hooks] installed Claude session + turn (Stop/StopFailure) hooks → ${settingsPath}`,- )- console.log('[hooks] (takes effect on the next claude session start)')- } catch (err) {- console.error('[hooks] failed to write settings.json:', err)- }-}--function writeJsonAtomic(file: string, value: unknown): void {- mkdirSync(dirname(file), { recursive: true })- const tmp = `${file}.${process.pid}.tmp`- writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')- renameSync(tmp, file)-}--/**- * Merge Machine's user-level Codex hooks without replacing unrelated hooks. A malformed existing- * file is left untouched: silently replacing it could disable user security/automation hooks.- *- * `codexHome` defaults to this machine's own default profile, but a Codex agent launched against a- * different CODEX_HOME profile (see `Agent.codexHome`/`agent_create`) reads hooks.json from THAT- * folder, not this one — so `onCreateAgent` calls this again with the chosen profile before- * spawning such an agent. Idempotent either way.- */-export function installCodexHooks(port: number, codexHome: string = env.CODEX_HOME): void {- const hooksPath = join(codexHome, 'hooks.json')- let settings: Settings = {}- if (existsSync(hooksPath)) {- try {- settings = JSON.parse(readFileSync(hooksPath, 'utf-8')) as Settings- } catch (err) {- console.error(`[hooks] Codex hooks file is invalid JSON; leaving it unchanged: ${hooksPath}`)- console.error('[hooks] fix the file, then restart harness login')- return- }- }- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}-- const cmd = command(port, 'codex', codexHome)- const required: Array<{ event: 'SessionStart' | 'UserPromptSubmit'; matcher?: string }> = [- { event: 'SessionStart', matcher: 'startup|resume|clear|compact' },- { event: 'UserPromptSubmit' },- ]- let changed = false- for (const { event, matcher } of required) {- const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []- const foreign = blocks.filter((b) => !isOurs(b))- const ours = blocks.filter(isOurs)- const canonical: HookBlock = {- ...(matcher ? { matcher } : {}),- hooks: [{ type: 'command', command: cmd, timeout: 5 }],- }- const current = ours[0]- if (ours.length !== 1 || current?.matcher !== matcher || current?.hooks?.[0]?.command !== cmd) changed = true- settings.hooks[event] = [...foreign, canonical]- }-- if (!changed) {- console.log(`[hooks] Codex SessionStart/UserPromptSubmit hooks already installed → ${hooksPath}`)- return- }- try {- writeJsonAtomic(hooksPath, settings)- console.log(`[hooks] installed Codex SessionStart/UserPromptSubmit hooks → ${hooksPath}`)- console.log('[hooks] Codex requires reviewing these user hooks with /hooks before normal use')- } catch (err) {- console.error('[hooks] failed to write Codex hooks.json:', err)- }-}-/** Merge the adapter's Grok lifecycle hooks into a dedicated global hook file. Grok loads every JSON* file in ~/.grok/hooks, so using our own file avoids touching the user's other hook packages. Normal* Stop is intentionally omitted because its record precedes Grok's final assistant chunk on disk. */diff --git a/docs/design/2026-10-05-engine-interface.md b/docs/design/2026-10-05-engine-interface.mdindex 9d5ed36a3..42e855d17 100644--- a/docs/design/2026-10-05-engine-interface.md+++ b/docs/design/2026-10-05-engine-interface.md@@ -2,8 +2,11 @@> **Status, 2026-10-07: resumed by the owner, a few engines per batch.** The first batch moves Claude> Code and Codex launch contracts, paged history and last-turn reads behind an `Engine` interface. It-> preserves their existing argv and transcript behavior. Launch metadata loads separately from readers.-> Hooks, discovery/resume, live ingestion, screen/input, models and one-shot handling remain to migrate.+> preserves their existing argv and transcript behavior. The second batch moves their hook installation,+> Claude Code's resume-path correction and Stop handling, and Codex's subagent admission behind a hooks+> facet. Launch metadata and hooks load separately from history readers. Core retains authenticated+> transport, process binding, prompt timestamps and event delivery. Discovery/resume, live ingestion,+> screen/input, models and one-shot handling remain to migrate.> The older all-engine branches (`engine-interface-1..5`, `engine-lane-*`, draft PR #842) are retained as> reference work; they are not the implementation currently landing. The phased plan below is the> target architecture, not a claim that all facets or engine isolation are already complete.@@ -1199,4 +1202,3 @@ All counts are on `main` at `31b4a0c27`, run from `cli/`, without spec files.`src/lib/sessionSearch/externals` 55,983 bytes.- The inventory tables (section 3): read from the code by file, with each decision's lines; the linesare on `31b4a0c27` and will move.-