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
fix(cli): route engine hooks to their pane owner daemon (#913)
Dee3b36bf8552ef
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex ffff1714a..cad0761d8 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -115,6 +115,8 @@ export function assertHooksContained(root: string, env: NodeJS.ProcessEnv): voidcheck('CODEX_HOME', env.CODEX_HOME)if (env.CLAUDE_CONFIG_DIR !== undefined) check('CLAUDE_CONFIG_DIR', env.CLAUDE_CONFIG_DIR)check('ZDOTDIR', env.ZDOTDIR)+ // Not a hook, but what routes every hook: a record outside the root would send the person's hooks here.+ if (env.HARNESS_HOOK_ROUTES_DIR !== undefined) check('HARNESS_HOOK_ROUTES_DIR', env.HARNESS_HOOK_ROUTES_DIR)for (const [folder, names] of Object.entries(PROFILES) as Array<[keyof typeof PROFILES, string[]]>) {for (const name of names) {const file = join(env[folder]!, name)@@ -237,6 +239,9 @@ export class IsolatedDaemon {// folders these tests have no engine for.DISABLE_HOOK_INSTALL: 'false',HOOK_INSTALL_ENGINES: 'claude,codex',+ // Where each daemon records its data folder and port for the hooks of its panes (lib/hookRoutes.ts):+ // under the home, as on a person's computer, so daemons beside each other share it.+ HARNESS_HOOK_ROUTES_DIR: join(dirs.home, '.harness', 'hook-routes'),ADAPTER_UPDATE_DISABLE: 'true',ANALYTICS_ENABLED: 'false',RECAP_FORCE: 'false',diff --git a/cli/e2e/twodaemons.e2e.ts b/cli/e2e/twodaemons.e2e.tsindex b5bb574b1..1faaf8fbd 100644--- a/cli/e2e/twodaemons.e2e.ts+++ b/cli/e2e/twodaemons.e2e.ts@@ -138,6 +138,71 @@ describe('two daemons on one computer', () => {atDev.close()})+ it('a dev daemon beside the release one: each daemon\'s agents\' hooks reach that daemon, whichever installed the hooks last', async () => {+ // A computer has one Claude Code hook entry and one Codex hook entry, and each daemon writes its own+ // port into them as it starts. The dev daemon, started second, took every hook: the release daemon's+ // agents' hooks went to it, it turned them away (not its panes), and the release daemon never heard+ // their session starts, prompts or turn ends. Each daemon now records where it listens under its pane+ // tag, and the hook goes to the daemon that made its pane (lib/hookRoutes.ts, notify.mjs).+ const release = await make('release')+ const dev = await make('dev', { beside: release })+ await release.start()+ await dev.start()+ const installed = () => [join(release.env.HOME!, '.claude', 'settings.json'), join(release.env.CODEX_HOME!, 'hooks.json')]+ .map((file) => readFileSync(file, 'utf8'))+ // The precondition of the incident: the entries every engine started from here on runs are the dev daemon's.+ for (const file of installed()) expect(file).toContain(`--port ${dev.port} `)++ const atRelease = await LocalClient.connect(release)+ const atDev = await LocalClient.connect(dev)+ const agents = {+ release: [await create(release, atRelease, 'claude', 'release-claude'), await create(release, atRelease, 'codex', 'release-codex')],+ dev: [await create(dev, atDev, 'claude', 'dev-claude'), await create(dev, atDev, 'codex', 'dev-codex')],+ }+ await Promise.all([+ ...agents.release.map((agent) => turn(atRelease, agent.id, 'a release turn')),+ ...agents.dev.map((agent) => turn(atDev, agent.id, 'a dev turn')),+ ])+ const heard = (daemon: IsolatedDaemon, agent: Row, event: string) => daemon.log().includes(`[hooks] ${String(agent.sessionId).slice(0, 8)} ${event}`)+ const reachedOnlyItsOwn = async (mine: IsolatedDaemon, other: IsolatedDaemon, agent: Row, engine: Engine) => {+ // Claude Code's prompt and turn-end hooks, Codex's session start and prompt (lib/hooks.ts installs no more).+ for (const event of engine === 'claude' ? ['UserPromptSubmit', 'turn-stop'] : ['SessionStart', 'UserPromptSubmit']) {+ await until(`${engine} ${agent.id}'s ${event} hook at its own daemon`, () => heard(mine, agent, event), 20_000, 250)+ }+ expect(other.log(), 'the other daemon heard none of its hooks').not.toContain(`[hooks] ${String(agent.sessionId).slice(0, 8)}`)+ expect(other.log(), 'the other daemon turned none of its hooks away').not.toContain(`hints=tmux:${agent.tmuxPane} `)+ }+ for (const [mine, other, [claude, codex]] of [[release, dev, agents.release], [dev, release, agents.dev]] as const) {+ await reachedOnlyItsOwn(mine, other, claude, 'claude')+ await reachedOnlyItsOwn(mine, other, codex, 'codex')+ }++ // And the other way round: restarted, the release daemon owns the entries; a new dev agent reaches dev.+ atRelease.close()+ await release.restart()+ for (const file of installed()) expect(file).toContain(`--port ${release.port} `)+ const later = await create(dev, atDev, 'claude', 'dev-later')+ await turn(atDev, later.id, 'a dev turn after the release daemon restarted')+ await reachedOnlyItsOwn(dev, release, later, 'claude')+ atDev.close()+ }, 240_000)++ it('a routes path that is a regular file leaves the daemon serving its own installed hooks', async () => {+ // Found by QA on a quiet machine: a routing warning must not become a startup failure in cleanup.+ const d = await make('route-unavailable', { noMaster: true })+ d.env.HARNESS_HOOK_ROUTES_DIR = join(d.root, 'blocked-routes')+ writeFileSync(d.env.HARNESS_HOOK_ROUTES_DIR, 'not a folder')+ await d.start()+ expect(d.log()).toContain('could not record this daemon\'s hook route')+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, 'claude', 'route-unavailable')+ await turn(client, agent.id, 'the installed command still names this daemon')+ await until('the hook at the installed command\'s daemon', () =>+ d.log().includes(`[hooks] ${String(agent.sessionId).slice(0, 8)} UserPromptSubmit`), 20_000)+ expect(readFileSync(d.env.HARNESS_HOOK_ROUTES_DIR, 'utf8')).toBe('not a folder')+ client.close()+ })+it('a second harness start while one runs leaves it alone; a foreground one leaves at once, touching nothing', async () => {const daemon = await make('running')await daemon.start()diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex f72eeefcc..83540497a 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -67,7 +67,14 @@ function modelName(value) {return typeof value?.id === 'string' ? value.id : null}+/**+ * The daemon this hook reports to, once the pane it came from has named it (`routeToPaneOwner`): its data+ * folder and port, in place of the `--data-dir` and `--port` the installed command carries.+ */+let routed = null+function argPort() {+ if (routed) return routed.portconst i = process.argv.indexOf('--port')if (i !== -1 && process.argv[i + 1]) return parseInt(process.argv[i + 1], 10)return parseInt(process.env.AGENT_ADAPTER_PORT || '18473', 10)@@ -106,7 +113,7 @@ function argAgyEvent() {function paths() {const cliDir = join(homedir(), '.harness', 'cli')- const dataDir = argValue('--data-dir', process.env.ADAPTER_DATA_DIR || join(cliDir, 'data'))+ const dataDir = routed?.dataDir ?? argValue('--data-dir', process.env.ADAPTER_DATA_DIR || join(cliDir, 'data'))const claudeProjectsDir = argValue('--claude-projects-dir', process.env.CLAUDE_PROJECTS_DIR || join(homedir(), '.claude', 'projects'))const codexHome = argValue('--codex-home', process.env.CODEX_HOME || join(homedir(), '.codex'))const grokHome = argValue('--grok-home', process.env.GROK_HOME || join(homedir(), '.grok'))@@ -475,16 +482,17 @@ function daemonPaneOwner(dataDir) {}/**- * The pane, as tmux describes it, in one call: its root process, and whether the daemon this hook writes- * for takes it for one of its agents at all, by the rule its discovery reads panes with (`ownedHere`):- * one it tagged, wherever the person moved it; an untagged one only in a session Harness named, or one an- * older build named (`<engine>-<ms>`) that its registry already holds (`taken: 'if-held'`); another- * daemon's, never. A session the person opened by hand is not an agent: with the daemon up, its hook is- * turned away. The offline fallback wrote a row for one all the same, and the daemon came back with an- * agent it would never have made and could not drive, "offline" for good (e2e/hookclient.e2e.ts).- * Undefined when tmux could not answer.+ * The pane, as tmux describes it, in one call: its root process, its session, and the tag of the daemon+ * that made it (from the pane's option, or before tmux 3.0 from its start command). Read once per hook:+ * the route to the daemon is chosen from it first, and the offline fallback reads it again. Undefined+ * when tmux could not answer.*/-async function paneFacts(pane, dataDir) {+const paneDescriptions = new Map()+function describePane(pane) {+ if (!paneDescriptions.has(pane)) paneDescriptions.set(pane, readPaneDescription(pane))+ return paneDescriptions.get(pane)+}+async function readPaneDescription(pane) {const format = (await tmuxHasPaneOptions()) ? PANE_OWNER_FORMAT : PANE_OWNER_FORMAT_OLD_TMUXconst stdout = await execFileText('tmux', ['display-message', '-p', '-t', pane, `#{pane_pid}|#{session_name}|${format}`], 2000)if (stdout === null) return undefined@@ -496,10 +504,68 @@ async function paneFacts(pane, dataDir) {const session = line.slice(first + 1, last)const field = line.slice(last + 1)const owner = field.startsWith(OWNER_COMMAND_PREFIX) ? field.slice(OWNER_COMMAND_PREFIX.length).split(' ')[0] : field+ return { pid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, session, owner }+}++/**+ * Whether the daemon this hook writes for takes the pane for one of its agents at all, by the rule its+ * discovery reads panes with (`ownedHere`): one it tagged, wherever the person moved it; an untagged one+ * only in a session Harness named, or one an older build named (`<engine>-<ms>`) that its registry+ * already holds (`taken: 'if-held'`); another daemon's, never. A session the person opened by hand is not+ * an agent: with the daemon up, its hook is turned away. The offline fallback wrote a row for one all the+ * same, and the daemon came back with an agent it would never have made and could not drive, "offline"+ * for good (e2e/hookclient.e2e.ts). Undefined when tmux could not answer.+ */+async function paneFacts(pane, dataDir) {+ const described = await describePane(pane)+ if (!described) return undefined+ const { pid, session, owner } = describedconst taken = owner ? (owner === daemonPaneOwner(dataDir) ? 'yes' : 'no'): session.startsWith(HARNESS_SESSION_PREFIX) ? 'yes': /^[a-z][a-z0-9]*-\d{13}$/.test(session) ? 'if-held' : 'no'- return { pid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, taken }+ return { pid, taken }+}++/**+ * Where every daemon on this computer says it listens, one file per pane tag (src/lib/hookRoutes.ts,+ * which hookNotify.spec.ts keeps this equal to).+ */+function hookRoutesDir() {+ return process.env.HARNESS_HOOK_ROUTES_DIR || join(homedir(), '.harness', 'hook-routes')+}++/**+ * Report to the daemon that made the pane, not to the one whose command this is.+ *+ * Claude Code's and Codex's hooks are installed once per computer, in ~/.claude/settings.json and+ * $CODEX_HOME/hooks.json, and each daemon wrote its own port and data folder into them as it started. With+ * a dev daemon beside the release one, the last to start owned every hook: the other daemon's agents'+ * hooks went to it, it turned them away (the pane was not its own), and their turn ends and session+ * starts were lost. Each daemon now records its data folder and port under the tag it puts on its panes+ * (`publishHookRoute`), and the hook looks the pane's tag up: a record whose data folder hashes to that tag+ * routes this hook, its credential, and any offline write to that daemon. A record still names a daemon+ * that is down: the hook's post fails and its offline write lands in that daemon's own registry, where it+ * will read it. A pane with no tag, or a tag with no record (a daemon from before the records), keeps the+ * command's own `--port` and `--data-dir`, as every installed command did.+ */+async function routeToPaneOwner(pane) {+ if (!/^%\d+$/.test(pane || '')) return null+ const described = await describePane(pane)+ const tag = described?.owner+ if (!tag || !/^[0-9a-f]{16}$/.test(tag)) return null+ try {+ const dir = hookRoutesDir()+ secureStateDirectory(dir, false)+ const record = JSON.parse(readPrivateStateFile(join(dir, `${tag}.json`), 4096))+ const dataDir = record?.dataDir+ const port = record?.port+ if (typeof dataDir !== 'string' || !isAbsolute(dataDir) || !Number.isInteger(port) || port < 1 || port > 65535) return null+ // The record must be the tag's own, and its folder still there: a folder since removed would be+ // created again by the offline write, for a daemon that will never read it.+ if (daemonPaneOwner(dataDir) !== tag || !statSync(dataDir).isDirectory()) return null+ routed = { dataDir, port }+ return routed+ } catch { return null }}function argvTokens(args) {@@ -1405,7 +1471,7 @@ async function fallbackSessionEnd(sessionId, reason, engine, tmuxPane) {}async function main() {- const port = argPort()+ let port = argPort()const engine = argEngine()const raw = await readStdin()let input = {}@@ -1418,6 +1484,8 @@ async function main() {const event = input.hook_event_name || input.hookEventNameconst tmuxPane = process.env.TMUX_PANEif (!tmuxPane) return+ // Before anything reads the data folder or posts: which daemon this pane is (routeToPaneOwner).+ if (await routeToPaneOwner(tmuxPane)) port = argPort()const mutationFields = { engine, ...terminalHookFields(tmuxPane) }if (engine === 'cursor' && input.is_background_agent === true) returnif (engine === 'codex' && isCodexSubagent(input, paths())) returndiff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 4b987ed0c..fd067875b 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -216,6 +216,10 @@ const fields = {// `app-*.log`/`cli-*.log`, so one directory holds everything a bug report needs. Not the data dir:// `harness.log` there is the daemon's console, and `harness reset` wipes it.HARNESS_LOGS_DIR: text(join(adapterRootDir, 'logs')),+ // Where each daemon on this computer records its data folder and port under the tag it puts on its+ // panes, so an engine's hook reaches the daemon that made its pane whichever daemon installed the hook+ // (lib/hookRoutes.ts). Product-root state, shared by every daemon of this user: not in a data folder.+ HARNESS_HOOK_ROUTES_DIR: text(join(adapterRootDir, 'hook-routes')),// Where domain-specific harnesses are installed (`harness dsh install`): one directory per// `<owner>/<name>` plus `installed.json`. Product-root state like the SSO session, not daemon data.DSH_DIR: text(join(adapterRootDir, 'dsh')),diff --git a/cli/src/config/envIsolation.spec.ts b/cli/src/config/envIsolation.spec.tsindex 758802207..5cc90cbdd 100644--- a/cli/src/config/envIsolation.spec.ts+++ b/cli/src/config/envIsolation.spec.ts@@ -25,6 +25,9 @@ describe('test environment isolation', () => {})it('keeps the lessons folder off the developer\'s ~/.harness, so no spec writes a lesson there', () => {})+ it('keeps the hook routes off the developer\'s ~/.harness, so no spec records a daemon beside theirs or routes by one', () => {+ expect(env.HARNESS_HOOK_ROUTES_DIR.startsWith(productRoot)).toBe(false)+ })it('keeps account reads and refreshes in the test-owned auth directory', () => {expect(AUTH_DIR).toBe(join(env.ADAPTER_DATA_DIR, 'auth'))expect(AUTH_DIR.startsWith(productRoot)).toBe(false)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex d5a1bc34a..090d703ff 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -145,6 +145,7 @@ import { startFleet } from '../services/fleet.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from '../harnessd/protocol.js'import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'import { saveDaemonPort } from '../lib/daemonEndpoint.js'+import { publishHookRoute } from '../lib/hookRoutes.js'import { commandBarService } from '../lib/commandBar.js'import { BackendSocket, isLocalClientId } from '../backendSocket.js'import { createGatewayLink } from './gatewayLink.js'@@ -1709,6 +1710,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {hookServer.close()throw error}+ publishHookRoute(env.ADAPTER_DATA_DIR, hookPort)// Claim the pid file for OURSELVES, and only now that the control port is bound. It used to be// written by whoever spawned us — so a parent that died mid-handover left a daemon nothing could// manage — and then, for a while, by us at the top of this function, before the bind — so a childdiff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 8943ea92f..28198adcc 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -1,13 +1,14 @@import { execFileSync, spawn, spawnSync } from 'child_process'import { createServer } from 'http'import { createServer as createNetServer } from 'net'-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'import { afterEach, describe, expect, it, vi } from 'vitest'import { ENGINES } from './engines/types.js'import { HARNESS_OWNER_OPTION, HARNESS_SESSION_PREFIX, harnessPaneOwner, ownerCommand, paneOwnerFormat } from './lib/harnessSessionLabel.js'+import { hookRouteFile, publishHookRoute } from './lib/hookRoutes.js'// Every case here spawns the real hook as a child process, and several spawn shell shims for tmux, ps// and sqlite3 on top of that. On a loaded machine — this file runs alongside 88 others — that chain@@ -74,18 +75,30 @@ function runHook(opts: RunHookOpts): Promise<string> {if (opts.env) Object.assign(env, opts.env)delete env.TMUX_PANEif (opts.tmuxPane) env.TMUX_PANE = opts.tmuxPane+ // Every hook asks tmux whose pane it is (notify.mjs routeToPaneOwner). Without a shim below, that+ // question must reach no server at all, least of all the developer's: TMUX outranks TMUX_TMPDIR, and+ // TMUX_TMPDIR has to exist or tmux falls back to the default socket.+ delete env.TMUX+ env.TMUX_TMPDIR = mkdtempSync(join(tmpdir(), 'adapter-hook-tmux-'))+ tmpDirs.push(env.TMUX_TMPDIR)delete env.MACHINE_IDif (opts.launcherId !== null) env.MACHINE_ID = opts.launcherId ?? '11111111-2222-4333-8444-555555555555'- if (opts.processEngine) {+ if (opts.processEngine || opts.paneOwner !== undefined || opts.paneSession !== undefined) {const binDir = mkdtempSync(join(tmpdir(), 'adapter-hook-bin-'))tmpDirs.push(binDir)- const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)- const processArgs = opts.processArgs ?? executableconst shellQuote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'"// The pane as tmux describes it: its root process, and the session and tag that say whose agent it// is (a Harness session, untagged, unless the test says otherwise).const paneFacts = `${opts.paneSession ?? 'harness-claude-1790000000000'}|${opts.paneOwner ?? ''}`writeFileSync(join(binDir, 'tmux'), `#!/bin/sh\nprintf '%s\\n' ${shellQuote(`7000|${paneFacts}`)}\n`, { mode: 0o755 })+ env.PATH = `${binDir}:${env.PATH ?? ''}`+ }+ if (opts.processEngine) {+ const binDir = mkdtempSync(join(tmpdir(), 'adapter-hook-bin-'))+ tmpDirs.push(binDir)+ const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)+ const processArgs = opts.processArgs ?? executable+ const shellQuote = (value: string) => "'" + value.replace(/'/g, "'\\''") + "'"writeFileSync(join(binDir, 'ps'), `#!/bin/sh\nprintf '%s\\n' '7000 1 zsh Mon Aug 10 10:00:00 2026 -zsh' ${shellQuote(`7001 7000 ${executable} Mon Aug 10 10:00:01 2026 ${processArgs}`)} '${process.pid} 7001 node Mon Aug 10 10:00:02 2026 hook-parent'\n`, { mode: 0o755 })if (opts.processEngine === 'cursor') {const target = join(binDir, 'cursor-agent-target')@@ -137,11 +150,12 @@ function runHook(opts: RunHookOpts): Promise<string> {}/** A throwaway localhost adapter that records every hook POST. */-async function collect(response: Record<string, unknown> = {}): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {+async function collect(response: Record<string, unknown> = {}, credential?: string): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {// Local service discovery may probe a test port. Only hook POSTs belong to this fixture.if (req.method !== 'POST') { res.writeHead(405).end(); return }+ if (credential && req.headers['x-harness-hook-token'] !== credential) { req.resume(); res.writeHead(401).end(); return }let raw = ''req.on('data', (chunk) => { raw += chunk.toString() })req.on('end', () => {@@ -1495,3 +1509,131 @@ describe('hook notify Command Code re-registration', () => {expect(requests.map((r) => r.url)).toEqual(['/api/hook/turn-stop'])})})++describe('a hook reaches the daemon that made its pane', () => {+ // A computer has one Claude Code entry and one Codex entry, and each daemon writes its own --port and+ // --data-dir into them as it starts. With a dev daemon beside the release one, the last to start took+ // every hook and turned the other's away. Each daemon records where it listens under its pane tag+ // (lib/hookRoutes.ts), and the hook follows the pane's tag there (notify.mjs routeToPaneOwner).+ function computer() {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'adapter-hook-routes-')))+ tmpDirs.push(dir)+ const routes = join(dir, 'hook-routes')+ const daemon = (name: string) => {+ const dataDir = join(dir, name)+ mkdirSync(dataDir, { recursive: true, mode: 0o700 })+ const credential = name[0].repeat(43)+ writeFileSync(join(dataDir, 'hook-credential'), `${credential}\n`, { mode: 0o600 })+ return { dataDir, tag: harnessPaneOwner(dataDir), credential }+ }+ return { dir, routes, release: daemon('release'), dev: daemon('dev') }+ }+ const sessionEnd = { hook_event_name: 'SessionEnd', session_id: 'session-routed', reason: 'logout' }++ it('follows the pane\'s tag to its daemon, whichever daemon\'s command ran it', async () => {+ const { routes, release, dev } = computer()+ const atRelease = await collect({}, release.credential)+ const atDev = await collect({}, dev.credential)+ publishHookRoute(release.dataDir, atRelease.port, routes)+ publishHookRoute(dev.dataDir, atDev.port, routes)+ // The dev daemon started last: the command is its own. The pane is the release daemon's.+ await runHook({+ port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%7', paneOwner: release.tag,+ env: { HARNESS_HOOK_ROUTES_DIR: routes }, input: sessionEnd,+ })+ expect(atRelease.requests.map((r) => r.url)).toEqual(['/api/hook/session-end'])+ expect(atDev.requests).toEqual([])+ // Its own pane, through its own command, as before.+ await runHook({+ port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%8', paneOwner: dev.tag,+ env: { HARNESS_HOOK_ROUTES_DIR: routes }, input: sessionEnd,+ })+ expect(atDev.requests.map((r) => r.url)).toEqual(['/api/hook/session-end'])+ // Before tmux 3.0 the tag rides in the pane's start command.+ await runHook({+ port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%9', paneOwner: ownerCommand(release.tag, []).join(' '),+ env: { HARNESS_HOOK_ROUTES_DIR: routes }, input: sessionEnd,+ })+ expect(atRelease.requests).toHaveLength(2)+ })++ it('the actual hook rejects malformed route records and uses its installed command', async () => {+ // These checks used to exercise an unused TypeScript reader, not the hook that consumes the file.+ const { routes, release, dev } = computer()+ const atRelease = await collect({}, release.credential)+ const atDev = await collect({}, dev.credential)+ publishHookRoute(release.dataDir, atRelease.port, routes)+ const bodies = ['broken', 'null', '{}', JSON.stringify({ dataDir: release.dataDir, port: 0 }),+ JSON.stringify({ dataDir: release.dataDir, port: 65_536 }),+ JSON.stringify({ dataDir: release.dataDir, port: String(atRelease.port) }),+ JSON.stringify({ dataDir: 7, port: atRelease.port }),+ JSON.stringify({ dataDir: dev.dataDir, port: atRelease.port })]+ for (const body of bodies) {+ writeFileSync(hookRouteFile(release.tag, routes), body, { mode: 0o600 })+ await runHook({ port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%7', paneOwner: release.tag,+ env: { HARNESS_HOOK_ROUTES_DIR: routes }, input: sessionEnd })+ }+ expect(atRelease.requests).toEqual([])+ expect(atDev.requests).toHaveLength(bodies.length)+ })++ it('keeps the command\'s own --port and --data-dir, as every installed command carried them, when the pane names no daemon it can trust', async () => {+ const { dir, routes, release, dev } = computer()+ const atRelease = await collect()+ const atDev = await collect()+ const hook = (paneOwner: string, extra: Partial<RunHookOpts> = {}) => runHook({+ port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%7', paneOwner, env: { HARNESS_HOOK_ROUTES_DIR: routes }, input: sessionEnd, ...extra,+ })+ const record = hookRouteFile(release.tag, routes)+ // An untagged pane in a session Harness named (a pane from before the tag), and a tag with no record+ // (a daemon from before the records).+ await hook('')+ await hook(release.tag)+ // A record that is not the tag's own: another daemon's folder under this tag.+ publishHookRoute(release.dataDir, atRelease.port, routes)+ writeFileSync(record, JSON.stringify({ dataDir: dev.dataDir, port: atRelease.port }), { mode: 0o600 })+ await hook(release.tag)+ // A record others could have written, in a folder others could write, and one whose folder is gone.+ publishHookRoute(release.dataDir, atRelease.port, routes)+ chmodSync(record, 0o666)+ await hook(release.tag)+ publishHookRoute(release.dataDir, atRelease.port, routes)+ chmodSync(routes, 0o777)+ await hook(release.tag)+ chmodSync(routes, 0o700)+ const gone = join(dir, 'gone')+ mkdirSync(gone)+ publishHookRoute(gone, atRelease.port, routes)+ rmSync(gone, { recursive: true })+ await hook(harnessPaneOwner(gone))+ expect(atRelease.requests).toEqual([])+ expect(atDev.requests).toHaveLength(6)+ // And with the record in order, the same hook goes to the release daemon.+ publishHookRoute(release.dataDir, atRelease.port, routes)+ await hook(release.tag)+ expect(atRelease.requests).toHaveLength(1)+ })++ it('offline, writes its registry row into the daemon that made the pane, which reads it when it is back', async () => {+ const { dir, routes, release, dev } = computer()+ const claudeProjectsDir = join(dir, 'claude-projects')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-offline.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ // The release daemon is down: nothing listens on port 9.+ publishHookRoute(release.dataDir, 9, routes)+ await runHook({+ port: 9, dataDir: dev.dataDir, tmuxPane: '%7', processEngine: 'claude', claudeProjectsDir,+ paneSession: 'mine', paneOwner: release.tag, env: { HARNESS_HOOK_ROUTES_DIR: routes },+ input: { hook_event_name: 'SessionStart', session_id: 'session-offline', transcript_path: transcriptPath, cwd: '/tmp/demo', source: 'startup' },+ })+ const rows = (folder: string) => { try { return JSON.parse(readFileSync(join(folder, 'registry.json'), 'utf8')) as Array<{ sessionId: string }> } catch { return null } }+ expect(rows(release.dataDir)?.map((row) => row.sessionId)).toEqual(['session-offline'])+ expect(rows(dev.dataDir)).toBeNull()+ })++ it('looks where the daemons record by default', () => {+ // lib/hookRoutes.ts writes under env.HARNESS_HOOK_ROUTES_DIR, whose default is the product root's.+ expect(readFileSync(HOOK, 'utf8')).toContain("process.env.HARNESS_HOOK_ROUTES_DIR || join(homedir(), '.harness', 'hook-routes')")+ })+})diff --git a/cli/src/lib/hookRoutes.spec.ts b/cli/src/lib/hookRoutes.spec.tsnew file mode 100644index 000000000..8da36b77c--- /dev/null+++ b/cli/src/lib/hookRoutes.spec.ts@@ -0,0 +1,94 @@+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { harnessPaneOwner } from './harnessSessionLabel.js'+import { hookRouteFile, publishHookRoute } from './hookRoutes.js'++const roots: string[] = []+afterEach(() => {+ vi.restoreAllMocks()+ for (const root of roots.splice(0)) { chmodSync(root, 0o700); rmSync(root, { recursive: true, force: true }) }+})++function root(): string {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'hook-routes-')))+ roots.push(dir)+ return dir+}++describe('hook routes', () => {+ it('never stops a daemon when the routes path is a regular file', () => {+ // Found by QA on a quiet machine: the optional route's finally block threw ENOTDIR after its warning.+ const base = root()+ const dir = join(base, 'hook-routes')+ writeFileSync(dir, 'not a folder')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ expect(() => publishHookRoute(join(base, 'data'), 18473, dir)).not.toThrow()+ expect(warn.mock.calls[0]?.[0]).toContain('could not record this daemon\'s hook route')+ expect(readFileSync(dir, 'utf8')).toBe('not a folder')+ })++ it('records a daemon under its pane tag, readable only by this user, and reads it back', () => {+ const base = root()+ const dir = join(base, 'hook-routes')+ const dataDir = join(base, 'data')+ mkdirSync(dataDir)+ publishHookRoute(dataDir, 18473, dir)+ const tag = harnessPaneOwner(dataDir)+ const file = hookRouteFile(tag, dir)+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ dataDir, port: 18473 })+ expect(statSync(file).mode & 0o777).toBe(0o600)+ expect(statSync(dir).mode & 0o777).toBe(0o700)+ })++ it('keeps one record per data folder, so a dev daemon and the release one never overwrite each other', () => {+ const base = root()+ const dir = join(base, 'hook-routes')+ const release = join(base, 'release'), dev = join(base, 'dev')+ for (const folder of [release, dev]) mkdirSync(folder)+ publishHookRoute(release, 18473, dir)+ publishHookRoute(dev, 18500, dir)+ // A daemon that bound another port on its next start (the port fallback) replaces its own record.+ publishHookRoute(dev, 41234, dir)+ expect(JSON.parse(readFileSync(hookRouteFile(harnessPaneOwner(release), dir), 'utf8'))).toEqual({ dataDir: release, port: 18473 })+ expect(JSON.parse(readFileSync(hookRouteFile(harnessPaneOwner(dev), dir), 'utf8'))).toEqual({ dataDir: dev, port: 41234 })+ })++ it('records the data folder with its symlinks resolved, as the tag is computed', () => {+ const base = root()+ const real = join(base, 'real')+ mkdirSync(real)+ const link = join(base, 'link')+ symlinkSync(real, link)+ publishHookRoute(link, 18473, join(base, 'hook-routes'))+ expect(JSON.parse(readFileSync(hookRouteFile(harnessPaneOwner(link), join(base, 'hook-routes')), 'utf8'))).toEqual({ dataDir: real, port: 18473 })+ })++ // Root writes through any mode: there is no unwritable folder to show.+ it.skipIf(process.getuid?.() === 0)('never stops a daemon from starting: an unwritable folder is said out loud and left', () => {+ const base = root()+ chmodSync(base, 0o500)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ expect(() => publishHookRoute(join(base, 'data'), 18473, join(base, 'hook-routes'))).not.toThrow()+ expect(warn.mock.calls[0]?.[0]).toContain('could not record this daemon\'s hook route')+ })++ it('tightens a folder others could write, which the hook would refuse', () => {+ const base = root()+ const dir = join(base, 'hook-routes')+ mkdirSync(join(base, 'data'))+ mkdirSync(dir)+ chmodSync(dir, 0o777)+ publishHookRoute(join(base, 'data'), 18473, dir)+ expect(statSync(dir).mode & 0o777).toBe(0o700)+ })++ it('lives at the product root by default, shared by every daemon of this user', () => {+ // vitest.setup.ts moves it into the test's data folder; the default is the product root's.+ expect(env.HARNESS_HOOK_ROUTES_DIR).toBe(join(process.env.ADAPTER_DATA_DIR!, 'hook-routes'))+ const source = readFileSync(new URL('../config/env.ts', import.meta.url), 'utf8')+ expect(source).toContain("HARNESS_HOOK_ROUTES_DIR: text(join(adapterRootDir, 'hook-routes'))")+ })+})diff --git a/cli/src/lib/hookRoutes.ts b/cli/src/lib/hookRoutes.tsnew file mode 100644index 000000000..06c02301a--- /dev/null+++ b/cli/src/lib/hookRoutes.ts@@ -0,0 +1,33 @@+/**+ * Found by QA on a quiet machine: the last daemon to install hooks took every daemon's hooks.+ * Each pane's owner tag now names its daemon's data folder and bound port. The hook validates this+ * record before routing; without one it keeps its command's port/data folder. Retain records on stop:+ * an offline hook must write its owner's registry, not fall back to another daemon's.+ */+import { chmodSync, mkdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../config/env.js'+import { harnessPaneOwner } from './harnessSessionLabel.js'++export function hookRouteFile(tag: string, dir: string = env.HARNESS_HOOK_ROUTES_DIR): string {+ return join(dir, `${tag}.json`)+}++/** Publish after the hook server binds. Failure leaves the installed command usable and never stops+ * the daemon. The actual reader is notify.mjs; keeping another unused reader here hid its real checks. */+export function publishHookRoute(dataDir: string, port: number, dir: string = env.HARNESS_HOOK_ROUTES_DIR): void {+ const target = hookRouteFile(harnessPaneOwner(dataDir), dir)+ const temporary = `${target}.${process.pid}.tmp`+ try {+ mkdirSync(dir, { recursive: true, mode: 0o700 })+ chmodSync(dir, 0o700)+ writeFileSync(temporary, JSON.stringify({ dataDir: realpathSync(dataDir), port }) + '\n', { mode: 0o600 })+ renameSync(temporary, target)+ } catch (error) {+ console.warn(`[hooks] could not record this daemon's hook route in ${dir}: ${error instanceof Error ? error.message : error}`+ + ' · hooks installed by another daemon will not reach this one\'s agents')+ } finally {+ // QA found ENOTDIR here turned the warning above into a failed daemon start.+ try { rmSync(temporary, { force: true }) } catch { /* the optional route's directory is unavailable */ }+ }+}diff --git a/cli/vitest.setup.ts b/cli/vitest.setup.tsindex 50097f6cf..43d30cbcb 100644--- a/cli/vitest.setup.ts+++ b/cli/vitest.setup.ts@@ -31,6 +31,9 @@ process.env.ZDOTDIR = process.env.ADAPTER_DATA_DIR// discover, refresh, or replace the developer's real Harness account session.process.env.HARNESS_AUTH_DIR = join(process.env.ADAPTER_DATA_DIR, 'auth')process.env.DSH_DIR = join(process.env.ADAPTER_DATA_DIR, 'dsh')+// Every daemon of this user records where it listens here (lib/hookRoutes.ts), and the hook reads it: a+// spec must neither write a record beside the person's daemons nor route a test hook by one of theirs.+process.env.HARNESS_HOOK_ROUTES_DIR = join(process.env.ADAPTER_DATA_DIR, 'hook-routes')// The Store catalog is fetched from GitHub by dsh_list; a test must never depend on what that branch// holds today (a published catalog turned a fixture registry of two into the live shelf of 23).// Loopback port 9 refuses at once, so the live catalog falls back to the registry each test stubs.