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
The end-to-end suite runs the installed hooks as the engines do; six real bugs fixed (#834)
Dee64b1d9fc0e00
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex 45777099f..1b058b86c 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -3,12 +3,18 @@* data directory, port, private tmux server and fake Claude Code and Codex engines, signed out and with* every optional feature that reaches beyond the machine turned off. Nothing it does can touch the* person's own daemon, tmux server, transcripts or credentials.+ *+ * It installs Claude Code's and Codex's hooks as it does on a person's computer, into the throwaway home+ * and CODEX_HOME, and the fake engines run them (fakeEngine.mjs): the real `hook/notify.mjs` carries+ * every hook event to the daemon, with its deadline and its offline registry writes. Before a daemon+ * starts, every folder it could install hooks into is checked to be inside the test's root+ * (`assertHooksContained`), and every file it says it wrote is checked again once it is up.*/import { execFile, spawn, type ChildProcess } from 'node:child_process'import { existsSync, readFileSync } from 'node:fs'import { mkdir, writeFile } from 'node:fs/promises'import { createServer } from 'node:net'-import { dirname, join, resolve } from 'node:path'+import { dirname, isAbsolute, join, relative, resolve } from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'import { promisify } from 'node:util'import { isolatedTmux, type IsolatedTmux } from '../../src/testing/isolatedTmux.js'@@ -17,6 +23,25 @@ const exec = promisify(execFile)const here = dirname(fileURLToPath(import.meta.url))export const CLI_ROOT = resolve(here, '../..')+/** What a fake engine's wrapper hands `fakeEngine.mjs` `run()`: where it writes, and which release it is. */+export interface EngineConfig {+ port: number+ dataDir: string+ claudeProjectsDir: string+ codexHome: string+ claudeModel?: string+ codexModel?: string+ /** The test's throwaway root: the engine runs no hooks from settings outside it. */+ root: string+ /** Where the engine notes each hook it ran. */+ hookLog: string+ version?: string+ without?: string[]+ startDelayMs?: number+ firstHookDelayMs?: number+ updateAvailable?: string+}+export interface DaemonOptions {/** Extra environment for the daemon. */env?: Record<string, string>@@ -39,9 +64,6 @@ export interface DaemonOptions {beside?: IsolatedDaemon/** Ask for this port instead of a free one: a daemon started on another daemon's port. */port?: number- /** The fake engines run the hooks the daemon installed (`DISABLE_HOOK_INSTALL: 'false'`) through a- * shell, as the real CLIs do, instead of posting to the daemon themselves. */- realHooks?: boolean}async function freePort(): Promise<number> {@@ -53,6 +75,76 @@ async function freePort(): Promise<number> {return address.port}+/** Inside `root`, or `root` itself. */+const inside = (root: string, path: string): boolean => {+ const rel = relative(resolve(root), resolve(path))+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))+}++/** The engines whose hooks a daemon under test may install: the two the fake engines stand in for. */+const HOOK_ENGINES = new Set(['claude', 'codex'])+/** The shell profiles a login shell in a pane reads, where a person moves an engine's home. */+const PROFILES = { ZDOTDIR: ['.zshenv', '.zprofile', '.zshrc', '.zlogin'], HOME: ['.bash_profile', '.bash_login', '.profile', '.bashrc'] }++/**+ * Refuse to start a daemon that could install hooks anywhere but inside the test's root. Claude Code's go+ * into `$HOME/.claude/settings.json` and into every moved home (CLAUDE_CONFIG_DIR, in the daemon's+ * environment, in the login shell's profile, or remembered in `engine-homes.json`); Codex's into+ * `$CODEX_HOME/hooks.json` and every moved CODEX_HOME. Any of them outside the root would be the person's+ * own settings, and their engines would then call a daemon that is gone when the test ends. Throws,+ * naming the setting.+ */+export function assertHooksContained(root: string, env: NodeJS.ProcessEnv): void {+ if (env.DISABLE_HOOK_INSTALL === 'true') return+ const engines = (env.HOOK_INSTALL_ENGINES ?? '').split(',').map((name) => name.trim()).filter(Boolean)+ if (!engines.length || engines.some((name) => !HOOK_ENGINES.has(name))) {+ throw new Error(`HOOK_INSTALL_ENGINES is ${env.HOOK_INSTALL_ENGINES ?? 'unset'}: a daemon under test installs Claude Code's and Codex's hooks alone (claude,codex)`)+ }+ const refuse = (what: string, path: string | undefined): never => {+ throw new Error(`${what} is ${path ?? 'unset'}: a daemon under test installs hooks only inside ${root}`)+ }+ const check = (what: string, path: string | undefined): void => {+ if (!path || !isAbsolute(path) || !inside(root, path)) refuse(what, path)+ }+ check('HOME', env.HOME)+ check('CODEX_HOME', env.CODEX_HOME)+ if (env.CLAUDE_CONFIG_DIR !== undefined) check('CLAUDE_CONFIG_DIR', env.CLAUDE_CONFIG_DIR)+ check('ZDOTDIR', env.ZDOTDIR)+ 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)+ let text = ''+ try { text = readFileSync(file, 'utf8') } catch { continue }+ for (const match of text.matchAll(/(?:^|[\s;])(?:export\s+)?(CLAUDE_CONFIG_DIR|CODEX_HOME)=("([^"]*)"|'([^']*)'|([^\s;]*))/gm)) {+ const value = match[3] ?? match[4] ?? match[5]+ // A value built from another variable cannot be checked from here, so it is not allowed.+ if (value.includes('$') || value.includes('~')) refuse(`${match[1]} in ${file}`, value)+ check(`${match[1]} in ${file}`, value)+ }+ }+ }+ try {+ const remembered = JSON.parse(readFileSync(join(env.ADAPTER_DATA_DIR!, 'engine-homes.json'), 'utf8')) as Record<string, unknown>+ for (const [engine, homes] of Object.entries(remembered)) {+ for (const home of Array.isArray(homes) ? homes : []) check(`the ${engine} home remembered in engine-homes.json`, String(home))+ }+ } catch { /* none remembered yet */ }+}++/**+ * The files a daemon's log says it installed hooks or plugins into, found them already in, or left alone.+ * The update line names the hook script first and the file it rewrote after ` in `.+ */+export function hookFilesNamed(log: string): string[] {+ const files: string[] = []+ for (const line of log.split('\n')) {+ if (!line.includes('[hooks]')) continue+ const named = line.includes('updated (path/port changed)') ? / in (\/\S+)\s*$/.exec(line) : /(?:→|unchanged:) (\/\S+)/.exec(line)+ if (named) files.push(named[1])+ }+ return files+}+export const until = async <T>(what: string, probe: () => Promise<T | null | undefined | false> | T | null | undefined | false, ms = 30_000, every = 100): Promise<T> => {const deadline = Date.now() + mslet last: unknown@@ -79,6 +171,8 @@ export class IsolatedDaemon {readonly port: number,readonly env: NodeJS.ProcessEnv,readonly options: DaemonOptions,+ /** What the fake engines' wrappers hand `fakeEngine.mjs` (updates.e2e.ts writes releases with it). */+ readonly engineConfig: EngineConfig,) {}static async create(options: DaemonOptions = {}): Promise<IsolatedDaemon> {@@ -95,10 +189,10 @@ export class IsolatedDaemon {projects: join(root, 'projects'),}for (const dir of Object.values(dirs)) await mkdir(dir, { recursive: true })- const config = {+ const config: EngineConfig = {port, dataDir: dirs.data, claudeProjectsDir: dirs.claudeProjects, codexHome: dirs.codexHome,claudeModel: options.claudeModel, codexModel: options.codexModel,- ...(options.realHooks ? { realHooks: true } : {}),+ root, hookLog: join(own, 'fake-engine-hooks.log'),}const engine = pathToFileURL(join(here, 'fakeEngine.mjs')).hreffor (const name of ['claude', 'codex']) {@@ -127,7 +221,11 @@ export class IsolatedDaemon {// Signed out, and nothing reaches beyond the machine.BACKEND_WS_URL: 'ws://127.0.0.1:9',WEB_URL: 'http://127.0.0.1:9',- DISABLE_HOOK_INSTALL: 'true',+ // Claude Code's and Codex's hooks, installed as on a person's computer, into this home and CODEX_HOME+ // (assertHooksContained), and run by the fake engines. Every other engine's installer writes into+ // folders these tests have no engine for.+ DISABLE_HOOK_INSTALL: 'false',+ HOOK_INSTALL_ENGINES: 'claude,codex',ADAPTER_UPDATE_DISABLE: 'true',ANALYTICS_ENABLED: 'false',RECAP_FORCE: 'false',@@ -139,7 +237,24 @@ export class IsolatedDaemon {TERMINAL_RECONCILE_INTERVAL_MS: '5000',...options.env,}- return new IsolatedDaemon(root, tmux, port, env, options)+ // A Claude Code home moved in the environment this run was started from is the person's: the daemon+ // would adopt it and install its hooks there (lib/engineHomes.ts). Only a test may move one.+ if (!options.env || !('CLAUDE_CONFIG_DIR' in options.env)) delete env.CLAUDE_CONFIG_DIR+ return new IsolatedDaemon(root, tmux, port, env, options, config)+ }++ /** What the fake engines noted of every hook they ran (fakeEngine.mjs `hookLog`); kept once the root is gone. */+ hookLog(): string {+ try { return readFileSync(this.engineConfig.hookLog, 'utf8') } catch { return this.closedHookLog }+ }+ private closedHookLog = ''++ /** Throws when the daemon said it put hooks outside the root, or an engine refused hooks found there. */+ private assertHooksStayedInside(): void {+ const outside = hookFilesNamed(this.output).filter((file) => !inside(this.root, file))+ if (outside.length) throw new Error(`the daemon under test wrote hooks outside ${this.root}: ${[...new Set(outside)].join(', ')}`)+ const refused = this.hookLog().split('\n').filter((line) => line.includes('REFUSED'))+ if (refused.length) throw new Error(`a fake engine refused to run hooks (test root ${this.root}):\n${refused.join('\n')}`)}get dataDir(): string { return this.env.ADAPTER_DATA_DIR! }@@ -166,6 +281,8 @@ export class IsolatedDaemon {* `'none'` as soon as the process is started. */async start(options: { ready?: 'none' | 'port' | 'wired' } = {}): Promise<void> {if (this.child) throw new Error('already running')+ // Checked at every start: a test writes a shell profile, or the data folder remembers a home, between them.+ assertHooksContained(this.root, this.env)const heap = this.options.heapMiB ? [`--max-old-space-size=${this.options.heapMiB}`] : []const entry = this.options.noMaster ? '__run' : '__harnessd'// Readiness is judged from what this start prints, never from an earlier boot's lines.@@ -196,6 +313,8 @@ export class IsolatedDaemon {// test); this line is printed once they are.if (options.ready !== 'port') {await until('the daemon to finish starting', () => /\[cli\] ready/.test(this.output.slice(from)), 60_000, 100)+ // Its hooks are installed before it says it is ready.+ this.assertHooksStayedInside()}})()])}@@ -251,6 +370,11 @@ export class IsolatedDaemon {async close(): Promise<void> {const core = this.options.noMaster ? null : this.corePid()await this.stop().catch(() => {})+ // Once the daemon has said all it will, and before the root (and the engines' hook log) is removed.+ let escaped: unknown = null+ try { this.assertHooksStayedInside() } catch (error) { escaped = error }+ // A failed test prints it after this close has removed the root.+ this.closedHookLog = this.hookLog()// A core whose master died during the test must not outlive it: 20 such cores, left by a run// whose masters crashed, spun on their closed output pipes for the rest of a parallel suite. Only// this test's core is killed — its pid, still running this daemon's entry, orphaned or ours.@@ -263,5 +387,6 @@ export class IsolatedDaemon {}// A daemon beside another shares its tmux server: that one closes it.if (!this.options.beside) await this.tmux.close()+ if (escaped) throw escaped}}diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 33f782d02..aa3126cac 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -2,8 +2,11 @@// under test. It behaves the way the daemon depends on the real CLIs behaving, and nothing more://// - answers `--version` / `--help` probes;-// - announces its session through the same authenticated hook the real `notify.mjs` uses, from-// inside the pane (so the daemon's pane/process binding is exercised for real);+// - runs the hooks its own settings carry, as the real CLIs run them: the commands the daemon+// installed (lib/hooks.ts), through a shell, from inside the pane, with the event on stdin, killed at+// their timeout and waited for. So the real `hook/notify.mjs` is what reaches the daemon, with its+// 500 ms deadline and its offline registry writes, and the daemon's pane/process binding is+// exercised for real;// - draws a composer, turns on bracketed paste, and treats Enter as submit;// - writes its conversation to a transcript in the engine's real record shapes, so the daemon's// normalizers, turn lifecycle, chips and attach read are exercised for real.@@ -31,14 +34,41 @@// to before it starts, and `startDelayMs` is how long it takes, once started, before// it draws or announces anything (an engine's first run after an update). `firstHookDelayMs` is how long// its first SessionStart takes to reach the daemon once the engine is up: the hook command starting on a-// loaded machine, while the daemon has already found the engine and its conversation. `realHooks` runs-// the hooks the daemon installed into the engine's settings, as the real CLIs do, instead of posting to-// the daemon.+// loaded machine, while the daemon has already found the engine and its conversation. `root` is the+// test's throwaway root, the only place whose hooks it will run, and `hookLog` where it notes every hook+// it ran.import { execFileSync, spawn } from 'node:child_process'import { randomUUID } from 'node:crypto'import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'-import { dirname, join } from 'node:path'+import { dirname, isAbsolute, join, relative, resolve } from 'node:path'++/**+ * The events each CLI fires that the daemon installs hooks for (lib/hooks.ts): Claude Code's session,+ * prompt and turn-end events, and Codex's SessionStart and UserPromptSubmit, the two it installs for+ * Codex and the two notify.mjs reads from it. A hook for any other event in the settings is not run,+ * as the CLI has no such moment to run it at.+ */+const HOOK_EVENTS = {+ claude: new Set(['SessionStart', 'UserPromptSubmit', 'Stop', 'StopFailure', 'SessionEnd']),+ codex: new Set(['SessionStart', 'UserPromptSubmit']),+}++/** Inside `root`, or `root` itself. */+const within = (root, path) => {+ const rel = relative(resolve(root), resolve(path))+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))+}++/**+ * Whether a hook block's matcher takes this value. Only SessionStart's matcher means anything to these+ * two CLIs (Codex's block carries `startup|resume|clear|compact`, matched against the event's source);+ * Stop and StopFailure ignore one (lib/hooks.ts). No matcher, an empty one or `*` takes everything.+ */+const matcherTakes = (matcher, value) => {+ if (matcher === undefined || matcher === null || matcher === '' || matcher === '*') return true+ try { return new RegExp(`^(?:${matcher})$`).test(String(value ?? '')) } catch { return false }+}export async function run(engine, config) {const args = process.argv.slice(2)@@ -125,12 +155,38 @@ export async function run(engine, config) {const ownCodexHome = engine === 'codex' && process.env.CODEX_HOME && process.env.CODEX_HOME !== config.codexHome ? process.env.CODEX_HOME : nullconst projectsDir = claudeHome ? join(claudeHome, 'projects') : config.claudeProjectsDirconst codexHome = ownCodexHome ?? config.codexHome- /** Whether this engine's own settings carry the daemon's hooks: a moved home has none unless the daemon put them there. */- const hooksInstalled = () => {- const file = claudeHome ? join(claudeHome, 'settings.json') : ownCodexHome ? join(ownCodexHome, 'hooks.json') : null- if (!file) return true- try { return readFileSync(file, 'utf8').includes('notify.mjs') } catch { return false }+ // The hooks this engine's settings carry, read once as it starts, where the real CLI reads them:+ // Claude Code's `settings.json` in its config folder (CLAUDE_CONFIG_DIR, else ~/.claude), Codex's+ // `hooks.json` in its CODEX_HOME. Claude Code snapshots its hooks at start-up ("takes effect on the+ // next claude session start", lib/hooks.ts) and Codex runs a user hook only once it was reviewed, so+ // a change reaches the next process, not this one: a moved home the daemon had not yet put its hooks+ // in starts an engine that never runs them. A settings file outside the test's root is refused out+ // loud before anything is run: those would be the person's own hooks, talking to their own daemon.+ const hookSettingsFile = engine === 'claude'+ ? join(claudeHome ?? join(homedir(), '.claude'), 'settings.json')+ : join(codexHome, 'hooks.json')+ // Every hook it ran, and how it ended, noted in a file and never in the pane: the real CLIs draw+ // nothing for a hook that exits 0, as notify.mjs always does, and a failure the fake once printed under+ // its composer read to the daemon as a draft the person had not sent, so a close waiting for the agent+ // to be idle waited for ever (e2e/ends.e2e.ts).+ // Beside the daemon's data folder when a wrapper names no log, as IsolatedDaemon's would be: a refusal+ // must reach the harness, which fails the test on it, from a wrapper a test wrote by hand as well.+ const hookLogFile = config.hookLog ?? (config.dataDir ? join(dirname(config.dataDir), 'fake-engine-hooks.log') : null)+ const hookLog = (line) => {+ if (!hookLogFile) return+ try { appendFileSync(hookLogFile, `${new Date().toISOString()} ${engine} pid=${process.pid} ${line}\n`) } catch { /* a note, never a failure */ }}+ if (!config.root || !within(config.root, hookSettingsFile)) {+ hookLog(config.root ? `REFUSED hooks outside the test root: ${hookSettingsFile}` : `REFUSED hooks: the wrapper names no test root (use IsolatedDaemon.engineConfig)`)+ process.stderr.write(`[fake ${engine}] refusing to run the hooks in ${hookSettingsFile}: outside the test root ${config.root ?? '(none given)'}\r\n`)+ process.exit(78)+ }+ const hookSettings = (() => {+ try {+ const parsed = JSON.parse(readFileSync(hookSettingsFile, 'utf8'))+ return parsed && typeof parsed.hooks === 'object' && parsed.hooks ? parsed.hooks : {}+ } catch { return {} }+ })()let transcript = engine === 'claude'? join(projectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`): resumed && !fork && config.rolloutFor?.[resumed]@@ -167,70 +223,90 @@ export async function run(engine, config) {codex('session_meta', { id: sessionId, cli_version: version, cwd, source: 'cli' })}- // The port the daemon actually bound, which it saves beside its data (lib/daemonEndpoint.ts) and- // writes into the hook command it installs: a daemon whose configured port was taken serves another.- const daemonPort = () => {- try {- const { port } = JSON.parse(readFileSync(join(config.dataDir, `daemon-${config.port}.json`), 'utf8'))- if (Number.isInteger(port) && port > 0) return port- } catch { /* not bound yet, or bound where it was asked to */ }- return config.port- }- // The command the daemon installed for `event` in this engine's settings (Claude Code's settings.json,- // Codex's hooks.json), and how long the engine gives it; null when there is none.- const installedHook = (event) => {- const file = engine === 'claude' ? join(claudeHome ?? join(homedir(), '.claude'), 'settings.json') : join(codexHome, 'hooks.json')- try {- for (const block of JSON.parse(readFileSync(file, 'utf8'))?.hooks?.[event] ?? []) {- for (const entry of block?.hooks ?? []) {- if (entry?.type === 'command' && typeof entry.command === 'string') return { command: entry.command, timeout: Number(entry.timeout) || 60 }- }- }- } catch { /* no settings, or not readable: no hook */ }- return null- }- /** Runs an installed hook as the CLIs do: through a shell, the event's JSON on stdin, killed at its timeout. */- const runHook = (event, payload) => new Promise((resolve) => {- const installed = installedHook(event)- if (!installed) { resolve(); return }- const child = spawn('/bin/sh', ['-c', installed.command], { stdio: ['pipe', 'ignore', 'ignore'], env: process.env })- const timer = setTimeout(() => child.kill('SIGKILL'), installed.timeout * 1000)- const done = () => { clearTimeout(timer); resolve() }- child.on('close', done)- child.on('error', done)- child.stdin.on('error', () => {})- child.stdin.end(JSON.stringify(payload))+ // What the CLI says about its permission mode in an event, read off its own argv as it reads it.+ const permissionMode = engine === 'claude'+ ? (args.includes('--dangerously-skip-permissions') ? 'bypassPermissions'+ : args.includes('--permission-mode') ? args[args.indexOf('--permission-mode') + 1] ?? 'default' : 'default')+ : (args.includes('--dangerously-bypass-approvals-and-sandbox') ? 'bypassPermissions' : 'default')+ const codexModel = config.codexModel ?? 'gpt-6'+ /**+ * The JSON an event hands its hooks on stdin, in each CLI's own shape: what notify.mjs reads (session,+ * transcript, folder, the event and its source, prompt or reason) and the rest of what the real CLIs+ * were recorded sending (src/lib/__fixtures__/swarm-prompt-hooks.json: Claude Code's prompt id and+ * permission mode, Codex's turn id, model and permission mode).+ */+ const hookInput = (event, fields) => ({+ session_id: sessionId,+ transcript_path: transcript,+ cwd,+ hook_event_name: event,+ ...(engine === 'codex' ? { model: codexModel, permission_mode: permissionMode } : {}),+ ...fields,})- const hook = async (path, body) => {- if (config.realHooks) {- const event = path === 'turn-stop' ? 'Stop' : path === 'session-end' ? 'SessionEnd' : body.hookEvent ?? 'SessionStart'- await runHook(event, {- session_id: sessionId, transcript_path: transcript, cwd, hook_event_name: event,- ...(body.source ? { source: body.source } : {}), ...(body.prompt !== undefined ? { prompt: body.prompt } : {}),- ...(body.reason ? { reason: body.reason } : {}),- })+ /**+ * One hook command, as the CLIs run one: through a shell, in the engine's folder and with its+ * environment (Claude Code adds CLAUDE_PROJECT_DIR), the event on stdin, killed once its `timeout`+ * (seconds) is up. Resolves when it exits or is killed: the CLI waits for its hooks before it goes on.+ */+ const runHookCommand = (event, command, timeoutSeconds, input) => new Promise((done) => {+ const started = Date.now()+ // What a test reads back: the event, why it fired, and the conversation it named.+ const what = `${event}${input.source || input.reason ? `(${input.source || input.reason})` : ''} session=${input.session_id}`+ const env = engine === 'claude' ? { ...process.env, CLAUDE_PROJECT_DIR: cwd } : process.env+ let child+ try {+ child = spawn('/bin/sh', ['-c', command], { cwd, env, stdio: ['pipe', 'ignore', 'pipe'] })+ } catch (error) {+ hookLog(`${what} could not start: ${error?.message ?? error}`)+ done()return}- if (!hooksInstalled()) return- const token = readFileSync(join(config.dataDir, 'hook-credential'), 'utf8').trim()- const pane = process.env.TMUX_PANE- const response = await fetch(`http://127.0.0.1:${daemonPort()}/api/hook/${path}`, {- method: 'POST',- headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },- body: JSON.stringify({- engine, sessionId, transcriptPath: transcript, cwd,- tmuxPane: pane, runtimeHints: pane ? [{ backend: 'tmux', paneId: pane }] : [], callerPid: process.pid,- ...body,- }),- }).catch((error) => ({ ok: false, status: 0, text: async () => String(error) }))- // Said in a file, never in the pane. The real hook (hook/notify.mjs) gives up silently and exits 0- // when the daemon cannot be reached, so the engine draws nothing; this line, printed under the- // composer while the daemon was stopped, read to the daemon as a draft the person had not sent, and a- // close waiting for the agent to be idle waited for ever (e2e/ends.e2e.ts).- if (!response.ok) appendFileSync(join(dirname(config.dataDir), 'fake-engine-hooks.log'), `${new Date().toISOString()} ${engine} ${sessionId} hook ${path} failed: ${response.status}\n`)+ let stderr = ''+ child.stderr.setEncoding('utf8')+ child.stderr.on('data', (chunk) => { if (stderr.length < 2_000) stderr += chunk })+ const limit = (Number(timeoutSeconds) > 0 ? Number(timeoutSeconds) : 60) * 1000+ let killed = false+ const timer = setTimeout(() => {+ killed = true+ hookLog(`${what} killed at its timeout of ${limit} ms`)+ child.kill('SIGTERM')+ done()+ }, limit)+ child.on('error', (error) => { clearTimeout(timer); hookLog(`${what} failed: ${error.message}`); done() })+ child.on('close', (code, signal) => {+ clearTimeout(timer)+ hookLog(`${what} ${killed ? 'ended after it was killed' : 'ran'} in ${Date.now() - started} ms · exit=${code ?? signal}`+ + (stderr.trim() ? ` · stderr=${JSON.stringify(stderr.trim().slice(0, 500))}` : ''))+ done()+ })+ child.stdin.on('error', () => { /* a hook that exits without reading its input */ })+ child.stdin.end(JSON.stringify(input))+ })+ /** Every hook the settings carry for this event, at once, each command once, and wait for them all. */+ const runHooks = async (event, fields = {}) => {+ if (!HOOK_EVENTS[engine].has(event)) return+ const blocks = Array.isArray(hookSettings[event]) ? hookSettings[event] : []+ const commands = new Map()+ for (const block of blocks) {+ if (event === 'SessionStart' && !matcherTakes(block?.matcher, fields.source)) continue+ for (const entry of Array.isArray(block?.hooks) ? block.hooks : []) {+ if (entry?.type !== 'command' || typeof entry.command !== 'string' || !entry.command) continue+ if (!commands.has(entry.command)) commands.set(entry.command, entry.timeout)+ }+ }+ if (!commands.size) return+ const input = hookInput(event, fields)+ await Promise.all([...commands].map(([command, timeout]) => runHookCommand(event, command, timeout, input)))}announceProcess()+ // The composer, as both CLIs keep it: the bottom of the screen, holding what is being typed and nothing+ // else. Enter takes the prompt off it at once and into the conversation; the turn's output is written+ // above it, and it is drawn again below. The fake used to leave a submitted prompt on its composer line+ // until the answer came, which the daemon reads as a draft never sent: it pressed Enter again for it+ // (sessionInput.ts) whenever the turn was slow to start, as one is behind its UserPromptSubmit hook.+ let buffer = ''+ let composerRows = 0// What Codex 0.160 draws under its empty composer in the two states the daemon must read off the pane// (tui/src/bottom_pane): a goal it is pursuing, on the right of its status line, and the footer of// its transcript browser, with the composer dimmed whole. Null draws the composer alone, as before.@@ -263,29 +339,43 @@ export async function run(engine, config) {: ` \x1b[2mreverse-i-search: \x1b[0m${query} \x1b[2menter accept · esc cancel\x1b[0m`return { search: true, query, match, composer: `› ${match ?? ''}`, footer }}- const draw = (line = '') => {- if (bottom?.pager) { process.stdout.write(bottom.pager); return }- if (bottom && !line) {+ /** Rows the composer takes now: a long or multi-line draft wraps. */+ const rowsOf = (text) => text.split('\n')+ .reduce((rows, line) => rows + Math.max(1, Math.ceil([...line].length / Math.max(20, process.stdout.columns || 80))), 0)+ /** Clears the composer and what is drawn under it, leaving the cursor where it began. */+ const eraseComposer = () => {+ process.stdout.write(`${composerRows > 1 ? `\x1b[${composerRows - 1}A` : ''}\r\x1b[0J`)+ composerRows = 0+ }+ const drawComposer = () => {+ if (bottom?.pager) { process.stdout.write(bottom.pager); composerRows = 0; return }+ if (bottom && !buffer) {// The footer on the row under the composer, then the cursor back to the composer, after its glyph.- process.stdout.write(`\r\x1b[2K${bottom.composer}\r\n\x1b[2K${bottom.footer}\x1b[1A\r\x1b[2C`)+ process.stdout.write(`${bottom.composer}\r\n\x1b[2K${bottom.footer}\x1b[1A\r\x1b[2C`)+ composerRows = 1return}- process.stdout.write(`\r\x1b[2K› ${line}`)+ process.stdout.write(`› ${buffer}`)+ composerRows = rowsOf(`› ${buffer}`)}- // Out of the browser, back to the composer: the pager's alternate screen left, or the footer row- // under the composer cleared. Enter rewinds on the way out.+ const draw = () => { eraseComposer(); drawComposer() }+ /** The conversation, written above the composer. `text` ends at the start of a line. */+ const say = (text) => { eraseComposer(); process.stdout.write(text); drawComposer() }+ // Out of the browser, back to the composer: the pager's alternate screen left, or the dimmed composer+ // and its footer cleared. Enter rewinds on the way out.const leaveBrowsing = (rewound) => {if (bottom.pager) process.stdout.write('\x1b[?1049l')- else process.stdout.write('\r\n\x1b[2K\x1b[1A')- if (rewound) process.stdout.write('\r\x1b[2K(rewound to an earlier prompt)\r\n')+ else eraseComposer()bottom = null- draw()+ composerRows = 0+ if (rewound) process.stdout.write('\r\x1b[2K(rewound to an earlier prompt)\r\n')+ drawComposer()}process.stdout.write(`\x1b[?2004h${engine === 'claude' ? '✻ Welcome to Claude Code (fake)' : '>_ OpenAI Codex (fake)'}\r\n`)process.stdout.write(` session ${sessionId}${resumed ? ' (resumed)' : ''}\r\n\r\n`)- draw()+ drawComposer()if (config.firstHookDelayMs && !resumed) await new Promise((resolve) => setTimeout(resolve, config.firstHookDelayMs))- await hook('session-start', { hookEvent: resumed ? 'SessionStart' : 'SessionStart', source: resumed ? 'resume' : 'startup' })+ await runHooks('SessionStart', { source: resumed ? 'resume' : 'startup' })let turn = 0let open = null@@ -337,7 +427,7 @@ export async function run(engine, config) {const dialogKeys = (chunk) => {for (const key of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[AB]|\x1b|\r|\n|./gs) ?? []) {if (!dialog) return- const settle = (choice) => { eraseDialog(); const asked = dialog; dialog = null; notes = asked.notes ?? ''; asked.resolve(choice) }+ const settle = (choice) => { eraseDialog(); const asked = dialog; dialog = null; notes = asked.notes ?? ''; drawComposer(); asked.resolve(choice) }const rows = dialog.kind === 'permit' ? 3 : engine === 'claude' ? CHOICES.length : CHOICES.length + 1if (key.startsWith('\x1b[200~')) {if (dialog.kind !== 'permit' && engine === 'codex') dialog.notes = key.slice(6).replace(/\x1b\[201~$/, '')@@ -369,38 +459,49 @@ export async function run(engine, config) {codex('compacted', { message: 'Summary of the conversation so far.', replacement_history: [] })}}- const finish = (text) => {+ const finish = async (text) => {if (engine === 'claude') {claude({ type: 'assistant', message: { id: `msg_${turn}`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'text', text }], stop_reason: 'end_turn' } })} else {codex('event_msg', { type: 'item_completed', item: { type: 'AgentMessage', content: [{ type: 'Text', text }], phase: 'final_answer' } })codex('event_msg', { type: 'task_complete', turn_id: open, last_agent_message: text })}- process.stdout.write(`\r\n${text}\r\n\r\n`)open = null- draw()- if (engine === 'claude') void hook('turn-stop', { status: 'ok' })+ say(`\r\n${text}\r\n\r\n`)+ // Claude Code's Stop hooks run once the answer is in, and the CLI waits for them before it takes the+ // next prompt; an interrupt ends a turn without them.+ await runHooks('Stop', { stop_hook_active: false })}const handle = async (raw) => {const prompt = raw.trim()- if (!prompt) { draw(); return }+ // Enter on an empty composer takes nothing.+ if (!prompt) returnhistory.push(prompt)- if (prompt === '!exit') { process.stdout.write('\x1b[?2004l\r\n'); process.exit(0) }+ // The prompt the CLI took, in the conversation, where both CLIs show what was sent.+ say(`> ${prompt.replace(/\n/g, '\r\n ')}\r\n`)+ if (prompt === '!exit') {+ // Leaving, the CLI reads no more input, and says so to its hooks first (Claude Code's SessionEnd,+ // reason prompt_input_exit): what is typed meanwhile stays in the terminal, for whatever runs next.+ process.stdin.removeAllListeners('data')+ process.stdin.pause()+ await runHooks('SessionEnd', { reason: 'prompt_input_exit' })+ process.stdout.write('\x1b[?2004l\r\n')+ process.exit(0)+ }if (prompt === '!compact') {// `/compact` is a command, not a turn: a summary replaces the history, and Claude Code announces// the same session again (SessionStart, source compact), which makes the daemon re-read it.compact()- process.stdout.write('\r\n(compacted)\r\n')- draw()- if (engine === 'claude') await hook('session-start', { hookEvent: 'SessionStart', source: 'compact' })+ say('(compacted)\r\n')+ if (engine === 'claude') await runHooks('SessionStart', { source: 'compact' })return}if (prompt === '!clear') {// The old conversation ends (its open turn first), a new id and transcript begin, and the engine// says both through its hooks, as the real CLIs do.- if (open) finish('(interrupted by a new conversation)')- await hook('session-end', { reason: 'clear' })+ if (open) await finish('(interrupted by a new conversation)')+ await runHooks('SessionEnd', { reason: 'clear' })sessionId = randomUUID()transcript = engine === 'claude'? join(projectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)@@ -411,21 +512,20 @@ export async function run(engine, config) {turn = 0if (engine === 'codex') codex('session_meta', { id: sessionId, cli_version: version, cwd, source: 'cli' })announceProcess()- process.stdout.write('\r\n(new conversation)\r\n')- draw()- await hook('session-start', { hookEvent: 'SessionStart', source: 'clear' })+ say('(new conversation)\r\n')+ await runHooks('SessionStart', { source: 'clear' })return}- if (open) finish('(interrupted by a new prompt)')- // Claude Code runs its UserPromptSubmit hook on every prompt, through the same door as SessionStart:- // the catch hook, which re-registers a session whose start-up announcement the daemon missed.- // Codex runs its UserPromptSubmit hook too, when the daemon installed one (`realHooks`).- if (engine === 'claude' || config.realHooks) await hook('session-start', { hookEvent: 'UserPromptSubmit', prompt })+ if (open) await finish('(interrupted by a new prompt)')+ // Both CLIs run their UserPromptSubmit hooks on every prompt, before the prompt is taken: notify.mjs+ // sends it through the same door as SessionStart, the catch hook that re-registers a session whose+ // start-up announcement the daemon missed. The fields beyond the prompt are those each CLI was+ // recorded sending.+ await runHooks('UserPromptSubmit', engine === 'claude'+ ? { prompt_id: randomUUID(), permission_mode: permissionMode, prompt }+ : { turn_id: `turn-${turn + 1}`, prompt })turn++open = `turn-${turn}`- // Onto the row under the composer, which holds a footer while one is drawn: cleared, as Codex redraws- // its whole bottom pane rather than leave the old one in the history above.- process.stdout.write(`\r\n\x1b[2K`)if (engine === 'claude') {claude({ type: 'user', message: { role: 'user', content: prompt } })claude({ type: 'assistant', message: { id: `msg_${turn}_t`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'thinking', thinking: `considering: ${prompt}` }], stop_reason: null } })@@ -461,26 +561,29 @@ export async function run(engine, config) {// Numbered, so whoever reads the terminal can tell a lost, repeated or reordered line.const kib = Number(directive[2]) || 256let written = 0+ eraseComposer()for (let line = 0; written < kib * 1024; line++) {const text = `flood ${String(line).padStart(7, '0')} ${'.'.repeat(80)}\r\n`process.stdout.write(text)written += text.length}- finish(`flooded ${kib} KiB`)+ drawComposer()+ await finish(`flooded ${kib} KiB`)return}if (directive?.[1] === 'compactmid') {// An automatic compaction in the middle of a turn: the turn goes on after it and ends once.await new Promise((resolve) => setTimeout(resolve, 300))compact()- if (engine === 'claude') await hook('session-start', { hookEvent: 'SessionStart', source: 'compact' })+ if (engine === 'claude') await runHooks('SessionStart', { source: 'compact' })await new Promise((resolve) => setTimeout(resolve, 300))}if (directive?.[1] === 'hold') returnif (directive?.[1] === 'permit') {const command = directive[2] || 'printf hi'await new Promise((resolve) => setTimeout(resolve, 2_000))- const row = await new Promise((resolve) => { dialog = { kind: 'permit', command, cursor: 0, drawn: 0, resolve }; drawDialog() })+ // The dialog takes the composer's place, as the CLIs draw theirs, until it is answered.+ const row = await new Promise((resolve) => { eraseComposer(); dialog = { kind: 'permit', command, cursor: 0, drawn: 0, resolve }; drawDialog() })const allowed = row === 0 || row === 1const id = `call_${turn}_p`if (allowed) {@@ -492,17 +595,17 @@ export async function run(engine, config) {codex('response_item', { type: 'function_call_output', call_id: id, output: `ran ${command}` })}}- finish(allowed ? `ran ${command}` : `did not run ${command}`)+ await finish(allowed ? `ran ${command}` : `did not run ${command}`)return}if (directive?.[1] === 'ask') {// A real engine thinks before it asks; a dialog already on screen when its turn began reads to the// daemon as the previous turn's (askQuestion.ts `noteTurnStart`).await new Promise((resolve) => setTimeout(resolve, 2_000))- const choice = await new Promise((resolve) => { dialog = { cursor: 0, drawn: 0, resolve }; drawDialog() })+ const choice = await new Promise((resolve) => { eraseComposer(); dialog = { cursor: 0, drawn: 0, resolve }; drawDialog() })if (choice === null) {- process.stdout.write('\r\n(question cancelled)\r\n')- finish('(question cancelled)')+ say('(question cancelled)\r\n')+ await finish('(question cancelled)')return}// The tool call is written once it is answered, as the real CLIs flush it.@@ -511,25 +614,25 @@ export async function run(engine, config) {const id = `toolu_${turn}`claude({ type: 'assistant', message: { id: `msg_${turn}_q`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'AskUserQuestion', input: { questions } }], stop_reason: 'tool_use' } })claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `User has answered your questions: "${QUESTION}"="${choice}"` }] } })- process.stdout.write(`\r\n⏺ User answered Claude's questions:\r\n ⎿ · ${QUESTION} → ${choice}\r\n`)+ say(`⏺ User answered Claude's questions:\r\n ⎿ · ${QUESTION} → ${choice}\r\n`)} else {const id = `call_${turn}_q`codex('response_item', { type: 'function_call', call_id: id, name: 'request_user_input', arguments: JSON.stringify({ questions }) })codex('response_item', { type: 'function_call_output', call_id: id, output: JSON.stringify({ answers: { [QUESTION]: choice } }) })- process.stdout.write(`\r\n• ${QUESTION} → ${choice}\r\n`)+ say(`• ${QUESTION} → ${choice}\r\n`)}- finish(`you chose ${choice}${notes ? ` (notes: ${notes})` : ''}`)+ await finish(`you chose ${choice}${notes ? ` (notes: ${notes})` : ''}`)return}- if (directive?.[1] === 'version') { finish(versionLine); return }+ if (directive?.[1] === 'version') { await finish(versionLine); return }if (engine === 'codex' && directive?.[1] === 'goal') {bottom = goalBottom(directive[2] === 'done' ? 'Goal achieved (1m)' : 'Pursuing goal (1m)')- finish(`answer ${turn}: ${prompt}`)+ await finish(`answer ${turn}: ${prompt}`)return}if (engine === 'claude' && directive?.[1] === 'transcript') {bottom = transcriptBottom(prompt, `answer ${turn}: ${prompt}`)- finish(`answer ${turn}: ${prompt}`)+ await finish(`answer ${turn}: ${prompt}`)return}if (engine === 'codex' && directive?.[1] === 'overlay') {@@ -545,16 +648,15 @@ export async function run(engine, config) {if (engine === 'codex' && directive?.[1] === 'browse') {// Reached in Codex by Esc twice on an empty composer; the directive goes straight there.bottom = directive[2] === 'scrollback' ? pagerBottom(prompt, `answer ${turn}: ${prompt}`) : browsingBottom- finish(`answer ${turn}: ${prompt}`)+ await finish(`answer ${turn}: ${prompt}`)return}if (directive?.[1] === 'slow') await new Promise((resolve) => setTimeout(resolve, Number(directive[2]) || 1000))- finish(`answer ${turn}: ${prompt}`)+ await finish(`answer ${turn}: ${prompt}`)}// Raw input: bracketed paste brackets the text, Enter (\r) submits, Ctrl-C interrupts.process.stdin.setEncoding('utf8')- let buffer = ''let queue = Promise.resolve()// Inside a bracketed paste a carriage return or newline is a newline in the prompt, as Ink and// ratatui read it; only one typed outside a paste submits. The paste's markers say which.@@ -593,10 +695,10 @@ export async function run(engine, config) {// composer (chat_composer/history_search.rs), its Esc and ctrl+c leave the composer as it was.let rest = ''const leave = (draft) => {- process.stdout.write('\r\n\x1b[2K\x1b[1A')+ eraseComposer()bottom = nullbuffer = draft- draw(buffer)+ drawComposer()}for (const token of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[0-9;]*[A-Za-z~]|\x1b|[\s\S]/g) ?? []) {if (!bottom?.search) { rest += token; continue }@@ -633,21 +735,24 @@ export async function run(engine, config) {if (part === '\x1b[201~') { pasting = false; continue }if (pasting && (part === '\r' || part === '\n')) { buffer += '\n'; continue }if (part === '\x03') {+ // Ctrl-C ends a running turn, and empties the composer either way.+ buffer = ''if (open) {if (engine === 'claude') claude({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: '[Request interrupted by user]' }] } })else codex('event_msg', { type: 'turn_aborted', turn_id: open })open = null- process.stdout.write('\r\n(interrupted)\r\n')- draw()- }- buffer = ''+ say('(interrupted)\r\n')+ } else draw()} else if (part === '\r' || part === '\n') {const line = bufferbuffer = ''+ // Taken off the composer at once, whatever the engine is doing: a prompt sent while a turn runs+ // waits its turn out of the composer, as both CLIs queue one.+ draw()queue = queue.then(() => handle(line))} else if (part) {buffer += part- draw(buffer)+ draw()}}})diff --git a/cli/e2e/hookclient.e2e.ts b/cli/e2e/hookclient.e2e.tsnew file mode 100644index 000000000..153d6c8d2--- /dev/null+++ b/cli/e2e/hookclient.e2e.ts@@ -0,0 +1,308 @@+/**+ * The hook client's own two roads, for Claude Code and Codex. Every hook an engine runs in this suite is+ * the real `hook/notify.mjs`, run by the fake engine the way the CLI runs it (harness/fakeEngine.mjs). It+ * gives the daemon 500 ms to answer. When it cannot reach the daemon at all, it writes the agent's row+ * into the registry itself (`fallbackRegister`), so the conversation an engine moves to while the daemon+ * is down is the one the daemon finds when it comes back.+ *+ * - A slow answer is not an outage. A daemon that took the event and answers late (held here, as a swap+ * storm or a debugger holds it, then made to wait for an agent's new process by a restart) handles the+ * event itself once it can, and the hook must leave the registry alone. A code review found the hook+ * writing its own row meanwhile, which the daemon's next save merged over its own: the agent lost the+ * name, permission mode and close plan the daemon kept. The suite could not see it, because its fake+ * engines used to post their events straight to the daemon, with no deadline and no fallback.+ * - A daemon that is down. The person goes on in the terminal, starting a new conversation and taking a+ * turn in it; the hook writes the agent's row, and the daemon, back, takes it in: the same agent, on the+ * conversation the hook named, with everything the daemon kept for it, and working.+ */+import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync, statSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Engine = 'claude' | 'codex'+type Row = Record<string, any>++const engines: Engine[] = ['claude', 'codex']+/** A mode other than the default for each engine, so a row rebuilt without it shows. */+const MODE: Record<Engine, { mode: string; flags: string[] }> = {+ claude: { mode: 'plan', flags: ['--permission-mode', 'plan'] },+ codex: { mode: 'readOnly', flags: ['--sandbox', 'read-only'] },+}++const rows = async (client: LocalClient): Promise<Row[]> =>+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)+const bound = (client: LocalClient, agentId: string, sessionId?: string) =>+ until(`${agentId.slice(0, 8)} to be bound and active`, async () => {+ const now = await row(client, agentId)+ return now?.status === 'active' && now.sessionId && (!sessionId || now.sessionId === sessionId) ? now : null+ }, 60_000, 250)+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine, name: string): Promise<Row> {+ const cwd = join(d.projectsDir, name)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine, cwd, name, permissionMode: MODE[engine].mode }, 90_000)+ expect(created.error, `${name}: ${JSON.stringify(created)}`).toBeUndefined()+ return bound(client, created.agent.id)+}+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)+ client.send('message', { agentId, content })+ expect((await started).payload?.userMessage).toBe(content)+ await ended+}+/** What the person said in a conversation, oldest first, as the apps read it back. */+async function said(client: LocalClient, sessionId: string): Promise<string[]> {+ const page = await client.request('session_get', { sessionId, limit: 50 }, 60_000)+ if (page.error) return []+ return (page.events as Row[]).filter((event) => event.type === 'user_message').map((event) => String(event.payload.content))+}++/** Typed into the agent's terminal by the person, as at a keyboard: the engine takes it without the daemon. */+async function type(d: IsolatedDaemon, pane: string, text: string): Promise<void> {+ await d.tmux.run('send-keys', '-t', pane, '-l', text)+ await d.tmux.run('send-keys', '-t', pane, 'Enter')+}++/**+ * The registry as it is on disk, and its boot mark. The daemon writes the boot mark only as it loads the+ * registry; the hook writes it on every fallback, just before the row (notify.mjs `fallbackRegister`). So+ * a boot mark replaced while the daemon runs is a hook that wrote the registry behind its back.+ */+function onDisk(d: IsolatedDaemon): { registry: string | null; boot: { bytes: string; inode: number } | null } {+ const read = (file: string) => { try { return readFileSync(file, 'utf8') } catch { return null } }+ const boot = join(d.dataDir, 'registry-boot')+ const bytes = read(boot)+ return {+ registry: read(join(d.dataDir, 'registry.json')),+ boot: bytes === null ? null : { bytes, inode: statSync(boot).ino },+ }+}+const rowOnDisk = (d: IsolatedDaemon, agentId: string): Row | undefined =>+ (JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Row[]).find((entry) => entry.agentId === agentId)++/** The hooks the engines noted since `from` (a length of the hook log), as `<event>(<cause>) session=<id> ran in <ms> ms`. */+const hooksSince = (d: IsolatedDaemon, from: number): string[] => d.hookLog().slice(from).split('\n').filter(Boolean)+const ran = (lines: string[], pattern: RegExp): string | undefined => lines.find((line) => pattern.test(line) && / ran in \d+ ms · exit=0/.test(line))+const tookMs = (line: string): number => Number(/ ran in (\d+) ms/.exec(line)?.[1])++/** The engine process's arguments, read off the process in the agent's pane. */+async function engineArgs(d: IsolatedDaemon, pane: string): Promise<string> {+ const root = Number((await d.tmux.run('display-message', '-p', '-t', pane, '#{pane_pid}')).trim())+ const table = execFileSync('ps', ['-A', '-o', 'pid=,ppid=,command='], { encoding: 'utf8' })+ .split('\n').map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)).filter(Boolean)+ .map((m) => ({ pid: Number(m![1]), ppid: Number(m![2]), command: m![3] }))+ const under = new Set([root])+ for (let grew = true; grew;) {+ grew = false+ for (const p of table) if (under.has(p.ppid) && !under.has(p.pid)) { under.add(p.pid); grew = true }+ }+ return table.filter((p) => under.has(p.pid) && /\/bin\/(claude|codex)\b/.test(p.command)).map((p) => p.command).join('\n')+}++const processState = (pid: number): string => {+ try { return execFileSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' }).trim() } catch { return '' }+}++describe('the hook client', () => {+ let daemon: IsolatedDaemon | undefined+ const stopped: number[] = []+ afterEach(async () => {+ for (const pid of stopped.splice(0)) { try { process.kill(pid, 'SIGCONT') } catch { /* gone */ } }+ await daemon?.close(); daemon = undefined+ })+ const fresh = async (): Promise<IsolatedDaemon> => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => {+ console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`)+ console.log(`---- hooks the engines ran\n${d.hookLog()}`)+ })+ await d.start()+ return d+ }++ it.each(engines)('%s: an answer later than 500 ms is not an outage, and the hook leaves the registry to the daemon', async (engine) => {+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `slow-${engine}`)+ await turn(client, agent.id, 'before the hold')+ // The prompts the daemon took through the hook, by its log: this one, so far.+ const prompts = () => [...d.log().matchAll(new RegExp(`\\[hooks\\] ${agent.sessionId.slice(0, 8)} UserPromptSubmit `, 'g'))].length+ await until('the daemon to have taken the first prompt\'s hook', () => prompts() === 1 || null, 15_000, 50)++ // The core held still, its socket still taking connections: an engine's hook connects, sends its+ // event and hears nothing back.+ const core = d.corePid()!+ process.kill(core, 'SIGSTOP')+ stopped.push(core)+ await until('the core to be held', () => processState(core).includes('T') || null, 10_000, 50)+ const before = onDisk(d)+ const from = d.hookLog().length+ await type(d, agent.tmuxPane, 'typed while the daemon was held')+ const lines = await until('the engine to run its hooks for the typed prompt', () => {+ const now = hooksSince(d, from)+ return ran(now, /^.* UserPromptSubmit /) && (engine === 'codex' || ran(now, /^.* Stop /)) ? now : null+ }, 30_000, 100)+ // Each waited out the hook's own deadline: the daemon had taken the event and not answered.+ expect(tookMs(ran(lines, / UserPromptSubmit /)!), lines.join('\n')).toBeGreaterThanOrEqual(500)+ expect(processState(core), 'the core is still held').toContain('T')+ // Nobody wrote the registry: the daemon could not, and the hook must not.+ expect(onDisk(d)).toEqual(before)++ // Let go, the daemon takes the event itself, the one the hook gave up waiting on: the typed turn+ // reaches the app, and the agent is as the daemon kept it.+ const typedStarted = client.next(isTurn('turn_started', agent.id), 60_000, 'turn_started (typed while held)')+ const typedEnded = client.next(isTurn('turn_ended', agent.id), 60_000, 'turn_ended (typed while held)')+ process.kill(core, 'SIGCONT')+ stopped.splice(stopped.indexOf(core), 1)+ expect((await typedStarted).payload?.userMessage).toBe('typed while the daemon was held')+ await typedEnded+ await until('the daemon to take the hook it did not answer in time', () => prompts() === 2 || null, 30_000, 100)+ expect(await said(client, agent.sessionId)).toEqual(['before the hold', 'typed while the daemon was held'])+ let now = await bound(client, agent.id, agent.sessionId)+ expect([now.name, now.permissionMode]).toEqual([`slow-${engine}`, MODE[engine].mode])+ await turn(client, agent.id, 'after the hold')++ // A restart: the new engine announces itself before the daemon has recorded its process, and the daemon+ // waits for the record before it answers (core/engines/hooks.ts), often past the hook's deadline.+ const restarted = await client.request('agent_restart', { agentId: agent.id }, 90_000)+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()+ now = await bound(client, agent.id, agent.sessionId)+ await turn(client, agent.id, 'after the restart')+ expect([now.name, now.permissionMode]).toEqual([`slow-${engine}`, MODE[engine].mode])+ expect(await engineArgs(d, now.tmuxPane)).toContain(MODE[engine].flags.join(' '))+ // Through all of it, no hook wrote the registry: the boot mark is the one the daemon wrote as it started.+ expect(onDisk(d).boot).toEqual(before.boot)+ client.close()+ })++ it.each(engines)('%s: the daemon down, the hook writes the agent\'s row, and the daemon back takes it in', async (engine) => {+ const d = await fresh()+ let client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `down-${engine}`)+ await turn(client, agent.id, 'before the daemon went down')+ client.close()+ await d.stop()+ // The row as the daemon left it.+ const kept = rowOnDisk(d, agent.id)!+ expect(kept).toMatchObject({ sessionId: agent.sessionId, defaultName: `down-${engine}`, permissionMode: MODE[engine].mode })+ const before = onDisk(d)++ // The person goes on in the terminal: a new conversation (Claude Code's `/clear`, Codex's `/new`).+ const from = d.hookLog().length+ await type(d, agent.tmuxPane, '!clear')+ const announced = await until('the engine to announce its new conversation', () =>+ ran(hooksSince(d, from), / SessionStart\(clear\) /), 30_000, 100)+ const sessionId = /session=(\S+)/.exec(announced)![1]+ expect(sessionId).not.toBe(agent.sessionId)+ // The hook could not reach the daemon, so it wrote the agent's row itself: the same agent, pane and+ // process, on the new conversation.+ const written = rowOnDisk(d, agent.id)+ expect(written, 'the agent\'s row after the hook').toMatchObject({+ sessionId, engine, tmuxPane: agent.tmuxPane, processIdentity: kept.processIdentity,+ })+ expect(onDisk(d).boot).not.toEqual(before.boot)+ // …and a turn in it, the daemon still down.+ await type(d, agent.tmuxPane, 'typed while the daemon was down')+ await until('the engine to take the typed prompt', () => ran(hooksSince(d, from), / UserPromptSubmit /) || null, 30_000, 100)++ // Back, the daemon takes the row in: one agent, on the conversation the hook named, still the agent+ // the daemon made, with the turn typed meanwhile, and working.+ await d.start()+ client = await LocalClient.connect(d)+ const back = await bound(client, agent.id, sessionId)+ expect((await rows(client)).filter((one) => one.status === 'active').map((one) => one.id)).toEqual([agent.id])+ expect([back.name, back.permissionMode, back.tmuxPane]).toEqual([`down-${engine}`, MODE[engine].mode, agent.tmuxPane])+ await until('the turn typed while the daemon was down', async () =>+ (await said(client, sessionId)).includes('typed while the daemon was down') || null, 60_000, 500)+ await turn(client, agent.id, 'after the daemon came back')+ expect(await said(client, sessionId)).toEqual(['typed while the daemon was down', 'after the daemon came back'])++ // And it relaunches as it was made: a restart keeps its permission mode.+ const restarted = await client.request('agent_restart', { agentId: agent.id }, 90_000)+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()+ const after = await bound(client, agent.id, sessionId)+ expect([after.name, after.permissionMode]).toEqual([`down-${engine}`, MODE[engine].mode])+ expect(await engineArgs(d, after.tmuxPane)).toContain(MODE[engine].flags.join(' '))+ await turn(client, agent.id, 'after the restart')+ client.close()+ })++ it.each(engines)('%s typed into a terminal tile while the daemon is down: the hook makes the tile its agent, and the daemon takes it in', async (engine) => {+ const d = await fresh()+ let client = await LocalClient.connect(d)+ // A terminal open in the app. Its row names the engine `terminal`, which the hook once read as a damaged+ // registry, so a hook with the daemon down registered nothing.+ const cwd = join(d.projectsDir, `in-terminal-${engine}`)+ mkdirSync(cwd, { recursive: true })+ const opened = await client.request('agent_create', { engine: 'terminal', cwd }, 60_000)+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()+ const tile = await until('the terminal tile to be up', async () => {+ const now = await row(client, opened.agent.id)+ return now?.status === 'active' && rowOnDisk(d, now.id)?.engine === 'terminal' ? now : null+ }, 60_000, 250)+ client.close()+ await d.stop()++ // The person starts the engine in that terminal.+ const from = d.hookLog().length+ await type(d, tile.tmuxPane, engine)+ const announced = await until('the engine to announce its conversation', () =>+ ran(hooksSince(d, from), / SessionStart\(startup\) /), 30_000, 100)+ const sessionId = /session=(\S+)/.exec(announced)![1]+ // Nothing listening, the hook wrote the row itself: the tile's own, now the engine's, as the daemon+ // would have made it.+ const rowsOnDisk = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Row[]+ expect(rowsOnDisk.filter((one) => one.tmuxPane === tile.tmuxPane), JSON.stringify(rowsOnDisk)).toEqual([+ expect.objectContaining({ agentId: tile.id, engine, sessionId, terminalHost: true, active: true }),+ ])++ // Back, the daemon takes it in: the tile is the agent, on the conversation the hook named, and works.+ await d.start()+ client = await LocalClient.connect(d)+ const back = await bound(client, tile.id, sessionId)+ expect([back.engine, back.name, back.tmuxPane]).toEqual([engine, tile.name, tile.tmuxPane])+ await turn(client, tile.id, 'to the engine typed into the terminal')+ // And when the engine exits, its conversation is kept under the agent's id and the pane is a terminal+ // again, under one of its own (retainExitedSession.ts), as for any engine typed into a terminal.+ client.send('message', { agentId: tile.id, content: '!exit' })+ await until('the pane to be a terminal again', async () => {+ const all = await rows(client)+ const shell = all.find((one) => one.tmuxPane === tile.tmuxPane && one.engine === 'terminal' && one.status === 'active')+ const kept = all.find((one) => one.id === tile.id)+ return shell && kept?.status === 'stopped' && kept.sessionId === sessionId ? shell : null+ }, 60_000, 500)+ client.close()+ })++ it.each(engines)('%s in a tmux session the person opened by hand is no agent, whether the daemon is down or up', async (engine) => {+ const d = await fresh()+ await d.stop()+ const before = onDisk(d)+ const cwd = join(d.projectsDir, `own-session-${engine}`)+ mkdirSync(cwd, { recursive: true })+ // Not a session Harness made: the daemon never takes one for an agent (harnessSessionLabel.ts).+ const from = d.hookLog().length+ const pane = await d.tmux.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', `own-${engine}`, '-c', cwd,+ ...['HOME', 'ZDOTDIR', 'PATH', 'CODEX_HOME', 'CLAUDE_PATH', 'CODEX_PATH'].flatMap((name) => ['-e', `${name}=${d.env[name]}`]),+ engine === 'claude' ? d.env.CLAUDE_PATH! : d.env.CODEX_PATH!)+ await until('the engine to run its start-up hook', () => ran(hooksSince(d, from), / SessionStart\(startup\) /), 30_000, 100)+ // With nothing listening, the hook wrote nothing for it either.+ expect(onDisk(d)).toEqual(before)++ // Back, the daemon lists no agent for it, and a prompt typed there, its hook now answered, makes none.+ await d.start()+ const client = await LocalClient.connect(d)+ await type(d, pane, 'typed in a session of my own')+ await until('the engine to take the prompt', () => ran(hooksSince(d, from), / UserPromptSubmit /), 30_000, 100)+ await new Promise((done) => setTimeout(done, 6_000))+ expect((await rows(client)).filter((one) => one.tmuxPane === pane)).toEqual([])+ client.close()+ })++})diff --git a/cli/e2e/input-safety.e2e.ts b/cli/e2e/input-safety.e2e.tsindex e3ece525c..07d732f88 100644--- a/cli/e2e/input-safety.e2e.ts+++ b/cli/e2e/input-safety.e2e.ts@@ -160,6 +160,28 @@ describe('what a message must never do', () => {client.close()})+ it.each(engines)('%s: what reached the pane as its engine went down never runs in the shell it leaves', async (engine) => {+ // An engine on its way out reads no more input: Claude Code runs its SessionEnd hooks first. What was+ // typed for it then, a message right behind \`/exit\` among them, waits in the terminal, and the shell+ // the pane becomes must not run it. Typed here once the engine has taken its \`!exit\`.+ const d = await fresh()+ const client = await LocalClient.connect(d)+ const agent = await create(d, client, engine, `went-down-${engine}`)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, '-l', '!exit')+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Enter')+ await until('the engine to take its exit', async () => (await d.capture(agent.tmuxPane)).includes('> !exit') || null, 15_000, 20)+ const marker = join(d.root, `pwned-on-the-way-out-${engine}`)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, command(marker), 'Enter')+ await until('the pane to be a shell', async () => (await d.capture(agent.tmuxPane)).includes('This pane is a shell now') || null, 30_000, 100)+ await new Promise((resolve) => setTimeout(resolve, 3_000))+ expect(existsSync(marker), 'what was typed for the engine ran in the shell').toBe(false)+ // The shell is the person's from here: what they type runs.+ const typed = join(d.root, `typed-in-the-shell-${engine}`)+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, command(typed), 'Enter')+ await until('the shell to run what was typed into it', () => existsSync(typed) || null, 10_000, 100)+ client.close()+ })+it.each(engines)('%s: keystrokes queued for a terminal whose engine exited are the person\'s own to send', async (engine) => {// The terminal is a terminal: what a person types into the pane goes to whatever runs there. The// composer is what must never type into a shell; this pins that the two stay apart.diff --git a/cli/e2e/races.e2e.ts b/cli/e2e/races.e2e.tsindex c6ef29f18..ffd30ec75 100644--- a/cli/e2e/races.e2e.ts+++ b/cli/e2e/races.e2e.ts@@ -44,7 +44,7 @@ const active = (client: LocalClient, agentId: string, sessionId?: string) =>/** The engine as it is installed for the agents created next: its config, plus what the test says* (e2e/harness/fakeEngine.mjs), written beside the old wrapper and renamed over it. */function install(d: IsolatedDaemon, engine: Engine, extra: Record<string, unknown>): void {- const config = { port: d.port, dataDir: d.dataDir, claudeProjectsDir: d.env.CLAUDE_PROJECTS_DIR, codexHome: d.env.CODEX_HOME, ...extra }+ const config = { ...d.engineConfig, ...extra }const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).hrefconst wrapper = join(d.root, 'bin', engine)writeFileSync(`${wrapper}.new`, `#!${process.execPath}\nimport(${JSON.stringify(module)}).then((m) => m.run(${JSON.stringify(engine)}, ${JSON.stringify(config)}))\n`, { mode: 0o755 })diff --git a/cli/e2e/releaseRehearsal.e2e.ts b/cli/e2e/releaseRehearsal.e2e.tsindex 681f68eb1..42dafd6be 100644--- a/cli/e2e/releaseRehearsal.e2e.ts+++ b/cli/e2e/releaseRehearsal.e2e.ts@@ -3,7 +3,7 @@* release (`REHEARSE_FROM`, its cli.js with its notify.mjs beside it) to this checkout's bundle, through* the real updater path and a local manifest, from the state that release leaves on a person's machine:* its own data folder, and its hooks installed into the (throwaway) home, which the fake engines run as- * Claude Code and Codex run theirs (`realHooks`).+ * Claude Code and Codex run theirs, as for every daemon under test (e2e/harness/fakeEngine.mjs).** At the moment of the update a Claude Code and a Codex agent are mid-turn, a window is connected and a* terminal tile is open. After it: the same agents on the same conversations, their turns finished and@@ -174,7 +174,6 @@ describe.skipIf(!FROM)('a release rehearsal: the update from a published releasedaemon = await IsolatedDaemon.create({scriptPath: join(cliDir(), 'cli.js'),noMaster: !fromHasMaster,- realHooks: true,env: {...(backend ? { BACKEND_WS_URL: backend.wsUrl, WEB_URL: backend.httpUrl, ADAPTER_COMPUTER_ID: MACHINE.computerId } : {}),ADAPTER_CLI_DIR: cliDir(),diff --git a/cli/e2e/teamsProcess.e2e.ts b/cli/e2e/teamsProcess.e2e.tsindex 88a9e2c38..bb25c292e 100644--- a/cli/e2e/teamsProcess.e2e.ts+++ b/cli/e2e/teamsProcess.e2e.ts@@ -133,6 +133,14 @@ describe('the teams\' prompt scopes in their own process', () => {const [moving, still] = [await create(d, client, 'scopes-moving'), await create(d, client, 'scopes-still')]await say(client, moving.id, 'hello from the alpha tab', 'tab-alpha')await say(client, still.id, 'hello from the gamma tab', 'tab-gamma')+ // A message's prompt hook can be heard after its turn: the hook gives the daemon 500 ms and the engine+ // goes on (hook/notify.mjs). A start still on its way to the teams process when it dies is a change on+ // its way, and its scope rightly reads as no team. The claim below is about a scope with nothing on its+ // way, so both hooks are heard and delivered first.+ for (const agent of [moving, still]) {+ const sid = agent.sessionId.slice(0, 8)+ await until(`${sid}'s prompt hook to be heard`, () => d.log().includes(`[hooks] ${sid} UserPromptSubmit `) || null, 30_000, 100)+ }await scopeBecomes(client, still.id, channelTeamId('tab-gamma'), 'the gamma team')await scopeBecomes(client, moving.id, channelTeamId('tab-alpha'), 'the alpha team')process.kill(teamsPid(d)!, 'SIGKILL')diff --git a/cli/e2e/updates.e2e.ts b/cli/e2e/updates.e2e.tsindex 6b013becb..9bbec5ed3 100644--- a/cli/e2e/updates.e2e.ts+++ b/cli/e2e/updates.e2e.ts@@ -30,7 +30,7 @@ const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))* gets the new one. The config is the one IsolatedDaemon gave the engine, plus the release.*/function install(d: IsolatedDaemon, engine: Engine, release: Release = {}): void {- const config = { port: d.port, dataDir: d.dataDir, claudeProjectsDir: d.env.CLAUDE_PROJECTS_DIR, codexHome: d.env.CODEX_HOME, ...release }+ const config = { ...d.engineConfig, ...release }const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).hrefconst wrapper = join(d.root, 'bin', engine)writeFileSync(`${wrapper}.new`, `#!${process.execPath}\nimport(${JSON.stringify(module)}).then((m) => m.run(${JSON.stringify(engine)}, ${JSON.stringify(config)}))\n`, { mode: 0o755 })diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex 224be5ba9..f72eeefcc 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -16,7 +16,7 @@import http from 'node:http'import { execFile, execFileSync } from 'node:child_process'-import { randomUUID } from 'node:crypto'+import { createHash, randomUUID } from 'node:crypto'import {accessSync,closeSync,@@ -441,11 +441,65 @@ function readProcField(pid, field) {try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }}-async function panePid(pane) {- const stdout = await execFileText('tmux', ['display-message', '-p', '-t', pane, '#{pane_pid}'], 2000)+// The tag a daemon puts on every pane it creates, and the name it gives their sessions (both in+// src/lib/harnessSessionLabel.ts, which hookNotify.spec.ts keeps these equal to). Before tmux 3.0 there+// are no pane options, and the tag rides in the pane's start command instead (`ownerCommand`); this format+// reads it there first and from the option otherwise, as the daemon's listing does on such a tmux+// (`paneOwnerFormat(false)`), and on a newer one a pane's start command never carries it.+const HARNESS_OWNER_OPTION = '@harness_daemon'+const HARNESS_SESSION_PREFIX = 'harness-'+const OWNER_COMMAND_PREFIX = '/usr/bin/env HARNESS_DAEMON='+// A pane's owner, read as the daemon reads it (harnessSessionLabel.ts paneOwnerFormat): from tmux 3.0 the+// pane's own option, which stays with the pane wherever the person moves it; before 3.0 the tag in its start+// command, or its window's tag in a session Harness named only, since elsewhere the window's tag names a+// pane the person split into, or joined into, an agent's window.+const PANE_OWNER_FORMAT = `#{${HARNESS_OWNER_OPTION}}`+const PANE_OWNER_FORMAT_OLD_TMUX = `#{?#{m:${OWNER_COMMAND_PREFIX}*,#{pane_start_command}},#{=${OWNER_COMMAND_PREFIX.length + 16}:pane_start_command},`+ + `#{?#{m:${HARNESS_SESSION_PREFIX}*,#{session_name}},#{${HARNESS_OWNER_OPTION}},}}`++let paneOptions+/** Whether this tmux has pane options (3.0+). A version it cannot read counts as new, as the daemon reads it (tmuxVersion.ts). */+async function tmuxHasPaneOptions() {+ if (paneOptions === undefined) {+ const version = /(\d+)\.(\d+)/.exec((await execFileText('tmux', ['-V'], 2000)) || '')+ paneOptions = !version || Number(version[1]) >= 3+ }+ return paneOptions+}++/** A daemon's tag: its data folder, symlinks resolved, hashed — `harnessPaneOwner` in the daemon. */+function daemonPaneOwner(dataDir) {+ let canonical = resolve(dataDir)+ try { canonical = realpathSync(dataDir) } catch { /* not there: as given */ }+ return createHash('sha256').update(canonical).digest('hex').slice(0, 16)+}++/**+ * 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.+ */+async function paneFacts(pane, dataDir) {+ const format = (await tmuxHasPaneOptions()) ? PANE_OWNER_FORMAT : PANE_OWNER_FORMAT_OLD_TMUX+ const stdout = await execFileText('tmux', ['display-message', '-p', '-t', pane, `#{pane_pid}|#{session_name}|${format}`], 2000)if (stdout === null) return undefined- const pid = Number((stdout || '').trim())- return Number.isSafeInteger(pid) && pid > 0 ? pid : null+ const line = (stdout || '').trim()+ const first = line.indexOf('|')+ const last = line.lastIndexOf('|')+ if (first < 0 || last <= first) return undefined+ const pid = Number(line.slice(0, first))+ 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+ const 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 }}function argvTokens(args) {@@ -677,13 +731,6 @@ async function enrichProcessImages(rows) {return rows.map((row) => images.has(row.pid) ? { ...row, imageFileKey: images.get(row.pid) } : row)}-async function paneEngineProcess(pane, engine) {- const rootPid = await panePid(pane)- if (rootPid === undefined) return { state: 'unknown' }- if (!rootPid) return { state: 'gone' }- return rootEngineProcess(rootPid, engine)-}-async function rootEngineProcess(rootPid, engine) {const rawRows = await processRows()if (!rawRows) return { state: 'unknown' }@@ -1120,9 +1167,13 @@ function mergeRuntimes(current, observed) {return [...merged.values()].sort((a, b) => runtimePlacementKey(a).localeCompare(runtimePlacementKey(b)))}+// Every engine a registry row can name: the daemon's own list (src/engines/types.ts ENGINES), which+// hookNotify.spec.ts keeps this one equal to. A row naming one missing here made the whole registry read+// as damaged, and a hook while the daemon was down then registered nothing at all: `terminal` was+// missing, so one terminal open on the machine was enough (e2e/hookclient.e2e.ts).const REGISTRY_ENGINES = new Set(['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',- 'agy', 'copilot',+ 'agy', 'copilot', 'terminal',])function validRegistryString(value, max = 4096) {@@ -1217,11 +1268,12 @@ async function fallbackRegister(input, engine, tmuxPane) {if (!transcriptOptional && !transcriptPath) returnif (transcriptPath && !validTranscriptPath(engine, transcriptPath, p)) returnconst observations = []- if (/^%\d+$/.test(tmuxPane || '')) {- const tmux = await paneEngineProcess(tmuxPane, engine)- if (tmux.state === 'alive' && tmux.identity && await callerOwns(tmux.identity)) {- observations.push({ identity: tmux.identity, runtime: { backend: 'tmux', paneId: tmuxPane } })- }+ const pane = /^%\d+$/.test(tmuxPane || '') ? await paneFacts(tmuxPane, p.dataDir) : undefined+ const taken = pane?.taken ?? 'no'+ if (taken === 'no' || !pane.pid) return+ const tmux = await rootEngineProcess(pane.pid, engine)+ if (tmux.state === 'alive' && tmux.identity && await callerOwns(tmux.identity)) {+ observations.push({ identity: tmux.identity, runtime: { backend: 'tmux', paneId: tmuxPane } })}if (!observations.length) returnconst process = observations[0]@@ -1244,28 +1296,36 @@ async function fallbackRegister(input, engine, tmuxPane) {// into an empty registry merely because the daemon is down.if (loaded === null) returnlet sessions = loaded+ const routeKeys = new Set(observedRuntimes.map(runtimeRouteKey))+ const onRoute = (s) => !!s && !!(Array.isArray(s.runtimes)+ ? s.runtimes.some((runtime) => routeKeys.has(runtimeRouteKey(runtime)))+ : s.tmuxPane && routeKeys.has(runtimeRouteKey({ backend: 'tmux', paneId: s.tmuxPane })))+ // A session an older build named is the daemon's only while its registry holds an agent there.+ if (taken === 'if-held' && !sessions.some(onRoute)) returnwriteBoot(p.bootFile)const now = Date.now()const sameRuntime = (s) => s && s.engine === engine&& s.processIdentity?.pid === process.identity.pid && s.processIdentity?.startMarker === process.identity.startMarker- const existingIndex = sessions.findIndex(sameRuntime)+ let existingIndex = sessions.findIndex(sameRuntime)+ // An engine typed into a terminal is that terminal's agent from then on, as the daemon adopts it+ // (registry.adoptEngine): the same agent, its name and its tile, now this engine's. Taken for a+ // stranger on its pane, the terminal's row was dropped for a new agent, and the tile the person had+ // open was gone when the daemon came back (e2e/hookclient.e2e.ts).+ if (existingIndex < 0) existingIndex = sessions.findIndex((s) => s?.engine === 'terminal' && onRoute(s))const existing = existingIndex >= 0 ? sessions[existingIndex] : null// A resumed session moves to this process agent; the previous process remains visible but unbound.sessions = sessions.map((s) => s && s.sessionId === sessionId && !sameRuntime(s)? { ...s, sessionId: '', boundAt: null, transcriptPath: null, source: null, updatedAt: now }: s)- const routeKeys = new Set(observedRuntimes.map(runtimeRouteKey))- if (existingIndex < 0) sessions = sessions.filter((s) => !s || !(Array.isArray(s.runtimes)- ? s.runtimes.some((runtime) => routeKeys.has(runtimeRouteKey(runtime)))- : s.tmuxPane && routeKeys.has(runtimeRouteKey({ backend: 'tmux', paneId: s.tmuxPane }))))+ if (existingIndex < 0) sessions = sessions.filter((s) => !onRoute(s))const agentId = typeof existing?.agentId === 'string' && existing.agentId ? existing.agentId : randomUUID()const runtimes = mergeRuntimes(existing?.runtimes, observedRuntimes)const tmuxProjection = runtimes.find((runtime) => runtime.backend === 'tmux')?.paneId || ''// What the daemon chose for this agent at launch and cannot re-derive from the process — the// grid launch (credential included), the Codex profile, the bypass flag, the observed grid and- // gateway — is carried forward exactly as `registry.register()` does. A hook arriving while the- // daemon is down must not be the one write that strips the row of them. `launch` is not: like- // there, a hook means the engine is up, whatever the launch was.+ // gateway — is carried forward, in the shapes `registry.register()` gives them. A hook arriving+ // while the daemon is down must not be the one write that strips the row of them. `launch` is not:+ // like there, a hook means the engine is up, whatever the launch was.const carried = {gateway: existing?.gateway === 'ori' ? 'ori' : null,grid: existing?.grid ?? null,@@ -1278,17 +1338,22 @@ async function fallbackRegister(input, engine, tmuxPane) {// When an app last opened this agent (RegisteredSession.lastOpenedAt): a fact about the person,// not the process, and the daemon's own rebuild carries it the same way....(Number.isSafeInteger(existing?.lastOpenedAt) && existing.lastOpenedAt > 0 ? { lastOpenedAt: existing.lastOpenedAt } : {}),- // …and the rest of what `register()` carries: the harness (DSH) and its runtime, the agent file,- // the permission mode, the subscription model, the default name, the web search a grid launch- // decided, and a close planned for after the task (#812). Dropped here, a hook in the seconds an- // update leaves the daemon down relaunched a harness as a plain engine and never closed an agent- // its person had asked to close. As there, a resume-only row's launch is over once a hook comes.- ...Object.fromEntries(['gridWebSearch', 'subscriptionModel', 'defaultName', 'dsh', 'dshRuntime', 'agent', 'permissionMode', 'closePlan']- .filter((key) => existing?.[key] !== undefined && existing?.[key] !== null).map((key) => [key, existing[key]])),- ...(existing?.resumeOnly === true ? { resumeOnly: true, launch: { state: 'ready' } } : {}),- ...(existing?.terminalHost === true ? { terminalHost: true } : {}),+ // A pane that was a terminal goes back to being one when this engine exits.+ ...(existing?.engine === 'terminal' || existing?.terminalHost === true ? { terminalHost: true } : {}),}+ // Everything else the daemon kept on the row goes on as it stands: the agent's name, permission mode,+ // harness (DSH) and its runtime, named agent, subscription model, the web search a grid launch decided,+ // the close planned for after the task (#812), whether it is a terminal, that a stop must be resumed+ // and not started over, and whatever the daemon keeps there next. Named fields alone were the row+ // rebuilt without them, which the daemon then loaded as its own: a hook in the seconds an update or a+ // restart leaves the daemon down relaunched a harness as a plain engine, out of the mode it was made+ // in and under another name, and never closed an agent its person had asked to close (#831;+ // e2e/hookclient.e2e.ts). The launch is over once a hook comes, as `registry.register()` has it:+ // left behind, or `ready` on a row that may only be resumed.+ const { launch: _launch, ...kept } = existing ?? {}const entry = {+ ...kept,+ ...(existing?.resumeOnly === true ? { launch: { state: 'ready' } } : {}),schemaVersion: 2,active: true,...carried,@@ -1319,7 +1384,10 @@ async function fallbackRegister(input, engine, tmuxPane) {cliVersion: typeof (input.cli_version || input.version) === 'string' ? (input.cli_version || input.version) : (existing?.cliVersion ?? null),processIdentity: process.identity,registeredAt: typeof existing?.registeredAt === 'number' ? existing.registeredAt : now,+ // A bind is a change to the row, as the daemon stamps one; `updatedAt` is that stamp's name for+ // a daemon from before 2026-09-27.updatedAt: now,+ touchedAt: now,lastHookAt: now,lastTranscriptAt: typeof existing?.lastTranscriptAt === 'number' ? existing.lastTranscriptAt : now,}diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 94fc0d324..8943ea92f 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -6,6 +6,8 @@ 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'// 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@@ -38,6 +40,9 @@ interface RunHookOpts {launcherId?: string | null/** Install deterministic tmux/ps fixtures so an offline fallback can prove process ownership. */processEngine?: 'claude' | 'codex' | 'cursor' | 'hermes' | 'devin' | 'commandcode' | 'grok'+ /** The tmux session the pane is in, and the daemon tag on it (`@harness_daemon`). */+ paneSession?: string+ paneOwner?: string/** Override the fixture's ps `comm` and full argv to exercise install-root-independent matching. */processExecutable?: stringprocessArgs?: string@@ -76,8 +81,11 @@ function runHook(opts: RunHookOpts): Promise<string> {tmpDirs.push(binDir)const executable = opts.processExecutable ?? (opts.processEngine === 'cursor' ? 'agent' : opts.processEngine)const processArgs = opts.processArgs ?? executable- writeFileSync(join(binDir, 'tmux'), '#!/bin/sh\necho 7000\n', { mode: 0o755 })const 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 })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')@@ -946,6 +954,196 @@ describe('hook notify terminal scope', () => {expect(JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))[0]).toMatchObject({ resumeOnly: true, launch: { state: 'ready' }, ...CHOSEN })})+ it('reads every engine the daemon can write a row for: its list is the daemon\'s', () => {+ // The hook cannot import the daemon's list (it runs without the adapter's modules), so it keeps a copy,+ // and a copy drifts: `terminal` was missing from it, and one terminal tile made the hook read the whole+ // registry as damaged and register nothing while the daemon was down.+ const source = readFileSync(HOOK, 'utf8')+ const literal = /const REGISTRY_ENGINES = new Set\(\[([^\]]*)\]\)/.exec(source)?.[1]+ expect(literal, 'REGISTRY_ENGINES in hook/notify.mjs').toBeDefined()+ const listed = [...literal!.matchAll(/'([^']+)'/g)].map((match) => match[1])+ expect([...listed].sort()).toEqual([...ENGINES].sort())+ expect(new Set(listed).size).toBe(listed.length)+ })++ it('registers an agent offline beside a terminal tile, and leaves the tile as it was', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-terminal-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-new.jsonl')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ writeFileSync(transcriptPath, '{}\n')+ // A terminal tile as the daemon saves one: no conversation and, until a scan sees its shell, no process.+ const tile = {+ schemaVersion: 2, active: true, defaultName: 'Terminal', agentId: 'agent-terminal', sessionId: '', boundAt: null,+ engine: 'terminal', terminalHost: true, gateway: null, grid: null, codexHome: null, transcriptPath: null,+ projectDir: 'demo', cwd: '/tmp/demo', runtimes: [{ backend: 'tmux', paneId: '%3' }], primaryRuntimeKey: 'tmux\u0000%3',+ tmuxPane: '%3', source: null, title: null, model: null, cliVersion: null, processIdentity: null,+ registeredAt: 1, touchedAt: 1, lastHookAt: 0, lastTranscriptAt: 1,+ }+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([tile]))++ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: 'SessionStart', session_id: 'session-new', transcript_path: transcriptPath, cwd: '/tmp/demo', source: 'startup' },+ })++ const rows = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))+ expect(rows).toHaveLength(2)+ expect(rows[0]).toEqual(tile)+ expect(rows[1]).toMatchObject({ engine: 'claude', sessionId: 'session-new', tmuxPane: '%7', processIdentity: { pid: 7001 } })+ })++ it('names a daemon\'s panes as the daemon does', () => {+ const source = readFileSync(HOOK, 'utf8')+ expect(/const HARNESS_OWNER_OPTION = '([^']+)'/.exec(source)?.[1]).toBe(HARNESS_OWNER_OPTION)+ expect(/const HARNESS_SESSION_PREFIX = '([^']+)'/.exec(source)?.[1]).toBe(HARNESS_SESSION_PREFIX)+ // The tag in a pane's start command, before tmux 3.0, read with the format the daemon reads it with.+ const prefix = /const OWNER_COMMAND_PREFIX = '([^']+)'/.exec(source)?.[1]+ expect(`${ownerCommand('0123456789abcdef', ['zsh']).slice(0, 2).join(' ')} zsh`.startsWith(`${prefix}0123456789abcdef`)).toBe(true)+ const format = `#{?#{m:${prefix}*,#{pane_start_command}},#{=${prefix!.length + 16}:pane_start_command},`+ + `#{?#{m:${HARNESS_SESSION_PREFIX}*,#{session_name}},#{${HARNESS_OWNER_OPTION}},}}`+ expect(format).toBe(paneOwnerFormat(false))+ // And the hook's own, read out of its source, are the daemon's: the old tmux one with the session check,+ // and from 3.0 the pane's own option.+ expect(source).toContain('#{?#{m:${HARNESS_SESSION_PREFIX}*,#{session_name}},#{${HARNESS_OWNER_OPTION}},}}')+ expect(source).toContain('const PANE_OWNER_FORMAT = `#{${HARNESS_OWNER_OPTION}}`')+ expect(paneOwnerFormat(true)).toBe(`#{${HARNESS_OWNER_OPTION}}`)+ })++ it('registers offline only a pane its daemon takes for an agent: never a session opened by hand or another daemon\'s', async () => {+ // With the daemon up, the hook of an engine in such a pane is turned away (discovery reads only the+ // daemon's own panes). Offline, the hook wrote a row for it anyway, and the daemon came back with an+ // agent it would never have made, offline for good.+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-owned-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ const register = async (name: string, pane: { paneSession: string; paneOwner?: string }, rows?: unknown[]) => {+ const dataDir = join(dir, name)+ mkdirSync(dataDir, { recursive: true, mode: 0o700 })+ if (rows) writeFileSync(join(dataDir, 'registry.json'), JSON.stringify(rows), { mode: 0o600 })+ const transcriptPath = join(claudeProjectsDir, 'demo', `${name}.jsonl`)+ writeFileSync(transcriptPath, '{}\n')+ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir, ...pane,+ input: { hook_event_name: 'SessionStart', session_id: name, transcript_path: transcriptPath, cwd: '/tmp/demo', source: 'startup' },+ })+ try { return (JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf8')) as Array<{ sessionId: string }>).map((row) => row.sessionId) } catch { return null }+ }+ expect(await register('by-hand', { paneSession: 'mine' })).toBeNull()+ expect(await register('another-daemon', { paneSession: 'harness-claude-1790000000000', paneOwner: 'abcdef0123456789' })).toBeNull()+ // Its own pane, wherever the person moved it, and an untagged one in a session Harness named.+ expect(await register('moved', { paneSession: 'mine', paneOwner: harnessPaneOwner(join(dir, 'moved')) })).toEqual(['moved'])+ expect(await register('untagged', { paneSession: 'harness-claude-1790000000000' })).toEqual(['untagged'])+ // Before tmux 3.0 the tag rides in the pane's start command, cut to its prefix and the tag.+ const startCommand = (dataDir: string) => ownerCommand(harnessPaneOwner(dataDir), []).join(' ')+ expect(await register('old-tmux', { paneSession: 'mine', paneOwner: startCommand(join(dir, 'old-tmux')) })).toEqual(['old-tmux'])+ expect(await register('old-tmux-other', { paneSession: 'harness-claude-1790000000000', paneOwner: startCommand(join(dir, 'elsewhere')) })).toBeNull()+ // A session an older build named, only while the registry holds an agent on that pane.+ expect(await register('legacy-new', { paneSession: 'claude-1790000000000' })).toBeNull()+ const held = {+ schemaVersion: 2, active: true, agentId: 'agent-legacy', sessionId: 'before', boundAt: 1, engine: 'claude',+ gateway: null, grid: null, codexHome: null, transcriptPath: null, projectDir: 'demo', cwd: '/tmp/demo',+ runtimes: [{ backend: 'tmux', paneId: '%7' }], primaryRuntimeKey: 'tmux\u0000%7', tmuxPane: '%7',+ source: null, title: null, model: null, cliVersion: null,+ processIdentity: { pid: 7001, executable: 'claude', startMarker: 'Mon Aug 10 10:00:01 2026' },+ registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,+ }+ expect(await register('legacy-held', { paneSession: 'claude-1790000000000' }, [held])).toEqual(['legacy-held'])+ })++ it('takes an engine typed into a terminal tile for that tile, as the daemon does', async () => {+ // The daemon adopts the tile (registry.adoptEngine): the same agent and name, now the engine's, and a+ // terminal again when the engine exits. The hook dropped the tile's row for a new agent instead.+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-terminal-adopt-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ const transcriptPath = join(claudeProjectsDir, 'demo', 'session-typed.jsonl')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ writeFileSync(transcriptPath, '{}\n')+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{+ schemaVersion: 2, active: true, defaultName: 'Terminal 10-5 9:41', agentId: 'agent-terminal', sessionId: '', boundAt: null,+ engine: 'terminal', gateway: null, grid: null, codexHome: null, transcriptPath: null,+ projectDir: 'demo', cwd: '/tmp/demo', runtimes: [{ backend: 'tmux', paneId: '%7' }], primaryRuntimeKey: 'tmux\u0000%7',+ tmuxPane: '%7', source: null, title: null, model: null, cliVersion: null,+ processIdentity: { pid: 7000, executable: 'zsh', startMarker: 'Mon Aug 10 10:00:00 2026' },+ registeredAt: 1, touchedAt: 1, lastHookAt: 0, lastTranscriptAt: 1,+ }]))++ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: 'SessionStart', session_id: 'session-typed', transcript_path: transcriptPath, cwd: '/tmp/demo', source: 'startup' },+ })++ const rows = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))+ expect(rows).toHaveLength(1)+ expect(rows[0]).toMatchObject({+ agentId: 'agent-terminal', defaultName: 'Terminal 10-5 9:41', engine: 'claude', terminalHost: true,+ sessionId: 'session-typed', tmuxPane: '%7', processIdentity: { pid: 7001 },+ })+ })++ it('keeps everything else the daemon kept on the row through an offline re-register, a new conversation included', async () => {+ // The hook rebuilt the row from the fields it named, and the daemon, back, loaded that as its own:+ // the agent came back under another name and relaunched out of the mode it was made in, its harness,+ // named agent and close plan gone (e2e/hookclient.e2e.ts, the daemon down while a conversation began).+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-kept-'))+ tmpDirs.push(dir)+ const claudeProjectsDir = join(dir, 'claude-projects')+ const dataDir = join(dir, 'data')+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })+ mkdirSync(dataDir, { recursive: true })+ chmodSync(dataDir, 0o755)+ const transcript = (sessionId: string) => {+ const path = join(claudeProjectsDir, 'demo', `${sessionId}.jsonl`)+ writeFileSync(path, '{}\n')+ return path+ }+ const kept = {+ defaultName: 'release notes',+ permissionMode: 'plan',+ dsh: 'acme/reviewer',+ dshRuntime: 'harness-runtime-1',+ agent: 'reviewer',+ terminalHost: true,+ resumeOnly: true,+ subscriptionModel: 'claude-opus-5-5',+ gridWebSearch: 'on',+ closePlan: { id: 'close-1', requestedAt: 1_790_000_000_000, identity: 'session-1', state: 'waiting' },+ forkedFrom: { agentId: 'agent-source', name: 'source', sessionId: 'session-0' },+ }+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{+ schemaVersion: 2, active: true, launch: { state: 'starting' }, agentId: 'agent-kept', sessionId: 'session-1', boundAt: 1,+ engine: 'claude', gateway: null, grid: null, codexHome: null, transcriptPath: transcript('session-1'), projectDir: 'demo',+ cwd: '/tmp/demo', runtimes: [{ backend: 'tmux', paneId: '%7' }], primaryRuntimeKey: 'tmux\u0000%7', tmuxPane: '%7',+ source: null, title: null, model: null, cliVersion: null,+ processIdentity: { pid: 7001, executable: 'claude', startMarker: 'Mon Aug 10 10:00:01 2026' },+ registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,+ ...kept,+ }]))++ for (const [event, sessionId, source] of [['UserPromptSubmit', 'session-1', undefined], ['SessionStart', 'session-2', 'clear']] as const) {+ await runHook({+ port: 9, tmuxPane: '%7', processEngine: 'claude', dataDir, claudeProjectsDir,+ input: { hook_event_name: event, session_id: sessionId, transcript_path: transcript(sessionId), cwd: '/tmp/demo', ...(source ? { source } : {}) },+ })+ const rows = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8'))+ expect(rows).toHaveLength(1)+ expect(rows[0]).toMatchObject({ agentId: 'agent-kept', sessionId, ...kept })+ // A hook means the engine is up, whatever the launch was: over, as `register()` has it, which on a+ // row that may only be resumed reads `ready`.+ expect(rows[0].launch).toEqual({ state: 'ready' })+ expect(rows[0].touchedAt).toBeGreaterThan(1)+ }+ })+it('an offline re-register of the session a row already holds keeps the row\'s folder', async () => {// Claude's UserPromptSubmit carries the tracked shell directory — wherever the agent last// `cd`'d — and a daemon-down rebuild must not move the row there any more than the daemon does.diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex e352b7f6f..cd53eb3a0 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -28,6 +28,7 @@ import {refusePermissionFlagIfUnsupported,resetCommandFlagSupportCache,engineFallbackPrelude,+ ENGINE_INPUT_DRAIN_SH,firstPromptArgs,gridPanePrelude,harnessNodePrelude,@@ -166,6 +167,9 @@ describe('buildEngineLaunchArgv', () => {const prelude = engineFallbackPrelude('codex', '/bin/bash', '/opt/homebrew/bin/tmux')expect(prelude).toContain(`[ -n "\${TMUX_PANE:-}" ] && { '/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)expect(prelude.indexOf('set-option')).toBeLessThan(prelude.indexOf("exec '/bin/bash'"))+ // What reached the terminal for the engine is dropped after the mark and before any shell reads it.+ expect(prelude.indexOf('set-option')).toBeLessThan(prelude.indexOf(ENGINE_INPUT_DRAIN_SH))+ expect(prelude.indexOf(ENGINE_INPUT_DRAIN_SH)).toBeLessThan(prelude.indexOf("exec '/bin/bash'"))expect(prelude).toContain('if [ "$harness_status" -eq 127 ]; then exit 127; fi')// zsh is a login shell; bash keeps its interactive rc (same rule as a terminal).expect(engineFallbackPrelude('codex', '/bin/zsh', null)).toContain("exec '/bin/zsh' -l\n")diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 90d5e3577..d2b3ad206 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -521,6 +521,22 @@ function waitForPidScript(wait: { pid: number; name: string }): string {+ `printf '\\033[H\\033[2J'\n`}+/**+ * Discards what reached the pane's terminal for the engine that just left, before a shell can read it.+ *+ * An engine does not leave the moment it is told to: Claude Code runs its SessionEnd hooks first, and+ * reads no more input meanwhile. A message the daemon typed in that window (it checked the engine was+ * there just before) sat in the terminal's input, and the shell handed over next ran it as a command:+ * end to end, a message sent right behind `/exit` became a shell command one run in four once the fake+ * engines ran the real hooks (e2e/input-safety.e2e.ts). Everything waiting is read and dropped, until+ * nothing more comes for 0.3 s; it was typed for the engine, and is nobody's to run. The terminal's+ * settings are put back as they were. Without `stty` (no terminal) nothing is touched.+ */+export const ENGINE_INPUT_DRAIN_SH = ' if harness_tty=$(stty -g 2>/dev/null) && stty -icanon -echo min 0 time 3 2>/dev/null; then\n'+ + ' while harness_waiting=$(dd bs=65536 count=1 2>/dev/null | wc -c) && [ "$((harness_waiting))" -gt 0 ]; do :; done\n'+ + ' stty "$harness_tty" 2>/dev/null || true\n'+ + ' fi\n'+/*** The shell function every engine launch runs its engine through, instead of a bare `exec`.*@@ -569,6 +585,7 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm// Only a pane — something with a terminal on stdin — gets a shell to type into. Run without one// (a spec exercising the script, a wrapper piped somewhere) the engine's own status is the answer.+ ' if ! [ -t 0 ]; then exit "$harness_status"; fi\n'+ + ENGINE_INPUT_DRAIN_SH+ ` printf '\\n%s\\n' ${shellSingleQuote(`harness: ${command} exited ($harness_status). This pane is a shell now — run ${command} again, or stop the pane.`).replace('($harness_status)', `('"$harness_status"')`)}\n`+ ` exec ${shellSingleQuote(shellPath)}${loginArgs}\n`+ '}\n'diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 01c9d6de8..c2910f141 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -137,9 +137,11 @@ export function installSessionHooks(port: number, settingsPath: string = SETTINGtry {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}`+ ? `[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)')diff --git a/cli/src/teams/promptScope.spec.ts b/cli/src/teams/promptScope.spec.tsindex caf6f73b7..eeb5c2a3a 100644--- a/cli/src/teams/promptScope.spec.ts+++ b/cli/src/teams/promptScope.spec.ts@@ -83,6 +83,28 @@ describe('prompt swarm origin', () => {expect(scopes.current(agent)).toBeNull()})+ it('keeps the team when the prompt\'s hook is heard after the transcript started it', () => {+ // The hook gives the daemon 500 ms and the engine goes on, so the turn can be read first. The late hook+ // used to find its message taken and read as no team (e2e/teamsProcess.e2e.ts with the real hook).+ const scopes = new SwarmPromptScopes()+ scopes.prepare(agent, 'hello from the alpha tab', 'swarm-a')+ scopes.started(agent, 'hello from the alpha tab')+ scopes.started(agent, 'hello from the alpha tab', 'hook', 'claude')+ expect(scopes.current(agent)).toBe(a)+ // Two prompts read before either hook: neither late hook moves the scope.+ scopes.prepare(agent, 'first', 'swarm-a')+ scopes.prepare(agent, 'second', 'swarm-b')+ scopes.started(agent, 'first')+ scopes.started(agent, 'second')+ scopes.started(agent, 'first', 'hook')+ scopes.started(agent, 'second', 'hook')+ expect(scopes.current(agent)).toBe(b)+ // Each start is acknowledged once: the same text sent again is a prompt of its own.+ scopes.prepare(agent, 'first', 'swarm-a')+ scopes.started(agent, 'first', 'hook')+ expect(scopes.current(agent)).toBe(a)+ })+it('matches native accepted text instead of treating permission keys as prompts', () => {const scopes = new SwarmPromptScopes()scopes.raw(agent, bytes('1\r'), 'swarm-b')diff --git a/cli/src/teams/promptScope.ts b/cli/src/teams/promptScope.tsindex 22f6906ae..4c5d0ac54 100644--- a/cli/src/teams/promptScope.ts+++ b/cli/src/teams/promptScope.ts@@ -18,6 +18,8 @@ interface State {paste: booleansubmissions: Submission[]observedHooks: string[]+ /** Prompts the transcript started before their hook was heard (see `started`). */+ observedStarts: string[]current: string | nullquestion: string | nullreturns: Map<string, { teamId: string | null; question: string | null }>@@ -34,7 +36,7 @@ export class SwarmPromptScopes {let state = this.states.get(agentId)if (!state) {state = { draft: [], cursor: 0, known: true, decoder: new StringDecoder('utf8'), escape: '', paste: false,- submissions: [], observedHooks: [], current: null, question: null, returns: new Map() }+ submissions: [], observedHooks: [], observedStarts: [], current: null, question: null, returns: new Map() }this.states.set(agentId, state)}state.submissions = state.submissions.filter(s => s.expires > this.now())@@ -64,15 +66,21 @@ export class SwarmPromptScopes {}/** Native prompt hooks run before tools. Transcript starts are the fallback and acknowledge- * already handled hooks without moving scope backwards when the watcher is delayed. */+ * already handled hooks without moving scope backwards when the watcher is delayed.+ *+ * And the other way round: a hook can be heard after the transcript started its prompt. The hook gives+ * the daemon 500 ms to answer (hook/notify.mjs) and the engine goes on while the daemon is still+ * matching the hook to its process, so the turn is often on disk first. Taken as a second start of the+ * same prompt, the hook found its message already taken and read as no team: every message from a tab+ * lost its team (e2e/teamsProcess.e2e.ts, once the engines ran the real hook). Each start now+ * acknowledges the other, whichever comes first. */started(agentId: string, text: string, source: 'hook' | 'transcript' = 'transcript', engine?: string): void {const state = this.state(agentId)const hashes = [fingerprint(text)]if (engine === 'claude') hashes.push(fingerprint(promptText(text)))- if (source === 'transcript') {- const acknowledged = state.observedHooks.findIndex(hash => hashes.includes(hash))- if (acknowledged >= 0) { state.observedHooks.splice(acknowledged, 1); return }- }+ const heard = source === 'transcript' ? state.observedHooks : state.observedStarts+ const acknowledged = heard.findIndex(hash => hashes.includes(hash))+ if (acknowledged >= 0) { heard.splice(acknowledged, 1); return }// Prefer the exact text. A user can literally type Claude's paste-wrapper syntax,// and another engine does not attach Claude's envelope semantics to that text.const hash = hashes.find(hash => state.submissions.some(s => s.hash === hash)) ?? hashes[0]@@ -93,10 +101,9 @@ export class SwarmPromptScopes {} else { state.question = null; state.returns.clear() }state.current = submission.teamId}- if (source === 'hook') {- state.observedHooks.push(hash)- if (state.observedHooks.length > LIMIT) state.observedHooks.shift()- }+ const observed = source === 'hook' ? state.observedHooks : state.observedStarts+ observed.push(hash)+ if (observed.length > LIMIT) observed.shift()}raw(agentId: string, bytes: Uint8Array, tabId?: string, pasted = false): void {