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
Core boundary, part 7: the engines' hooks become modules (#728)
Deeda1d69552dc3
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex dd0336cda..9481c597e 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -51,7 +51,7 @@ import { DeviceLink } from './device/deviceLink.js'import { DeviceFleet } from './device/deviceFleet.js'import { registry, projectDisplayName, sessionDisplayTitle, validTranscriptPath, type RegisteredSession } from './lib/registry.js'import { engineSessionTitle } from './lib/sessionTitle.js'-import { installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installGrokHooks, installAgyHooks, installCopilotHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'+import { installCodexHooks } from './lib/hooks.js'import { PID_FILE, daemonPort, isAlive, isDaemonRunning, readPid } from './lib/daemonState.js'import { clearSafeModeMarker, readSafeModeMarker, runBootHandoff, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from './lib/daemonSafeMode.js'import { awakeTimeout } from './lib/sleepAware.js'@@ -135,17 +135,13 @@ import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'import { TerminalStreamManager } from './lib/terminalStreamManager.js'import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'-import { processRows } from './lib/terminalAgentDiscovery.js'import { remoteCommand } from './remoteCommand.js'import { tuiCommand } from './tui/index.js'import { newCommand } from './lib/newCommand.js'import { gridSetupCommand } from './lib/gridSetupCommand.js'import { WebSocket as NewCommandSocket } from 'ws'-import {- type TerminalRuntimeRef,-} from './lib/terminalTypes.js'import { Watcher } from './watcher/watcher.js'-import { chooseHookAgent, startHookServer } from './hookServer.js'+import { startHookServer } from './hookServer.js'import { connectToMaster } from './harnessd/coreLink.js'import { createTerminalControl } from './core/terminals/control.js'import { createAgentEvents } from './core/agents/events.js'@@ -175,6 +171,8 @@ import { createAgentRetargeter } from './core/agents/retarget.js'import { createAgentRestarter } from './core/agents/restart.js'import { createAgentLifecycle } from './core/agents/lifecycle.js'import { createAgentClosing } from './core/agents/close.js'+import { createEngineHooks, installEngineHooks } from './core/engines/hooks.js'+import { createCursorTaskHooks } from './core/engines/cursorTasks.js'import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'@@ -215,11 +213,8 @@ import { updateManagedTui } from './tui/manage.js'import { startTuiUpdater } from './tui/update.js'import { ensureHnLauncher, ensureLauncher, ensureManagedGrid, ensureManagedRuntime, startGridPinRecheck } from './lib/runtimeInstall.js'import { type ActivityFrame } from './lib/turnActivity.js'-import { CursorNormalizer } from './engines/cursor/normalizer.js'import { CursorTranscriptDiscovery } from './engines/cursor/discovery.js'-import { cursorConfigDir, cursorDataDir } from './engines/cursor/home.js'-import { CursorSubagentManager } from './engines/cursor/subagent.js'-import { CursorTaskHookQueue } from './engines/cursor/taskHookQueue.js'+import { cursorDataDir } from './engines/cursor/home.js'import { loadCursorPendingTasks } from './engines/cursor/pendingTasks.js'import { readOpencodeMessages } from './engines/opencode/reader.js'import { opencodeMajorVersion } from './engines/opencode/version.js'@@ -2416,26 +2411,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {questionWatcher,mirror,})- const cursorSubagents = new CursorSubagentManager(cursorConfigDir(), emitSessionEvents, cursorDataDir())- const cursorTaskHooks = new CursorTaskHookQueue({- drainTranscript: (sessionId) => watcher.pollSession(sessionId),- emit: emitSessionEvents,- register: (sessionId, hook, normalizer) => cursorSubagents.register(sessionId, hook, normalizer),- isActive: (sessionId) => registry.bySession(sessionId)?.engine === 'cursor',- onError: (sessionId, error) => {- console.error(`[cursor] Task hook queue failed (${sessionId}):`, error instanceof Error ? error.message : error)- },- })- const onCursorTaskStart = (sessionId: string, toolUseId: string, toolInput: unknown): void => {- const session = registry.resolve(sessionId)- if (!session || session.engine !== 'cursor') return- let normalizer = cursorNormalizers.get(sessionId)- if (!normalizer) {- normalizer = new CursorNormalizer('live', sessionId)- cursorNormalizers.set(sessionId, normalizer)- }- cursorTaskHooks.enqueue(sessionId, { toolUseId, input: toolInput }, normalizer)- }+ // Cursor's Task hooks and the sub-agents they start (core/engines/cursorTasks.ts).+ const cursorTasks = createCursorTaskHooks({ emitSessionEvents, watcher, registry, cursorNormalizers })+ const cursorSubagents = cursorTasks.cursorSubagents+ const cursorTaskHooks = cursorTasks.cursorTaskHooks+ const onCursorTaskStart = cursorTasks.onCursorTaskStart// Release a session's binding, or remove a process-owned agent everywhere (core/agents/forget.ts).const forgetSession = createForgetSession({@@ -2530,12 +2510,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {},})- // SessionEnd describes the mutable engine session, never process lifetime. Reconcile now; discovery- // decides whether the agent still exists from terminal inventory + ps.- const onSessionEnd = (_sessionId: string, _reason: string | undefined): void => {- void agentReconciler.trigger()- }-/** Proxy a control-plane call to backend using THIS daemon's own SSO session — the local caller* (e.g. the desktop app) never needs a bearer token of its own, loopback trust does the* authenticating. Forwards backend's response status/body verbatim, success or error alike, so a@@ -2709,6 +2683,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {mirror,dataDir: env.ADAPTER_DATA_DIR,})+ // Which agent a hook belongs to, and what a SessionEnd means (core/engines/hooks.ts).+ const engineHooks = createEngineHooks({ tmuxBackend, agentReconciler, registry })const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {onCommandBar: commandBarService,onAutonomousDeviceRequest: async (method, target, body) => {@@ -2731,71 +2707,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {receipt: target => ({ receipt: autonomousDeviceService!.receipt(target.deviceId, target.idempotencyKey) }),}, method, target, body)},- resolveHookAgent: async ({ engine, runtimeHints, callerPid }) => {- if (!callerPid) return null- const resolved: TerminalRuntimeRef[] = []- for (const hint of runtimeHints ?? []) {- if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })- }- for (const runtime of resolved) await agentReconciler.triggerHint(runtime, engine)-- const rows = await processRows()- if (!rows) return null- const callerBelongsTo = (session: RegisteredSession): boolean => {- const expectedPid = session.processIdentity?.pid- if (!expectedPid) return false- const byPid = new Map(rows.map((row) => [row.pid, row.parentPid]))- let pid = callerPid- const visited = new Set<number>()- while (pid > 0 && !visited.has(pid)) {- if (pid === expectedPid) return true- visited.add(pid)- pid = byPid.get(pid) ?? 0- }- return false- }- const candidates = new Map<string, RegisteredSession>()- /**- * Agents the hint points at whose ancestry we could NOT confirm.- *- * Caller ancestry is the strongest evidence and stays the first choice, but it assumes every engine- * spawns its hook from inside its own process tree — and Cursor does not. Measured on both- * backends: `agent` in a pane registers fine, then every one of its hooks is rejected because the- * process that POSTs is not a descendant of the pane's engine, so no session ever binds.- *- * Keep that exception specific to Cursor. A delayed hook from an exited process can still name- * a pane now owned by its replacement; the pane and hook credential alone cannot prove that a- * Codex (or other engine's) old transcript belongs to the new process.- */- const onHintedRuntime = new Map<string, RegisteredSession>()- for (const runtime of resolved) {- const candidate = registry.byRuntimeEngine(runtime, engine)- if (!candidate) continue- if (callerBelongsTo(candidate)) candidates.set(candidate.agentId, candidate)- else onHintedRuntime.set(candidate.agentId, candidate)- }- const choice = chooseHookAgent([...candidates.values()], [...onHintedRuntime.values()], engine)- if (choice.agent) {- if (choice.reason === 'runtime') {- console.log(`[hooks] ${engine} hook accepted on runtime evidence alone`- + ` · agent=${sid(choice.agent.agentId)} · caller=${callerPid} is outside that engine's process tree`)- }- return choice.agent- }- // Say WHY, once per rejected hook. "no_matching_engine_process" alone sent two people down the- // wrong path already: the interesting question is never "did it match" but which of the three- // gates closed — no runtime resolved from the hint, no registered agent on that runtime, or the- // hook's own process is not a descendant of the engine we registered.- const onRuntime = resolved.map((runtime) => registry.byRuntimeEngine(runtime, engine)).filter(Boolean)- console.log(`[hooks] unmatched ${engine} hook · hints=${(runtimeHints ?? []).map((hint) => `${hint.backend}:${hint.paneId}`).join(',') || 'none'}`- + ` · resolvedRuntimes=${resolved.length} · agentsOnRuntime=${onRuntime.length}`- + ` · callerPid=${callerPid}${onRuntime.length && !candidates.size ? ' · caller is not a descendant of that engine process' : ''}`- + `${candidates.size > 1 ? ` · ambiguous (${candidates.size} candidates)` : ''}`)- return null- },+ resolveHookAgent: engineHooks.resolveHookAgent,onRegistered: handleRegistered,onPromptSubmitted: (id, text) => backend.swarmPromptScopes.started(id, text, 'hook', registry.byAgent(id)?.engine),- onSessionEnd,+ onSessionEnd: engineHooks.onSessionEnd,// What the engines' own hooks say about a turn (core/turns/turnHooks.ts).onTurnStart: turnHooks.onTurnStart,onToolStart: turnHooks.onToolStart,@@ -3409,33 +3324,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Cut to the wire's limit here rather than let the far daemon drop the whole claim over a long name.localClient: () => ({ kind: 'desktop', name: terminalHintMachineName().slice(0, 64), machineId: backend.machineId }),})- // Install both CLI hooks with the port the local server actually bound.- //- // One vendor at a time, each behind its own guard: these write into thirteen different settings- // files owned by thirteen different CLIs, and one that is malformed, read-only or mid-write is not- // a reason for the other twelve to go uninstalled — let alone for the daemon not to come up.- const hookStep = (vendor: string, install: () => void): void => {- try { install() } catch (error) {- console.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)- }- }- if (!env.DISABLE_HOOK_INSTALL) {- hookStep('claude', () => installSessionHooks(hookPort))- hookStep('codex', () => installCodexHooks(hookPort))- hookStep('cursor', () => installCursorHooks(hookPort))- hookStep('opencode', () => installOpencodePlugin(hookPort))- hookStep('kilo', () => installKiloPlugin(hookPort))- hookStep('pi', () => installPiExtension(hookPort))- // A self-update refreshes plugin files here; running engine processes pick them up according to each- // vendor's own plugin reload lifecycle.- hookStep('amp', () => installAmpPlugin(hookPort))- hookStep('hermes', () => installHermesHooks(hookPort))- hookStep('devin', () => installDevinHooks(hookPort))- hookStep('commandcode', () => installCommandCodeHooks(hookPort))- hookStep('grok', () => installGrokHooks(hookPort))- hookStep('agy', () => installAgyHooks(hookPort))- hookStep('copilot', () => installCopilotHooks(hookPort))- }+ // Every engine's hooks, pointed at the port the local server actually bound (core/engines/hooks.ts).+ if (!env.DISABLE_HOOK_INSTALL) installEngineHooks(hookPort)backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approveconsole.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)diff --git a/cli/src/core/engines/cursorTasks.spec.ts b/cli/src/core/engines/cursorTasks.spec.tsnew file mode 100644index 000000000..aaed7c846--- /dev/null+++ b/cli/src/core/engines/cursorTasks.spec.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { CursorNormalizer } from '../../engines/cursor/normalizer.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createCursorTaskHooks, type CursorTaskDeps } from './cursorTasks.js'++vi.mock('../../engines/cursor/home.js', () => ({ cursorConfigDir: () => '/cursor/config', cursorDataDir: () => '/cursor/data' }))+vi.mock('../../engines/cursor/subagent.js', () => ({+ CursorSubagentManager: class {+ readonly args: unknown[]+ register = vi.fn()+ constructor(...args: unknown[]) { this.args = args }+ },+}))+vi.mock('../../engines/cursor/taskHookQueue.js', () => ({+ CursorTaskHookQueue: class {+ enqueue = vi.fn()+ constructor(readonly options: Record<string, (...args: never[]) => unknown>) {}+ },+}))++type Manager = { args: unknown[]; register: ReturnType<typeof vi.fn> }+type Queue = { options: Record<string, (...args: unknown[]) => unknown>; enqueue: ReturnType<typeof vi.fn> }+const cursor = { agentId: 'a1', sessionId: 's1', engine: 'cursor' } as RegisteredSession++function setup(row: RegisteredSession | null = cursor) {+ const deps: CursorTaskDeps = {+ emitSessionEvents: vi.fn(),+ watcher: { pollSession: vi.fn(async () => {}) } as unknown as CursorTaskDeps['watcher'],+ registry: { bySession: vi.fn(() => row ?? undefined), resolve: vi.fn(() => row ?? undefined) } as unknown as CursorTaskDeps['registry'],+ cursorNormalizers: new Map(),+ }+ const tasks = createCursorTaskHooks(deps)+ return { deps, tasks, manager: tasks.cursorSubagents as unknown as Manager, queue: tasks.cursorTaskHooks as unknown as Queue }+}++describe('Cursor\'s Task hooks', () => {+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('follow sub-agents in Cursor\'s own folders, emitting through the funnel', () => {+ const { deps, manager } = setup()+ expect(manager.args).toEqual(['/cursor/config', deps.emitSessionEvents, '/cursor/data'])+ })++ it('queue each Task behind a drain of its transcript, for live Cursor sessions only', async () => {+ const { deps, manager, queue } = setup()+ await queue.options.drainTranscript('s1')+ expect(deps.watcher.pollSession).toHaveBeenCalledWith('s1')+ expect(queue.options.emit).toBe(deps.emitSessionEvents)+ const hook = { toolUseId: 't1', input: {} }+ queue.options.register('s1', hook, 'normalizer')+ expect(manager.register).toHaveBeenCalledWith('s1', hook, 'normalizer')+ expect(queue.options.isActive('s1')).toBe(true)+ expect(setup({ ...cursor, engine: 'claude' } as RegisteredSession).queue.options.isActive('s1')).toBe(false)+ expect(setup(null).queue.options.isActive('s1')).toBe(false)+ })++ it('say which session\'s queue failed, and why', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const { queue } = setup()+ queue.options.onError('s1', new Error('drain failed'))+ expect(error).toHaveBeenCalledWith('[cursor] Task hook queue failed (s1):', 'drain failed')+ queue.options.onError('s1', 'gone')+ expect(error).toHaveBeenLastCalledWith('[cursor] Task hook queue failed (s1):', 'gone')+ })++ it('start a Task on the session\'s live normalizer, making one when it has none yet', () => {+ const { deps, tasks, queue } = setup()+ tasks.onCursorTaskStart('s1', 't1', { prompt: 'look' })+ const made = deps.cursorNormalizers.get('s1')+ expect(made).toBeInstanceOf(CursorNormalizer)+ expect(queue.enqueue).toHaveBeenCalledWith('s1', { toolUseId: 't1', input: { prompt: 'look' } }, made)+ tasks.onCursorTaskStart('s1', 't2', null)+ expect(queue.enqueue).toHaveBeenLastCalledWith('s1', { toolUseId: 't2', input: null }, made)+ expect(deps.cursorNormalizers.size).toBe(1)+ })++ it('ignore a Task for a session that is gone or is not Cursor\'s', () => {+ const gone = setup(null)+ gone.tasks.onCursorTaskStart('s1', 't1', {})+ const other = setup({ ...cursor, engine: 'codex' } as RegisteredSession)+ other.tasks.onCursorTaskStart('s1', 't1', {})+ expect(gone.queue.enqueue).not.toHaveBeenCalled()+ expect(other.queue.enqueue).not.toHaveBeenCalled()+ expect(other.deps.cursorNormalizers.size).toBe(0)+ })+})diff --git a/cli/src/core/engines/cursorTasks.ts b/cli/src/core/engines/cursorTasks.tsnew file mode 100644index 000000000..0cc60cec5--- /dev/null+++ b/cli/src/core/engines/cursorTasks.ts@@ -0,0 +1,45 @@+/**+ * Cursor's Task hooks. Cursor's preToolUse hook can beat its transcript, so a Task's start is queued+ * behind a transcript drain, and the sub-agent it starts is registered to be followed.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).+ */+import { cursorConfigDir, cursorDataDir } from '../../engines/cursor/home.js'+import { CursorNormalizer } from '../../engines/cursor/normalizer.js'+import { CursorSubagentManager } from '../../engines/cursor/subagent.js'+import { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'+import type { LiveEvent } from '../../lib/normalize.js'+import type { registry } from '../../lib/registry.js'+import type { Watcher } from '../../watcher/watcher.js'++export interface CursorTaskDeps {+ emitSessionEvents: (sessionId: string, events: LiveEvent[]) => void+ watcher: Pick<Watcher, 'pollSession'>+ registry: Pick<typeof registry, 'bySession' | 'resolve'>+ /** The live Cursor normalizers, by session (the normalizer table's). */+ cursorNormalizers: Map<string, CursorNormalizer>+}++export function createCursorTaskHooks({ emitSessionEvents, watcher, registry, cursorNormalizers }: CursorTaskDeps) {+ const cursorSubagents = new CursorSubagentManager(cursorConfigDir(), emitSessionEvents, cursorDataDir())+ const cursorTaskHooks = new CursorTaskHookQueue({+ drainTranscript: (sessionId) => watcher.pollSession(sessionId),+ emit: emitSessionEvents,+ register: (sessionId, hook, normalizer) => cursorSubagents.register(sessionId, hook, normalizer),+ isActive: (sessionId) => registry.bySession(sessionId)?.engine === 'cursor',+ onError: (sessionId, error) => {+ console.error(`[cursor] Task hook queue failed (${sessionId}):`, error instanceof Error ? error.message : error)+ },+ })+ const onCursorTaskStart = (sessionId: string, toolUseId: string, toolInput: unknown): void => {+ const session = registry.resolve(sessionId)+ if (!session || session.engine !== 'cursor') return+ let normalizer = cursorNormalizers.get(sessionId)+ if (!normalizer) {+ normalizer = new CursorNormalizer('live', sessionId)+ cursorNormalizers.set(sessionId, normalizer)+ }+ cursorTaskHooks.enqueue(sessionId, { toolUseId, input: toolInput }, normalizer)+ }+ return { cursorSubagents, cursorTaskHooks, onCursorTaskStart }+}diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsnew file mode 100644index 000000000..a6948c204--- /dev/null+++ b/cli/src/core/engines/hooks.spec.ts@@ -0,0 +1,141 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import * as hooks from '../../lib/hooks.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { processRows } from '../../lib/terminalAgentDiscovery.js'+import { createEngineHooks, installEngineHooks, type EngineHookDeps } from './hooks.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(),+ installPiExtension: vi.fn(),+ installAmpPlugin: vi.fn(),+ installHermesHooks: vi.fn(),+ installDevinHooks: vi.fn(),+ installCommandCodeHooks: vi.fn(),+ installGrokHooks: vi.fn(),+ installAgyHooks: vi.fn(),+ installCopilotHooks: vi.fn(),+}))++const agent = (agentId: string, pid?: number) =>+ ({ agentId, engine: 'claude', ...(pid ? { processIdentity: { pid, startMarker: 'm' } } : {}) }) as unknown as RegisteredSession+/** A process tree: each [pid, parentPid]. */+const tree = (...pairs: Array<[number, number]>) => pairs.map(([pid, parentPid]) => ({ pid, parentPid, startMarker: 'm', args: '' }))+const hint = (paneId: string) => ({ backend: 'tmux' as const, paneId })++function setup(onPane: Record<string, RegisteredSession> = {}, over: Partial<EngineHookDeps> = {}) {+ const deps: EngineHookDeps = {+ tmuxBackend: {},+ agentReconciler: { triggerHint: vi.fn(async () => {}), trigger: vi.fn(async () => {}) } as unknown as EngineHookDeps['agentReconciler'],+ registry: { byRuntimeEngine: vi.fn((runtime: { paneId: string }) => onPane[runtime.paneId]) } as unknown as EngineHookDeps['registry'],+ ...over,+ }+ return { deps, hooks: createEngineHooks(deps) }+}++describe('which agent a hook belongs to', () => {+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('none, for a hook that did not say which process sent it', async () => {+ const { deps, hooks } = setup()+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')] })).toBeNull()+ expect(deps.agentReconciler.triggerHint).not.toHaveBeenCalled()+ })++ it('the agent on the hinted pane whose engine the caller descends from, once the pane is reconciled', async () => {+ const a1 = agent('a1', 100)+ const { deps, hooks } = setup({ '%1': a1 })+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBe(a1)+ expect(deps.agentReconciler.triggerHint).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')+ expect(deps.registry.byRuntimeEngine).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')+ expect(console.log).not.toHaveBeenCalled()+ })++ it('none when the process table cannot be read', async () => {+ vi.mocked(processRows).mockResolvedValueOnce(null)+ expect(await setup({ '%1': agent('a1', 100) }).hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBeNull()+ })++ it('a Cursor agent on the pane alone, saying the caller is outside its process tree', async () => {+ const c1 = { ...agent('cursor-1'), engine: 'cursor' } as RegisteredSession+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 1]) as never)+ expect(await setup({ '%1': c1 }).hooks.resolveHookAgent({ engine: 'cursor', runtimeHints: [hint('%1')], callerPid: 300 })).toBe(c1)+ expect(console.log).toHaveBeenCalledWith('[hooks] cursor hook accepted on runtime evidence alone · agent=cursor-1 · caller=300 is outside that engine\'s process tree')+ })++ it('none for any other engine on the pane alone, saying the caller is not its descendant', async () => {+ // 300's parent 200 is not in the table; the walk stops there.+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [100, 1]) as never)+ expect(await setup({ '%1': agent('a1', 100) }).hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBeNull()+ expect(console.log).toHaveBeenCalledWith('[hooks] unmatched claude hook · hints=tmux:%1 · resolvedRuntimes=1 · agentsOnRuntime=1'+ + ' · callerPid=300 · caller is not a descendant of that engine process')+ })++ it('none for an agent with no process to descend from, and a process table that loops', async () => {+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 400], [400, 300]) as never)+ const { hooks } = setup({ '%1': agent('no-pid'), '%2': agent('a2', 100) })+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1'), hint('%2')], callerPid: 300 })).toBeNull()+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('agentsOnRuntime=2 · callerPid=300 · caller is not a descendant'))+ })++ it('none when two agents could own the hook, saying it is ambiguous', async () => {+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)+ const { hooks } = setup({ '%1': agent('a1', 100), '%2': agent('a2', 200) })+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1'), hint('%2')], callerPid: 300 })).toBeNull()+ expect(console.log).toHaveBeenCalledWith('[hooks] unmatched claude hook · hints=tmux:%1,tmux:%2 · resolvedRuntimes=2 · agentsOnRuntime=2'+ + ' · callerPid=300 · ambiguous (2 candidates)')+ })++ it('none when no agent is on the pane, when there is no tmux to resolve it, or no pane was named', async () => {+ const empty = setup()+ expect(await empty.hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%9')], callerPid: 300 })).toBeNull()+ expect(console.log).toHaveBeenLastCalledWith('[hooks] unmatched claude hook · hints=tmux:%9 · resolvedRuntimes=1 · agentsOnRuntime=0 · callerPid=300')++ const noTmux = setup({ '%1': agent('a1', 100) }, { tmuxBackend: null })+ expect(await noTmux.hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBeNull()+ expect(noTmux.deps.agentReconciler.triggerHint).not.toHaveBeenCalled()+ expect(console.log).toHaveBeenLastCalledWith('[hooks] unmatched claude hook · hints=tmux:%1 · resolvedRuntimes=0 · agentsOnRuntime=0 · callerPid=300')++ expect(await empty.hooks.resolveHookAgent({ engine: 'claude', runtimeHints: undefined as never, callerPid: 300 })).toBeNull()+ expect(console.log).toHaveBeenLastCalledWith('[hooks] unmatched claude hook · hints=none · resolvedRuntimes=0 · agentsOnRuntime=0 · callerPid=300')+ })++ it('a SessionEnd only asks for a reconcile: discovery decides whether the agent still exists', () => {+ const { deps, hooks } = setup()+ hooks.onSessionEnd('s1', 'exit')+ expect(deps.agentReconciler.trigger).toHaveBeenCalledTimes(1)+ })+})++describe('installing every engine\'s hooks', () => {+ const installs = [+ hooks.installSessionHooks, hooks.installCodexHooks, hooks.installCursorHooks, hooks.installOpencodePlugin,+ hooks.installKiloPlugin, hooks.installPiExtension, hooks.installAmpPlugin, hooks.installHermesHooks,+ hooks.installDevinHooks, hooks.installCommandCodeHooks, hooks.installGrokHooks, hooks.installAgyHooks,+ hooks.installCopilotHooks,+ ]+ beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}) })+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('points all thirteen at the bound port', () => {+ installEngineHooks(4242)+ for (const install of installs) expect(install).toHaveBeenCalledWith(4242)+ expect(console.warn).not.toHaveBeenCalled()+ })++ 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(hooks.installGrokHooks).mockImplementationOnce(() => { throw 'settings mid-write' })+ installEngineHooks(4242)+ expect(console.warn).toHaveBeenCalledWith('[hooks] codex install skipped · config.toml is read-only')+ expect(console.warn).toHaveBeenCalledWith('[hooks] grok install skipped · settings mid-write')+ for (const install of installs) expect(install).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsnew file mode 100644index 000000000..674ac5798--- /dev/null+++ b/cli/src/core/engines/hooks.ts@@ -0,0 +1,128 @@+/**+ * The engines' own hooks: which registered agent a hook belongs to, what a SessionEnd means, and+ * installing every engine's hooks so they call this daemon.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).+ */+import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'+import {+ installAgyHooks, installAmpPlugin, installCodexHooks, 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'+import { processRows } from '../../lib/terminalAgentDiscovery.js'+import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'+import type { TerminalRuntimeRef } from '../../lib/terminalTypes.js'++type ResolveHookAgent = NonNullable<HookServerHandlers['resolveHookAgent']>++export interface EngineHookDeps {+ /** Hints name tmux panes; without tmux there is nothing they can point at. */+ tmuxBackend: unknown+ agentReconciler: Pick<TerminalAgentReconciler, 'triggerHint' | 'trigger'>+ registry: Pick<typeof registry, 'byRuntimeEngine'>+}++export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: EngineHookDeps) {+ const resolveHookAgent: ResolveHookAgent = async ({ engine, runtimeHints, callerPid }) => {+ if (!callerPid) return null+ const resolved: TerminalRuntimeRef[] = []+ for (const hint of runtimeHints ?? []) {+ if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })+ }+ for (const runtime of resolved) await agentReconciler.triggerHint(runtime, engine)++ const rows = await processRows()+ if (!rows) return null+ const callerBelongsTo = (session: RegisteredSession): boolean => {+ const expectedPid = session.processIdentity?.pid+ if (!expectedPid) return false+ const byPid = new Map(rows.map((row) => [row.pid, row.parentPid]))+ let pid = callerPid+ const visited = new Set<number>()+ while (pid > 0 && !visited.has(pid)) {+ if (pid === expectedPid) return true+ visited.add(pid)+ pid = byPid.get(pid) ?? 0+ }+ return false+ }+ const candidates = new Map<string, RegisteredSession>()+ /**+ * Agents the hint points at whose ancestry we could NOT confirm.+ *+ * Caller ancestry is the strongest evidence and stays the first choice, but it assumes every engine+ * spawns its hook from inside its own process tree — and Cursor does not. Measured on both+ * backends: `agent` in a pane registers fine, then every one of its hooks is rejected because the+ * process that POSTs is not a descendant of the pane's engine, so no session ever binds.+ *+ * Keep that exception specific to Cursor. A delayed hook from an exited process can still name+ * a pane now owned by its replacement; the pane and hook credential alone cannot prove that a+ * Codex (or other engine's) old transcript belongs to the new process.+ */+ const onHintedRuntime = new Map<string, RegisteredSession>()+ for (const runtime of resolved) {+ const candidate = registry.byRuntimeEngine(runtime, engine)+ if (!candidate) continue+ if (callerBelongsTo(candidate)) candidates.set(candidate.agentId, candidate)+ else onHintedRuntime.set(candidate.agentId, candidate)+ }+ const choice = chooseHookAgent([...candidates.values()], [...onHintedRuntime.values()], engine)+ if (choice.agent) {+ if (choice.reason === 'runtime') {+ console.log(`[hooks] ${engine} hook accepted on runtime evidence alone`+ + ` · agent=${sid(choice.agent.agentId)} · caller=${callerPid} is outside that engine's process tree`)+ }+ return choice.agent+ }+ // Say WHY, once per rejected hook. "no_matching_engine_process" alone sent two people down the+ // wrong path already: the interesting question is never "did it match" but which of the three+ // gates closed — no runtime resolved from the hint, no registered agent on that runtime, or the+ // hook's own process is not a descendant of the engine we registered.+ const onRuntime = resolved.map((runtime) => registry.byRuntimeEngine(runtime, engine)).filter(Boolean)+ console.log(`[hooks] unmatched ${engine} hook · hints=${(runtimeHints ?? []).map((hint) => `${hint.backend}:${hint.paneId}`).join(',') || 'none'}`+ + ` · resolvedRuntimes=${resolved.length} · agentsOnRuntime=${onRuntime.length}`+ + ` · callerPid=${callerPid}${onRuntime.length && !candidates.size ? ' · caller is not a descendant of that engine process' : ''}`+ + `${candidates.size > 1 ? ` · ambiguous (${candidates.size} candidates)` : ''}`)+ return null+ }++ // SessionEnd describes the mutable engine session, never process lifetime. Reconcile now; discovery+ // decides whether the agent still exists from terminal inventory + ps.+ const onSessionEnd = (_sessionId: string, _reason: string | undefined): void => {+ void agentReconciler.trigger()+ }+ return { resolveHookAgent, onSessionEnd }+}++/**+ * Install every engine's hooks with the port the local server actually bound.+ *+ * One vendor at a time, each behind its own guard: these write into thirteen different settings+ * files owned by thirteen different CLIs, and one that is malformed, read-only or mid-write is not+ * a reason for the other twelve to go uninstalled — let alone for the daemon not to come up.+ */+export function installEngineHooks(port: number): void {+ const hookStep = (vendor: string, install: () => void): void => {+ try { install() } catch (error) {+ console.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)+ }+ }+ hookStep('claude', () => installSessionHooks(port))+ hookStep('codex', () => installCodexHooks(port))+ hookStep('cursor', () => installCursorHooks(port))+ hookStep('opencode', () => installOpencodePlugin(port))+ hookStep('kilo', () => installKiloPlugin(port))+ hookStep('pi', () => installPiExtension(port))+ // A self-update refreshes plugin files here; running engine processes pick them up according to each+ // vendor's own plugin reload lifecycle.+ hookStep('amp', () => installAmpPlugin(port))+ hookStep('hermes', () => installHermesHooks(port))+ hookStep('devin', () => installDevinHooks(port))+ hookStep('commandcode', () => installCommandCodeHooks(port))+ hookStep('grok', () => installGrokHooks(port))+ hookStep('agy', () => installAgyHooks(port))+ hookStep('copilot', () => installCopilotHooks(port))+}diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex ce41929c3..6a60d99b8 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -391,13 +391,15 @@ Done so far:that passed its canary but crashed the core restarted every machine on it once a minute. Testedend to end on real release bundles served from a local manifest (`e2e/update.e2e.ts`): one kept,one rolled back and left alone, then a newer one kept.-- **The core boundary, steps 1 to 11** (#716, #717, #721, #723, #725 and part 6): `runForeground`- is down from 5,306 lines to 2,880. 29 modules under `cli/src/core` hold terminal control, session- events, the normalizer table, input, questions, the turns (activity, heartbeats, recaps, the event- funnel, stop hooks, the agy backstop, cancel), the transcripts (attach, ingest, last turn) and the- agent lifecycle (forget, bind, discovery, launch, new panes, adoption, create, fork, the pane swap,- retarget, restart, stop, purge, resume, close). Each file is held to 100% by `npm run test:core`,- which CI runs; the unit and e2e suites pass at every step. Steps 12 to 14 remain.+- **The core boundary, steps 1 to 12** (#716, #717, #721, #723, #725, #727 and part 7):+ `runForeground` is down from 5,306 lines to 2,775. 31 modules under `cli/src/core` hold terminal+ control, session events, the normalizer table, input, questions, the turns (activity, heartbeats,+ recaps, the event funnel, stop hooks, the agy backstop, cancel), the transcripts (attach, ingest,+ last turn), the agent lifecycle (forget, bind, discovery, launch, new panes, adoption, create,+ fork, the pane swap, retarget, restart, stop, purge, resume, close) and the engines' hooks (which+ agent a hook belongs to, Cursor's Task hooks, installing every engine's hooks). Each file is held+ to 100% by `npm run test:core`, which CI runs; the unit and e2e suites pass at every step. Steps+ 13 and 14 remain.Next, in order: