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
Make native hook preparation durable and bounded (#1158)
Deeeef21b18b040
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 2cbaa87cb..12f919154 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -18,8 +18,10 @@"dotenv": "^17.2.3","pngjs": "^7.0.0","qrcode-generator": "^2.0.4",+ "smol-toml": "1.9.0","werift": "0.24.4","ws": "^8.18.0",+ "yaml": "2.9.1","zod": "^4.0.0"},"bin": {@@ -2370,6 +2372,18 @@"dev": true,"license": "ISC"},+ "node_modules/smol-toml": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz",+ "integrity": "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "url": "https://github.com/sponsors/cyyynthia"+ }+ },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",@@ -3237,6 +3251,21 @@}}},+ "node_modules/yaml": {+ "version": "2.9.1",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },"node_modules/zod": {"version": "4.4.3","resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",diff --git a/cli/package.json b/cli/package.jsonindex caf7d0cfc..c953fe549 100644--- a/cli/package.json+++ b/cli/package.json@@ -38,8 +38,10 @@"dotenv": "^17.2.3","pngjs": "^7.0.0","qrcode-generator": "^2.0.4",+ "smol-toml": "1.9.0","werift": "0.24.4","ws": "^8.18.0",+ "yaml": "2.9.1","zod": "^4.0.0"},"devDependencies": {diff --git a/cli/scripts/handoff-2026-10-08/mutate-hook-preparation.py b/cli/scripts/handoff-2026-10-08/mutate-hook-preparation.pynew file mode 100644index 000000000..ca3014757--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-hook-preparation.py@@ -0,0 +1,65 @@+"""Break durable hook wiring in an explicitly owned disposable worktree."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+assert (cli.parent / '.git').is_file(), 'An owned disposable worktree is required'+assert os.environ.get('HARNESS_HOOK_MUTATIONS_OWNED') == '1'+golden = 'src/engines/nativeVersion.golden.spec.ts'+hooks = 'src/engines/nativeHooks.ts'+files = 'src/engines/kit/nativeHookFiles.ts'+attempts = 'src/engines/kit/nativeHookAttempts.spec.ts'+preparation = 'src/engines/nativeHookPreparation.spec.ts'+mutations = [+ ('wrong plugin port', hooks, 'port: String(port)', "port: '19475'", golden, ''),+ ('core installer disconnected', 'src/core/engines/hooks.ts', 'return await (snapshot ? nativeHooks.installOpencodePlugin(port, snapshot) : nativeHooks.installOpencodePlugin(port)) !== false', 'return true', golden, ''),+ ('upgrade removal disconnected', hooks, 'const removedOrInstalled = await legacy.commit(attempt)', 'const removedOrInstalled = { verify: () => {} }', golden, ''),+ ('disk confirmation bypassed', files, 'fsync(fd, settled)', 'queueMicrotask(() => settled(null))', attempts, 'event loop available'),+ ('joining deadline ignored', files, "if (performance.now() >= deadline) throw new HookPreparationHeld('the joining preparation exceeded its deadline')", 'void deadline', attempts, 'timer phase'),+ ('joining authority ignored', files, "if (options.current?.() === false) throw new HookPreparationHeld('the joining owner changed')", 'void options', attempts, 'each joining owner'),+ ('joined proof keeps wrong route', files, 'const proof = preparationProof(files, verifyRoutes)', 'const proof = preparationProof(pending.proof!.files.map(file => file.file), verifyRoutes)', attempts, 'final launch proof'),+ ('revoked caller gets newer success', hooks, '|| options.current?.() === false || snapshot?.current() === false || current.proofs', '|| snapshot?.current() === false || current.proofs', preparation, 'revoked older caller'),+ ('reservation extends original deadline', hooks, '&& opencodeInstallation.major === major && performance.now() < deadline', '&& opencodeInstallation.major === major', preparation, 'stalling reservation reads'),+ ('late proof ignores deadline', hooks, ' if (performance.now() >= deadline) return false', ' void deadline', preparation, 'after final proof reads'),+ ('peer bytes adopted as proof', files, ' // that arrived between the last verification and its filesystem reads.\n verify()', ' // that arrived between the last verification and its filesystem reads.\n check()', 'src/engines/kit/nativeHookFiles.spec.ts', 'peer edit during final proof capture'),+ ('foreign command ownership broadened', 'src/engines/kit/notifyHooks.ts', r'if (/[;&|<>$`(){}*?\[\]~#]/.test(char))', 'if (/[;&|<>$`(){}]/.test(char))', preparation, 'foreign shell command'),+]+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')+for key in ('TMUX', 'TMUX_PANE', 'RECORD_NATIVE_VERSION_GOLDEN', 'RECORD_OTHER_ENGINES_GOLDEN'):+ environment.pop(key, None)+tmux = cli.parent / '.harness/tmux'+tmux.mkdir(parents=True, exist_ok=True)+environment['TMUX_TMPDIR'] = str(tmux)+++def run(specs, pattern=''):+ command = ['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=1']+ if pattern:+ command += ['-t', pattern]+ return subprocess.run(command, cwd=cli, env=environment, text=True, capture_output=True, timeout=180)+++baseline = run([golden, attempts, preparation, 'src/engines/kit/nativeHookFiles.spec.ts'])+assert baseline.returncode == 0, 'Unchanged baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr+print('Unchanged baselines passed', flush=True)+failures = []+for label, relative, before, after, spec, pattern in mutations:+ path = cli / relative+ original = path.read_text()+ expected = 2 if label == 'joining authority ignored' else 1+ assert original.count(before) == expected, (label, original.count(before))+ try:+ path.write_text(original.replace(before, after))+ result = run([spec], pattern)+ output = result.stdout + result.stderr+ if result.returncode == 0 or 'AssertionError' not in output:+ failures.append(label)+ print(label + ': NOT caught by assertion\n' + output, flush=True)+ else:+ print(label + ': caught by assertion', flush=True)+ finally:+ path.write_text(original)+if failures:+ raise SystemExit('Uncaught mutations: ' + ', '.join(failures))diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 7eb582462..331d3a236 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -36,7 +36,11 @@ vi.mock('../../engines/inProcess.js', async (real) => {return { ...actual, loadEngine: vi.fn(actual.loadEngine) }})vi.mock('../../engines/launchControl.js', () => ({ opencodeMajorVersion: vi.fn(async () => 2) }))-vi.mock('../../engines/kit/nativePlugin.js', () => ({ installNativePlugin: vi.fn(), removeNativePlugin: vi.fn() }))+vi.mock('../../engines/kit/nativePlugin.js', () => ({+ prepareNativePlugin: vi.fn(() => ({ verify: () => {}, commit: async () => ({ verify: () => {} }) })),+ prepareNativePluginRemoval: vi.fn(() => ({ verify: () => {}, commit: async () => ({ verify: () => {} }) })),+}))+vi.mock('../../engines/kit/nativeHookFiles.js', () => ({ runHookPreparation: async (_files: string[], work: () => Promise<unknown>) => work() }))// The engines' folder trust (engines/launchPrep.ts), one spy per engine: never the person's own config.const trust = vi.hoisted(() => ({claudeTrusts: vi.fn((_path: string) => false), codexTrusts: vi.fn((_path: string, _profile?: string | null) => false),@@ -72,7 +76,7 @@ const buildGridLaunch = vi.fn(async (request: GridLaunchRequest): Promise<GridLa}))vi.mock('../../engines/hooks.js', async (real) => {const actual = await real<typeof import('../../engines/hooks.js')>()- return { ...actual, engineHooks: { ...actual.engineHooks, codex: { ...actual.engineHooks.codex, installIn: vi.fn() } } }+ return { ...actual, engineHooks: { ...actual.engineHooks, codex: { ...actual.engineHooks.codex, installIn: vi.fn(async () => true) } } }})vi.mock('../../lib/sessionSearch/external.js', async (real) => ({ ...await real<object>(), stopSessionOwner: vi.fn(async () => true) }))vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}) }))@@ -132,6 +136,29 @@ describe('creating an agent', () => {})afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it('does not open a Codex pane before its profile hooks are durably confirmed', async () => {+ let finish!: (installed: boolean) => void+ vi.mocked(engineHooks.codex.installIn).mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))+ const { create } = setup()+ const input = request({ engine: 'codex', codexHome: '/profiles/work' })+ const first = create(input)+ await vi.waitFor(() => expect(engineHooks.codex.installIn).toHaveBeenCalled())+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ finish(false)+ expect(await first).toMatchObject({ ok: false, error: 'NATIVE_LAUNCH_HELD' })+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ expect(await create(input)).toMatchObject({ ok: true })+ expect(createAndRegisterPane).toHaveBeenCalledTimes(1)+ })++ it('reaches the existing first-install pane route when OpenCode is absent', async () => {+ vi.mocked(opencodeMajorVersion).mockResolvedValueOnce(null)+ const { create } = setup({ installOpencodePlugin })+ expect(await create(request({ engine: 'opencode' }))).toMatchObject({ ok: true })+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('opencode', expect.objectContaining({ installIfMissing: { install: 'recipe' } }))+ expect(createAndRegisterPane).toHaveBeenCalledTimes(1)+ })+it('hands external resume to its durable controller before folder, instructions or engine preparation', async () => {const externalResume = vi.fn<CreateAgentDeps['externalResume']>(async () => ({ ok: true, session: pending }))const test = setup({ externalResume })diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex b9e15eb1d..339c2343c 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -234,7 +234,9 @@ export function createAgentCreator({// THAT folder, not the one `harness login` already installed into — without this, such an agent// fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.// Idempotent, so paying this on every create against an already-set-up profile is free.- if (codexHome && !hooksDisabled) engineHooks.codex.installIn(hookPort, codexHome)+ if (codexHome && !hooksDisabled && !await engineHooks.codex.installIn(hookPort, codexHome)) return {+ ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm Codex’s hooks in the selected profile.',+ }// OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must// not discover our old server plugin; the cached version probe changes with the executable.// Native installation is eager. A plugin is how this engine tells the daemon its session.diff --git a/cli/src/core/agents/externalPreflight.spec.ts b/cli/src/core/agents/externalPreflight.spec.tsindex ad67f7445..a7f263bf0 100644--- a/cli/src/core/agents/externalPreflight.spec.ts+++ b/cli/src/core/agents/externalPreflight.spec.ts@@ -5,7 +5,7 @@ import { buildEngineCommandArgv, refusePermissionFlagIfUnsupported } from '../..import { workspaceMissing } from '../../lib/workspaceCheck.js'import { createExternalPreflight } from './externalPreflight.js'vi.mock('../../engines/inProcess.js', () => ({ loadEngine: vi.fn(async () => ({})) }))-vi.mock('../../engines/hooks.js', () => ({ engineHooks: { codex: { installIn: vi.fn() } } }))+vi.mock('../../engines/hooks.js', () => ({ engineHooks: { codex: { installIn: vi.fn(async () => true) } } }))vi.mock('../../lib/engineLaunch.js', () => ({ buildEngineCommandArgv: vi.fn(() => []), refusePermissionFlagIfUnsupported: vi.fn(async () => null) }))vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))afterEach(() => { vi.clearAllMocks() })@@ -45,3 +45,15 @@ it('prepares a custom Codex hook home only when hooks are enabled, and verifiesexpect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/fixture/profile')expect(buildEngineCommandArgv).toHaveBeenLastCalledWith('codex', expect.objectContaining({ resumeSessionId: 'conversation', extraArgs: ['-p', 'work'] }))})++it('waits for profile durability before admitting a takeover and retains an unavailable profile', async () => {+ let finish!: (installed: boolean) => void+ vi.mocked(engineHooks.codex.installIn).mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))+ const pending = setup().prepare(row('codex', { codexHome: '/fixture/profile' }), session)+ await vi.waitFor(() => expect(engineHooks.codex.installIn).toHaveBeenCalled())+ expect(buildEngineCommandArgv).not.toHaveBeenCalled()+ finish(false)+ expect(await pending).toMatchObject({ detail: expect.stringContaining('hooks') })+ expect(buildEngineCommandArgv).not.toHaveBeenCalled()+ expect(await setup().prepare(row('codex', { codexHome: '/fixture/profile' }), session)).toBeNull()+})diff --git a/cli/src/core/agents/externalPreflight.ts b/cli/src/core/agents/externalPreflight.tsindex 29c4ca916..5ed067ae0 100644--- a/cli/src/core/agents/externalPreflight.ts+++ b/cli/src/core/agents/externalPreflight.ts@@ -19,7 +19,9 @@ export function createExternalPreflight(deps: {if (row.engine === 'opencode' && !deps.hooksDisabled && !await deps.installOpencodePlugin(deps.hookPort)) {return { detail: 'Waiting for OpenCode’s launch support to become available.' }}- if (row.codexHome && !deps.hooksDisabled) engineHooks.codex.installIn(deps.hookPort, row.codexHome)+ if (row.codexHome && !deps.hooksDisabled && !await engineHooks.codex.installIn(deps.hookPort, row.codexHome)) {+ return { detail: 'Waiting to confirm Codex’s hooks in the selected profile.' }+ }buildEngineCommandArgv(row.engine, { cwd: session.cwd, resumeSessionId: session.sessionId,bypassPermission: row.bypassPermission, permissionMode: row.permissionMode, extraArgs: session.launchArgs })return nulldiff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.tsindex 84d99791f..a606ab1a0 100644--- a/cli/src/core/agents/restoreLaunch.spec.ts+++ b/cli/src/core/agents/restoreLaunch.spec.ts@@ -32,7 +32,7 @@ describe('restore preparation keeps session authority in core', () => {authority: createLaunchAuthority({ byAgent: () => live, revision: () => 1, cancelled: () => false }),prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),- tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null },+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(async () => true), readCodexConfig: () => null },})const { deps } = setup()const build = createRestoreLaunch({ ...deps, relaunchOverrides: helpers.relaunchOverrides })@@ -50,7 +50,7 @@ describe('restore preparation keeps session authority in core', () => {authority: createLaunchAuthority({ byAgent: () => live, revision: () => 1, cancelled: () => false }),prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),- tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null,+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(async () => true), readCodexConfig: () => null,dshLaunch: async () => { live.permissionMode = 'ask'; return { ok: true, launch: { env: {}, args: [] } } } },})const { deps } = setup()diff --git a/cli/src/core/engines/homeAdoptions.spec.ts b/cli/src/core/engines/homeAdoptions.spec.tsindex cdcf4b075..c9d324e0e 100644--- a/cli/src/core/engines/homeAdoptions.spec.ts+++ b/cli/src/core/engines/homeAdoptions.spec.ts@@ -97,3 +97,39 @@ it('fences queued retries and late login-shell callbacks when the owning daemonexpect(c.deps.install).not.toHaveBeenCalled()expect(vi.getTimerCount()).toBe(0)})++it('keeps an asynchronous install pending, lets a sibling complete, and acknowledges only success', async () => {+ let reject!: (error: Error) => void+ const install = vi.fn<HomeAdoptionDeps['install']>()+ .mockImplementationOnce(() => new Promise<void>((_, fail) => { reject = fail }))+ .mockResolvedValue(undefined)+ const c = setup({ confirm: vi.fn(() => ({ claude: '/slow', codex: '/ready' })), install })+ c.submit({}); c.retry()+ expect(install).toHaveBeenCalledTimes(2)+ expect(c.deps.held).toHaveBeenLastCalledWith('Waiting for hook installation in an adopted home.')+ await vi.advanceTimersByTimeAsync(0)+ c.retry()+ expect(install).toHaveBeenCalledTimes(2)+ reject(new Error('disk unavailable'))+ await vi.advanceTimersByTimeAsync(0)+ expect(c.deps.held).toHaveBeenLastCalledWith('disk unavailable')+ await vi.advanceTimersByTimeAsync(1_000)+ expect(install.mock.calls).toEqual([['claude', '/slow'], ['codex', '/ready'], ['claude', '/slow']])+ expect(c.deps.held).toHaveBeenLastCalledWith(null)+ expect(vi.getTimerCount()).toBe(0)+})++it.each([true, false])('revokes an in-flight home installation and ignores its late success=%s on shutdown', async succeeds => {+ let finish!: () => void+ const c = setup({ read: () => ({ claude: ['/pending'], codex: [] }), install: () => new Promise<void>((done, reject) => {+ finish = () => succeeds ? done() : reject(new Error('late'))+ }) })+ c.retry()+ expect(c.current()).toBe(true)+ const reports = vi.mocked(c.deps.held).mock.calls.length+ c.close(); finish()+ await vi.advanceTimersByTimeAsync(10_000)+ expect(c.current()).toBe(false)+ expect(c.deps.held).toHaveBeenCalledTimes(reports)+ expect(vi.getTimerCount()).toBe(0)+})diff --git a/cli/src/core/engines/homeAdoptions.ts b/cli/src/core/engines/homeAdoptions.tsindex c74d375c5..179ee5b74 100644--- a/cli/src/core/engines/homeAdoptions.ts+++ b/cli/src/core/engines/homeAdoptions.ts@@ -4,7 +4,7 @@ import type { SessionStoreEngine } from '../../engines/sessionStoreContracts.js'export interface HomeAdoptionDeps {read(): HomeCatalogconfirm(environment: NodeJS.ProcessEnv): Record<SessionStoreEngine, string | null>- install(engine: SessionStoreEngine, home: string): void+ install(engine: SessionStoreEngine, home: string): void | Promise<void>held(reason: string | null): void}@@ -15,6 +15,18 @@ export function createHomeAdoptions(deps: HomeAdoptionDeps) {const requests = new Map<string, NodeJS.ProcessEnv>()const installs = new Map<string, [SessionStoreEngine, string]>()const installed = new Set<string>()+ const inFlight = new Set<string>()+ const failures = new Map<string, string>()+ let catalogHold: string | null = null+ const progress = (): void => {+ if (closed) return+ const held = catalogHold ?? failures.values().next().value ?? (inFlight.size ? 'Waiting for hook installation in an adopted home.' : null)+ if (held !== reported) { reported = held; deps.held(held) }+ if ((restoring || requests.size || [...installs.keys()].some(key => !inFlight.has(key))) && !timer) {+ timer = setTimeout(() => { timer = undefined; retry() }, 1_000)+ timer.unref()+ }+ }const queue = (engine: SessionStoreEngine, home: string): void => {const key = JSON.stringify([engine, home])if (!installed.has(key)) installs.set(key, [engine, home])@@ -38,18 +50,27 @@ export function createHomeAdoptions(deps: HomeAdoptionDeps) {restoring = false} catch (error) { held ??= reason(error) }}+ catalogHold = heldfor (const [key, [engine, home]] of installs) {- try { deps.install(engine, home); installed.add(key); installs.delete(key) }- catch (error) { held ??= reason(error) }- }- if (held !== reported) { reported = held; deps.held(held) }- if ((restoring || requests.size || installs.size) && !timer) {- timer = setTimeout(() => { timer = undefined; retry() }, 1_000)- timer.unref()+ if (inFlight.has(key)) continue+ const confirm = () => { installed.add(key); installs.delete(key); failures.delete(key) }+ try {+ const result = deps.install(engine, home)+ if (!result) { confirm(); continue }+ inFlight.add(key)+ void result.then(() => {+ if (!closed) confirm()+ }, error => { if (!closed) failures.set(key, reason(error)) }).finally(() => {+ inFlight.delete(key); progress()+ })+ } catch (error) { failures.set(key, reason(error)) }}+ progress()}+return {retry,+ current: () => !closed,submit(environment: NodeJS.ProcessEnv): void {if (closed) return// Only two declared home variables survive this callback; never retain login-shell credentials.@@ -62,7 +83,7 @@ export function createHomeAdoptions(deps: HomeAdoptionDeps) {close(): void {closed = trueif (timer) clearTimeout(timer)- timer = undefined; requests.clear(); installs.clear(); installed.clear()+ timer = undefined; requests.clear(); installs.clear(); installed.clear(); failures.clear()},}}diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsindex 4c5c9dd7f..90b235d1c 100644--- a/cli/src/core/engines/hooks.spec.ts+++ b/cli/src/core/engines/hooks.spec.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'import * as hooks from '../../engines/nativeHooks.js'import { engineHooks } from '../../engines/hooks.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -11,8 +11,8 @@ import { createPaneOperations } from '../agents/paneOperations.js'vi.mock('../../engines/hooks.js', async (real) => {const actual = await real<typeof import('../../engines/hooks.js')>()return { ...actual, engineHooks: {- claude: { ...actual.engineHooks.claude, install: vi.fn(), installIn: vi.fn() },- codex: { ...actual.engineHooks.codex, install: vi.fn(), installIn: vi.fn() },+ claude: { ...actual.engineHooks.claude, install: vi.fn(() => true), installIn: vi.fn(() => true) },+ codex: { ...actual.engineHooks.codex, install: vi.fn(() => true), installIn: vi.fn(() => true) },} }})vi.mock('../../lib/engineHomes.js', () => ({@@ -411,9 +411,44 @@ describe('installing every engine\'s hooks', () => {expect(await installOpencodePluginBeforeSpawn(4242)).toBe(false)})+ it('passes the confirmed executable through to native preparation', async () => {+ const snapshot = { command: '/fixture/opencode', identity: 'file-v2', major: 2, current: () => true }+ vi.mocked(hooks.installOpencodePlugin).mockResolvedValueOnce(true)+ expect(await installOpencodePluginBeforeSpawn(4242, snapshot)).toBe(true)+ expect(hooks.installOpencodePlugin).toHaveBeenLastCalledWith(4242, snapshot)+ })++ it('reports synchronous and asynchronous holds without suppressing sibling installers', async () => {+ ;(hooks.installCursorHooks as Mock).mockReturnValueOnce(false)+ vi.mocked(hooks.installOpencodePlugin).mockResolvedValueOnce(false)+ const installed = await installEngineHooks(4242, { environment: {} })+ expect(console.warn).toHaveBeenCalledWith('[hooks] cursor install skipped · native hook preparation is unavailable')+ expect(console.warn).toHaveBeenCalledWith('[hooks] opencode install skipped · native hook preparation is unavailable')+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(4242)+ installed.close()+ })++ it('retries failed hook preparation before considering a home adopted', async () => {+ vi.useFakeTimers()+ vi.mocked(recoverEngineHomes).mockReturnValue({ claude: ['/fixture/claude'], codex: [] })+ vi.mocked(engineHooks.claude.installIn).mockResolvedValueOnce(false)+ const installed = await installEngineHooks(4242, { environment: {} })+ await vi.advanceTimersByTimeAsync(0)+ try {+ expect(console.warn).toHaveBeenCalledWith('[hooks] home adoption held · Claude Code hook preparation is unavailable')+ expect(engineHooks.claude.installIn).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(1_000)+ expect(engineHooks.claude.installIn).toHaveBeenCalledTimes(2)+ expect(engineHooks.claude.installIn).toHaveBeenLastCalledWith(4242, '/fixture/claude', { current: expect.any(Function) })+ } finally {+ installed.close(); vi.useRealTimers()+ vi.mocked(recoverEngineHomes).mockReturnValue({ claude: [], codex: [] })+ }+ })+it('installs synchronously in the original order before returning the completion promise', async () => {const order: string[] = []- for (const [index, install] of installs.entries()) vi.mocked(install).mockImplementationOnce(() => { order.push(String(index)) })+ for (const [index, install] of installs.entries()) (install as Mock).mockImplementationOnce(() => { order.push(String(index)); return index === 3 ? Promise.resolve(true) : true })const done = installEngineHooks(4242)expect(order).toEqual(installs.map((_, index) => String(index)))await done@@ -424,7 +459,7 @@ describe('installing every engine\'s hooks', () => {vi.mocked(recoverEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })await installEngineHooks(4242, { only: new Set(['codex']), environment: {} })expect(engineHooks.codex.install).toHaveBeenCalledWith(4242)- expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex', { current: expect.any(Function) })for (const install of installs.filter((one) => one !== engineHooks.codex.install)) expect(install).not.toHaveBeenCalled()expect(engineHooks.claude.installIn).not.toHaveBeenCalled()// Claude Code's and Codex's alone load none of the other engines' code.@@ -446,8 +481,8 @@ describe('installing every engine\'s hooks', () => {it('puts the hooks in every home adopted on an earlier boot, at every start', async () => {vi.mocked(recoverEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })await installEngineHooks(4242, { environment: {} })- expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/w/claude')- expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')+ expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/w/claude', { current: expect.any(Function) })+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex', { current: expect.any(Function) })expect(recoverEngineHomes).toHaveBeenCalledTimes(1)})@@ -460,11 +495,13 @@ describe('installing every engine\'s hooks', () => {.mockReturnValueOnce({ claude: null, codex: '/s/codex' })void installEngineHooks(4242, { environment: own, loginShell: Promise.resolve(shell) })expect(confirmHomes).toHaveBeenCalledWith(own)- expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/m/claude')+ expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/m/claude', { current: expect.any(Function) })+ await Promise.resolve()expect(log).toHaveBeenCalledWith('[hooks] Claude Code hooks installed in its adopted home')await Promise.resolve()expect(confirmHomes).toHaveBeenLastCalledWith(shell)- expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/s/codex')+ expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/s/codex', { current: expect.any(Function) })+ await Promise.resolve()expect(log).toHaveBeenCalledWith('[hooks] Codex hooks installed in its adopted home')})@@ -496,6 +533,7 @@ describe('installing every engine\'s hooks', () => {vi.useFakeTimers()vi.mocked(confirmHomes).mockImplementationOnce(() => { throw new Error('fixture durability unavailable') })const installed = await installEngineHooks(4242, { environment: {} })+ await vi.advanceTimersByTimeAsync(0)try {expect(console.warn).toHaveBeenCalledWith('[hooks] home adoption held · fixture durability unavailable')for (const install of installs) expect(install).toHaveBeenCalledWith(4242)diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsindex 8a20dec21..b5e1f6631 100644--- a/cli/src/core/engines/hooks.ts+++ b/cli/src/core/engines/hooks.ts@@ -10,6 +10,7 @@ import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'import { confirmHomes, recoverEngineHomes } from '../../lib/engineHomes.js'import { createHomeAdoptions } from './homeAdoptions.js'import * as nativeHooks from '../../engines/nativeHooks.js'+import type { OpencodeLaunchSnapshot } from '../../engines/launchControl.js'import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import { processRows } from '../../lib/terminalAgentDiscovery.js'@@ -210,8 +211,8 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane* from 1.x to 2.x under a running daemon, and its new TUI must not find the old server plugin. Installation* never depends on loading its optional interpreter.*/-export async function installOpencodePluginBeforeSpawn(port: number): Promise<boolean> {- return await nativeHooks.installOpencodePlugin(port) !== false+export async function installOpencodePluginBeforeSpawn(port: number, snapshot?: OpencodeLaunchSnapshot): Promise<boolean> {+ return await (snapshot ? nativeHooks.installOpencodePlugin(port, snapshot) : nativeHooks.installOpencodePlugin(port)) !== false}export interface InstallEngineHooksOptions {@@ -226,7 +227,7 @@ export interface InstallEngineHooksOptions {/*** The other engines' declarations are installed in their original order, without an optional import.*/-const OTHER_INSTALLERS: Array<[string, (port: number) => void | Promise<unknown>]> = [+const OTHER_INSTALLERS: Array<[string, (port: number) => void | boolean | Promise<unknown>]> = [['cursor', nativeHooks.installCursorHooks],['opencode', nativeHooks.installOpencodePlugin],['kilo', nativeHooks.installKiloPlugin],@@ -255,14 +256,17 @@ const OTHER_INSTALLERS: Array<[string, (port: number) => void | Promise<unknown>*/export async function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): Promise<{ close(): void }> {const pending: Promise<void>[] = []- const hookStep = (vendor: string, install: () => void | Promise<unknown>): void => {+ const hookStep = (vendor: string, install: () => void | boolean | Promise<unknown>): void => {if (options.only && !options.only.has(vendor)) returnconst failed = (error: unknown) => {console.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)}try {const result = install()- if (result) pending.push(result.then(() => {}, failed))+ if (result === false) failed('native hook preparation is unavailable')+ else if (result && typeof result !== 'boolean') pending.push(result.then(answer => {+ if (answer === false) failed('native hook preparation is unavailable')+ }, failed))} catch (error) { failed(error) }}// The homes the person moved (lib/engineHomes.ts, by each engine's declared session store) get the hooks@@ -272,9 +276,9 @@ export async function installEngineHooks(port: number, options: InstallEngineHooconst adoptions = createHomeAdoptions({read: recoverEngineHomes,confirm: confirmHomes,- install: (engine, home) => {+ install: async (engine, home) => {if (options.only && !options.only.has(engine)) return- engineHooks[engine].installIn(port, home)+ if (!await engineHooks[engine].installIn(port, home, { current: adoptions.current })) throw new Error(`${sessionStoreContracts[engine].product} hook preparation is unavailable`)console.log(`[hooks] ${sessionStoreContracts[engine].product} hooks installed in its adopted home`)},held: reason => {diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex de5475d8d..eef367558 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1984,7 +1984,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {gridLaunch,writeGridConfigDir,tmuxSupportsSessionEnv,- installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) engineHookFacets.codex.installIn(hookPort, codexHome) },+ installCodexHooks: (codexHome) => env.DISABLE_HOOK_INSTALL ? true : engineHookFacets.codex.installIn(hookPort, codexHome),dshLaunch: dshLaunch.relaunch,}// What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restorediff --git a/cli/src/dsh/launch.spec.ts b/cli/src/dsh/launch.spec.tsindex 55ccbc1a1..b0b6c7320 100644--- a/cli/src/dsh/launch.spec.ts+++ b/cli/src/dsh/launch.spec.ts@@ -47,7 +47,7 @@ describe('buildLaunchOverrides with a DSH', () => {machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async () => '/cfg',tmuxSupportsSessionEnv: async () => true,- installCodexHooks: () => undefined,+ installCodexHooks: () => true,dshLaunch: async (id, workspace, engine) => id === installed.id ? { ok: true, launch: dshLaunch(installed, workspace, {}, engine) } : { ok: false, error: 'DSH_NOT_INSTALLED', detail: `${id} is not installed on this machine` },}diff --git a/cli/src/dsh/portability.integration.spec.ts b/cli/src/dsh/portability.integration.spec.tsindex 75f31b1b0..601e283a1 100644--- a/cli/src/dsh/portability.integration.spec.ts+++ b/cli/src/dsh/portability.integration.spec.ts@@ -142,7 +142,7 @@ for (const engine of PROCESS_ENGINES) it(`${engine}: prepare → spawn → toolexpect(JSON.parse(readFileSync(join(workspace, '.harness/verdict.json'), 'utf8'))).toEqual({ ready: true, artifact: 'scene.txt' })expect(readFileSync(join(workspace, 'scene.txt'), 'utf8')).toBe('drawn by test/portable\n')const restored = await buildLaunchOverrides({ machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/unused',- tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => true,dshLaunch: async (_id, ws, selected, key) => ({ ok: true, launch: prepareHarnessLaunch(pkg, ws, selected, key) }) }, engine,{ dsh: pkg.id, cwd: workspace, dshRuntime: 'created' }, 'registered')expect(restored.ok).toBe(true)diff --git a/cli/src/dsh/runtime.spec.ts b/cli/src/dsh/runtime.spec.tsindex d082ec304..797b4ca9d 100644--- a/cli/src/dsh/runtime.spec.ts+++ b/cli/src/dsh/runtime.spec.ts@@ -95,7 +95,7 @@ describe('session isolation and lifecycle', () => {it('does not inherit the previous account private grid on a harness relaunch', async () => {const result = await buildLaunchOverrides({ machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async () => '/unused', tmuxSupportsSessionEnv: async () => true,- installCodexHooks: () => {}, dshLaunch: async () => ({ ok: true, launch: prepareHarnessLaunch(pkg, ws, 'claude', 'new-account') }),+ installCodexHooks: () => true, dshLaunch: async () => ({ ok: true, launch: prepareHarnessLaunch(pkg, ws, 'claude', 'new-account') }),}, 'claude', { dsh: pkg.id, cwd: ws }, 'agent')if (!result.ok) throw new Error(result.detail)const [, , script] = buildEngineLaunchArgv('claude', { clearEnv: result.overrides.clearEnv }, '/bin/sh', undefined, undefined, null)@@ -138,7 +138,7 @@ describe('session isolation and lifecycle', () => {pkg.manifest.agent!.env = { TOOLCHAIN: 'changed' }write(join(pkg.realDir, 'AGENTS.md'), '# Updated instructions\n')const deps = { machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/cfg',- tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => true,dshLaunch: async (_id: string, workspace: string, engine: typeof PROCESS_ENGINES[number] | 'terminal', key: string) =>({ ok: true as const, launch: prepareHarnessLaunch(pkg, workspace, engine, key, { privateGrid: 'new-grid' }) }) }const result = await buildLaunchOverrides(deps, 'claude', { dsh: pkg.id, cwd: ws, dshRuntime: 'original' }, 'registry-agent-id')@@ -157,7 +157,7 @@ describe('session isolation and lifecycle', () => {it('keeps older rows stable using their agent id and supports package renames', async () => {const deps = { machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/cfg',- tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {},+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => true,dshLaunch: async (_id: string, workspace: string, engine: typeof PROCESS_ENGINES[number] | 'terminal', key: string) => ({ ok: true as const, launch: prepareHarnessLaunch(pkg, workspace, engine, key) }) }const first = await buildLaunchOverrides(deps, 'codex', { dsh: pkg.id, cwd: ws }, 'old-agent')pkg.manifest.formerly = [pkg.id]@@ -168,7 +168,7 @@ describe('session isolation and lifecycle', () => {it('reports preparation failures, missing dependencies, or no resolver before a relaunch', async () => {const deps = { machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/cfg',- tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => {} }+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: () => true }expect(await buildLaunchOverrides(deps, 'codex', { dsh: pkg.id, cwd: ws }, 'key')).toMatchObject({ ok: false, error: 'DSH_NOT_INSTALLED' })expect(await buildLaunchOverrides({ ...deps, dshLaunch: () => { throw new Error('broken context') } }, 'codex', { dsh: pkg.id, cwd: ws }, 'key')).toMatchObject({ ok: false, error: 'DSH_RUNTIME_FAILED', detail: 'Error: broken context' })diff --git a/cli/src/engines/__fixtures__/native-version.golden.json b/cli/src/engines/__fixtures__/native-version.golden.jsonindex a6370f7cc..a85f2ec0c 100644--- a/cli/src/engines/__fixtures__/native-version.golden.json+++ b/cli/src/engines/__fixtures__/native-version.golden.json@@ -45,6 +45,45 @@}]},+ "linux:downgrade-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },+ "linux:current-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },"darwin:v1": {"installed": true,"first": 1,@@ -90,5 +129,44 @@"source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"}]+ },+ "darwin:downgrade-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },+ "darwin:current-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]}}diff --git a/cli/src/engines/claude/hookContract.ts b/cli/src/engines/claude/hookContract.tsindex 99dc9d0a1..5088591c2 100644--- a/cli/src/engines/claude/hookContract.ts+++ b/cli/src/engines/claude/hookContract.ts@@ -19,8 +19,6 @@ export const hooks: HookContract = {events: [{ event: 'SessionStart' }, { event: 'SessionEnd' }, { event: 'UserPromptSubmit' }, { event: 'Stop' }, { event: 'StopFailure' }],timeout: 5,commandNamesHome: false,- unreadable: 'replace',- write: 'in-place',upToDate: { command: 'first-ours', matcher: false },messages: {current: '[hooks] Claude session + turn (Stop/StopFailure) hooks already installed',diff --git a/cli/src/engines/codex/hookContract.ts b/cli/src/engines/codex/hookContract.tsindex f7ee1afdf..5a3557fa1 100644--- a/cli/src/engines/codex/hookContract.ts+++ b/cli/src/engines/codex/hookContract.ts@@ -14,10 +14,6 @@ export const hooks: HookContract = {events: [{ event: 'SessionStart', matcher: 'startup|resume|clear|compact' }, { event: 'UserPromptSubmit' }],timeout: 5,commandNamesHome: true,- // A malformed existing file is left untouched: silently replacing it could disable user- // security/automation hooks.- unreadable: 'keep',- write: 'atomic',upToDate: { command: 'first', matcher: true },messages: {current: '[hooks] Codex SessionStart/UserPromptSubmit hooks already installed → {file}',diff --git a/cli/src/engines/facets/hooks.ts b/cli/src/engines/facets/hooks.tsindex 41d75f4f4..3cef3570b 100644--- a/cli/src/engines/facets/hooks.ts+++ b/cli/src/engines/facets/hooks.ts@@ -1,3 +1,4 @@+import type { HookPreparationOptions } from '../kit/nativeHookFiles.js'import type { Env } from '../../config/env.js'import type { LiveEvent } from '../kit/events.js'import type { LiveTurn } from './live.js'@@ -29,10 +30,8 @@ export type FolderSetting = { [K in keyof Env]: Env[K] extends string ? K : neve/*** Where an engine reads its hooks, and how Harness keeps its own block there. Declared data, applied by the- * one kit installer (kit/hookSettings.ts), synchronously, at daemon start and before a spawn. Core authors- * the command every block runs (kit/notifyHooks.ts). Copied from the former engines/{claude,codex}/- * installHooks.ts, whose every write, mode and log line the kit reproduces (engines/hookInstallers.golden.spec.ts):- * the two treated a malformed file, a symlink and a drifted block differently, and so do these fields.+ * one kit installer (kit/hookSettings.ts) before spawn. Core authors the command+ * every block runs; unavailable configuration remains unchanged and holds launch.*/export interface HookSettings {/** The engine's home when core names none: a folder in the person's home, or a daemon setting. */@@ -45,16 +44,6 @@ export interface HookSettings {timeout: number/** The command names this home as the engine's (`--codex-home`): a profile's sessions are in its own store. */commandNamesHome: boolean- /**- * A file that cannot be read or parsed. `replace`: start from empty settings, and the write replaces it.- * `keep`: leave it as it is and say so, since replacing it could switch off the person's own hooks.- */- unreadable: 'replace' | 'keep'- /**- * `in-place`: write the file where it is, through a symlink, keeping its mode. `atomic`: write a new file- * beside it and rename it over the old one, which replaces a symlink and takes the new file's mode.- */- write: 'in-place' | 'atomic'/*** When the block of ours already there needs no write. It is the only block of ours, and its command is* the current one: the command of its first notify.mjs hook (`first-ours`) or of its first hook (`first`).@@ -130,8 +119,8 @@ export interface HookContract {/** What core calls, composed from an engine's contract and the kit's mechanics (engines/hooks.ts). */export interface EngineHooks {- install(port: number): void- installIn(port: number, home: string): void+ install(port: number, options?: HookPreparationOptions): Promise<boolean>+ installIn(port: number, home: string, options?: HookPreparationOptions): Promise<boolean>transcriptFor?(body: HookSession, agent: HookSession | undefined): string | undefinedadmit?(body: HookSession): HookAdmissiononStop?(context: HookTurnContext, body: HookStop): void | Promise<void>diff --git a/cli/src/engines/hookInstallers.golden.spec.ts b/cli/src/engines/hookInstallers.golden.spec.tsindex ad566dc79..7897a07d8 100644--- a/cli/src/engines/hookInstallers.golden.spec.ts+++ b/cli/src/engines/hookInstallers.golden.spec.ts@@ -15,6 +15,7 @@ import { tmpdir } from 'node:os'import { dirname, join, relative } from 'node:path'import { fileURLToPath } from 'node:url'import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { expectForeignHooksPreserved, preservedHookFiles } from '../testing/hookGoldenSafety.js'const GOLDEN = fileURLToPath(new URL('./__fixtures__/hook-installers.golden.json', import.meta.url))const RECORD = process.env.RECORD_HOOK_GOLDEN === '1'@@ -255,13 +256,14 @@ function reset(): void {mkdirSync(join(root, 'home'), { recursive: true })}-function run(engine: Engine, via: Via, scenario: Case): Outcome {+async function run(engine: Engine, via: Via, scenario: Case) {reset()const home = homes()[engine][via]const commandFor = (port: number): string => engine === 'claude' ? command(port, 'claude') : command(port, 'codex', home)const target: Target = { engine, via, home, file: join(home, FILE[engine]), cmd: commandFor(PORT), otherCmd: commandFor(OTHER_PORT), elsewhere: join(root, 'elsewhere') }if (!scenario.noHome) mkdirSync(home, { recursive: true })scenario.setup?.(target)+ const before = snapshot(), ready: boolean[] = []const runs: Run[] = []for (let i = 0; i < 2; i++) {const logs: string[] = []@@ -272,15 +274,16 @@ function run(engine: Engine, via: Via, scenario: Case): Outcome {vi.spyOn(console, 'warn').mockImplementation(capture('warn'))]let threw: string | null = nulltry {- if (via === 'install') hooks[engine].install(PORT)- else hooks[engine].installIn(PORT, home)+ ready.push(via === 'install' ? await hooks[engine].install(PORT) : await hooks[engine].installIn(PORT, home))} catch (error) { threw = describeError(error) } finally { for (const spy of spies) spy.mockRestore() }runs.push({ logs, threw })}- return { runs, files: snapshot() }+ return { outcome: { runs, files: snapshot() }, before, ready, file: normalize(relative(root, target.file)) }}+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!beforeAll(async () => {+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })root = mkdtempSync(join(tmpdir(), 'hook-golden-'))for (const name of ['HOME', 'CODEX_HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_PROJECTS_DIR']) saved[name] = process.env[name]// Every folder the hook command names is inside the throwaway root, so the command reads the same on every machine.@@ -318,21 +321,42 @@ beforeAll(async () => {})afterAll(() => {+ Object.defineProperty(process, 'platform', platform)for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = valueif (root) { reset(); rmSync(root, { recursive: true, force: true }) }if (RECORD) writeFileSync(GOLDEN, JSON.stringify(recorded, null, 1) + '\n')})+// These recorded cases exposed destructive recovery, unknown ownership or+// permission failures. Keep their original artifact and assert preservation.+const HELD = new Set(['empty file', 'whitespace only', 'malformed JSON', 'byte order mark', 'JSON null', 'JSON array',+ 'JSON string', 'JSON number', 'hooks is a string', 'hooks is an array', 'hooks is null', 'an event is not a list',+ 'odd blocks', 'a command that is not text', 'a dangling symlink', 'a symlink into a missing folder',+ 'a read-only file', 'an unreadable file', 'a read-only folder', 'a read-only folder holding a writable file', 'the file is a folder'])+const PRESERVE_COMMANDS = new Set(['our old hook', 'our old hook beside foreign hooks',+ 'ours current on some events, old or missing on others', 'ours twice, the first old'])+describe.each(['claude', 'codex'] as const)('%s hook installer, byte for byte', (engine) => {for (const via of ['installIn', 'install'] as const) {for (const scenario of CASES.filter((one) => via === 'installIn' || DEFAULT_HOME_CASES.has(one.name))) {const key = `${engine} ${via}: ${scenario.name}`- it.skipIf(scenario.permissions && ROOT_USER)(key, () => {+ it.skipIf(scenario.permissions && ROOT_USER)(key, async () => {const previous = process.umask(0o022)try {- const outcome = run(engine, via, scenario)+ const { outcome, before, ready, file } = await run(engine, via, scenario)recorded[key] = outcome- if (!RECORD) expect(outcome).toEqual(golden[key])+ if (!RECORD) {+ if (HELD.has(scenario.name)) {+ expect(ready).toEqual([false, false])+ expect(outcome.files).toEqual(before)+ for (const run of outcome.runs) { expect(run.threw).toBeNull(); expect(run.logs.some(line => line.startsWith('error '))).toBe(true) }+ } else if (PRESERVE_COMMANDS.has(scenario.name) || (engine === 'codex' && scenario.name === 'our block led by a foreign hook')) {+ expect(ready).toEqual([true, true])+ expectForeignHooksPreserved(before, outcome.files, golden[key].files, file)+ } else {+ expect(outcome).toEqual({ ...golden[key], files: preservedHookFiles(before, golden[key].files) })+ }+ }} finally { process.umask(previous) }})}diff --git a/cli/src/engines/hooks.spec.ts b/cli/src/engines/hooks.spec.tsindex 2c775b994..123223559 100644--- a/cli/src/engines/hooks.spec.ts+++ b/cli/src/engines/hooks.spec.ts@@ -31,10 +31,10 @@ it('keeps every contract plain data: nothing in it runs', () => {expect(JSON.parse(JSON.stringify(hookContracts))).toEqual(hookContracts)})-it('installs Claude hooks into the requested home through its facet', () => {+it('installs Claude hooks into the requested home through its facet', async () => {const home = mkdtempSync(join(tmpdir(), 'claude-hook-facet-'))try {- engineHooks.claude.installIn(19473, home)+ await engineHooks.claude.installIn(19473, home)const file = join(home, 'settings.json')const first = readFileSync(file, 'utf8')const settings = JSON.parse(first)@@ -43,7 +43,7 @@ it('installs Claude hooks into the requested home through its facet', () => {expect(command).toContain('--port 19473')expect(command).toContain(fileURLToPath(new URL('../../hook/notify.mjs', import.meta.url)))expect(command).not.toContain('--engine')- engineHooks.claude.installIn(19473, home)+ await engineHooks.claude.installIn(19473, home)expect(readFileSync(file, 'utf8')).toBe(first)} finally { rmSync(home, { recursive: true, force: true }) }})diff --git a/cli/src/engines/hooks.ts b/cli/src/engines/hooks.tsindex 8924d1f01..eeba102e9 100644--- a/cli/src/engines/hooks.ts+++ b/cli/src/engines/hooks.ts@@ -15,8 +15,8 @@ export const hookContracts = { claude, codex } satisfies Record<string, HookCont/** An engine's hooks as core calls them: the kit's mechanics, run on that engine's declaration. */function composed(engine: HookEngine, { settings, children, sessionFile, stopClosesTurns }: HookContract): EngineHooks {return {- install: (port) => installHookSettings(engine, settings, port),- installIn: (port, home) => installHookSettings(engine, settings, port, home),+ install: (port, options) => installHookSettings(engine, settings, port, undefined, options),+ installIn: (port, home, options) => installHookSettings(engine, settings, port, home, options),...(sessionFile ? { transcriptFor: (body: HookSession, agent: HookSession | undefined) => knownTranscript(body, agent, sessionFile) } : {}),...(children ? {admit: (body: HookSession): HookAdmission => body.transcriptPath && isChildSession(body.transcriptPath, children)diff --git a/cli/src/engines/kit/hookReview.spec.ts b/cli/src/engines/kit/hookReview.spec.tsindex ca5728cdd..f70baf765 100644--- a/cli/src/engines/kit/hookReview.spec.ts+++ b/cli/src/engines/kit/hookReview.spec.ts@@ -47,30 +47,30 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {])})- it('installs the hooks and records them, so Codex runs them without asking; a second start changes nothing', () => {+ it('installs the hooks and records them, so Codex runs them without asking; a second start changes nothing', async () => {const codexHome = home()vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)const installed = JSON.parse(readFileSync(join(codexHome, 'hooks.json'), 'utf8'))const config = readFileSync(join(codexHome, 'config.toml'), 'utf8')for (const [key, hash] of reviewRecords(record, join(codexHome, 'hooks.json'), installed)) {expect(config).toContain(`[hooks.state.${JSON.stringify(key)}]\ntrusted_hash = ${JSON.stringify(hash)}\n`)}expect(lstatSync(join(codexHome, 'config.toml')).mode & 0o777).toBe(0o600)- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)expect(readFileSync(join(codexHome, 'config.toml'), 'utf8')).toBe(config)})- it('records them for hooks an earlier start installed, and again when Harness’s command changes', () => {+ it('records them for hooks an earlier start installed, and again when Harness’s command changes', async () => {const codexHome = home()vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)writeFileSync(join(codexHome, 'config.toml'), 'model = "gpt-6"\n')- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)const first = readFileSync(join(codexHome, 'config.toml'), 'utf8')expect(first.startsWith('model = "gpt-6"\n\n[hooks.state.')).toBe(true)// Another port: another command, so another hash, in the same tables.- installHookSettings('codex', hooks.settings, 18999, codexHome)+ await installHookSettings('codex', hooks.settings, 18999, codexHome)const second = readFileSync(join(codexHome, 'config.toml'), 'utf8')expect(second.match(/^\[hooks\.state\./gm)).toHaveLength(2)expect(second).not.toBe(first)@@ -97,16 +97,16 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {expect(withReviewRecords(crlf, record, records)).toBe(crlf.replace('sha256:old', 'sha256:new'))})- it('records what hooks.json holds on disk: a block of the person’s before Harness’s, another timeout', () => {+ it('records what hooks.json holds on disk: a block of the person’s before Harness’s, another timeout', async () => {const codexHome = home()vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)const installed = JSON.parse(readFileSync(join(codexHome, 'hooks.json'), 'utf8'))// Harness's block first, the person's added after it, and a timeout of their own: current, so not rewritten.installed.hooks.UserPromptSubmit = [{ hooks: [{ ...installed.hooks.UserPromptSubmit[0].hooks[0], timeout: 30 }] }, { hooks: [{ type: 'command', command: 'echo theirs' }] }]writeFileSync(join(codexHome, 'hooks.json'), JSON.stringify(installed))rmSync(join(codexHome, 'config.toml'))- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)expect(readFileSync(join(codexHome, 'hooks.json'), 'utf8')).toBe(JSON.stringify(installed))const config = readFileSync(join(codexHome, 'config.toml'), 'utf8')const hook = installed.hooks.UserPromptSubmit[0].hooks[0]@@ -114,15 +114,15 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {expect(config).not.toContain('user_prompt_submit:1:0')})- it('records nothing for hooks that never reached the file', () => {+ it('records nothing for hooks that never reached the file', async () => {const codexHome = home()writeFileSync(join(codexHome, 'hooks.json'), '[]\n')vi.spyOn(console, 'log').mockImplementation(() => {})- recordReviewed(record, codexHome, join(codexHome, 'hooks.json'))+ await recordReviewed(record, codexHome, join(codexHome, 'hooks.json'))expect(existsSync(join(codexHome, 'config.toml'))).toBe(false)})- it('leaves a config alone that defines the table in a form an appended table could collide with', () => {+ it('leaves a config alone that defines the table in a form an appended table could collide with', async () => {const records = new Map([['/h/hooks.json:session_start:0:0', 'sha256:new']])for (const text of ['hooks = { state = {} }\n',@@ -142,25 +142,26 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {]) expect(withReviewRecords(text, record, records), text).toBe('unsafe')const codexHome = home()writeFileSync(join(codexHome, 'config.toml'), '[hooks]\nstate = {}\n')- const log = vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, codexHome)+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ expect(await installHookSettings('codex', hooks.settings, 19473, codexHome)).toBe(false)expect(readFileSync(join(codexHome, 'config.toml'), 'utf8')).toBe('[hooks]\nstate = {}\n')- expect(log.mock.calls.flat().join('\n')).toContain('defines hooks.state in a form Harness does not edit')+ expect(existsSync(join(codexHome, 'hooks.json'))).toBe(false)+ expect(error).toHaveBeenCalledWith(hooks.settings.messages.failed, expect.objectContaining({ name: 'HookPreparationHeld' }))})- it('keys a symlinked hooks.json by its own name in CODEX_HOME, not its target, as Codex does', () => {+ it('keys a symlinked hooks.json by its own name in CODEX_HOME, not its target, as Codex does', async () => {const codexHome = home()const dotfiles = home()writeFileSync(join(dotfiles, 'hooks.json'), '{}\n')symlinkSync(join(dotfiles, 'hooks.json'), join(codexHome, 'hooks.json'))vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, codexHome)+ await installHookSettings('codex', hooks.settings, 19473, codexHome)const config = readFileSync(join(codexHome, 'config.toml'), 'utf8')expect(config).toContain(`[hooks.state.${JSON.stringify(`${codexHome}/hooks.json:session_start:0:0`)}]`)expect(config).not.toContain(dotfiles)})- it('keys by the real path of a symlinked CODEX_HOME, as Codex does, and writes through a symlinked config', () => {+ it('keys by the real path of a symlinked CODEX_HOME, as Codex does, and writes through a symlinked config', async () => {const real = home()const link = `${real}-link`symlinkSync(real, link)@@ -169,16 +170,16 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {writeFileSync(join(dotfiles, 'config.toml'), 'model = "gpt-6"\n')symlinkSync(join(dotfiles, 'config.toml'), join(real, 'config.toml'))vi.spyOn(console, 'log').mockImplementation(() => {})- installHookSettings('codex', hooks.settings, 18473, link)+ await installHookSettings('codex', hooks.settings, 19473, link)expect(lstatSync(join(real, 'config.toml')).isSymbolicLink()).toBe(true)const config = readFileSync(join(dotfiles, 'config.toml'), 'utf8')expect(config).toContain(`[hooks.state.${JSON.stringify(`${real}/hooks.json:session_start:0:0`)}]`)expect(config).not.toContain(link)})- it('never throws: an unreadable settings path is a hook Codex asks about, as before', () => {+ it('never throws: an unreadable settings path is a hook Codex asks about, as before', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {})- expect(() => recordReviewed(record, '/nonexistent-home', '/nonexistent-home/hooks.json')).not.toThrow()+ expect(await recordReviewed(record, '/nonexistent-home', '/nonexistent-home/hooks.json')).toBe(false)expect(error).toHaveBeenCalled()})})diff --git a/cli/src/engines/kit/hookReview.ts b/cli/src/engines/kit/hookReview.tsindex 922547713..2079e938a 100644--- a/cli/src/engines/kit/hookReview.ts+++ b/cli/src/engines/kit/hookReview.ts@@ -14,11 +14,11 @@* Only Harness's own blocks, never another hook in the same file. The config file is edited the way* folderTrust.ts edits it: through a symlink, atomically, and only where the table cannot end up defined twice.*/+import { parse as parseToml } from 'smol-toml'import { createHash } from 'node:crypto'-import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'-import { basename, dirname, join } from 'node:path'+import { basename, join } from 'node:path'import type { HookReviewRecord } from '../facets/hooks.js'-import { replaceConfigFile } from './folderTrust.js'+import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationAttempt } from './nativeHookFiles.js'import { isOurs, type Settings } from './notifyHooks.js'/** Every object's keys sorted, as the engine sorts them before it hashes. */@@ -167,33 +167,47 @@ export function withReviewRecords(text: string, record: HookReviewRecord, recordreturn next === text ? 'unchanged' : next}-/**- * Record Harness's own blocks in the engine's settings file, as the file is on disk now, as reviewed in the- * engine's config file: the engine keys and hashes what it reads, so an order or a timeout Harness did not- * write itself is recorded as it is. Created when the engine has not written one yet: a new person's first- * Codex pane is the one that asks. Never throws: a hook that is not recorded is asked about, as before.- */-export function recordReviewed(record: HookReviewRecord, home: string, settingsFile: string): void {+/** Inspect approvals before publishing hooks. An unreadable or conflicting+ * config cannot authorize even the first write of the installation. */+export function prepareReviewed(record: HookReviewRecord, home: string, settingsFile: string, settings: Settings) {+ const config = join(home, record.file), observed = inspectHookFile(config, 0o600)+ // Codex uses the real home plus the literal hooks filename, even when that+ // leaf is an alias. The config's own leaf alias does not change that home.+ const records = reviewRecords(record, join(observed.directory, basename(settingsFile)), settings)+ if (records.size === 0) throw new HookPreparationHeld('the hooks have no verifiable approval records')+ const text = observed.content ?? ''+ try { parseToml(text, { integersAsBigInt: true, maxDepth: 64 }) }+ catch { throw new HookPreparationHeld('the hook review configuration is not complete TOML') }+ const next = withReviewRecords(text, record, records)+ if (next === 'unsafe') throw new HookPreparationHeld('the hook review configuration cannot be safely updated')+ const output = next === 'unchanged' ? text : next+ try { parseToml(output, { integersAsBigInt: true, maxDepth: 64 }) }+ catch { throw new HookPreparationHeld('the prepared hook reviews are not complete TOML') }+ observed.prepare(output)+ return {+ verify: observed.verify,+ commit: async (attempt: HookPreparationAttempt) => {+ const published = await observed.replace(next === 'unchanged' ? text : next, attempt)+ if (next !== 'unchanged') console.log(record.messages.recorded.replace('{config}', config))+ return published+ },+ }+}++/** Record the exact settings already on disk. Failure is explicit so launch+ * remains held until both the hook and its approval are confirmed durable. */+export async function recordReviewed(record: HookReviewRecord, home: string, settingsFile: string): Promise<boolean> {const config = join(home, record.file)- const say = (line: string): string => line.replace('{config}', config)- try {- const settings = JSON.parse(readFileSync(settingsFile, 'utf8')) as Settings- if (!settings || typeof settings !== 'object' || Array.isArray(settings) || !settings.hooks || typeof settings.hooks !== 'object') return- // Codex keys a hook by the real path of CODEX_HOME joined with the file's name (codex-cli 0.162.0): a- // symlinked home names its target, a symlinked hooks.json in it keeps its own name.- const records = reviewRecords(record, join(realpathSync(dirname(settingsFile)), basename(settingsFile)), settings)- if (records.size === 0) return- const text = existsSync(config) ? readFileSync(config, 'utf8') : ''- const next = withReviewRecords(text, record, records)- if (next === 'unchanged') return- if (next === 'unsafe') {- console.log(say(record.messages.skipped))- return- }- if (existsSync(config)) replaceConfigFile(config, next)- else writeFileSync(config, next, { mode: 0o600 })- console.log(say(record.messages.recorded))- } catch (err) {- console.error(say(record.messages.skipped), err)+ try { return await runHookPreparation([settingsFile, config], async attempt => {+ const source = inspectHookFile(settingsFile)+ const settings = JSON.parse(source.content ?? 'null') as Settings+ if (!settings || typeof settings !== 'object' || Array.isArray(settings) || !settings.hooks || typeof settings.hooks !== 'object') return false+ const prepared = prepareReviewed(record, home, settingsFile, settings)+ source.verify(); const published = await prepared.commit(attempt)+ source.verify(); published.verify()+ return true+ }) } catch (err) {+ console.error(record.messages.skipped.replace('{config}', config), err)+ return false}}diff --git a/cli/src/engines/kit/hookSettings.spec.ts b/cli/src/engines/kit/hookSettings.spec.tsindex 7f7e58bec..8872e742e 100644--- a/cli/src/engines/kit/hookSettings.spec.ts+++ b/cli/src/engines/kit/hookSettings.spec.ts@@ -21,23 +21,23 @@ it('finds an engine\'s home in the person\'s home or in a daemon setting', () =>expect(defaultHookHome(codex.settings)).toBe(env.CODEX_HOME)})-it('names a home literally in its log lines, whatever characters the path holds', () => {+it('names a home literally in its log lines, whatever characters the path holds', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})// `$&` and `$1` mean something to String.replace with a string replacement, and {port} to the templates.const home = join(root, 'a$&b$1{port}{file}')const file = join(home, 'settings.json')- installHookSettings('claude', { ...claude.settings, messages: { ...claude.settings.messages, installed: '{file}|{script}|{port}' } }, 19473, home)+ await installHookSettings('claude', { ...claude.settings, messages: { ...claude.settings.messages, installed: '{file}|{script}|{port}' } }, 19473, home)expect(log.mock.calls[0]).toEqual([`${file}|${HOOK_SCRIPT}|19473`])expect(JSON.parse(readFileSync(file, 'utf8')).hooks.Stop[0].hooks[0].command).toContain('--port 19473')})-it('keeps a malformed file quietly for an engine that declares no lines for it', () => {+it('reports a held malformed file even when an engine declares no malformed-file lines', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {})const home = join(root, 'codex')mkdirSync(home)writeFileSync(join(home, 'hooks.json'), '{not-json')const { malformed: _, ...messages } = codex.settings.messages- installHookSettings('codex', { ...codex.settings, messages }, 19473, home)- expect(error).not.toHaveBeenCalled()+ expect(await installHookSettings('codex', { ...codex.settings, messages }, 19473, home)).toBe(false)+ expect(error).toHaveBeenCalledWith(codex.settings.messages.failed, expect.any(SyntaxError))expect(readFileSync(join(home, 'hooks.json'), 'utf8')).toBe('{not-json')})diff --git a/cli/src/engines/kit/hookSettings.ts b/cli/src/engines/kit/hookSettings.tsindex eef517502..7e5d69d2a 100644--- a/cli/src/engines/kit/hookSettings.ts+++ b/cli/src/engines/kit/hookSettings.ts@@ -2,18 +2,16 @@* The one installer of the engines' declared hook settings (facets/hooks.ts `HookSettings`): Harness's block* merged into the settings file an engine reads its hooks from, every other block left as it was.*- * It replaces Claude Code's and Codex's own installers, statement for statement, and writes the same bytes,- * modes and log lines in every state their files were recorded in (engines/hookInstallers.golden.spec.ts).- * It runs in core, synchronously: at daemon start (core/engines/hooks.ts) and before a Codex agent starts in- * a profile of its own (core/agents/create.ts), where a hook installed late is a hook that never fires.+ * It runs eagerly before launch. Unknown files are held, foreign commands are+ * preserved, and hook and approval destinations are inspected before publication.*/-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'-import { dirname, join } from 'node:path'+import { join } from 'node:path'import { env } from '../../config/env.js'import type { HookSettings } from '../facets/hooks.js'-import { recordReviewed } from './hookReview.js'-import { command, HOOK_SCRIPT, isOurs, writeJsonAtomic, type Settings } from './notifyHooks.js'+import { prepareReviewed } from './hookReview.js'+import { command, HOOK_SCRIPT, isOurs, foreignHookBlocks, type Settings } from './notifyHooks.js'+import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationOptions } from './nativeHookFiles.js'/** The engines whose hooks run the notify.mjs command. */export type HookEngine = Parameters<typeof command>[1]@@ -23,70 +21,64 @@ export function defaultHookHome(settings: HookSettings): string {return 'setting' in settings.home ? env[settings.home.setting] : join(homedir(), settings.home.inHome)}-export function installHookSettings(engine: HookEngine, settings: HookSettings, port: number, home: string = defaultHookHome(settings)): void {+export async function installHookSettings(engine: HookEngine, settings: HookSettings, port: number, home: string = defaultHookHome(settings), options: HookPreparationOptions = {}): Promise<boolean> {const file = join(home, settings.file)+ const cmd = command(port, engine, settings.commandNamesHome ? home : undefined)const say = (line: string): string => line.replace(/\{(file|script|port)\}/g, (_, name: string) =>name === 'file' ? file : name === 'script' ? HOOK_SCRIPT : String(port))const { messages } = settings- let current: Settings = {}- if (settings.unreadable === 'replace') {- try {- current = JSON.parse(readFileSync(file, 'utf-8')) as Settings- } catch {- // missing / unreadable → start from empty settings- }- } else if (existsSync(file)) {- try {- current = JSON.parse(readFileSync(file, 'utf-8')) as Settings- } catch {- for (const line of messages.malformed ?? []) console.error(say(line))- return+ try { return await runHookPreparation([file, ...(settings.reviewed ? [join(home, settings.reviewed.file)] : [])], async attempt => {+ const observed = inspectHookFile(file)+ const current = (observed.content === null ? {} : JSON.parse(observed.content)) as Settings+ if (!current || typeof current !== 'object' || Array.isArray(current)+ || (current.hooks !== undefined && (!current.hooks || typeof current.hooks !== 'object' || Array.isArray(current.hooks)))) {+ throw new HookPreparationHeld('the hook settings do not have the declared object shape')}- }-- if (!current.hooks || typeof current.hooks !== 'object') current.hooks = {}- const cmd = command(port, engine, settings.commandNamesHome ? home : undefined)- let changed = false- let updated = false // true when an EXISTING block's command changed (path/port drift)+ current.hooks ??= {}+ let changed = false+ let updated = false // true when an EXISTING block's command changed (path/port drift)- for (const { event, matcher } of settings.events) {- const blocks = Array.isArray(current.hooks[event]) ? current.hooks[event] : []- // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and keep every- // non-ours block untouched.- const foreign = blocks.filter((b) => !isOurs(b))- const ours = blocks.filter(isOurs)- if (ours.length !== 1) changed = true // none yet, or duplicates to drop- const existing = ours[0]- if (existing) {- // A prior block with a different command (moved checkout / dev↔dist / changed port / interpreter) is- // overwritten in place by the canonical one below.- const existingCmd = settings.upToDate.command === 'first-ours'- ? existing.hooks?.find((h) => isOurs({ hooks: [h] }))?.command- : existing.hooks?.[0]?.command- if (existingCmd !== cmd) { changed = true; updated = true }- if (settings.upToDate.matcher && existing.matcher !== matcher) changed = true+ for (const { event, matcher } of settings.events) {+ if (current.hooks[event] !== undefined && !Array.isArray(current.hooks[event])) throw new HookPreparationHeld('a hook event is not a list')+ const blocks = current.hooks[event] ?? []+ // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and keep every+ // non-ours block untouched.+ const foreign = foreignHookBlocks(blocks)+ const ours = blocks.filter(isOurs)+ if (ours.length !== 1) changed = true // none yet, or duplicates to drop+ const existing = ours[0]+ if (existing) {+ // A prior block with a different command (moved checkout / dev↔dist / changed port / interpreter) is+ // overwritten in place by the canonical one below.+ const existingCmd = settings.upToDate.command === 'first-ours'+ ? existing.hooks?.find((h) => isOurs({ hooks: [h] }))?.command+ : existing.hooks?.[0]?.command+ if (existingCmd !== cmd) { changed = true; updated = true }+ if (settings.upToDate.matcher && existing.matcher !== matcher) changed = true+ }+ current.hooks[event] = [...foreign, { ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command: cmd, timeout: settings.timeout }] }]}- current.hooks[event] = [...foreign, { ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command: cmd, timeout: settings.timeout }] }]- }-- if (!changed) {- console.log(say(messages.current))- // Installed by an earlier start, or by a release before the engine asked: recorded now, as the file has it.- if (settings.reviewed) recordReviewed(settings.reviewed, home, file)- return- }- try {- if (settings.write === 'atomic') writeJsonAtomic(file, current)- else {- mkdirSync(dirname(file), { recursive: true })- writeFileSync(file, JSON.stringify(current, null, 2) + '\n')+ const next = changed ? JSON.stringify(current, null, 2) + '\n' : observed.content!+ const reviewed = settings.reviewed ? prepareReviewed(settings.reviewed, home, file, JSON.parse(next) as Settings) : null+ reviewed?.verify()+ if (!changed) {+ const published = await observed.replace(next, attempt)+ console.log(say(messages.current))+ // Installed by an earlier start, or by a release before the engine asked: recorded now, as the file has it.+ const approval = await reviewed?.commit(attempt)+ published.verify(); approval?.verify()+ return true}++ const published = await observed.replace(next, attempt)console.log(say(updated && messages.updated ? messages.updated : messages.installed))console.log(say(messages.after))- } catch (err) {+ const approval = await reviewed?.commit(attempt)+ published.verify(); approval?.verify()+ return true+ }, { ...options, identity: JSON.stringify([engine, settings, port, home, cmd]) }) } catch (err) {console.error(say(messages.failed), err)- return+ return false}- if (settings.reviewed) recordReviewed(settings.reviewed, home, file)}diff --git a/cli/src/engines/kit/nativeHookAttempts.spec.ts b/cli/src/engines/kit/nativeHookAttempts.spec.tsnew file mode 100644index 000000000..c9dda889c--- /dev/null+++ b/cli/src/engines/kit/nativeHookAttempts.spec.ts@@ -0,0 +1,192 @@+import { closeSync, fstatSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync, unlinkSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { inspectHookFile, runHookPreparation } from './nativeHookFiles.js'++const disk = vi.hoisted(() => ({ held: true, pending: new Map<number, (error: Error | null) => void>() }))+vi.mock('node:fs', async original => ({ ...await original<typeof import('node:fs')>(),+ fsync: (fd: number, done: (error: Error | null) => void) => {+ if (disk.held) disk.pending.set(fd, done)+ else queueMicrotask(() => done(null))+ },+}))+let root: string+const drain = async () => { for (let n = 0; n < 80; n++) await Promise.resolve() }+async function release() {+ disk.held = false+ for (const done of disk.pending.values()) done(null)+ disk.pending.clear()+ await drain()+}+beforeEach(() => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-hook-attempts-')))+ disk.held = true+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })+})+afterEach(async () => { await release(); vi.useRealTimers(); rmSync(root, { recursive: true, force: true }) })++it('keeps the event loop available and retains the descriptor and reservation after its reply deadline', async () => {+ const file = join(root, 'hooks'); writeFileSync(file, 'before')+ const pending = runHookPreparation([file], attempt => inspectHookFile(file).replace('after', attempt), { timeoutMs: 20 }).catch(error => error)+ await drain()+ const fd = [...disk.pending.keys()][0]+ expect(fd).toBeTypeOf('number')+ expect(fstatSync(fd).isFile()).toBe(true)+ let stopped = false+ setTimeout(() => { stopped = true }, 1)+ await vi.advanceTimersByTimeAsync(20)+ expect(stopped).toBe(true)+ expect((await pending).message).toMatch(/deadline/)+ expect(readFileSync(file, 'utf8')).toBe('before')+ expect(fstatSync(fd).isFile()).toBe(true)+ await expect(runHookPreparation([file], async () => true)).rejects.toThrow(/still owns/)+ await release()+ expect(() => fstatSync(fd)).toThrow()+ expect(readdirSync(root)).toEqual(['hooks'])+ expect(readFileSync(file, 'utf8')).toBe('before')+ await runHookPreparation([file], attempt => inspectHookFile(file).replace('recovered', attempt))+ expect(readFileSync(file, 'utf8')).toBe('recovered')+})++it('reserves aliases together, joins identical work, and prevents a superseded port from publishing', async () => {+ const file = join(root, 'hooks'), alias = join(root, 'alias'); writeFileSync(file, 'before'); symlinkSync(file, alias)+ const first = runHookPreparation([file], attempt => inspectHookFile(file).replace('old port', attempt), { identity: 'old port' }).catch(error => error)+ const duplicate = vi.fn(async () => true)+ const joined = runHookPreparation([alias], duplicate, { identity: 'old port' }).catch(error => error)+ await drain()+ expect(duplicate).not.toHaveBeenCalled()+ await expect(runHookPreparation([alias], async () => true, { identity: 'new port' })).rejects.toThrow(/still owns/)+ await release()+ expect((await first).message).toMatch(/owner changed/)+ expect((await joined).message).toMatch(/owner changed/)+ expect(readFileSync(file, 'utf8')).toBe('before')+})++it('rechecks the original caller after a flush without acknowledging or publishing for a closed owner', async () => {+ const file = join(root, 'hooks'); writeFileSync(file, 'before')+ let current = true+ const prepared = runHookPreparation([file], attempt => inspectHookFile(file).replace('late', attempt), { current: () => current }).catch(error => error)+ await drain(); current = false; await release()+ expect((await prepared).message).toMatch(/owner changed/)+ expect(readFileSync(file, 'utf8')).toBe('before')+})++it('bounds outstanding flushes and releases undispatched work when its deadline expires', async () => {+ const replies: Promise<unknown>[] = []+ for (let n = 0; n < 16; n++) {+ const file = join(root, String(n)); writeFileSync(file, 'before')+ replies.push(runHookPreparation([file], async attempt => {+ const fd = openSync(file, 'r')+ try { await attempt.flush(fd) } finally { closeSync(fd) }+ }, { timeoutMs: 10 }).catch(error => error))+ }+ await drain()+ expect(disk.pending.size).toBe(2)+ await expect(runHookPreparation([join(root, 'overflow')], async () => true)).rejects.toThrow(/slots/)+ await vi.advanceTimersByTimeAsync(10)+ await Promise.all(replies)+ expect(disk.pending.size).toBe(2)+ expect(await runHookPreparation([join(root, 'available')], async () => true)).toBe(true)+ await release()+ expect(await runHookPreparation([join(root, 'recovered')], async () => true)).toBe(true)+})+++it('checks a changed second destination before publishing the first after a disk wait', async () => {+ const hooks = join(root, 'hooks'), approvals = join(root, 'approvals')+ writeFileSync(hooks, 'old hooks'); writeFileSync(approvals, 'old approvals')+ const pending = runHookPreparation([hooks, approvals], async attempt => {+ const first = inspectHookFile(hooks), second = inspectHookFile(approvals)+ const published = await first.replace('new hooks', attempt)+ await second.replace('new approvals', attempt)+ published.verify()+ }).catch(error => error)+ await drain()+ writeFileSync(approvals, 'foreign edit')+ await release()+ expect((await pending).message).toMatch(/changed/)+ expect(readFileSync(hooks, 'utf8')).toBe('old hooks')+ expect(readFileSync(approvals, 'utf8')).toBe('foreign edit')+})++it('checks each joining owner and deadline without cancelling the original installation', async () => {+ const file = join(root, 'hooks'); writeFileSync(file, 'before')+ const original = runHookPreparation([file], async attempt => {+ await inspectHookFile(file).replace('ready', attempt)+ return true+ }, { identity: 'same' })+ await drain()+ const work = vi.fn(async () => true)+ let refused: unknown+ void runHookPreparation([file], work, { identity: 'same', current: () => false }).catch(error => { refused = error })+ await drain()+ expect(refused).toEqual(expect.objectContaining({ message: expect.stringMatching(/joining owner/) }))+ const short = runHookPreparation([file], work, { identity: 'same', timeoutMs: 5 }).catch(error => error)+ let current = true+ const cancelled = runHookPreparation([file], work, { identity: 'same', current: () => current }).catch(error => error)+ await vi.advanceTimersByTimeAsync(5)+ expect((await short).message).toMatch(/joining preparation.*deadline/)+ current = false+ await release()+ expect(await original).toBe(true)+ expect((await cancelled).message).toMatch(/joining owner/)+ expect(work).not.toHaveBeenCalled()+ expect(readFileSync(file, 'utf8')).toBe('ready')+})+++it('keeps a queued destination bound to the route it reserved before asynchronous dispatch', async () => {+ const first = join(root, 'first'), second = join(root, 'second'), alias = join(root, 'alias')+ writeFileSync(first, 'first'); writeFileSync(second, 'second'); symlinkSync(first, alias)+ const work = vi.fn(async () => true)+ const pending = runHookPreparation([alias], work).catch(error => error)+ unlinkSync(alias); symlinkSync(second, alias)+ await drain()+ expect((await pending).message).toMatch(/route changed/)+ expect(work).not.toHaveBeenCalled()+ expect(readFileSync(first, 'utf8')).toBe('first')+ expect(readFileSync(second, 'utf8')).toBe('second')+})+++it('does not acknowledge an alias redirected while its identical preparation is joined', async () => {+ const file = join(root, 'hooks'), alias = join(root, 'alias'), other = join(root, 'other')+ writeFileSync(file, 'old'); writeFileSync(other, 'foreign'); symlinkSync(file, alias)+ const original = runHookPreparation([file], attempt => inspectHookFile(file).replace('ready', attempt), { identity: 'same' })+ await drain()+ const joined = runHookPreparation([alias], async () => true, { identity: 'same' }).catch(error => error)+ unlinkSync(alias); symlinkSync(other, alias)+ await release(); await original+ expect((await joined).message).toMatch(/changed/)+ expect(readFileSync(alias, 'utf8')).toBe('foreign')+})++it('checks the joining deadline even when the timer phase has not run', async () => {+ const file = join(root, 'hooks'); writeFileSync(file, 'old')+ let finish!: (value: boolean) => void+ const work = new Promise<boolean>(resolve => { finish = resolve })+ const original = runHookPreparation([file], () => work, { identity: 'same' })+ const joined = runHookPreparation([file], async () => true, { identity: 'same', timeoutMs: 5 }).catch(error => error)+ await drain()+ const now = vi.spyOn(performance, 'now').mockReturnValue(10)+ finish(true)+ expect(await original).toBe(true)+ expect(await joined).toEqual(expect.objectContaining({ message: expect.stringMatching(/deadline/) }))+ now.mockRestore()+})++it('retains the joining caller’s alias in its final launch proof', async () => {+ const file = join(root, 'hooks'), alias = join(root, 'alias'), other = join(root, 'other')+ writeFileSync(file, 'old'); writeFileSync(other, 'foreign'); symlinkSync(file, alias)+ const original = runHookPreparation([file], attempt => inspectHookFile(file).replace('ready', attempt), { identity: 'same' })+ await drain()+ const confirmed = vi.fn()+ const joined = runHookPreparation([alias], async () => true, { identity: 'same', confirmed })+ await release(); await original; await joined+ const proof = confirmed.mock.calls[0]![0]+ expect(proof.files[0].file).toBe(alias)+ expect(proof.current()).toBe(true)+ unlinkSync(alias); symlinkSync(other, alias)+ expect(proof.current()).toBe(false)+})diff --git a/cli/src/engines/kit/nativeHookFiles.spec.ts b/cli/src/engines/kit/nativeHookFiles.spec.tsnew file mode 100644index 000000000..b8205c670--- /dev/null+++ b/cli/src/engines/kit/nativeHookFiles.spec.ts@@ -0,0 +1,251 @@+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync, chmodSync, fstatSync, statSync, renameSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import { inspectHookFile, runHookPreparation } from './nativeHookFiles.js'++const fault = vi.hoisted(() => ({ sync: false, write: false, onSync: undefined as ((fd: number) => void) | undefined, openAs: undefined as string | undefined, onStat: undefined as ((file: unknown, options: unknown) => void) | undefined }))+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ return { ...fs,+ lstatSync: (...args: Parameters<typeof fs.lstatSync>) => { fault.onStat?.(...args); return fs.lstatSync(...args) },+ fsync: (fd: number, callback: (error: Error | null) => void) => {+ try { if (fault.sync) throw new Error('fixture sync unavailable'); fault.onSync?.(fd); fs.fsync(fd, callback) }+ catch (error) { queueMicrotask(() => callback(error as Error)) }+ },+ openSync: (...args: Parameters<typeof fs.openSync>) => fs.openSync(fault.openAs ?? args[0], ...args.slice(1) as [number, number?]),+ writeFileSync: (...args: Parameters<typeof fs.writeFileSync>) => {+ if (fault.write && typeof args[0] === 'number') throw new Error('fixture disk full')+ return fs.writeFileSync(...args)+ },+ }+})+const roots: string[] = []+function prepared(file: string) {+ const observed = inspectHookFile(file)+ return { ...observed,+ replace: (next: string) => runHookPreparation([file], attempt => observed.replace(next, attempt)),+ remove: () => runHookPreparation([file], attempt => observed.remove(attempt)),+ }+}+function fixture() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-hook-files-')))+ roots.push(root)+ return { root, file: join(root, 'config.json') }+}+afterEach(() => { fault.sync = false; fault.write = false; fault.onSync = undefined; fault.openAs = undefined; fault.onStat = undefined; vi.restoreAllMocks(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })++it('publishes complete bytes durably, preserves private permissions and leaves no staging file', async () => {+ const { root, file } = fixture()+ writeFileSync(file, 'old', { mode: 0o600 })+ await prepared(file).replace('new')+ expect(readFileSync(file, 'utf8')).toBe('new')+ expect(readdirSync(root)).toEqual(['config.json'])+ expect(inspectHookFile(file).content).toBe('new')+ await prepared(file).replace('new')+})++it('never turns a peer edit during final proof capture into a confirmed output', async () => {+ const { file } = fixture()+ writeFileSync(file, 'prepared hooks')+ const confirmed = vi.fn()+ await expect(runHookPreparation([file], async attempt => {+ const expected = inspectHookFile(file)+ attempt.observe(file, () => {+ expected.verify()+ // The next leaf read occurs after checking the published observation.+ // A peer writes real bytes at that boundary, before proof capture.+ fault.onStat = path => {+ if (path !== file) return+ fault.onStat = undefined+ writeFileSync(file, 'peer hooks')+ }+ })+ return true+ }, { confirmed })).rejects.toThrow(/changed/)+ expect(confirmed).not.toHaveBeenCalled()+ expect(readFileSync(file, 'utf8')).toBe('peer hooks')+})++it('creates and syncs a missing directory chain', async () => {+ const { root } = fixture(), file = join(root, 'new', 'nested', 'hooks.json')+ await prepared(file).replace('prepared')+ expect(readFileSync(file, 'utf8')).toBe('prepared')+ await prepared(file).remove()+ expect(inspectHookFile(file).content).toBeNull()+ await prepared(file).remove()+})++it('preserves a relocated config home and its file alias', async () => {+ const { root } = fixture(), real = join(root, 'real'), link = join(root, 'link')+ mkdirSync(real); symlinkSync(real, link)+ const target = join(real, 'settings.json'), file = join(link, 'settings.json')+ writeFileSync(target, 'old')+ const alias = join(root, 'alias.json'); symlinkSync(file, alias)+ await prepared(alias).replace('new')+ expect(realpathSync(alias)).toBe(target)+ expect(readFileSync(target, 'utf8')).toBe('new')+})++it('retains an intervening peer edit instead of overwriting a stale snapshot', async () => {+ const { file } = fixture()+ writeFileSync(file, 'before')+ const old = prepared(file)+ writeFileSync(file, 'peer edit')+ await expect(old.replace('ours')).rejects.toThrow(/changed/)+ await expect(old.remove()).rejects.toThrow(/changed/)+ expect(readFileSync(file, 'utf8')).toBe('peer edit')+})++it('refuses a replaced config alias and leaves both destinations untouched', async () => {+ const { root, file } = fixture(), first = join(root, 'first'), second = join(root, 'second')+ writeFileSync(first, 'one'); writeFileSync(second, 'two'); symlinkSync(first, file)+ const old = prepared(file)+ unlinkSync(file); symlinkSync(second, file)+ await expect(old.replace('ours')).rejects.toThrow(/changed/)+ expect(readFileSync(first, 'utf8')).toBe('one')+ expect(readFileSync(second, 'utf8')).toBe('two')+})++it('refuses directories, dangling aliases, oversized settings and read-only files', async () => {+ const { root, file } = fixture()+ expect(() => inspectHookFile(root)).toThrow()+ symlinkSync(join(root, 'absent'), file)+ expect(() => inspectHookFile(file)).toThrow()+ unlinkSync(file); writeFileSync(file, 'x'.repeat(1024 * 1024 + 1))+ expect(() => inspectHookFile(file)).toThrow(/bounded/)+ writeFileSync(file, 'foreign'); chmodSync(file, 0o444)+ await expect(prepared(file).replace('ours')).rejects.toThrow(/read-only/)+ expect(readFileSync(file, 'utf8')).toBe('foreign')+})++it('does not truncate the prior file or leave staging files after a write failure', async () => {+ const { root, file } = fixture()+ writeFileSync(file, 'previous'); fault.write = true+ await expect(prepared(file).replace('new')).rejects.toThrow(/disk full/)+ expect(readFileSync(file, 'utf8')).toBe('previous')+ expect(readdirSync(root)).toEqual(['config.json'])+ fault.write = false+ await prepared(file).replace('new')+ expect(readFileSync(file, 'utf8')).toBe('new')+})++it('cannot acknowledge a failed sync even when the desired bytes already exist', async () => {+ const { file } = fixture()+ writeFileSync(file, 'already prepared'); fault.sync = true+ await expect(prepared(file).replace('already prepared')).rejects.toThrow(/sync unavailable/)+ fault.sync = false+ await expect(prepared(file).replace('already prepared')).resolves.toBeDefined()+})++it('retains removal uncertainty until a retry can sync the parent directory', async () => {+ const { file } = fixture()+ writeFileSync(file, 'owned'); fault.sync = true+ await expect(prepared(file).remove()).rejects.toThrow(/sync unavailable/)+ expect(inspectHookFile(file).content).toBeNull()+ await expect(prepared(file).remove()).rejects.toThrow(/sync unavailable/)+ fault.sync = false+ await expect(prepared(file).remove()).resolves.toBeDefined()+})++it('holds invalid UTF-8 without replacing its original bytes', async () => {+ const { file } = fixture(), bytes = Buffer.from([0x7b, 0xff, 0x7d])+ writeFileSync(file, bytes)+ expect(() => inspectHookFile(file)).toThrow()+ expect(readFileSync(file)).toEqual(bytes)+})++it('does not acknowledge a destination changed while its parent is being synced', async () => {+ const { file } = fixture()+ writeFileSync(file, 'old')+ fault.onSync = fd => {+ if (fstatSync(fd).isDirectory()) { fault.onSync = undefined; writeFileSync(file, 'peer replacement') }+ }+ await expect(prepared(file).replace('ours')).rejects.toThrow(/changed/)+ expect(readFileSync(file, 'utf8')).toBe('peer replacement')+})++it('does not acknowledge a removed plugin recreated during parent sync', async () => {+ const { file } = fixture()+ writeFileSync(file, 'managed')+ fault.onSync = fd => {+ if (fstatSync(fd).isDirectory()) { fault.onSync = undefined; writeFileSync(file, 'recreated') }+ }+ await expect(prepared(file).remove()).rejects.toThrow(/recreated/)+ expect(readFileSync(file, 'utf8')).toBe('recreated')+})++it('holds a plugin alias without deleting its shared target or the alias', async () => {+ const { root, file } = fixture(), target = join(root, 'shared.js')+ writeFileSync(target, 'shared plugin'); symlinkSync(target, file)+ await expect(prepared(file).remove()).rejects.toThrow(/alias/)+ expect(realpathSync(file)).toBe(target)+ expect(readFileSync(target, 'utf8')).toBe('shared plugin')+})++it('reconfirms an ancestor name left uncertain by an earlier failed parent sync', async () => {+ const { root } = fixture(), file = join(root, 'a', 'b', 'hooks.json'), inode = statSync(root).ino+ fault.onSync = fd => { if (fstatSync(fd).ino === inode) throw new Error('fixture ancestor publication unavailable') }+ await expect(prepared(file).replace('new')).rejects.toThrow(/ancestor publication/)+ let confirmed = false+ fault.onSync = fd => { if (fstatSync(fd).ino === inode) confirmed = true }+ await prepared(file).replace('new')+ expect(confirmed).toBe(true)+ expect(readFileSync(file, 'utf8')).toBe('new')+})++it('compares the unchanged file descriptor with the reviewed inode before syncing', async () => {+ const { root, file } = fixture(), other = join(root, 'other')+ writeFileSync(file, 'same'); writeFileSync(other, 'same')+ const observed = inspectHookFile(file)+ await expect(runHookPreparation([file], attempt => {+ fault.openAs = other+ return observed.replace('same', attempt)+ })).rejects.toThrow(/changed before sync/)+ expect(readFileSync(file, 'utf8')).toBe('same')+})+++it.each(['replacement', 'in-place edit'])('preserves the destination if the staging file suffers a %s during its flush', async change => {+ const { root, file } = fixture()+ writeFileSync(file, 'original')+ fault.onSync = fd => {+ if (fstatSync(fd).isDirectory()) return+ fault.onSync = undefined+ const temporary = join(root, readdirSync(root).find(name => name.startsWith('.harness-hook-'))!)+ if (change === 'replacement') {+ const other = join(root, 'other'); writeFileSync(other, 'foreign'); renameSync(other, temporary)+ } else writeFileSync(temporary, 'foreign')+ }+ await expect(prepared(file).replace('ours')).rejects.toThrow(/staging file changed/)+ expect(readFileSync(file, 'utf8')).toBe('original')+ if (change === 'replacement') {+ const temporary = readdirSync(root).find(name => name.startsWith('.harness-hook-'))!+ expect(readFileSync(join(root, temporary), 'utf8')).toBe('foreign')+ }+})++it.each([0o022, 0o077])('preserves an existing shared file mode under umask %s', async mask => {+ const { file } = fixture()+ writeFileSync(file, 'old'); chmodSync(file, 0o660)+ const previous = process.umask(mask)+ try { await prepared(file).replace('new') } finally { process.umask(previous) }+ expect(statSync(file).mode & 0o777).toBe(0o660)+})+++it('rechecks the deadline after the last filesystem observation before removal', async () => {+ const { file } = fixture()+ writeFileSync(file, 'owned')+ let now = 0, leafChecks = 0+ vi.spyOn(performance, 'now').mockImplementation(() => now)+ const observed = inspectHookFile(file)+ await expect(runHookPreparation([file], attempt => {+ fault.onStat = (path, options) => {+ if (path === file && options === undefined && ++leafChecks === 2) now = 20+ }+ return observed.remove(attempt)+ }, { timeoutMs: 10 })).rejects.toThrow(/expired/)+ expect(leafChecks).toBe(2)+ expect(readFileSync(file, 'utf8')).toBe('owned')+})diff --git a/cli/src/engines/kit/nativeHookFiles.ts b/cli/src/engines/kit/nativeHookFiles.tsnew file mode 100644index 000000000..ec183c8a9--- /dev/null+++ b/cli/src/engines/kit/nativeHookFiles.ts@@ -0,0 +1,388 @@+/** Hook preparation owns only a verified file version. Unknown contents are+ * never an empty configuration, and a completed write includes its directory. */+import { randomUUID } from 'node:crypto'+import { accessSync, closeSync, constants, fchmodSync, fstatSync, fsync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync, type BigIntStats } from 'node:fs'+import { basename, dirname, join } from 'node:path'+import { NativeEvidenceBudget } from './nativeEvidence.js'+import { NativePaths, verifyNativePathFacts } from './nativePaths.js'++export class HookPreparationHeld extends Error {+ constructor(detail: string) { super(`Hook preparation is waiting: ${detail}`); this.name = 'HookPreparationHeld' }+}+const version = (info: BigIntStats) => `${info.dev}:${info.ino}:${info.uid}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`+const fileIdentity = (info: BigIntStats) => `${info.dev}:${info.ino}:${info.uid}:${info.mode}`+export interface HookFilePublication { verify(): void }+export interface HookPreparationProof {+ files: readonly { file: string; target: string; stamp: string | null; facts: ReturnType<NativePaths['snapshot']> }[]+ current(): boolean+}+const MAX_BYTES = 1024 * 1024+const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'++async function syncDirectory(path: string, attempt: HookPreparationAttempt): Promise<void> {+ attempt.check()+ const expected = fileIdentity(lstatSync(path, { bigint: true }))+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)+ try {+ if (fileIdentity(fstatSync(fd, { bigint: true })) !== expected) throw new HookPreparationHeld('the directory changed before sync')+ await attempt.flush(fd)+ if (fileIdentity(lstatSync(path, { bigint: true })) !== expected) throw new HookPreparationHeld('the directory changed during sync')+ } finally { closeSync(fd) }+}++/** Retry must also confirm names created before an earlier parent sync failed.+ * Seeing an existing ancestor cannot prove that its publication was durable. */+async function syncDirectoryChain(path: string, attempt: HookPreparationAttempt): Promise<void> {+ for (let depth = 0; depth < 256; depth++) {+ attempt.check(); await syncDirectory(path, attempt)+ if (path === '/') return+ path = dirname(path)+ }+ throw new HookPreparationHeld('the directory sync exceeds its path limit')+}++/** Create only absent directories. The final leaf-to-root flush confirms every name. Existing+ * aliases are resolved before use; no directory is chmodded or replaced. */+function ensureDirectory(path: string, attempt: HookPreparationAttempt): void {+ attempt.check()+ try {+ if (!lstatSync(path).isDirectory()) throw new HookPreparationHeld('the configuration directory changed type')+ } catch (error) {+ if (!missing(error)) throw error+ ensureDirectory(dirname(path), attempt)+ attempt.verify(); attempt.check()+ try { mkdirSync(path) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }+ }+}++/** Resolve a missing descendant through a bounded, verified existing ancestor. */+function directoryPath(path: string): string {+ const suffix: string[] = []+ for (let depth = 0; depth < 256; depth++) {+ const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(path, true)+ if (route) {+ if (!route.info.isDirectory()) throw new HookPreparationHeld('the configuration parent is not a directory')+ return join(route.path, ...suffix)+ }+ suffix.unshift(basename(path)); path = dirname(path)+ }+ throw new HookPreparationHeld('the configuration directory exceeds its path limit')+}++/** The result is local to one preparation attempt, not a settings cache.+ * A changed alias, owner, file or contents invalidates the whole observation. */+export function inspectHookFile(file: string, defaultMode = 0o666) {+ const paths = new NativePaths(new NativeEvidenceBudget(250))+ const located = paths.resolveSync(file, true)+ const facts = paths.snapshot()+ const directory = directoryPath(dirname(file))+ const target = located?.path ?? join(directory, basename(file))+ let before: string | null = null, content: string | null = null, mode = defaultMode+ if (located) {+ const fd = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)+ try {+ const info = fstatSync(fd, { bigint: true })+ if (!info.isFile() || info.size > MAX_BYTES || info.dev !== located.info.dev || info.ino !== located.info.ino+ || (typeof process.getuid === 'function' && info.uid !== BigInt(process.getuid()))) {+ throw new HookPreparationHeld('the settings file is not a bounded file owned by this account')+ }+ before = version(info); mode = Number(info.mode & 0o777n)+ const bytes = Buffer.alloc(Number(info.size))+ let offset = 0+ for (let reads = 0; offset < bytes.length; reads++) {+ if (reads >= 128) throw new HookPreparationHeld('the settings read exceeded its operation limit')+ const read = readSync(fd, bytes, offset, bytes.length - offset, offset)+ if (!read) throw new HookPreparationHeld('the settings file changed while being read')+ offset += read+ }+ if (version(fstatSync(fd, { bigint: true })) !== before) throw new HookPreparationHeld('the settings file changed while being read')+ content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)+ } finally { closeSync(fd) }+ }+ const verify = () => {+ verifyNativePathFacts(facts.filter(fact => fact.identity !== null))+ // Another destination in the same preparation may have created a shared+ // absent directory. New ordinary directories are fine; a newly inserted+ // alias is not authority to write at a different location.+ const fresh = new NativePaths(new NativeEvidenceBudget(250))+ fresh.resolveSync(file, true)+ const knownAliases = new Set(facts.filter(fact => fact.alias).map(fact => fact.path))+ if (fresh.snapshot().some(fact => fact.alias && !knownAliases.has(fact.path))) {+ throw new HookPreparationHeld('the settings route gained an unconfirmed alias')+ }+ let now: BigIntStats | null+ try { now = lstatSync(target, { bigint: true }) } catch (error) { if (!missing(error)) throw error; now = null }+ if ((now ? version(now) : null) !== before) throw new HookPreparationHeld('the settings file changed before publication')+ }+ const prepare = (next: string | null) => {+ verify()+ if (next !== null && Buffer.byteLength(next) > MAX_BYTES) throw new HookPreparationHeld('the prepared settings exceed their size limit')+ if (next === null && content !== null && lstatSync(file).isSymbolicLink()) throw new HookPreparationHeld('the plugin entry is an alias')+ if (content === next) return+ if (content !== null && next !== null && (mode & 0o200) === 0) throw new HookPreparationHeld('the settings file is read-only')+ let parent = dirname(target)+ for (let depth = 0; depth < 256; depth++) {+ const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(parent, true)+ if (route) { accessSync(route.path, constants.W_OK | constants.X_OK); return }+ parent = dirname(parent)+ }+ throw new HookPreparationHeld('the configuration parent exceeds its path limit')+ }+ verify()+ return {+ content, directory, stamp: before,+ verify, prepare,+ async replace(next: string, attempt: HookPreparationAttempt): Promise<HookFilePublication> {+ attempt.verify(); prepare(next)+ if (content === next) {+ // A previous rename may have succeeded before directory sync failed.+ // Equality alone cannot turn that uncertainty into a durable success.+ const fd = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)+ try {+ if (version(fstatSync(fd, { bigint: true })) !== before) throw new HookPreparationHeld('the settings changed before sync')+ await attempt.flush(fd)+ if (version(fstatSync(fd, { bigint: true })) !== before) throw new HookPreparationHeld('the settings changed during sync')+ } finally { closeSync(fd) }+ await syncDirectoryChain(dirname(target), attempt)+ verify()+ return { verify }+ }+ // Resolve an existing ancestor before creating descendants; this preserves+ // relocated config homes without following a replaced alias at publish.+ const parent = directoryPath(dirname(target))+ ensureDirectory(parent, attempt)+ const actual = join(parent, target.slice(dirname(target).length + 1))+ // Creation invalidates absent-ancestor facts; capture the new route and+ // still require the exact old leaf (or its observed absence).+ const fresh = inspectHookFile(actual)+ if (fresh.content !== content) throw new HookPreparationHeld('the settings changed while their directory was prepared')+ const temporary = join(parent, `.harness-hook-${randomUUID()}.tmp`)+ let fd: number | undefined+ let stagedIdentity: string | undefined+ try {+ fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode)+ stagedIdentity = fileIdentity(fstatSync(fd, { bigint: true }))+ if (content !== null) { fchmodSync(fd, mode); stagedIdentity = fileIdentity(fstatSync(fd, { bigint: true })) }+ writeFileSync(fd, next)+ const stagedVersion = version(fstatSync(fd, { bigint: true }))+ await attempt.flush(fd)+ if (version(fstatSync(fd, { bigint: true })) !== stagedVersion || version(lstatSync(temporary, { bigint: true })) !== stagedVersion) {+ throw new HookPreparationHeld('the staging file changed before publication')+ }+ fresh.verify()+ // Retained existing ancestors/aliases must still name the original+ // route; only directories created above can replace an absent fact.+ verifyNativePathFacts(facts.filter(fact => fact.identity !== null))+ attempt.verify()+ renameSync(temporary, actual)+ const committed = inspectHookFile(file)+ if (committed.content !== next || committed.stamp !== version(fstatSync(fd, { bigint: true }))) {+ throw new HookPreparationHeld('the published settings changed before sync')+ }+ attempt.observe(file, committed.verify)+ await syncDirectoryChain(parent, attempt)+ attempt.verify()+ verifyNativePathFacts(facts.filter(fact => fact.identity !== null && fact.path !== target))+ const published = inspectHookFile(file)+ if (published.content !== next || published.stamp !== version(fstatSync(fd, { bigint: true }))) {+ throw new HookPreparationHeld('the published settings changed before confirmation')+ }+ return { verify: published.verify }+ } finally {+ try { if (fd !== undefined) closeSync(fd) } finally {+ try {+ if (fileIdentity(lstatSync(temporary, { bigint: true })) !== stagedIdentity) throw new HookPreparationHeld('the staging file changed before cleanup')+ unlinkSync(temporary)+ } catch (error) { if (!missing(error)) throw error }+ }+ }+ },+ async remove(attempt: HookPreparationAttempt): Promise<HookFilePublication> {+ attempt.verify(); prepare(null)+ // Removing a discovered entry never authorizes deleting another profile's+ // shared target. A leaf alias requires the owner to resolve that conflict.+ if (content !== null && lstatSync(file).isSymbolicLink()) throw new HookPreparationHeld('the plugin entry is an alias')+ attempt.check()+ if (content !== null) unlinkSync(target)+ attempt.observe(file, inspectHookFile(file).verify)+ let parent = dirname(target)+ for (let depth = 0; depth < 256; depth++) {+ const route = new NativePaths(new NativeEvidenceBudget(250)).resolveSync(parent, true)+ if (route) { await syncDirectoryChain(route.path, attempt); break }+ parent = dirname(parent)+ }+ verifyNativePathFacts(facts.filter(fact => fact.identity !== null && fact.path !== target))+ const removed = inspectHookFile(file)+ if (removed.content !== null) throw new HookPreparationHeld('the removed plugin was recreated before confirmation')+ return { verify: removed.verify }+ },+ }+}+++export interface HookPreparationAttempt {+ /** The original caller and deadline still authorize another effect. */+ check(): void+ /** All unfinished destinations and already-published outputs still match. */+ verify(): void+ observe(file: string, verify: () => void): void+ /** Own the descriptor until the actual syscall settles, even after a reply timeout. */+ flush(fd: number): Promise<void>+}+export interface HookPreparationOptions {+ /** Join only the same port, executable, command and complete destination set. */+ identity?: string+ current?(): boolean+ timeoutMs?: number+ /** Evidence retained by this launch; never a global success cache. */+ confirmed?(proof: HookPreparationProof): void+}+interface PendingPreparation { identity?: string; keys: string[]; revoke(): void; reply: Promise<unknown>; waiters: number; proof?: HookPreparationProof }+function preparationProof(files: readonly string[], verifyRoutes: () => void): HookPreparationProof {+ verifyRoutes()+ const confirmed = files.map(file => {+ const paths = new NativePaths(new NativeEvidenceBudget(250)), located = paths.resolveSync(file, true)+ const observed = inspectHookFile(file)+ return { file, target: located?.path ?? join(directoryPath(dirname(file)), basename(file)), stamp: observed.stamp, facts: paths.snapshot(), verify: observed.verify }+ })+ const proof = { files: confirmed.map(({ verify: _verify, ...file }) => file), current: () => {+ try { verifyRoutes(); for (const file of confirmed) file.verify(); return true } catch { return false }+ } }+ if (!proof.current()) throw new HookPreparationHeld('the prepared settings changed before acknowledgement')+ return proof+}+async function joinPreparation<T>(pending: PendingPreparation, options: HookPreparationOptions, verifyRoutes: () => void, files: readonly string[]): Promise<T> {+ const deadline = performance.now() + (options.timeoutMs ?? 5_000)+ verifyRoutes()+ if (options.current?.() === false) throw new HookPreparationHeld('the joining owner changed')+ if (pending.waiters >= 16) throw new HookPreparationHeld('the preparation waiters are occupied')+ pending.waiters+++ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const result = await Promise.race([pending.reply, new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new HookPreparationHeld('the joining preparation exceeded its deadline')), options.timeoutMs ?? 5_000)+ })])+ verifyRoutes()+ if (pending.proof && !pending.proof.current()) throw new HookPreparationHeld('the prepared settings changed before acknowledgement')+ // Joining shares the publication, not the caller's aliases. Retain this+ // caller's route all the way through the final pane guard.+ const proof = preparationProof(files, verifyRoutes)+ if (!pending.proof?.current() || proof.files.some(file => !pending.proof!.files.some(expected => expected.target === file.target && expected.stamp === file.stamp))) {+ throw new HookPreparationHeld('the prepared settings changed while their proof was captured')+ }+ if (performance.now() >= deadline) throw new HookPreparationHeld('the joining preparation exceeded its deadline')+ if (options.current?.() === false) throw new HookPreparationHeld('the joining owner changed')+ options.confirmed?.(proof)+ return result as T+ } finally { clearTimeout(timer); pending.waiters-- }+}+const pendingPreparations = new Set<PendingPreparation>()+const MAX_PREPARATIONS = 16+// fsync shares libuv's pool with native transcript reads. Leave capacity for+// those reads even when a disk confirmation never completes. Core starts with+// a fixed process environment; a one-thread pool cannot spare a disk writer.+const configuredThreads = Number.parseInt(process.env.UV_THREADPOOL_SIZE ?? '4', 10)+const MAX_FLUSHES = Math.max(0, Math.min(2, (Number.isFinite(configuredThreads) ? configuredThreads : 1) - 1))+let activeFlushes = 0+const flushQueue = new Set<() => void>()+function dispatchFlushes(): void {+ while (activeFlushes < MAX_FLUSHES && flushQueue.size) {+ const next = flushQueue.values().next().value!+ flushQueue.delete(next); next()+ }+}++/** Disk waits remain in eager core code. Reservations survive a timeout until+ * actual I/O settles: a late fsync must never use a closed, recycled descriptor. */+export async function runHookPreparation<T>(files: readonly string[], work: (attempt: HookPreparationAttempt) => Promise<T>, options: HookPreparationOptions = {}): Promise<T> {+ if (!files.length || files.length > 32) throw new HookPreparationHeld('the destination set exceeds its limit')+ const reservations = files.map(file => {+ const paths = new NativePaths(new NativeEvidenceBudget(250))+ const located = paths.resolveSync(file, true), facts = paths.snapshot()+ const key = located?.path ?? join(directoryPath(dirname(file)), basename(file))+ return { file, key, facts: facts.filter(fact => fact.identity !== null && fact.path !== located?.path),+ aliases: new Set(facts.filter(fact => fact.alias).map(fact => fact.path)) }+ })+ const verifyRoutes = () => {+ for (const { file, key, facts, aliases } of reservations) {+ if (facts.length) verifyNativePathFacts(facts)+ const fresh = new NativePaths(new NativeEvidenceBudget(250)), located = fresh.resolveSync(file, true)+ const target = located?.path ?? join(directoryPath(dirname(file)), basename(file))+ if (target !== key || fresh.snapshot().some(fact => fact.alias && !aliases.has(fact.path))) {+ throw new HookPreparationHeld('the reserved destination route changed')+ }+ }+ }+ const keys = [...new Set(reservations.map(reservation => reservation.key))].sort()+ const conflicts = [...pendingPreparations].filter(pending => pending.keys.some(key => keys.includes(key)))+ if (conflicts.length) {+ const same = conflicts.length === 1 && options.identity !== undefined && conflicts[0].identity === options.identity+ && JSON.stringify(conflicts[0].keys) === JSON.stringify(keys)+ if (same) return await joinPreparation<T>(conflicts[0], options, verifyRoutes, files)+ for (const pending of conflicts) pending.revoke()+ throw new HookPreparationHeld('another preparation still owns these destinations')+ }+ if (pendingPreparations.size >= MAX_PREPARATIONS) throw new HookPreparationHeld('the disk preparation slots are occupied')+ const deadline = performance.now() + (options.timeoutMs ?? 5_000)+ let revoked = false+ const cancellations = new Set<() => void>()+ const revoke = () => { revoked = true; for (const cancel of [...cancellations]) cancel() }+ const check = () => {+ if (revoked || performance.now() >= deadline || options.current?.() === false) {+ throw new HookPreparationHeld('the preparation expired or its owner changed')+ }+ }+ const observations = new Map<string, () => void>()+ const verify = () => { check(); verifyRoutes(); for (const inspect of observations.values()) inspect(); check() }+ const attempt: HookPreparationAttempt = {+ check, verify,+ observe: (file, inspect) => { observations.set(file, inspect) },+ async flush(fd) {+ check()+ if (!MAX_FLUSHES) throw new HookPreparationHeld('filesystem capacity cannot spare a disk confirmation')+ await new Promise<void>((done, reject) => {+ const cancel = () => {+ flushQueue.delete(start); cancellations.delete(cancel)+ reject(new HookPreparationHeld('the queued disk confirmation was revoked'))+ }+ const start = () => {+ cancellations.delete(cancel)+ try { check() } catch (error) { reject(error); return }+ activeFlushes+++ const settled = (error: Error | null) => {+ activeFlushes--; dispatchFlushes()+ if (error) reject(error); else done()+ }+ try { fsync(fd, settled) } catch (error) { settled(error as Error) }+ }+ cancellations.add(cancel); flushQueue.add(start); dispatchFlushes()+ })+ check()+ },+ }+ let timer: ReturnType<typeof setTimeout> | undefined+ const pending: PendingPreparation = { identity: options.identity, keys, revoke, reply: Promise.resolve(), waiters: 0 }+ pendingPreparations.add(pending)+ // Dispatch only after the reservation is visible. A timeout ends the caller's+ // wait; the finally below runs only when the actual work (and its FDs) finishes.+ const actual = Promise.resolve().then(() => {+ verify()+ for (const file of files) observations.set(file, inspectHookFile(file).verify)+ return work(attempt)+ }).then(result => {+ verify()+ pending.proof = preparationProof(files, verifyRoutes)+ // The proof may describe only the outputs just published, never peer bytes+ // that arrived between the last verification and its filesystem reads.+ verify()+ options.confirmed?.(pending.proof)+ return result+ }).finally(() => {+ pendingPreparations.delete(pending)+ clearTimeout(timer)+ })+ pending.reply = Promise.race([actual, new Promise<never>((_, reject) => {+ timer = setTimeout(() => { revoke(); reject(new HookPreparationHeld('disk confirmation exceeded its deadline')) }, options.timeoutMs ?? 5_000)+ })])+ return await pending.reply as T+}diff --git a/cli/src/engines/kit/nativeHookLiterals.spec.ts b/cli/src/engines/kit/nativeHookLiterals.spec.tsindex e8edb3859..e6de322fa 100644--- a/cli/src/engines/kit/nativeHookLiterals.spec.ts+++ b/cli/src/engines/kit/nativeHookLiterals.spec.ts@@ -8,20 +8,20 @@ import { installNativePlugin } from './nativePlugin.js'let root = ''afterEach(() => { if (root) rmSync(root, { recursive: true, force: true }); root = ''; vi.restoreAllMocks() })-it('reports a JSON settings destination verbatim', () => {+it('reports a JSON settings destination verbatim', async () => {root = mkdtempSync(join(tmpdir(), 'native-hook-literals-'))const file = join(root, '$&-${credential}.json')const log = vi.spyOn(console, 'log').mockImplementation(() => {})- installNativeHookSettings({ file, engine: 'copilot', schema: 'file', version: 1, eventFlag: '--copilot-event', events: ['sessionStart'],+ await installNativeHookSettings({ file, engine: 'copilot', schema: 'file', version: 1, eventFlag: '--copilot-event', events: ['sessionStart'],messages: { current: 'current', installed: 'installed {file}', failed: 'failed' } }, 19473)expect(JSON.parse(readFileSync(file, 'utf8')).hooks.sessionStart[0].command).toContain('--port 19473')expect(log).toHaveBeenCalledWith(`installed ${file}`)})-it('renders plugin argument contents once and reports its destination verbatim', () => {+it('renders plugin argument contents once and reports its destination verbatim', async () => {root = mkdtempSync(join(tmpdir(), 'native-hook-literals-'))const file = join(root, '$&-${version}.js')const log = vi.spyOn(console, 'log').mockImplementation(() => {})- installNativePlugin({ file, template: ['credential=', { argument: 'credential' }, ';version=', { argument: 'version' }],+ await installNativePlugin({ file, template: ['credential=', { argument: 'credential' }, ';version=', { argument: 'version' }],messages: { current: 'current', installed: 'installed {file}', after: [], failed: 'failed' } },{ credential: '${version}$&', version: 'fixture', port: '19473' })expect(readFileSync(file, 'utf8')).toBe('credential=${version}$&;version=fixture')diff --git a/cli/src/engines/kit/nativeHookSettings.ts b/cli/src/engines/kit/nativeHookSettings.tsindex b410ae3be..5895dfdc8 100644--- a/cli/src/engines/kit/nativeHookSettings.ts+++ b/cli/src/engines/kit/nativeHookSettings.ts@@ -1,6 +1,6 @@-/** Eager mechanics for the native JSON hook schemas. Each engine declares its events and ownership rules. */-import { existsSync, readFileSync } from 'node:fs'-import { command, isOurs, writeJsonAtomic, type Settings, type HookBlock } from './notifyHooks.js'+/** Eager mechanics for native JSON hook schemas; unreadable settings are never empty settings. */+import { command, isOurs, isManagedHookCommand, foreignHookBlocks, type Settings, type HookBlock } from './notifyHooks.js'+import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationOptions } from './nativeHookFiles.js'export interface NativeHookSettings {file: string@@ -16,78 +16,68 @@ export interface NativeHookSettings {}type Entry = { type?: string; command: string; timeout?: number; failClosed?: boolean }type EntrySettings = { version?: number; hooks?: Record<string, Entry[]> } & Record<string, unknown>-type NamedSettings = Record<string, Record<string, Entry[]> | unknown>-const UNREADABLE = Symbol('unreadable')-function readSettings(rule: NativeHookSettings, file: string): unknown | typeof UNREADABLE {- if (!existsSync(file)) return {}- try { return JSON.parse(readFileSync(file, 'utf-8')) } catch {- for (const line of rule.messages.malformed ?? []) console.error(line.replace('{file}', () => file))- return UNREADABLE+const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)+const ours = (entry: Entry) => isManagedHookCommand(entry?.command)+function entries(value: unknown): Entry[] {+ if (value === undefined) return []+ if (!Array.isArray(value)) throw new HookPreparationHeld('a hook event is not a list')+ if (value.some(entry => !object(entry) || (entry.command !== undefined && typeof entry.command !== 'string'))) {+ throw new HookPreparationHeld('a hook entry has an unconfirmed shape')}-}-function writeSettings(rule: NativeHookSettings, file: string, settings: unknown): void {- try {- writeJsonAtomic(file, settings)- console.log(rule.messages.installed.replace('{file}', () => file))- if (rule.messages.after) console.log(rule.messages.after)- } catch (err) { console.error(rule.messages.failed, err) }+ return value}-export function installNativeHookSettings(rule: NativeHookSettings, port: number): void {- const file = rule.file- if (rule.schema === 'file') {- const cmd = command(port, rule.engine)- const settings = { version: rule.version!, hooks: Object.fromEntries(rule.events.map(event =>- [event, [{ type: 'command', command: `${cmd} ${rule.eventFlag} ${event}` }]])) }- let existing: unknown = null- if (existsSync(file)) { try { existing = JSON.parse(readFileSync(file, 'utf-8')) } catch { existing = null } }- if (JSON.stringify(existing) === JSON.stringify(settings)) { console.log(rule.messages.current); return }- writeSettings(rule, file, settings)- return- }- const parsed = readSettings(rule, file)- if (parsed === UNREADABLE) return- if (rule.schema === 'named') {- const settings: NamedSettings = !parsed || typeof parsed !== 'object' || Array.isArray(parsed) ? {} : parsed as NamedSettings- const cmd = command(port, rule.engine)- const block = Object.fromEntries(rule.events.map(event => [event,- [{ type: 'command', command: `${cmd} ${rule.eventFlag} ${event}`, timeout: rule.timeout }]]))- if (JSON.stringify(settings[rule.block!]) === JSON.stringify(block)) { console.log(rule.messages.current); return }- settings[rule.block!] = block- writeSettings(rule, file, settings)- return- }- if (rule.schema === 'entries') {- const settings = parsed as EntrySettings- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}- if (typeof settings.version !== 'number') settings.version = rule.version- const cmd = command(port, rule.engine)+export async function installNativeHookSettings(rule: NativeHookSettings, port: number, options: HookPreparationOptions = {}): Promise<boolean> {+ const cmd = command(port, rule.engine)+ try { return await runHookPreparation([rule.file], async attempt => {+ const observed = inspectHookFile(rule.file)+ const parsed: unknown = observed.content === null ? {} : JSON.parse(observed.content)+ if (!object(parsed)) throw new HookPreparationHeld('the settings do not have the declared object shape')let changed = false- for (const event of rule.events) {- const entries = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []- const foreign = entries.filter(entry => !entry?.command?.includes('notify.mjs'))- const ours = entries.filter(entry => entry?.command?.includes('notify.mjs'))- const canonical: Entry = { command: cmd, failClosed: rule.failClosed }- if (ours.length !== 1 || ours[0]?.command !== cmd || ours[0]?.failClosed !== rule.failClosed) changed = true- settings.hooks[event] = [...foreign, canonical]+ if (rule.schema === 'named') {+ const prior = parsed[rule.block!]+ if (prior !== undefined && !object(prior)) throw new HookPreparationHeld('the named hooks block is not an object')+ const block = { ...(prior as Record<string, unknown> | undefined) }+ for (const event of rule.events) {+ const list = entries(block[event])+ block[event] = [...list.filter(entry => !ours(entry)),+ { type: 'command', command: `${cmd} ${rule.eventFlag} ${event}`, timeout: rule.timeout }]+ }+ changed = JSON.stringify(prior) !== JSON.stringify(block)+ parsed[rule.block!] = block+ } else {+ if (rule.schema === 'file' && parsed.version === undefined) { parsed.version = rule.version; changed = true }+ if (parsed.hooks !== undefined && !object(parsed.hooks)) throw new HookPreparationHeld('the hooks member is not an object')+ const hooks = (parsed.hooks ??= {}) as Record<string, unknown>+ if (rule.schema === 'entries' || rule.schema === 'file') {+ const settings = parsed as EntrySettings+ if (settings.version === undefined) { settings.version = rule.version; changed = true }+ for (const event of rule.events) {+ const list = entries(hooks[event]), owned = list.filter(ours)+ const canonical: Entry = rule.schema === 'file'+ ? { type: 'command', command: `${cmd} ${rule.eventFlag} ${event}` }+ : { command: cmd, failClosed: rule.failClosed }+ if (owned.length !== 1 || JSON.stringify(owned[0]) !== JSON.stringify(canonical)) changed = true+ hooks[event] = [...list.filter(entry => !ours(entry)), canonical]+ }+ } else {+ const settings = parsed as Settings+ for (const event of rule.events) {+ const blocks = entries(hooks[event]) as unknown as HookBlock[]+ const owned = blocks.filter(isOurs)+ if (owned.length !== 1 || owned[0]?.hooks?.[0]?.command !== cmd) changed = true+ settings.hooks![event] = [...foreignHookBlocks(blocks), { hooks: [{ type: 'command', command: cmd, timeout: rule.timeout }] }]+ }+ }}- if (!changed) { console.log(rule.messages.current); return }- writeSettings(rule, file, settings)- return- }- const settings = parsed as Settings- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}- const cmd = command(port, rule.engine)- let changed = false- for (const event of rule.events) {- const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []- const foreign = blocks.filter(block => !isOurs(block))- const ours = blocks.filter(isOurs)- const canonical: HookBlock = { hooks: [{ type: 'command', command: cmd, timeout: rule.timeout }] }- if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true- settings.hooks[event] = [...foreign, canonical]+ const published = await observed.replace(changed ? JSON.stringify(parsed, null, 2) + '\n' : observed.content!, attempt)+ published.verify()+ console.log(changed ? rule.messages.installed.replace('{file}', () => rule.file) : rule.messages.current)+ if (changed && rule.messages.after) console.log(rule.messages.after)+ return true+ }, { ...options, identity: JSON.stringify([rule, port, cmd]) }) } catch (error) {+ console.error(rule.messages.failed, error)+ return false}- if (!changed) { console.log(rule.messages.current); return }- writeSettings(rule, file, settings)}diff --git a/cli/src/engines/kit/nativeHookYaml.ts b/cli/src/engines/kit/nativeHookYaml.tsindex 9ee9d9956..137449904 100644--- a/cli/src/engines/kit/nativeHookYaml.ts+++ b/cli/src/engines/kit/nativeHookYaml.ts@@ -1,7 +1,9 @@/** A managed YAML hook block and exact-command approvals, applied from eager engine declarations. */-import { readFileSync, writeFileSync } from 'node:fs'+import { isMap, isScalar, Lexer, parseDocument } from 'yaml'import { basename, join } from 'node:path'-import { writeJsonAtomic } from './notifyHooks.js'+import { HookPreparationHeld, inspectHookFile, type HookFilePublication, runHookPreparation, type HookPreparationAttempt, type HookPreparationOptions } from './nativeHookFiles.js'+import { NativeEvidenceBudget } from './nativeEvidence.js'+import { isManagedHookCommand } from './notifyHooks.js'import { nativeHookHomes, type NativeHookHomes } from './nativeHookHomes.js'export interface NativeYamlHooks {@@ -19,13 +21,13 @@ function message(template: string, values: Record<string, string>): string {return template.replace(/\{(file|removed)\}/g, (_, key: string) => values[key])}-function allowlistHook(rule: NativeYamlHooks, cmd: string, home: string): void {+function prepareAllowlist(rule: NativeYamlHooks, cmd: string, home: string): (attempt: HookPreparationAttempt) => Promise<HookFilePublication> {const allowlistPath = join(home, rule.allowlist)- let data: { approvals?: Array<{ event?: string; command?: string }> } = { approvals: [] }- try {- const parsed = JSON.parse(readFileSync(allowlistPath, 'utf-8')) as typeof data- if (parsed && Array.isArray(parsed.approvals)) data = parsed- } catch { /* absent or unreadable → start from an empty skeleton */ }+ const observed = inspectHookFile(allowlistPath)+ const data = (observed.content === null ? { approvals: [] } : JSON.parse(observed.content)) as { approvals?: Array<{ event?: string; command?: string }> }+ if (!data || typeof data !== 'object' || Array.isArray(data) || (data.approvals !== undefined && !Array.isArray(data.approvals))) {+ throw new HookPreparationHeld('the hook approvals are not a readable list')+ }const previous = data.approvals ?? []// Drop OUR stale approvals before adding the current one. Each command change — a new port, a moved// install, a new Node runtime — otherwise leaves five dead entries here forever, and the entry is@@ -33,7 +35,7 @@ function allowlistHook(rule: NativeYamlHooks, cmd: string, home: string): void {// are somebody else's business and are copied through untouched.const isOurStaleApproval = (a: { command?: string }) =>typeof a?.command === 'string' &&- rule.ownership.every(fragment => a.command!.includes(fragment)) &&+ isManagedHookCommand(a.command) && rule.ownership.every(fragment => a.command!.includes(fragment)) &&a.command !== cmdconst approvals = previous.filter((a) => !isOurStaleApproval(a))let changed = approvals.length !== previous.length@@ -43,8 +45,9 @@ function allowlistHook(rule: NativeYamlHooks, cmd: string, home: string): void {approvals.push({ event, command: cmd })changed = true}- if (!changed) return- writeJsonAtomic(allowlistPath, { ...data, approvals })+ const next = changed ? JSON.stringify({ ...data, approvals }, null, 2) + '\n' : observed.content!+ observed.prepare(next)+ return attempt => observed.replace(next, attempt)}function hooksBlock(rule: NativeYamlHooks, cmd: string): string {@@ -57,7 +60,14 @@ function hooksBlock(rule: NativeYamlHooks, cmd: string): string {/** True for a top-level `hooks:` mapping that is ours (every command runs our notify.mjs for this engine). */function isOwnedHooksBody(rule: NativeYamlHooks, body: string[]): boolean {const commands = body.filter((line) => /^\s*- command:/.test(line))- return commands.length > 0 && commands.every((line) => rule.ownership.every(fragment => line.includes(fragment)))+ return commands.length > 0 && commands.every(line => {+ try {+ const cmd: unknown = JSON.parse(line.trim().slice('- command:'.length))+ return isManagedHookCommand(cmd) && rule.ownership.every(fragment => (cmd as string).includes(fragment))+ } catch { return false }+ })+ && body.every(line => !line.trim() || /^\s+- command:/.test(line) || /^\s+timeout:\s+\d+\s*$/.test(line)+ || rule.events.some(event => line === ` ${event}:`))}/**@@ -65,7 +75,7 @@ function isOwnedHooksBody(rule: NativeYamlHooks, body: string[]): boolean {* left behind by the earlier buggy rewrite (identified by its notify.mjs commands). Returns the cleaned* document plus whether a FOREIGN `hooks:` key survives — the caller must not touch the file then.*/-function stripOwnedBlocks(rule: NativeYamlHooks, config: string): { cleaned: string; foreignHooks: boolean; removed: number } {+function stripOwnedBlocks(rule: NativeYamlHooks, config: string, hookLines: ReadonlySet<number>): { cleaned: string; foreignHooks: boolean; removed: number } {const lines = config.split('\n')const out: string[] = []let removed = 0@@ -73,15 +83,21 @@ function stripOwnedBlocks(rule: NativeYamlHooks, config: string): { cleaned: strfor (let i = 0; i < lines.length; i++) {const line = lines[i]- if (line.trim() === rule.begin) {- // Skip through the END marker (or, for a truncated block, to the end of the mapping).+ if (line === rule.begin && hookLines.has(i + 1)) {+ // A truncated marker gives no evidence about where the person's remaining+ // configuration begins. Keep the whole document until it can be verified.let j = i + 1while (j < lines.length && lines[j].trim() !== rule.end) j++- i = j < lines.length ? j : lines.length - 1+ if (j === lines.length) throw new HookPreparationHeld('the managed YAML block has no closing marker')+ if (lines[i + 1] !== 'hooks:' || !isOwnedHooksBody(rule, lines.slice(i + 2, j))) {+ throw new HookPreparationHeld('the managed YAML block contains unconfirmed configuration')+ }+ i = jremoved++continue}- if (/^hooks:\s*$/.test(line)) {+ if (hookLines.has(i) && !/^hooks:\s*$/.test(line)) foreignHooks = true+ if (hookLines.has(i) && /^hooks:\s*$/.test(line)) {let j = i + 1while (j < lines.length && (lines[j].startsWith(' ') || lines[j].startsWith('\t') || lines[j].trim() === '')) j++const body = lines.slice(i + 1, j)@@ -96,46 +112,89 @@ function stripOwnedBlocks(rule: NativeYamlHooks, config: string): { cleaned: str}/** Installs only homes with a config, each with its own command and allowlist. */-export function installNativeYamlHooks(rule: NativeYamlHooks, commandForHome: (home: string) => string): void {- for (const home of nativeHookHomes(rule.homes, rule.home)) installIn(rule, commandForHome(home), home)+export async function installNativeYamlHooks(rule: NativeYamlHooks, commandForHome: (home: string) => string, selectedHome?: string, options: HookPreparationOptions = {}): Promise<boolean> {+ const homes = selectedHome ? [selectedHome] : nativeHookHomes(rule.homes, rule.home)+ let next = 0, installed = true+ const worker = async () => {+ while (next < homes.length) {+ const home = homes[next++]+ if (!await installIn(rule, commandForHome(home), home, options)) installed = false+ }+ }+ // The declared catalog includes up to 64 profiles. Starting them all at once+ // starved the same tail behind the preparation pool on every healthy retry.+ await Promise.all(Array.from({ length: Math.min(4, homes.length) }, worker))+ return installed}-function installIn(rule: NativeYamlHooks, cmd: string, home: string): void {+async function installIn(rule: NativeYamlHooks, cmd: string, home: string, options: HookPreparationOptions): Promise<boolean> {const configPath = join(home, rule.homes.file)- let config = ''- try {- config = readFileSync(configPath, 'utf-8')- } catch {- if (home === rule.home) console.log(message(rule.messages.missing, { file: configPath }))- return- }+ try { return await runHookPreparation([configPath, join(home, rule.allowlist)], async attempt => {+ const observed = inspectHookFile(configPath), config = observed.content+ if (config === null) {+ if (home === rule.home) console.log(message(rule.messages.missing, { file: configPath }))+ return false+ }- const { cleaned, foreignHooks, removed } = stripOwnedBlocks(rule, config)- if (foreignHooks) {- console.error(message(rule.messages.foreign, { file: configPath }))- console.error(rule.messages.manual)- for (const event of rule.events) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: ${rule.timeout} }]`)- return- }+ const budget = new NativeEvidenceBudget(250)+ let tokens = 0+ for (const _token of new Lexer().lex(config)) {+ budget.step()+ if (++tokens > 4096) throw new HookPreparationHeld('the YAML configuration exceeds its structure limit')+ }+ // Parse before examining markers: marker-like text inside a quoted scalar+ // is somebody else's configuration. Duplicate managed mappings from older+ // installs are removable, but every remaining key must be unique.+ const original = parseDocument(config, { strict: true, uniqueKeys: false, prettyErrors: false })+ if (original.errors.length || original.warnings.length || (original.contents !== null && !isMap(original.contents))) {+ throw new HookPreparationHeld('the YAML configuration is not a complete mapping')+ }+ const hookLines = new Set<number>()+ if (isMap(original.contents)) for (const pair of original.contents.items) {+ if (isScalar(pair.key) && pair.key.value === 'hooks' && pair.key.range) {+ hookLines.add(config.slice(0, pair.key.range[0]).split('\n').length - 1)+ }+ }+ const { cleaned, foreignHooks, removed } = stripOwnedBlocks(rule, config, hookLines)+ const document = parseDocument(cleaned, { strict: true, uniqueKeys: true, prettyErrors: false })+ budget.step()+ if (document.errors.length || document.warnings.length || (document.contents !== null && !isMap(document.contents))) {+ throw new HookPreparationHeld('the YAML configuration is not a complete mapping')+ }+ if (foreignHooks || document.has('hooks')) {+ console.error(message(rule.messages.foreign, { file: configPath }))+ console.error(rule.messages.manual)+ for (const event of rule.events) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: ${rule.timeout} }]`)+ return false+ }- const next = `${cleaned.replace(/\s*$/, '')}\n${hooksBlock(rule, cmd)}`- if (next === config) {- allowlistHook(rule, cmd, home) // keep the allowlist in sync even when the block is current- console.log(rule.messages.current + (home === rule.home ? '' : ` (${basename(home)})`))- return- }+ const next = `${cleaned.replace(/\s*$/, '')}\n${hooksBlock(rule, cmd)}`+ const combined = parseDocument(next, { strict: true, uniqueKeys: true, prettyErrors: false })+ budget.step()+ if (combined.errors.length || combined.warnings.length) throw new HookPreparationHeld('the managed hooks cannot be appended to this YAML document')+ // Inspect approvals before writing YAML. A malformed or unreadable allowlist+ // must never be replaced with an empty one, nor leave half an installation.+ observed.prepare(next)+ const approve = prepareAllowlist(rule, cmd, home)+ if (next === config) {+ const installed = await observed.replace(config, attempt), approved = await approve(attempt)+ installed.verify(); approved.verify()+ console.log(rule.messages.current + (home === rule.home ? '' : ` (${basename(home)})`))+ return true+ }- try {- writeFileSync(configPath, next)- allowlistHook(rule, cmd, home)+ const installed = await observed.replace(next, attempt), approved = await approve(attempt)+ installed.verify(); approved.verify()console.log(removed > 1? message(rule.messages.collapsed, { removed: String(removed), file: configPath }): message(rule.messages.installed, { file: configPath }),)console.log(rule.messages.after)- } catch (err) {+ return true+ }, { ...options, identity: JSON.stringify([rule, cmd, home]) }) } catch (err) {console.error(rule.messages.failed, err)+ return false}}diff --git a/cli/src/engines/kit/nativePlugin.ts b/cli/src/engines/kit/nativePlugin.tsindex 21cf1d2fd..a328262d3 100644--- a/cli/src/engines/kit/nativePlugin.ts+++ b/cli/src/engines/kit/nativePlugin.ts@@ -1,6 +1,6 @@/** Native plugin bytes are engine declarations. Installing them never loads an interpreter. */-import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, unlinkSync } from 'node:fs'-import { dirname } from 'node:path'+import { mkdirSync } from 'node:fs'+import { HookPreparationHeld, inspectHookFile, type HookFilePublication, runHookPreparation, type HookPreparationAttempt, type HookPreparationOptions } from './nativeHookFiles.js'export interface NativePlugin {file: string@@ -9,30 +9,44 @@ export interface NativePlugin {messages: { current: string; installed: string; after: readonly string[]; failed: string }}export interface NativePluginValues { port: string; credential: string; version: string }+export interface PreparedNativePlugin { verify(): void; commit(attempt: HookPreparationAttempt): Promise<HookFilePublication> }/** Joining parts once keeps a path's contents literal, even when it resembles a template argument. */export function nativePluginSource(rule: NativePlugin, values: NativePluginValues): string {return rule.template.map(part => typeof part === 'string' ? part : values[part.argument]).join('')}-export function installNativePlugin(rule: NativePlugin, values: NativePluginValues): void {- const source = nativePluginSource(rule, values)- const file = rule.file- try {- if (existsSync(file) && readFileSync(file, 'utf-8') === source) {- console.log(rule.messages.current)- return+/** Observe every destination before a multi-file installation changes any of them. */+export function prepareNativePlugin(rule: NativePlugin, values: NativePluginValues): PreparedNativePlugin {+ const source = nativePluginSource(rule, values), observed = inspectHookFile(rule.file)+ const current = observed.content === source+ // The generated first line declares this managed artifact's engine and owner.+ // An occupied path without that declaration belongs to its author.+ const prefix = source.slice(0, source.indexOf('\n') + 1)+ if (!current && observed.content !== null && (!prefix || !observed.content.startsWith(prefix))) {+ throw new HookPreparationHeld('the plugin path contains another author’s file')+ }+ observed.prepare(source)+ return { verify: observed.verify, commit: async attempt => {+ attempt.verify()+ observed.verify()+ for (const directory of current ? [] : rule.directories ?? []) {+ attempt.verify(); attempt.check()+ mkdirSync(directory.path, { recursive: true, mode: directory.mode })}- } catch { /* unreadable — rewrite it */ }- try {- mkdirSync(dirname(file), { recursive: true })- for (const directory of rule.directories ?? []) mkdirSync(directory.path, { recursive: true, mode: directory.mode })- const tmp = `${file}.${process.pid}.tmp`- writeFileSync(tmp, source)- renameSync(tmp, file)- console.log(rule.messages.installed.replace('{file}', () => file))- for (const line of rule.messages.after) console.log(line)- } catch (err) { console.error(rule.messages.failed, err) }+ const published = await observed.replace(source, attempt)+ console.log(current ? rule.messages.current : rule.messages.installed.replace('{file}', () => rule.file))+ if (!current) for (const line of rule.messages.after) console.log(line)+ return published+ } }+}++export async function installNativePlugin(rule: NativePlugin, values: NativePluginValues, options: HookPreparationOptions = {}): Promise<boolean> {+ try { return await runHookPreparation([rule.file], async attempt => {+ const published = await prepareNativePlugin(rule, values).commit(attempt)+ published.verify(); return true+ }, { ...options, identity: nativePluginSource(rule, values) }) }+ catch (err) { console.error(rule.messages.failed, err); return false }}export interface NativePluginRemoval {@@ -42,15 +56,26 @@ export interface NativePluginRemoval {removed: stringfailed: string}-/** The engine may still discover an older plugin with an incompatible API. Remove only our artifact. */-export function removeNativePlugin(rule: NativePluginRemoval): void {- try {- const source = readFileSync(rule.file, 'utf8')- if (source.startsWith(rule.prefix) && source.includes(rule.contains)) {- unlinkSync(rule.file)- console.log(rule.removed)- }- } catch (err) {- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') console.error(rule.failed, err)++export function prepareNativePluginRemoval(rule: NativePluginRemoval): PreparedNativePlugin {+ const observed = inspectHookFile(rule.file), source = observed.content+ if (source !== null && !(source.startsWith(rule.prefix) && source.includes(rule.contains))) {+ throw new HookPreparationHeld('the incompatible plugin path contains another author’s file')}+ observed.prepare(null)+ return { verify: observed.verify, commit: async attempt => {+ attempt.check()+ const removed = await observed.remove(attempt)+ if (source !== null) console.log(rule.removed)+ return removed+ } }+}++/** The engine may discover an older incompatible plugin. Remove only our artifact. */+export async function removeNativePlugin(rule: NativePluginRemoval): Promise<boolean> {+ try { return await runHookPreparation([rule.file], async attempt => {+ const removed = await prepareNativePluginRemoval(rule).commit(attempt)+ removed.verify(); return true+ }, { identity: JSON.stringify(rule) }) }+ catch (err) { console.error(rule.failed, err); return false }}diff --git a/cli/src/engines/kit/nativeVersion.ts b/cli/src/engines/kit/nativeVersion.tsindex 0424ee48a..33c0d3f19 100644--- a/cli/src/engines/kit/nativeVersion.ts+++ b/cli/src/engines/kit/nativeVersion.ts@@ -6,13 +6,25 @@ import { resolveBinaryOnPath } from '../../lib/binaryOnPath.js'export interface VersionRule { output: RegExp; args: readonly string[]; timeoutMs: number }export interface VersionProbe { identity(): string | null; read(): string | Promise<string> }+export interface NativeVersionProbe extends VersionProbe { command(): string | null }+export interface NativeExecutableSnapshot {+ command: string+ identity: string+ current(): boolean+}++/** Retain the file used by the probe through later preparation and dispatch. */+export function executableSnapshot(probe: NativeVersionProbe): NativeExecutableSnapshot | null {+ const command = probe.command(), identity = probe.identity()+ return command && identity ? { command, identity, current: () => probe.identity() === identity } : null+}export function parseMajor(rule: VersionRule, output: string): number | null {const match = rule.output.exec(output)return match ? Number(match[1]) : null}-export function nativeVersionProbe(rule: VersionRule, binary: () => string): VersionProbe {+export function nativeVersionProbe(rule: VersionRule, binary: () => string): NativeVersionProbe {// One attempt resolves one command. Previously identity() and read() resolved// independently, so a PATH/config change could cache B's answer under A's key.let selected: string | null | undefined@@ -24,13 +36,14 @@ export function nativeVersionProbe(rule: VersionRule, binary: () => string): Verreturn selected}return {+ command: path,identity: () => {const file = path()if (!file) return nulltry {- const target = realpathSync(file), info = statSync(file)+ const target = realpathSync(file), info = statSync(file, { bigint: true })if (!info.isFile()) return null- return `${file}:${target}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`+ return `${file}:${target}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`} catch { return null }},read: () => new Promise<string>((done, failed) => {@@ -44,7 +57,8 @@ export function nativeVersionProbe(rule: VersionRule, binary: () => string): Ver}}-/** Compatibility behavior: one answer per installed file; absent files have no cache key. */+/** Compatibility behavior: one answer per installed file; absent files have no cache key.+ * Whole-launch preparation replaces this legacy cache policy with its snapshot. */const publishing = new WeakMap<Map<string, number | null>, Map<string, object>>()export async function majorVersion(rule: VersionRule, probe: VersionProbe, memo: Map<string, number | null>): Promise<number | null> {const identity = probe.identity()diff --git a/cli/src/engines/kit/notifyHooks.spec.ts b/cli/src/engines/kit/notifyHooks.spec.tsnew file mode 100644index 000000000..58115bcd9--- /dev/null+++ b/cli/src/engines/kit/notifyHooks.spec.ts@@ -0,0 +1,25 @@+import { expect, it } from 'vitest'+import { isManagedHookCommand } from './notifyHooks.js'++it.each([+ "node '/fixture/notify.mjs' --port 19473 --data-dir '/fixture/harness'",+ "'/fixture/node' '/fixture/has space/notify.mjs' --data-dir '/fixture/harness' --port 19473 --engine codex",+ "'/fixture/node' '/fixture/home/.harness/cli/hook/notify.mjs' 19473 codex",+ "node '/fixture/notify.mjs' --port 19473 --data-dir '/fixture/harness' --engine copilot --copilot-event sessionStart",+])('recognizes a literal managed hook protocol: %s', command => {+ expect(isManagedHookCommand(command)).toBe(true)+})++it.each([+ undefined, 42, '', 'node /project/notify.mjs',+ 'node /project/notify.mjs --port 19473',+ 'echo node /fixture/notify.mjs --port 19473 --data-dir /fixture/harness',+ 'node /fixture/notify.mjs --port 19473 --data-dir /fixture/harness; echo foreign',+ 'node /fixture/notify.mjs --port 19473 --data-dir /fixture/harness --data-dir /other',+ 'node /fixture/notify.mjs --port 19473 --data-dir',+ 'node /fixture/notify.mjs --port 19473 --data-dir relative',+ 'node /fixture/notify.mjs --port 19473 --data-dir "$HOME"',+ "node '/unterminated/notify.mjs --port 19473 --data-dir /fixture/harness",+])('does not claim a foreign or nonliteral command: %s', command => {+ expect(isManagedHookCommand(command)).toBe(false)+})diff --git a/cli/src/engines/kit/notifyHooks.ts b/cli/src/engines/kit/notifyHooks.tsindex 3ecd360e4..1ffdf25e1 100644--- a/cli/src/engines/kit/notifyHooks.ts+++ b/cli/src/engines/kit/notifyHooks.ts@@ -1,9 +1,10 @@/** The notify.mjs command and JSON merge primitives shared by shell-hook engines. */-import { existsSync, mkdirSync, writeFileSync, renameSync } from 'node:fs'-import { dirname, join } from 'node:path'+import { existsSync } from 'node:fs'+import { basename, dirname, isAbsolute, join } from 'node:path'import { fileURLToPath } from 'node:url'import { env } from '../../config/env.js'import { managedNodePath } from '../../lib/nodeRuntime.js'+import { HookPreparationHeld } from './nativeHookFiles.js'import { cursorDataDir } from '../cursor/contract.js'// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):@@ -65,14 +66,62 @@ export function command(].join(' ')}-/** True if a block already points at our notify.mjs script (any path — robust across layout/version). */+/** Accept only a literal Node invocation with Harness's protocol arguments.+ * A foreign script sharing the notify.mjs basename is not ours to remove. */+export function isManagedHookCommand(value: unknown): boolean {+ if (typeof value !== 'string' || value.length > 64 * 1024) return false+ const args: string[] = []+ let word = '', active = false, quote = ''+ for (let index = 0; index < value.length; index++) {+ const char = value[index]+ if (quote) {+ if (char === quote) { quote = ''; continue }+ if (quote === '"' && /[$`\\]/.test(char)) return false+ word += char; continue+ }+ if (char === "'" || char === '"') { quote = char; active = true; continue }+ if (char === '\\') {+ if (++index === value.length || /[\r\n]/.test(value[index])) return false+ word += value[index]; active = true; continue+ }+ if (/[\r\n]/.test(char)) return false+ if (/[ \t]/.test(char)) { if (active) { args.push(word); word = ''; active = false }; continue }+ if (/[;&|<>$`(){}*?\[\]~#]/.test(char)) return false+ word += char; active = true+ }+ if (quote) return false+ if (active) args.push(word)+ if (!/^(?:node|nodejs)(?:\.exe)?$/.test(basename(args[0] ?? '')) || !isAbsolute(args[1] ?? '') || basename(args[1] ?? '') !== 'notify.mjs') return false+ // The original positional protocol was installed only under Harness's own+ // CLI directory. Later commands identify the data root explicitly.+ if (args.length === 4 && /\/\.harness\/cli\/(?:hook\/)?notify\.mjs$/.test(args[1])+ && /^\d+$/.test(args[2]) && /^(?:claude|codex)$/.test(args[3])) return true+ const flags = new Map<string, string>()+ for (let index = 2; index < args.length; index += 2) {+ const key = args[index], value = args[index + 1]+ if (!/^--(?:port|data-dir|claude-projects-dir|(?:codex|grok|cursor|hermes|commandcode|devin|agy|copilot)-home|engine|event|agy-event|copilot-event)$/.test(key)+ || value === undefined || flags.has(key)) return false+ flags.set(key, value)+ }+ return /^\d+$/.test(flags.get('--port') ?? '') && isAbsolute(flags.get('--data-dir') ?? '')+}+export function isOurs(block: HookBlock): boolean {- return Array.isArray(block?.hooks) && block.hooks.some((h) => h?.command?.includes('notify.mjs'))+ return Array.isArray(block?.hooks) && block.hooks.some(hook => isManagedHookCommand(hook?.command))}-export function writeJsonAtomic(file: string, value: unknown): void {- mkdirSync(dirname(file), { recursive: true })- const tmp = `${file}.${process.pid}.tmp`- writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')- renameSync(tmp, file)+/** A managed command can share a block with somebody else's command. Updating+ * ours must keep those siblings and the block's matcher and other fields. */+export function foreignHookBlocks(blocks: HookBlock[]): HookBlock[] {+ for (const block of blocks) {+ if (!block || typeof block !== 'object' || !Array.isArray(block.hooks) || block.hooks.some(hook =>+ !hook || typeof hook !== 'object' || (hook.command !== undefined && typeof hook.command !== 'string'))) {+ throw new HookPreparationHeld('a hook block has an unconfirmed shape')+ }+ }+ return blocks.flatMap(block => {+ if (!isOurs(block)) return [block]+ const hooks = block.hooks.filter(hook => !isOurs({ hooks: [hook] }))+ return hooks.length ? [{ ...block, hooks }] : []+ })}diff --git a/cli/src/engines/launchArgv.golden.spec.ts b/cli/src/engines/launchArgv.golden.spec.tsindex 16ff39923..17606e827 100644--- a/cli/src/engines/launchArgv.golden.spec.ts+++ b/cli/src/engines/launchArgv.golden.spec.ts@@ -407,7 +407,7 @@ async function overridesCases(): Promise<Record<string, unknown>> {machine: () => ({ hermesSystemManaged: false, opencodeMajor: null }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key, files) => { calls.push(`writeGridConfigDir ${key} ${files.map((file) => file.name).join(',')}`); return `/state/grid-engine-config/${key}` },tmuxSupportsSessionEnv: async () => true,- installCodexHooks: (home) => { calls.push(`installCodexHooks ${home}`) },+ installCodexHooks: (home) => { calls.push(`installCodexHooks ${home}`); return true },readCodexConfig: (path) => { calls.push(`readCodexConfig ${path}`); return config },dshLaunch: async (dsh, workspace, eng, key) => {calls.push(`dshLaunch ${dsh} ${workspace} ${eng} ${key}`)diff --git a/cli/src/engines/launchControl.ts b/cli/src/engines/launchControl.tsindex 235566222..c209e1dfe 100644--- a/cli/src/engines/launchControl.ts+++ b/cli/src/engines/launchControl.ts@@ -1,7 +1,7 @@/** Eager native launch control. Importing it neither probes a binary nor reads or writes a store. */import { opencodeBinAsync } from '../lib/engineBin.js'import { OPENCODE_SESSION_MODEL, OPENCODE_VERSION } from './opencode/contract.js'-import { majorVersion, nativeVersionProbe, parseMajor, type VersionProbe } from './kit/nativeVersion.js'+import { executableSnapshot, majorVersion, nativeVersionProbe, parseMajor, type NativeExecutableSnapshot, type VersionProbe } from './kit/nativeVersion.js'import { createSessionModelControl, type NativeApiRun, type NativeModelResult, type NativeSessionModel, type NativeModelAuthority } from './kit/nativeSessionModel.js'export { isOpencodeV2 } from './opencode/contract.js'@@ -16,6 +16,16 @@ export async function opencodeMajorVersion(probe?: VersionProbe, memo = versionMreturn majorVersion(OPENCODE_VERSION, probe, memo)}+export interface OpencodeLaunchSnapshot extends NativeExecutableSnapshot { major: number }+export async function opencodeLaunchSnapshot(binary?: string): Promise<OpencodeLaunchSnapshot | null> {+ const command = binary ?? await opencodeBinAsync()+ const probe = nativeVersionProbe(OPENCODE_VERSION, () => command)+ const executable = executableSnapshot(probe)+ if (!executable) return null+ const major = await majorVersion(OPENCODE_VERSION, probe, versionMemo)+ return major !== null && executable.current() ? { ...executable, major } : null+}+export type OpencodeSessionModel = NativeSessionModelexport type SetOpencodeSessionModelResult = NativeModelResultexport type OpencodeApiRun = NativeApiRundiff --git a/cli/src/engines/nativeHookPreparation.spec.ts b/cli/src/engines/nativeHookPreparation.spec.tsnew file mode 100644index 000000000..4d2535f1c--- /dev/null+++ b/cli/src/engines/nativeHookPreparation.spec.ts@@ -0,0 +1,344 @@+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, chmodSync, symlinkSync, renameSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'++const probe = vi.hoisted(() => ({ major: 1 as number | null, failSync: false, failRemove: false, beforeSync: undefined as (() => Promise<void>) | undefined, onStat: undefined as ((path: unknown) => void) | undefined }))+vi.mock('./launchControl.js', () => ({ opencodeMajorVersion: async () => probe.major }))+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ return { ...fs,+ lstatSync: (...args: Parameters<typeof fs.lstatSync>) => { probe.onStat?.(args[0]); return fs.lstatSync(...args) },+ fsync: (fd: number, callback: (error: Error | null) => void) => { if (probe.failSync) queueMicrotask(() => callback(new Error('fixture sync failure'))); else if (probe.beforeSync) void probe.beforeSync().then(() => fs.fsync(fd, callback)); else fs.fsync(fd, callback) },+ unlinkSync: (file: string) => {+ if (probe.failRemove && file.endsWith('/plugin/launcher-register.js')) throw new Error('fixture removal failure')+ return fs.unlinkSync(file)+ },+ }+})+const roots: string[] = []+afterEach(() => {+ probe.major = 1; probe.failSync = false; probe.failRemove = false; probe.beforeSync = undefined; probe.onStat = undefined+ vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.resetModules()+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+})+async function fixture() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-hook-preparation-'))); roots.push(root)+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'OPENCODE_CONFIG_DIR', 'OPENCODE_PLUGIN_DIR', 'OPENCODE_DATA_DIR', 'CODEX_HOME', 'HERMES_HOME', 'CURSOR_CONFIG_DIR']) {+ const path = join(root, name === 'OPENCODE_PLUGIN_DIR' ? 'plugin' : name); mkdirSync(path); vi.stubEnv(name, path)+ }+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.resetModules()+ const { installOpencodePlugin } = await import('./nativeHooks.js')+ const { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN } = await import('./opencode/contract.js')+ return { root, install: installOpencodePlugin, legacy: OPENCODE_LEGACY_PLUGIN.file, tui: OPENCODE_TUI_PLUGIN.file }+}++it('preserves the legacy first-install TUI preparation while the version is absent', async () => {+ const { install, legacy, tui } = await fixture()+ probe.major = null+ expect(await install(4242)).toBe(true)+ expect(() => readFileSync(legacy)).toThrow()+ expect(readFileSync(tui, 'utf8')).toContain('4242')+ probe.major = 1+ expect(await install(4343)).toBe(true)+ expect(readFileSync(legacy, 'utf8')).toContain('4343')+})++it('holds an upgrade if removal fails and only acknowledges it after recovery', async () => {+ const { install, legacy } = await fixture()+ expect(await install(4242)).toBe(true)+ probe.major = 2; probe.failRemove = true+ expect(await install(4242)).toBe(false)+ expect(readFileSync(legacy, 'utf8')).toContain('MachineRegister')+ probe.failRemove = false+ expect(await install(4242)).toBe(true)+})++it('does not acknowledge either new or already-current hooks while durability is unavailable', async () => {+ const { install } = await fixture()+ expect(await install(4242)).toBe(true)+ probe.failSync = true+ expect(await install(4242)).toBe(false)+ expect(await install(4343)).toBe(false)+ probe.failSync = false+ expect(await install(4343)).toBe(true)+})++it.each([1, 2])('preserves an occupied plugin path before writing any other surface for v%s', async major => {+ const { install, legacy, tui } = await fixture()+ probe.major = major+ mkdirSync(dirname(legacy), { recursive: true })+ writeFileSync(legacy, 'export const ForeignPlugin = {}\n')+ expect(await install(4242)).toBe(false)+ expect(readFileSync(legacy, 'utf8')).toBe('export const ForeignPlugin = {}\n')+ expect(() => readFileSync(tui)).toThrow()+})++it('preserves an occupied TUI path and an existing legacy plugin on upgrade', async () => {+ const { install, legacy, tui } = await fixture()+ expect(await install(4242)).toBe(true)+ const before = readFileSync(legacy, 'utf8')+ writeFileSync(tui, 'export default { id: "foreign" }\n'); probe.major = 2+ expect(await install(4242)).toBe(false)+ expect(readFileSync(legacy, 'utf8')).toBe(before)+ expect(readFileSync(tui, 'utf8')).toBe('export default { id: "foreign" }\n')+})++it('rejects a stale executable snapshot before publishing hooks', async () => {+ const { install, legacy, tui } = await fixture()+ const snapshot = { command: '/fixture/opencode', identity: 'before-upgrade', major: 1, current: () => false }+ expect(await install(4242, snapshot)).toBe(false)+ expect(() => readFileSync(legacy)).toThrow()+ expect(() => readFileSync(tui)).toThrow()+})++it('does not join installation for a different executable identity on the same port', async () => {+ const { install } = await fixture()+ const first = install(4242, { command: '/fixture/one', identity: 'one', major: 1, current: () => true })+ const second = install(4242, { command: '/fixture/two', identity: 'two', major: 2, current: () => true })+ expect(await first).toBe(false)+ // A changed executable cannot take a destination still owned by the old attempt.+ expect(await second).toBe(false)+ expect(await install(4242, { command: '/fixture/two', identity: 'two', major: 2, current: () => true })).toBe(true)+})++it('keeps mixed foreign commands when refreshing Claude and Codex hooks', async () => {+ const { root } = await fixture()+ const { engineHooks } = await import('./hooks.js')+ const { command } = await import('./kit/notifyHooks.js')+ for (const engine of ['claude', 'codex'] as const) {+ const home = join(root, engine); mkdirSync(home)+ const file = join(home, engine === 'codex' ? 'hooks.json' : 'settings.json')+ const foreign = { type: 'command', command: 'foreign command', custom: { preserve: true } }+ writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [{ matcher: 'foreign matcher', marker: 'preserve', hooks: [+ foreign, { type: 'command', command: command(4343, engine, home) },+ ] }] }, keep: 42 }))+ expect(await engineHooks[engine].installIn(4242, home)).toBe(true)+ const after = JSON.parse(readFileSync(file, 'utf8'))+ expect(after.keep).toBe(42)+ expect(after.hooks.SessionStart[0]).toEqual({ matcher: 'foreign matcher', marker: 'preserve', hooks: [foreign] })+ expect(after.hooks.SessionStart[1].hooks[0].command).toContain('--port 4242')+ }+})++it('holds Codex before hook publication when its approval configuration is unconfirmed', async () => {+ const { root } = await fixture()+ const { engineHooks } = await import('./hooks.js')+ const home = join(root, 'CODEX_HOME'), file = join(home, 'hooks.json'), config = join(home, 'config.toml')+ const original = JSON.stringify({ keep: true })+ writeFileSync(file, original); writeFileSync(config, 'hooks = { state = {} }\n')+ expect(await engineHooks.codex.installIn(4242, home)).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe(original)+ expect(readFileSync(config, 'utf8')).toBe('hooks = { state = {} }\n')+ writeFileSync(config, 'model = "fixture"\n')+ expect(await engineHooks.codex.installIn(4242, home)).toBe(true)+ expect(readFileSync(config, 'utf8')).toContain('trusted_hash')+})++it.each(['{malformed', '{"approvals":{}}'])('preserves Hermes configuration when approvals are unreadable: %s', async approvals => {+ const { root } = await fixture()+ const { installHermesHooks } = await import('./nativeHooks.js')+ const { HERMES_HOOK_SETTINGS: rule } = await import('./hermes/contract.js')+ const home = join(root, 'HERMES_HOME'), file = join(home, rule.homes.file), allowlist = join(home, rule.allowlist)+ writeFileSync(file, 'model: fixture\n'); writeFileSync(allowlist, approvals)+ expect(await installHermesHooks(4242, home)).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe('model: fixture\n')+ expect(readFileSync(allowlist, 'utf8')).toBe(approvals)+ writeFileSync(allowlist, JSON.stringify({ approvals: [{ command: 'foreign', event: 'foreign' }], keep: 42 }))+ expect(await installHermesHooks(4242, home)).toBe(true)+ const after = JSON.parse(readFileSync(allowlist, 'utf8'))+ expect(after.keep).toBe(42)+ expect(after.approvals).toContainEqual({ command: 'foreign', event: 'foreign' })+})++it('preserves the rest of a Hermes document after a truncated or edited managed block', async () => {+ const { root } = await fixture()+ const { installHermesHooks } = await import('./nativeHooks.js')+ const { HERMES_HOOK_SETTINGS: rule } = await import('./hermes/contract.js')+ const home = join(root, 'HERMES_HOME'), file = join(home, rule.homes.file)+ for (const text of [+ `model: fixture\n${rule.begin}\nhooks:\n foreign: keep\n`,+ `model: fixture\n${rule.begin}\nhooks:\n foreign: keep\n${rule.end}\n`,+ ]) {+ writeFileSync(file, text)+ expect(await installHermesHooks(4242, home)).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe(text)+ }+})++it('holds an upgrade whose legacy plugin is a shared alias', async () => {+ const { root, install, legacy, tui } = await fixture()+ expect(await install(4242)).toBe(true)+ const shared = join(root, 'shared-plugin.js'), previousTui = readFileSync(tui, 'utf8')+ renameSync(legacy, shared); symlinkSync(shared, legacy); probe.major = 2+ expect(await install(4343)).toBe(false)+ expect(realpathSync(legacy)).toBe(shared)+ expect(readFileSync(shared, 'utf8')).toContain('MachineRegister')+ expect(readFileSync(tui, 'utf8')).toBe(previousTui)+})++it('preserves foreign notify.mjs commands when adding managed hooks', async () => {+ const { root } = await fixture()+ const { engineHooks } = await import('./hooks.js')+ const home = join(root, 'CODEX_HOME'), file = join(home, 'hooks.json')+ const foreign = { type: 'command', command: 'node /project/notify.mjs' }+ writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [{ hooks: [foreign] }] } }))+ expect(await engineHooks.codex.installIn(4242, home)).toBe(true)+ expect(JSON.parse(readFileSync(file, 'utf8')).hooks.SessionStart[0]).toEqual({ hooks: [foreign] })+})++it.each(['description = """', 'a=[1 #', '[invalid', 'same = 1\nsame = 2'])('holds malformed TOML before publishing hooks: %s', async malformed => {+ const { root } = await fixture()+ const { engineHooks } = await import('./hooks.js')+ const home = join(root, 'CODEX_HOME'), file = join(home, 'hooks.json'), config = join(home, 'config.toml')+ writeFileSync(config, malformed)+ expect(await engineHooks.codex.installIn(4242, home)).toBe(false)+ expect(() => readFileSync(file)).toThrow()+ expect(readFileSync(config, 'utf8')).toBe(malformed)+})++it.each(['hooks: {foreign: [{command: "foreign"}]}\n', '"hooks": {}\n', "'hooks': {}\n", 'model: [unfinished'])('holds foreign or incomplete YAML: %s', async config => {+ const { root } = await fixture()+ const { installHermesHooks } = await import('./nativeHooks.js')+ const home = join(root, 'HERMES_HOME'), file = join(home, 'config.yaml')+ writeFileSync(file, config)+ expect(await installHermesHooks(4242, home)).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe(config)+})++it.each(['codex', 'hermes'])('checks read-only %s approvals before writing hooks', async engine => {+ const { root } = await fixture()+ const home = join(root, engine === 'codex' ? 'CODEX_HOME' : 'HERMES_HOME')+ const config = join(home, engine === 'codex' ? 'config.toml' : 'shell-hooks-allowlist.json')+ const hookFile = join(home, engine === 'codex' ? 'hooks.json' : 'config.yaml')+ const original = engine === 'codex' ? '{}' : 'model: fixture\n'+ writeFileSync(hookFile, original)+ writeFileSync(config, engine === 'codex' ? 'model = "fixture"\n' : '{"approvals":[]}')+ chmodSync(config, 0o444)+ const { engineHooks } = await import('./hooks.js')+ const { installHermesHooks } = await import('./nativeHooks.js')+ expect(engine === 'codex' ? await engineHooks.codex.installIn(4242, home) : await installHermesHooks(4242, home)).toBe(false)+ expect(readFileSync(hookFile, 'utf8')).toBe(original)+})++it('preserves marker-like text inside a foreign YAML scalar', async () => {+ const { root } = await fixture()+ const { installHermesHooks } = await import('./nativeHooks.js')+ const { HERMES_HOOK_SETTINGS: rule } = await import('./hermes/contract.js')+ const home = join(root, 'HERMES_HOME'), file = join(home, 'config.yaml')+ const config = `description: "text\n ${rule.begin}\n hooks:\n foreign: keep\n ${rule.end}\n end"\n`+ writeFileSync(file, config)+ expect(await installHermesHooks(4242, home)).toBe(true)+ expect(readFileSync(file, 'utf8')).toContain(config)+})++it('holds a large YAML structure before parsing or modifying it', async () => {+ const { root } = await fixture()+ const { installHermesHooks } = await import('./nativeHooks.js')+ const home = join(root, 'HERMES_HOME'), file = join(home, 'config.yaml')+ const config = Array.from({ length: 5000 }, (_, index) => `key${index}: value`).join('\n')+ writeFileSync(file, config)+ expect(await installHermesHooks(4242, home)).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe(config)+})+++it('installs every healthy Hermes profile beyond the asynchronous preparation pool capacity', async () => {+ const { root } = await fixture()+ const home = join(root, 'HERMES_HOME')+ writeFileSync(join(home, 'config.yaml'), 'model: fixture\n')+ for (let n = 0; n < 18; n++) {+ const profile = join(home, 'profiles', String(n)); mkdirSync(profile, { recursive: true })+ writeFileSync(join(profile, 'config.yaml'), 'model: fixture\n')+ }+ const { installHermesHooks } = await import('./nativeHooks.js')+ expect(await installHermesHooks(4242)).toBe(true)+ for (let n = 0; n < 18; n++) expect(readFileSync(join(home, 'profiles', String(n), 'config.yaml'), 'utf8')).toContain('--port 4242')+}, 20_000)+++it('does not join hook preparation across a managed Node command change', async () => {+ const { root } = await fixture()+ const runtime = await import('../lib/nodeRuntime.js')+ const node = vi.spyOn(runtime, 'managedNodePath').mockReturnValue('/fixture/node-before')+ const { engineHooks } = await import('./hooks.js')+ const home = join(root, 'HOME'), file = join(home, 'settings.json')+ writeFileSync(file, '{}\n')+ let release!: () => void, started!: () => void+ const blocked = new Promise<void>(resolve => { release = resolve })+ const syncing = new Promise<void>(resolve => { started = resolve })+ probe.beforeSync = () => { started(); return blocked }+ const first = engineHooks.claude.installIn(4242, home)+ await syncing+ node.mockReturnValue('/fixture/node-after')+ expect(await engineHooks.claude.installIn(4242, home)).toBe(false)+ release()+ expect(await first).toBe(false)+ expect(readFileSync(file, 'utf8')).toBe('{}\n')+ probe.beforeSync = undefined+ expect(await engineHooks.claude.installIn(4242, home)).toBe(true)+ expect(readFileSync(file, 'utf8')).toContain('/fixture/node-after')+ expect(readFileSync(file, 'utf8')).not.toContain('/fixture/node-before')+})+++it.each([+ 'node /foreign/*/notify.mjs --port 42 --data-dir /foreign',+ 'node /foreign/notify.mjs\n--port 42 --data-dir /foreign',+ 'node /foreign/notify.mjs --port 42 --data-dir /foreign?path',+])('preserves a foreign shell command during hook preparation: %s', async command => {+ const { root } = await fixture()+ const { engineHooks } = await import('./hooks.js')+ const home = join(root, 'HOME'), file = join(home, 'settings.json')+ const foreign = { hooks: [{ type: 'command', command }] }+ writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [foreign] } }))+ expect(await engineHooks.claude.installIn(4242, home)).toBe(true)+ expect(JSON.parse(readFileSync(file, 'utf8')).hooks.SessionStart[0]).toEqual(foreign)+})+++it('does not credit a newer OpenCode installation to a revoked older caller', async () => {+ const { install } = await fixture()+ const control = await import('./launchControl.js')+ let release!: (major: number) => void, current = true+ vi.spyOn(control, 'opencodeMajorVersion').mockImplementationOnce(() => new Promise(resolve => { release = resolve }))+ const first = install(4242, undefined, { current: () => current })+ let releaseDisk!: () => void+ const disk = new Promise<void>(resolve => { releaseDisk = resolve })+ const entered = vi.fn(async () => disk)+ probe.beforeSync = entered+ const second = install(4242)+ await vi.waitFor(() => expect(entered).toHaveBeenCalled())+ release(1)+ // The older caller has joined the newer preparation while still authorized.+ for (let n = 0; n < 80; n++) await Promise.resolve()+ current = false; probe.beforeSync = undefined; releaseDisk()+ expect(await second).toBe(true)+ expect(await first).toBe(false)+})++it('cannot extend the OpenCode deadline by stalling reservation reads', async () => {+ const { install, legacy, tui } = await fixture()+ let time = 0+ vi.spyOn(performance, 'now').mockImplementation(() => time)+ const fs = await import('node:fs')+ vi.spyOn(fs, 'fsync').mockImplementation((_fd, done) => { queueMicrotask(() => done(null)) })+ probe.onStat = path => { if (path === dirname(legacy)) time = 20 }+ expect(await install(4242, undefined, { timeoutMs: 10 })).toBe(false)+ expect(() => readFileSync(legacy)).toThrow()+ expect(() => readFileSync(tui)).toThrow()+})++it('rechecks the OpenCode deadline after final proof reads', async () => {+ const { install } = await fixture()+ let time = 0+ vi.spyOn(performance, 'now').mockImplementation(() => time)+ const files = await import('./kit/nativeHookFiles.js')+ vi.spyOn(files, 'runHookPreparation').mockImplementationOnce(async (_files, _work, options) => {+ options?.confirmed?.({ files: [], current: () => { time = 20; return true } })+ return true as never+ })+ expect(await install(4242, undefined, { timeoutMs: 10 })).toBe(false)+})diff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.tsindex 3c0a4e056..0cf2d4fa1 100644--- a/cli/src/engines/nativeHooks.ts+++ b/cli/src/engines/nativeHooks.ts@@ -1,5 +1,6 @@/** Native hook installation is eager. Optional transcript and screen readers own no hook files. */import { join } from 'node:path'+import { runHookPreparation, type HookPreparationOptions, type HookPreparationProof } from './kit/nativeHookFiles.js'import { env } from '../config/env.js'import { VERSION } from '../version.js'import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN, OPENCODE_LEGACY_REMOVAL, OPENCODE_VERSION } from './opencode/contract.js'@@ -7,8 +8,8 @@ import { KILO_PLUGIN } from './kilo/contract.js'import { PI_EXTENSION } from './pi/contract.js'import { AMP_PLUGIN } from './amp/contract.js'import { HERMES_HOOK_SETTINGS } from './hermes/contract.js'-import { opencodeMajorVersion } from './launchControl.js'-import { installNativePlugin, removeNativePlugin } from './kit/nativePlugin.js'+import { opencodeMajorVersion, type OpencodeLaunchSnapshot } from './launchControl.js'+import { installNativePlugin, prepareNativePlugin, prepareNativePluginRemoval } from './kit/nativePlugin.js'import { installNativeYamlHooks } from './kit/nativeHookYaml.js'import { command } from './kit/notifyHooks.js'import { GROK_HOOK_SETTINGS } from './grok/contract.js'@@ -19,48 +20,64 @@ import { COMMANDCODE_HOOK_SETTINGS } from './commandcode/contract.js'import { DEVIN_HOOK_SETTINGS } from './devin/contract.js'import { installNativeHookSettings } from './kit/nativeHookSettings.js'-export const installGrokHooks = (port: number): void => installNativeHookSettings(GROK_HOOK_SETTINGS, port)-export const installAgyHooks = (port: number): void => installNativeHookSettings(AGY_HOOK_SETTINGS, port)-export const installCopilotHooks = (port: number): void => installNativeHookSettings(COPILOT_HOOK_SETTINGS, port)-export const installCursorHooks = (port: number): void => installNativeHookSettings(CURSOR_HOOK_SETTINGS, port)-export const installCommandCodeHooks = (port: number): void => installNativeHookSettings(COMMANDCODE_HOOK_SETTINGS, port)-export const installDevinHooks = (port: number): void => installNativeHookSettings(DEVIN_HOOK_SETTINGS, port)+export const installGrokHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(GROK_HOOK_SETTINGS, port, options)+export const installAgyHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(AGY_HOOK_SETTINGS, port, options)+export const installCopilotHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(COPILOT_HOOK_SETTINGS, port, options)+export const installCursorHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(CURSOR_HOOK_SETTINGS, port, options)+export const installCommandCodeHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(COMMANDCODE_HOOK_SETTINGS, port, options)+export const installDevinHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(DEVIN_HOOK_SETTINGS, port, options)const pluginValues = (port: number) => ({port: String(port), credential: JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential')), version: JSON.stringify(VERSION),})-export const installKiloPlugin = (port: number): void => installNativePlugin(KILO_PLUGIN, pluginValues(port))-export const installPiExtension = (port: number): void => installNativePlugin(PI_EXTENSION, pluginValues(port))-export const installAmpPlugin = (port: number): void => installNativePlugin(AMP_PLUGIN, pluginValues(port))-export const installHermesHooks = (port: number): void =>- installNativeYamlHooks(HERMES_HOOK_SETTINGS, home => command(port, 'hermes', env.CODEX_HOME, home))+export const installKiloPlugin = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(KILO_PLUGIN, pluginValues(port), options)+export const installPiExtension = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(PI_EXTENSION, pluginValues(port), options)+export const installAmpPlugin = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(AMP_PLUGIN, pluginValues(port), options)+export const installHermesHooks = (port: number, selectedHome?: string, options?: HookPreparationOptions): Promise<boolean> =>+ installNativeYamlHooks(HERMES_HOOK_SETTINGS, home => command(port, 'hermes', env.CODEX_HOME, home), selectedHome, options)/** Install both discovery surfaces for v1; v2 must not load our incompatible v1 export. */-interface OpencodeInstallation { port: number; done: Promise<boolean> }+interface OpencodeInstallation { port: number; executable?: string; major?: number | null; done: Promise<boolean>; proofs: HookPreparationProof[] }let opencodeInstallation: OpencodeInstallation | undefined-export async function installOpencodePlugin(port: number): Promise<boolean> {- const installation: OpencodeInstallation = { port, done: Promise.resolve(false) }+export async function installOpencodePlugin(port: number, snapshot?: OpencodeLaunchSnapshot, options: HookPreparationOptions = {}): Promise<boolean> {+ const deadline = performance.now() + (options.timeoutMs ?? OPENCODE_VERSION.timeoutMs)+ const installation: OpencodeInstallation = { port, executable: snapshot?.identity, done: Promise.resolve(false), proofs: [] }opencodeInstallation = installationinstallation.done = (async () => {const values = pluginValues(port)- const major = await opencodeMajorVersion()+ const major = snapshot ? snapshot.major : await opencodeMajorVersion()+ installation.major = major// A newer request may have installed an upgraded/downgraded engine's hooks// while this probe waited. Only the latest request can change those files.- if (installation !== opencodeInstallation) return false- if (major === 1) installNativePlugin(OPENCODE_LEGACY_PLUGIN, values)- else removeNativePlugin(OPENCODE_LEGACY_REMOVAL)- installNativePlugin(OPENCODE_TUI_PLUGIN, values)- return true+ if (installation !== opencodeInstallation || snapshot?.current() === false) return false+ // Keep the existing first-install route until installer-only continuation+ // can return through launch preparation. A missing executable also gives+ // null here; refusing it would prevent create from reaching its installer.+ // Whole-launch preparation must confirm a version before native dispatch.+ try { return await runHookPreparation([OPENCODE_LEGACY_PLUGIN.file, OPENCODE_TUI_PLUGIN.file], async attempt => {+ // Inspect both destinations before publishing. A foreign legacy plugin+ // cannot authorize even the first half of an upgrade's writes.+ const legacy = major === 1 ? prepareNativePlugin(OPENCODE_LEGACY_PLUGIN, values) : prepareNativePluginRemoval(OPENCODE_LEGACY_REMOVAL)+ const tui = prepareNativePlugin(OPENCODE_TUI_PLUGIN, values)+ legacy.verify(); tui.verify()+ const removedOrInstalled = await legacy.commit(attempt), installed = await tui.commit(attempt)+ removedOrInstalled.verify(); installed.verify()+ return snapshot?.current() !== false+ }, { ...options, timeoutMs: Math.max(0, deadline - performance.now()), confirmed: proof => installation.proofs.push(proof), identity: JSON.stringify([port, snapshot?.identity, major]),+ current: () => opencodeInstallation?.port === port && opencodeInstallation.executable === installation.executable+ && opencodeInstallation.major === major && performance.now() < deadline && snapshot?.current() !== false && options.current?.() !== false }) } catch (error) {+ console.error('[hooks] OpenCode preparation held:', error)+ return false+ }})()let current = installation, installed = await current.done- const deadline = performance.now() + OPENCODE_VERSION.timeoutMswhile (current !== opencodeInstallation) {current = opencodeInstallation!// Two healthy creates must not fail merely because they overlap. Follow the// current installation without restoring an obsolete request's write rights.// A port change or continuing churn cannot make this caller wait forever.const remaining = deadline - performance.now()- if (current.port !== port || remaining <= 0) return false+ if (current.port !== port || current.executable !== installation.executable || snapshot?.current() === false || options.current?.() === false || remaining <= 0) return falselet timer: ReturnType<typeof setTimeout> | undefinedtry {const result = await Promise.race([current.done, new Promise<'timeout'>(done => {@@ -70,5 +87,8 @@ export async function installOpencodePlugin(port: number): Promise<boolean> {installed = result} finally { clearTimeout(timer) }}- return installed+ if (!installed || performance.now() >= deadline || options.current?.() === false || snapshot?.current() === false || current.proofs.some(proof => !proof.current())) return false+ if (performance.now() >= deadline) return false+ for (const proof of current.proofs) options.confirmed?.(proof)+ return true}diff --git a/cli/src/engines/nativeVersion.golden.spec.ts b/cli/src/engines/nativeVersion.golden.spec.tsindex a2b936878..4a4d96e92 100644--- a/cli/src/engines/nativeVersion.golden.spec.ts+++ b/cli/src/engines/nativeVersion.golden.spec.ts@@ -1,4 +1,4 @@-/** Healthy native version and hook selection, recorded before the probe becomes asynchronous. */+/** Healthy native version and hook selection, including an upgrade, downgrade and repeated preparation. */import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, existsSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -60,11 +60,11 @@ it.each(['linux', 'darwin'])('preserves versioned native hook selection on %s',const files = () => [OPENCODE_LEGACY_PLUGIN.file, OPENCODE_TUI_PLUGIN.file].map(file => ({file, source: existsSync(file) ? readFileSync(file, 'utf8').split(VERSION).join('<version>') : null,}))- for (const major of [1, 2]) {- native.major = major; native.stamp = major; native.calls.length = 0+ for (const [name, major, stamp] of [['v1', 1, 1], ['v2', 2, 2], ['downgrade-v1', 1, 3], ['current-v1', 1, 3]] as const) {+ native.major = major; native.stamp = stamp; native.calls.length = 0const installed = await installOpencodePluginBeforeSpawn(4242)const first = await opencodeMajorVersion(), repeat = await opencodeMajorVersion()- const key = `${platform}:v${major}`+ const key = `${platform}:${name}`observations[key] = JSON.parse(JSON.stringify({ installed, first, repeat, calls: native.calls, files: files() }).split(root).join('<root>'))if (!record) expect({ key, value: observations[key] }).toEqual({ key, value: expected[key] })}diff --git a/cli/src/engines/opencode/tuiFlags.spec.ts b/cli/src/engines/opencode/tuiFlags.spec.tsindex 48b8ae789..b251fe442 100644--- a/cli/src/engines/opencode/tuiFlags.spec.ts+++ b/cli/src/engines/opencode/tuiFlags.spec.ts@@ -28,7 +28,7 @@ describe.skipIf(!installed)('the installed opencode TUI accepts every flag we pamachine: async () => ({ hermesSystemManaged: false, opencodeMajor: await major }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,tmuxSupportsSessionEnv: async () => true,- installCodexHooks: () => {},+ installCodexHooks: () => true,readCodexConfig: () => null,}const GRID = {diff --git a/cli/src/engines/otherHooks.golden.spec.ts b/cli/src/engines/otherHooks.golden.spec.tsindex abd4925bd..80be31bbe 100644--- a/cli/src/engines/otherHooks.golden.spec.ts+++ b/cli/src/engines/otherHooks.golden.spec.ts@@ -20,6 +20,7 @@ import { tmpdir } from 'node:os'import { dirname, join, relative } from 'node:path'import { fileURLToPath } from 'node:url'import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { expectForeignHooksPreserved, preservedHookFiles } from '../testing/hookGoldenSafety.js'const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-hooks.golden.json', import.meta.url))const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'@@ -274,16 +275,17 @@ async function install(vendor: Vendor, port: number): Promise<Run> {return { logs, threw }}-async function run(vendor: Vendor, scenario: Case): Promise<Outcome> {+async function run(vendor: Vendor, scenario: Case) {reset()opencode(scenario.opencode === undefined ? 2 : scenario.opencode)const file = targets()[vendor]const home = dirname(file)if (!scenario.noHome) mkdirSync(home, { recursive: true })scenario.setup?.({ vendor, file, home, elsewhere: join(root, 'elsewhere'), texts: texts[vendor] })+ const before = snapshot()const runs: Run[] = []for (let i = 0; i < 2; i++) runs.push(await install(vendor, PORT))- return { runs, files: snapshot() }+ return { outcome: { runs, files: snapshot() }, before, file: normalize(relative(root, file)) }}/** What an install writes into a clean home for `port`: the current file, read raw. */@@ -334,7 +336,7 @@ beforeAll(async () => {}legacyOpencodePlugin = await installed('opencode', PORT, 1)} finally { process.umask(previous) }-})+}, 60_000)afterAll(() => {Object.defineProperty(process, 'platform', platform)@@ -345,19 +347,48 @@ afterAll(() => {const casesFor = (vendor: Vendor): Case[] => CASES.filter((one) => !one.vendors || one.vendors.includes(vendor))+// Keep the former artifact intact. Its destructive/unknown-input cases now+// assert a visible hold and exact preservation, while healthy cases remain a+// byte-for-byte compatibility check (including modes and aliases).+const IO_HELD = new Set(['a dangling symlink', 'a symlink into a missing folder', 'a read-only file', 'an unreadable file',+ 'a read-only folder', 'a read-only folder holding a writable file', 'the file is a folder'])+const INVALID_VALUE = new Set(['empty file', 'whitespace only', 'malformed JSON', 'byte order mark', 'JSON null', 'JSON array', 'JSON string', 'JSON number'])+const INVALID_HOOKS = new Set(['hooks is a string', 'hooks is an array', 'hooks is null'])+const FOREIGN_SOURCE = new Set([...INVALID_VALUE, ...INVALID_HOOKS, 'foreign content', 'a symlink to foreign content', 'a private file', 'a temporary file left by this process'])+function held(vendor: Vendor, name: string): boolean {+ if (IO_HELD.has(name)) return true+ if (KIND[vendor] === 'source') return FOREIGN_SOURCE.has(name)+ || name === "OpenCode 2 with a foreign plugin where OpenCode 1's goes" || name === "OpenCode 2 with a folder where OpenCode 1's plugin goes"+ if (KIND[vendor] === 'json') return INVALID_VALUE.has(name) || (vendor !== 'agy' && INVALID_HOOKS.has(name))+ return ['no file', 'no home folder', 'malformed JSON', 'byte order mark', 'JSON null', 'JSON array', 'JSON string', 'JSON number',+ ...INVALID_HOOKS, 'a foreign hooks mapping'].includes(name)+}+describe.each(VENDORS)('%s\'s hooks, installed by the core, byte for byte', (vendor) => {for (const scenario of casesFor(vendor)) {const key = `${vendor}: ${scenario.name}`it.skipIf(scenario.permissions && ROOT_USER)(key, async () => {const previous = process.umask(0o022)try {- const outcome = await run(vendor, scenario)+ const { outcome, before, file } = await run(vendor, scenario)recorded.outcomes[key] = outcomeif (!RECORD) {const expected = golden.outcomes[key]const files = (outcome: Outcome, table: Record<string, string>) => Object.fromEntries(Object.entries(outcome.files).map(([path, entry]) => [path, entry.text ? { ...entry, text: table[entry.text] } : entry]))- expect({ runs: outcome.runs, files: files(outcome, recorded.texts) }).toEqual({ runs: expected?.runs, files: expected && files(expected, golden.texts) })+ const initial = files({ runs: [], files: before }, recorded.texts), after = files(outcome, recorded.texts), former = files(expected, golden.texts)+ if (held(vendor, scenario.name)) {+ expect(after).toEqual(initial)+ for (const run of outcome.runs) {+ expect(run.threw).toBeNull()+ expect(run.logs.some(line => line.startsWith(`warn [hooks] ${vendor} install skipped ·`))).toBe(true)+ }+ } else if (vendor === 'copilot' && ['foreign content', 'a symlink to foreign content', 'a private file', 'a temporary file left by this process'].includes(scenario.name)) {+ const location = initial[file].type === 'link' ? initial[file].target!.replace('<root>/', '') : file+ const corrected = preservedHookFiles(initial, former)+ expectForeignHooksPreserved(initial, after, corrected, location)+ if (location !== file) expect(after[file]).toEqual(initial[file])+ } else expect({ runs: outcome.runs, files: after }).toEqual({ runs: expected.runs, files: preservedHookFiles(initial, former) })}} finally { process.umask(previous) }})diff --git a/cli/src/lib/controlTranscript.spec.ts b/cli/src/lib/controlTranscript.spec.tsindex cce1046bc..184bf4642 100644--- a/cli/src/lib/controlTranscript.spec.ts+++ b/cli/src/lib/controlTranscript.spec.ts@@ -293,10 +293,23 @@ it('preserves a repaired parent through Stop and the final real forget archive',stopJobs: new Map(), tmuxBackend: { kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })) },agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },forgetSession: forget, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: async () => {} })- await stop(row.agentId, { checkpoint: async session => {+ const checkpoint = async (session: typeof row) => {expect(session.transcriptPath).toBe(parent)stopped.save({ ...row, title: 'A hook saved the stale child path' })- } })+ }+ // Other Linux shard fixtures create/remove siblings under /tmp. The native+ // reader correctly refuses an ancestor changed during enumeration; retry the+ // untouched Stop just as its caller can, rather than treating that hold as loss.+ for (let attempt = 0; ; attempt++) {+ try { await stop(row.agentId, { checkpoint }); break }+ catch (error) {+ if (attempt >= 2) throw error+ expect(error).toMatchObject({ code: 'IDENTITY_UNAVAILABLE',+ message: 'Conversation identity is held: a binding directory or ancestor changed during enumeration.' })+ expect(registry.byAgent(row.agentId)?.sessionId).toBe(A)+ await new Promise(done => setTimeout(done, 10))+ }+ }expect(registry.byAgent(row.agentId)).toBeUndefined()expect(stopped.get(row.agentId)).toMatchObject({ active: false, sessionId: A, transcriptPath: parent })})diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex c4e41ed46..9a13018a1 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -68,7 +68,7 @@ describe('generated discovery scripts', () => {vi.resetModules()vi.stubEnv('PI_HOME', piHome)const { installPiExtension } = await import('./hooks.js')- installPiExtension(18473)+ expect(await installPiExtension(4242)).toBe(true)const src = readFileSync(join(piHome, 'agent', 'extensions', 'launcher-register.ts'), 'utf-8')expect(src).toContain('process.env.TMUX_PANE')@@ -186,13 +186,13 @@ describe('generated discovery scripts', () => {expect(readFileSync(settings, 'utf8')).toBe(settingsText)})- it('does not plant a v1 plugin before the pane installs OpenCode for the first time', async () => {+ it('preserves first-install TUI preparation before OpenCode is installed', async () => {const config = scratch()const pluginDir = join(config, 'plugin')version.major = nullvi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)const { installOpencodePlugin } = await import('./hooks.js')- await installOpencodePlugin(18473)+ expect(await installOpencodePlugin(4242)).toBe(true)expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)expect(existsSync(join(config, 'plugins', 'launcher-register', 'tui.js'))).toBe(true)})diff --git a/cli/src/lib/gridWebSearchFrame.spec.ts b/cli/src/lib/gridWebSearchFrame.spec.tsindex 65970f959..ed18c0209 100644--- a/cli/src/lib/gridWebSearchFrame.spec.ts+++ b/cli/src/lib/gridWebSearchFrame.spec.ts@@ -46,7 +46,7 @@ const DEPS: LaunchOverridesDeps = {machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,tmuxSupportsSessionEnv: async () => true,- installCodexHooks: () => {},+ installCodexHooks: () => true,}const IDENTITY = { pid: 4242, executable: 'claude', startMarker: 'boot-1' }diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.tsindex 90a7991c4..35d5f0ca9 100644--- a/cli/src/lib/hooks.spec.ts+++ b/cli/src/lib/hooks.spec.ts@@ -51,7 +51,7 @@ describe('Codex hook installation', () => {process.argv[1] = join(cliDir, 'cli.js')try {const { codex } = await loadHooks()- codex.install(19473)+ await codex.install(19473)expect(readFileSync(join(codexHome, 'hooks.json'), 'utf-8')).toContain(join(cliDir, 'notify.mjs'))} finally {process.argv[1] = script@@ -70,7 +70,7 @@ describe('Codex hook installation', () => {}))const { codex } = await loadHooks()- codex.install(19473)+ await codex.install(19473)const first = readFileSync(file, 'utf-8')const parsed = JSON.parse(first)@@ -81,7 +81,7 @@ describe('Codex hook installation', () => {expect(parsed.hooks.UserPromptSubmit[1]).not.toHaveProperty('matcher')expect(parsed.hooks.UserPromptSubmit[1].hooks[0].command).toContain('--engine codex')- codex.install(19473)+ await codex.install(19473)expect(readFileSync(file, 'utf-8')).toBe(first)})@@ -89,7 +89,7 @@ describe('Codex hook installation', () => {const customProfile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))try {const { codex } = await loadHooks()- codex.installIn(19473, customProfile)+ await codex.installIn(19473, customProfile)const profileFile = join(customProfile, 'hooks.json')const first = readFileSync(profileFile, 'utf-8')@@ -101,7 +101,7 @@ describe('Codex hook installation', () => {expect(existsSync(join(codexHome, 'hooks.json'))).toBe(false)// Idempotent: a second install into the same profile is a no-op.- codex.installIn(19473, customProfile)+ await codex.installIn(19473, customProfile)expect(readFileSync(profileFile, 'utf-8')).toBe(first)} finally {rmSync(customProfile, { recursive: true, force: true })@@ -113,7 +113,7 @@ describe('Codex hook installation', () => {writeFileSync(file, '{not-json')const { codex } = await loadHooks()- codex.install(19473)+ await codex.install(19473)expect(readFileSync(file, 'utf-8')).toBe('{not-json')expect(existsSync(`${file}.${process.pid}.tmp`)).toBe(false)@@ -127,7 +127,7 @@ describe('Codex hook installation', () => {hooks: { preToolUse: [{ command: 'foreign-task', failClosed: true }] },}))const { installCursorHooks } = await loadHooks()- installCursorHooks(19473)+ await installCursorHooks(19473)const first = readFileSync(file, 'utf8')const parsed = JSON.parse(first)expect(parsed.version).toBe(7)@@ -139,7 +139,7 @@ describe('Codex hook installation', () => {'preToolUse', 'sessionStart', 'beforeSubmitPrompt', 'stop', 'sessionEnd',])- installCursorHooks(19473)+ await installCursorHooks(19473)expect(readFileSync(file, 'utf8')).toBe(first)})@@ -150,7 +150,7 @@ describe('Codex hook installation', () => {vi.stubEnv('CURSOR_DATA_DIR', data)try {const { installCursorHooks } = await loadHooks()- installCursorHooks(19473)+ await installCursorHooks(19473)const hooks = JSON.parse(readFileSync(join(config, 'hooks.json'), 'utf8'))expect(hooks.hooks.sessionStart[0].command).toContain(`--cursor-home '${data}'`)expect(existsSync(join(data, 'hooks.json'))).toBe(false)@@ -170,7 +170,7 @@ describe('Grok hook installation', () => {it('installs camelCase lifecycle hooks without the early Stop signal', async () => {const { installGrokHooks } = await loadHooks()- installGrokHooks(18473)+ await installGrokHooks(18473)const file = join(grokHome, 'hooks', 'harness.json')const first = readFileSync(file, 'utf8')const out = JSON.parse(first) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }@@ -179,7 +179,7 @@ describe('Grok hook installation', () => {expect(out.hooks.SessionStart[0].hooks[0].command).toContain('--engine grok')expect(out.hooks.SessionStart[0].hooks[0].command).toContain(`--grok-home '${grokHome}'`)- installGrokHooks(18473)+ await installGrokHooks(18473)expect(readFileSync(file, 'utf8')).toBe(first)})@@ -188,7 +188,7 @@ describe('Grok hook installation', () => {mkdirSync(join(grokHome, 'hooks'), { recursive: true })writeFileSync(file, '{not-json')const { installGrokHooks } = await loadHooks()- installGrokHooks(18473)+ await installGrokHooks(18473)expect(readFileSync(file, 'utf8')).toBe('{not-json')})})@@ -213,7 +213,7 @@ describe('Command Code hook installation', () => {}))const { installCommandCodeHooks } = await loadHooks()- installCommandCodeHooks(18473)+ await installCommandCodeHooks(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as {model: string@@ -229,16 +229,16 @@ describe('Command Code hook installation', () => {expect(out.hooks.PreToolUse[0].hooks[0].command).toContain('--engine commandcode')const first = readFileSync(file, 'utf8')- installCommandCodeHooks(18473)+ await installCommandCodeHooks(18473)expect(readFileSync(file, 'utf8')).toBe(first)})it('collapses duplicate machine blocks left by an older path/port', async () => {- const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --port ${port} --engine commandcode` }] })+ const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port ${port} --engine commandcode` }] })writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [stale(19918), stale(19919)], Stop: [stale(19918)] } }))const { installCommandCodeHooks } = await loadHooks()- installCommandCodeHooks(18473)+ await installCommandCodeHooks(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, unknown[]> }expect(out.hooks.SessionStart).toHaveLength(1) // both stale entries collapsed into the canonical one@@ -249,7 +249,7 @@ describe('Command Code hook installation', () => {it('leaves a malformed settings file untouched', async () => {writeFileSync(file, '{ not json')const { installCommandCodeHooks } = await loadHooks()- installCommandCodeHooks(18473)+ await installCommandCodeHooks(18473)expect(readFileSync(file, 'utf8')).toBe('{ not json')})})@@ -281,7 +281,7 @@ describe('Devin hook installation', () => {}))const { installDevinHooks } = await loadHooks()- installDevinHooks(18473)+ await installDevinHooks(18473)const out = JSON.parse(readFileSync(devinConfigPath, 'utf8')) as {version: number@@ -298,16 +298,16 @@ describe('Devin hook installation', () => {expect(out.hooks.Stop[0].hooks[0].command).toContain('notify.mjs')const first = readFileSync(devinConfigPath, 'utf8')- installDevinHooks(18473)+ await installDevinHooks(18473)expect(readFileSync(devinConfigPath, 'utf8')).toBe(first)})it('collapses duplicate machine blocks left by an older path/port', async () => {- const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --port ${port} --engine devin` }] })+ const stale = (port: number) => ({ hooks: [{ type: 'command', command: `node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port ${port} --engine devin` }] })writeFileSync(devinConfigPath, JSON.stringify({ hooks: { SessionStart: [stale(19918), stale(19919)], Stop: [stale(19918)] } }))const { installDevinHooks } = await loadHooks()- installDevinHooks(18473)+ await installDevinHooks(18473)const out = JSON.parse(readFileSync(devinConfigPath, 'utf8')) as { hooks: Record<string, unknown[]> }expect(out.hooks.SessionStart).toHaveLength(1)@@ -317,12 +317,12 @@ describe('Devin hook installation', () => {it('creates the config when the user has none, and leaves a malformed one untouched', async () => {const { installDevinHooks } = await loadHooks()- installDevinHooks(18473)+ await installDevinHooks(18473)expect(JSON.parse(readFileSync(devinConfigPath, 'utf8')).hooks.SessionStart).toHaveLength(1)writeFileSync(devinConfigPath, '{ not json')const again = await loadHooks()- again.installDevinHooks(18473)+ await again.installDevinHooks(18473)expect(readFileSync(devinConfigPath, 'utf8')).toBe('{ not json')})})@@ -353,7 +353,7 @@ describe('Hermes hook installation', () => {it('appends one managed block, preserves the user config, and allowlists the command', async () => {const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const out = readFileSync(file, 'utf8')expect(blockCount(out)).toBe(1)@@ -372,8 +372,8 @@ describe('Hermes hook installation', () => {it('collapses to a SINGLE block when the port changes (no duplicate hooks: key)', async () => {const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)- installHermesHooks(19999)+ await installHermesHooks(18473)+ await installHermesHooks(19999)const out = readFileSync(file, 'utf8')expect(blockCount(out)).toBe(1)@@ -382,11 +382,11 @@ describe('Hermes hook installation', () => {it('absorbs an orphaned block left by an earlier buggy install', async () => {// Shape produced by the old marker-only rewrite: a bare `hooks:` mapping with our command.- const orphan = "\nhooks:\n pre_llm_call:\n - command: \"node '/old/notify.mjs' --port 19918 --engine hermes\"\n timeout: 10\n"+ const orphan = "\nhooks:\n pre_llm_call:\n - command: \"node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port 19918 --engine hermes\"\n timeout: 10\n"writeFileSync(file, `${USER_CONFIG}${orphan}`)const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const out = readFileSync(file, 'utf8')expect(blockCount(out)).toBe(1)@@ -396,9 +396,9 @@ describe('Hermes hook installation', () => {it('is idempotent', async () => {const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const first = readFileSync(file, 'utf8')- installHermesHooks(18473)+ await installHermesHooks(18473)expect(readFileSync(file, 'utf8')).toBe(first)})@@ -407,7 +407,7 @@ describe('Hermes hook installation', () => {writeFileSync(file, mine)const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)expect(readFileSync(file, 'utf8')).toBe(mine)expect(existsSync(join(hermesHome, 'shell-hooks-allowlist.json'))).toBe(false)@@ -429,7 +429,7 @@ describe('Hermes hook installation', () => {it('installs into every profile, each naming ITS OWN home', async () => {const demo = profileConfig('demo')const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const out = readFileSync(demo, 'utf8')expect(blockCount(out)).toBe(1)@@ -450,13 +450,13 @@ describe('Hermes hook installation', () => {// What `hermes profile create` leaves behind: our own block, frozen at the version that was// current when the ROOT config was last written — old port, old path, default home.const stale = "\n# machine-adapter: session discovery (managed block — safe to delete)\nhooks:\n"- + " on_session_start:\n - command: \"node '/old/notify.mjs' --port 19918 --hermes-home '/home/u/.hermes' --engine hermes\"\n timeout: 10\n"+ + " on_session_start:\n - command: \"node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port 19918 --hermes-home '/home/u/.hermes' --engine hermes\"\n timeout: 10\n"+ '# machine-adapter: end\n'const demo = profileConfig('demo')writeFileSync(demo, `${USER_CONFIG}${stale}`)const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const out = readFileSync(demo, 'utf8')expect(blockCount(out)).toBe(1)@@ -468,7 +468,7 @@ describe('Hermes hook installation', () => {it('a profile with no config of its own is not written to', async () => {mkdirSync(join(hermesHome, 'profiles', 'fresh'), { recursive: true })const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)expect(existsSync(join(hermesHome, 'profiles', 'fresh', 'config.yaml'))).toBe(false)})})@@ -505,7 +505,7 @@ describe('the Node interpreter baked into hook commands', () => {it('names an absolute, runnable interpreter and never the bare word node', async () => {const file = join(codexHome, 'hooks.json')const { codex } = await loadHooks()- codex.install(18473)+ await codex.install(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }const command = out.hooks.SessionStart[0].hooks[0].command@@ -527,7 +527,7 @@ describe('the Node interpreter baked into hook commands', () => {const file = join(codexHome, 'hooks.json')const { codex } = await loadHooks()- codex.install(18473)+ await codex.install(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }expect(interpreterOf(out.hooks.SessionStart[0].hooks[0].command)).toBe(upgraded)@@ -539,7 +539,7 @@ describe('the Node interpreter baked into hook commands', () => {const file = join(codexHome, 'hooks.json')const { codex } = await loadHooks()- codex.install(18473)+ await codex.install(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }// A hook naming an interpreter that cannot run is strictly worse than one naming the interpreter@@ -553,7 +553,7 @@ describe('the Node interpreter baked into hook commands', () => {const file = join(codexHome, 'hooks.json')const { codex } = await loadHooks()- codex.install(18473)+ await codex.install(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }expect(interpreterOf(out.hooks.SessionStart[0].hooks[0].command)).toBe(process.execPath)@@ -566,12 +566,12 @@ describe('the Node interpreter baked into hook commands', () => {const file = join(codexHome, 'hooks.json')writeFileSync(file, JSON.stringify({hooks: {- SessionStart: [{ hooks: [{ type: 'command', command: "node '/Users/someone/.harness/cli/notify.mjs' --port 18473 --engine codex" }] }],+ SessionStart: [{ hooks: [{ type: 'command', command: "node '/fixture/home/.harness/cli/notify.mjs' --data-dir '/fixture/old-harness' --port 18473 --engine codex" }] }],},}))const { codex } = await loadHooks()- codex.install(18473)+ await codex.install(18473)const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }const commands = out.hooks.SessionStart.flatMap((block) => block.hooks.map((h) => h.command))@@ -601,14 +601,14 @@ describe('Hermes hook allowlist', () => {const allowlist = join(hermesHome, 'shell-hooks-allowlist.json')writeFileSync(allowlist, JSON.stringify({approvals: [- { event: 'on_session_start', command: "node '/old/notify.mjs' --port 19918 --engine hermes" },- { event: 'pre_llm_call', command: "node '/old/notify.mjs' --port 19918 --engine hermes" },+ { event: 'on_session_start', command: "node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port 19918 --engine hermes" },+ { event: 'pre_llm_call', command: "node '/old/notify.mjs' --data-dir '/fixture/old-harness' --port 19918 --engine hermes" },{ event: 'on_session_start', command: '/usr/local/bin/somebody-elses-hook.sh' },],}))const { installHermesHooks } = await loadHooks()- installHermesHooks(18473)+ await installHermesHooks(18473)const out = JSON.parse(readFileSync(allowlist, 'utf8')) as { approvals: Array<{ event: string; command: string }> }expect(out.approvals.some((a) => a.command.includes('/old/notify.mjs'))).toBe(false)@@ -634,13 +634,13 @@ describe('Claude Code hooks in a moved home', () => {mkdirSync(join(home, 'work'), { recursive: true })writeFileSync(file, JSON.stringify({ model: 'opus', hooks: { Stop: [{ hooks: [{ type: 'command', command: 'say done' }] }] } }))const { claude } = await loadHooks()- claude.installIn(19473, join(home, 'work'))+ await claude.installIn(19473, join(home, 'work'))const first = readFileSync(file, 'utf-8')const settings = JSON.parse(first)expect(settings.model).toBe('opus')expect(settings.hooks.SessionStart[0].hooks[0].command).toContain('notify.mjs')expect(settings.hooks.Stop.map((block: { hooks: Array<{ command: string }> }) => block.hooks[0].command)).toEqual(['say done', expect.stringContaining('notify.mjs')])- claude.installIn(19473, join(home, 'work'))+ await claude.installIn(19473, join(home, 'work'))expect(readFileSync(file, 'utf-8')).toBe(first)})})diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex 72a5b732b..d21738b7d 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -25,7 +25,7 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key) => { calls.push(`writeConfig:${key}`); return `/state/grid-engine-config/${key}` },tmuxSupportsSessionEnv: async () => true,- installCodexHooks: (home) => { calls.push(`hooks:${home}`) },+ installCodexHooks: (home) => { calls.push(`hooks:${home}`); return true },// No Codex configuration unless a test says so — otherwise every relaunch built here would// consult the config.toml of whoever is running the suite.readCodexConfig: () => null,@@ -35,6 +35,21 @@ function deps(overrides: Partial<LaunchOverridesDeps> = {}) {}describe('buildLaunchOverrides — a relaunch comes back where the agent was', () => {+ it('awaits profile hook durability, holds an unavailable profile and checks ownership after completion', async () => {+ let finish!: (installed: boolean) => void, allowed = true, replied = false+ const install = vi.fn(() => new Promise<boolean>(resolve => { finish = resolve }))+ const { d } = deps({ installCodexHooks: install })+ const first = buildLaunchOverrides(d, 'codex', { codexHome: '/profiles/work' }, 'agent-1', () => allowed)+ .finally(() => { replied = true })+ await vi.waitFor(() => expect(install).toHaveBeenCalledTimes(1))+ expect(replied).toBe(false)+ finish(false)+ expect(await first).toMatchObject({ ok: false, unavailable: 'native' })+ const second = buildLaunchOverrides(d, 'codex', { codexHome: '/profiles/work' }, 'agent-1', () => allowed)+ await vi.waitFor(() => expect(install).toHaveBeenCalledTimes(2))+ allowed = false; finish(true)+ expect(await second).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })+ })it.each(['before', 'models', 'Store', 'commit', 'write'] as const)('revocation at %s cannot apply a stale preparation', async stage => {let allowed = stage !== 'before'const { d, calls } = deps({diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex f88a4db50..9b2c324fa 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -80,7 +80,7 @@ export interface LaunchOverridesDeps {tmuxSupportsSessionEnv: () => Promise<boolean>/** Install the daemon's hooks into a non-default Codex profile. The caller decides whether hook* installation is enabled at all. */- installCodexHooks: (codexHome: string) => void+ installCodexHooks: (codexHome: string) => boolean | Promise<boolean>/*** Read a Codex `config.toml`, for the provider an agent goes back to when it leaves a grid.*@@ -315,7 +315,9 @@ async function prepareBaseLaunchOverrides(// not the one `harness login` installed into — without this it fires no hook at all. Idempotent.const home = source.codexHomereturn { ok: true, commit: async () => {- deps.installCodexHooks(home)+ if (!await deps.installCodexHooks(home)) return {+ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm Codex’s hooks in the selected profile.',+ }return {ok: true,overrides: {diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.tsindex b1dbef636..f6eada8e5 100644--- a/cli/src/lib/resumeAgentService.spec.ts+++ b/cli/src/lib/resumeAgentService.spec.ts@@ -103,7 +103,7 @@ describe('production resume handler', () => {authority: createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: id => deps.restartJobs.revision(id), cancelled: id => deps.stopJobs.has(id) }),prepareApiTools: apiNotes, setGridLaunch: vi.fn(), setTail: vi.fn(),launchOverridesDeps: { machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(),- tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(), readCodexConfig: () => null },+ tmuxSupportsSessionEnv: async () => true, writeGridConfigDir: vi.fn(), installCodexHooks: vi.fn(async () => true), readCodexConfig: () => null },})deps.relaunchOverrides = helpers.relaunchOverridesexpect(registry.byAgent(saved.agentId)).toBeUndefined()diff --git a/cli/src/scm/scmLaunch.spec.ts b/cli/src/scm/scmLaunch.spec.tsindex 9c30b48e3..644281a73 100644--- a/cli/src/scm/scmLaunch.spec.ts+++ b/cli/src/scm/scmLaunch.spec.ts@@ -30,7 +30,7 @@ function deps(): LaunchOverridesDeps {machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,tmuxSupportsSessionEnv: async () => true,- installCodexHooks: () => {},+ installCodexHooks: () => true,readCodexConfig: () => null,}}diff --git a/cli/src/testing/hookGoldenSafety.ts b/cli/src/testing/hookGoldenSafety.tsnew file mode 100644index 000000000..85f275c4e--- /dev/null+++ b/cli/src/testing/hookGoldenSafety.ts@@ -0,0 +1,47 @@+/** Corrections to unsafe former file operations, without rewriting their goldens.+ * Healthy bytes and logs still compare with the recorded former implementation. */+import { expect } from 'vitest'++type File = { type: string; mode?: string; text?: string; target?: string }+export type HookFiles = Record<string, File>++/** Atomic publication now preserves file modes, leaf aliases and pre-existing+ * temporary files. Apply those explicit ownership changes to the former result. */+export function preservedHookFiles(before: HookFiles, former: HookFiles): HookFiles {+ const expected = structuredClone(former)+ for (const [path, entry] of Object.entries(before)) {+ if (entry.type === 'file' && expected[path]?.type === 'file') expected[path].mode = entry.mode+ if (path.endsWith('.<pid>.tmp')) expected[path] = entry+ if (entry.type === 'link' && expected[path]?.type === 'file') {+ const target = entry.target!.replace('<root>/', '')+ expected[target] = { ...expected[path], mode: before[target].mode }+ expected[path] = entry+ }+ }+ return expected+}++/** An old basename-only ownership guess could erase these commands. The new+ * installation must retain every foreign command and still add the recorded+ * canonical hooks, without changing unrelated settings. */+export function expectForeignHooksPreserved(before: HookFiles, after: HookFiles, former: HookFiles, file: string): void {+ const prior = JSON.parse(before[file].text!), actual = JSON.parse(after[file].text!), canonical = JSON.parse(former[file].text!)+ for (const [key, value] of Object.entries(prior)) if (key !== 'hooks') expect(actual[key]).toEqual(value)+ for (const [event, blocks] of Object.entries(prior.hooks ?? {})) {+ for (const block of blocks as Array<Record<string, unknown>>) {+ if (Array.isArray(block.hooks)) {+ const foreign = block.hooks.filter((hook: { command?: string }) => !hook.command?.startsWith('<command '))+ if (foreign.length) expect(actual.hooks[event]).toContainEqual({ ...block, hooks: foreign })+ } else expect(actual.hooks[event]).toContainEqual(block)+ }+ }+ for (const [event, blocks] of Object.entries(canonical.hooks ?? {})) {+ for (const block of blocks as Array<Record<string, unknown>>) {+ if (typeof block.command === 'string' && block.command.startsWith('<command ')) expect(actual.hooks[event]).toContainEqual(block)+ else if (Array.isArray(block.hooks) && block.hooks.some((hook: { command?: string }) => hook.command?.startsWith('<command '))) {+ expect(actual.hooks[event]).toContainEqual(block)+ }+ }+ }+ expect(after[file].mode).toBe(before[file].mode)+}diff --git a/cli/src/testing/launchShapes.ts b/cli/src/testing/launchShapes.tsindex 2b15939e7..9aa46c455 100644--- a/cli/src/testing/launchShapes.ts+++ b/cli/src/testing/launchShapes.ts@@ -86,7 +86,7 @@ export function launchShapes(world: LaunchWorld) {gridLaunch,writeGridConfigDir,tmuxSupportsSessionEnv: world.tmuxSupportsSessionEnv,- installCodexHooks: () => {},+ installCodexHooks: () => true,readCodexConfig: world.readCodexConfig,dshLaunch: dshLaunch.relaunch,}diff --git a/docs/research/2026-10-11-native-launch-preparation.md b/docs/research/2026-10-11-native-launch-preparation.mdnew file mode 100644index 000000000..d7ae7e4cf--- /dev/null+++ b/docs/research/2026-10-11-native-launch-preparation.md@@ -0,0 +1,200 @@+# Native launch preparation++Status: hook durability mechanics are in final validation. They are part of+group 2 of the [daemon core checklist](2026-10-09-daemon-core-completion.md).+The whole-launch integration below remains in progress in a separate worktree;+neither group 2 nor the daemon refactor is complete. No release is authorized.++The healthy OpenCode v1 → v2 → v1 → current behavior was recorded from main+`10adc628d` in its own commit, `d5d796623`. Its fixture remains unchanged.+The earlier Claude/Codex and other-engine hook fixtures also remain unchanged.+The tests pin platform, replace host executable paths, and run under+`TZ=UTC TMPDIR=/tmp` with private configuration homes.++## Implemented mechanics++- Executable observations retain their identity. An executable observation owns+ one resolved command and the file version that answered its version probe.+- Hook preparation inspects every destination before publication, preserves+ foreign commands and settings, rejects malformed or ambiguous configuration,+ follows only retained home/file aliases, and preserves existing permissions.+- Codex approvals and Hermes allowlists are prepared before changing their hook+ settings. OpenCode prepares both discovery surfaces before removing its v1+ plugin or installing its TUI plugin. Final confirmation checks every output.+- Atomic replacements use exclusive staging files, file synchronization, rename,+ and directory synchronization. A failed confirmation remains unavailable even+ when the intended bytes are already present; retry repeats the durability proof.+- Synchronization is asynchronous in eager code. A timed-out attempt retains its+ descriptor and destination reservations until the actual syscall settles. Its+ revoked authority prevents any later rename, removal, or acknowledgement.+ There are at most sixteen actual preparations, with at most thirty-two+ destinations each. Aliases reserve their canonical destinations together.+- Home adoption distinguishes a confirmed home from confirmed installed hooks.+ An in-flight installation does not acknowledge success or run twice. A stalled+ home leaves sibling installation and shutdown available.++The JSON command ownership rule checks the literal Harness notification protocol,+not merely the substring `notify.mjs`. Full TOML and YAML parsing preserves unknown+configuration instead of treating it as empty. Parsers are pinned to+`smol-toml` 1.9.0 and `yaml` 2.9.1. TOML depth and YAML lexer work are bounded;+no YAML aliases are expanded. The TOML pin includes the fix for+[GHSA-7w5x-hrqm-74c2](https://github.com/advisories/GHSA-7w5x-hrqm-74c2).+The YAML API is documented by its [maintainer](https://eemeli.org/yaml/).++Some old golden scenarios recorded destructive recovery of malformed/foreign+files. Those fixture bytes remain available for comparison; the scenario now+asserts exact preservation and an explicit unavailable result. Healthy scenarios+still compare against the former artifacts. Mode, alias, and unrelated temporary+file preservation are asserted explicitly.++## Validation checkpoint++On October 10, UTC, using Node 22.23.2 on macOS:++- `20261010T234958.425927Z-92785`: typecheck passed; 183 focused tests passed.+ These include blocked flush, deadline, retained descriptor/reservation,+ executable supersession, shutdown, independent home retry, and recovery cases.+- `20261010T234840.092679Z-87419`: all 441 hook golden cases passed. The focused+ suite in this earlier receipt failed a test that mixed a fake timer with the+ real monotonic clock; the later focused receipt above covers its correction.+- The native version golden passes unchanged in the focused suite.+- Core/harnessd coverage, launch integration, wiring mutations, private e2e,+ final architecture acceptance, and exact-head independent review are pending.+ This checkpoint is not landing evidence for those gates.++The same private workload compared main with the candidate in three alternating+pairs: thirteen installers, cold/current/changed-port/current. Both used the same+Node runtime, a fixture version executable, private homes, and no daemon or tmux.+Medians are descriptive measurements, not new numerical gates:++| Measurement | Main | Async durable candidate |+| --- | ---: | ---: |+| Total wall time, including imports | 558 ms | 3,368 ms |+| CPU | 156 ms | 518 ms |+| Peak RSS | 91 MiB | 107 MiB |+| Cold round maximum callback gap | 13.5 ms | 31.0 ms |+| First current round maximum callback gap | 3.0 ms | 5.8 ms |+| Changed-port maximum callback gap | 6.6 ms | 21.4 ms |+| Last current round maximum callback gap | 1.9 ms | 4.2 ms |++Durable preparation does more work than the former best-effort writes. An initial+synchronous implementation took a median 3,880 ms total and could block session+control while syncing. The asynchronous candidate leaves the event loop available+during those waits; callback gaps measure that distinction, not actual Stop latency.+Whole-launch cost, readiness, and unrelated Stop latency still require integration+measurement. There is no cross-request configuration or durability cache.++## Remaining launch integration++Every create/fork/restart/retarget/restore/external-resume path must use a confirmed+snapshot for permission probing, versioned choices, hooks, native APIs, and argv.+The shell must execute that exact binary after its startup files, with a final+identity check. Missing engines need an installer-only phase that returns to core+preparation before native execution. An unknown version cannot be guessed as v1.++Preparation failures must become visible durable holds, including manual requests.+A held operation against a running pane must preserve the live row and process;+only inert panes may use the existing held-launch state. Startup hook coordination+must stop waiting for disk work only when these per-launch checks are wired.+Retries must preserve the original request and ownership, work independently, and+be revoked by Stop/Close. These caller migrations remain unfinished; the mechanics+PR does not enable the draft whole-launch integration.++## Time accounting++This slice began October 10 at 22:49 UTC. The checkpoint above was reached about+an hour later, including implementation, focused validation and design review.+Implementation and validation overlapped; receipt durations describe individual+checks, not total delivery time. Merge and publication are both zero for this slice.++## Independent review corrections++Review of `7a2cedfd1` identified eight races or preservation gaps: staging-file+replacement during a flush, stale second-file preflight, destination alias changes+before dispatch, joining owners/deadlines, an expiring removal deadline, changed+managed-Node commands joining old work, Hermes profile-pool starvation, and umask+changing existing shared permissions. Each now has a regression and an implementation+fix; final exact-head approval remains pending. Filesystem confirmations use at most+two libuv slots, leaving capacity for native transcript reads. Queued work cancels+before dispatch when its owner or deadline expires.++The October 11 00:06 UTC receipt passed typecheck and all 441 unchanged golden+cases. Focused checks passed 192 of 193; the 19-home Hermes capacity case exceeded+the test's five-second total timeout (each individual preparation has its own+five-second deadline). Its total test allowance is now 20 seconds for the five+sequential waves; the per-preparation production deadline and assertions are unchanged.+The matched three-pair measurement reported median baseline/candidate totals of+586.6/3328.5 ms, CPU 142.3/623.6 ms, and peak RSS 91.4/109.5 MiB. Cold-install+maximum timer gaps were 11.5/59.2 ms. These results show the extra durability cost;+they do not prove native-read latency under a stalled filesystem. Final acceptance+will measure that separately after launch integration.++Review of `ace259746` found four additional gaps: a joining deadline could pass+before its timer callback, an alias join could acknowledge a different route,+OpenCode could credit a newer installation to a revoked older caller, and shell+globs/newlines could cause a foreign command to be mistaken for an owned hook.+The corrections have regressions. Each confirmed publication also retains its+exact file and alias facts for the later launch guard; an alias join retains its+own route. The OpenCode follow deadline includes the original preparation.++The integration worktree's 00:33 UTC receipt passed typecheck and focused hooks+and launch tests. A later expanded run exposed a local type annotation error in+the unfinished held-launch integration and one native-process fixture failure+under load; the isolated native-version rerun passed all eleven tests without a+production change. These are development evidence, not the final mechanics gate.+The mechanics branch integrates main `93d49e9c8` (routing changes only) and runs+its own final gates, independent review, mutations and private e2e lanes.++Review of `28264b32a` found three remaining mechanics defects: custom Codex+profile callers discarded the asynchronous installation result; a proof capture+could adopt a peer edit between verification and its own filesystem reads; and+OpenCode reservation/final-proof reads could outlive the original deadline.+The callers now await installation before pane creation or external takeover,+proofs must still match the original publication, and the original deadline is+checked across reservation and final acknowledgement. Regressions also cover+owner revocation while waiting. The revoked-joiner mutation now uses an oracle+that actually joins while the caller still owns its request.++The mechanics gate at 00:49 UTC passed typecheck, architecture, harnessd coverage+and 441 golden cases. Core and affected tests exposed three obsolete test+fixtures after the asynchronous API change: a removed mock export, an unawaited+Pi installation and the former unknown-OpenCode-version expectation. The+00:56 UTC receipt (`20261011T005625.232631Z-71860`) covers their corrections and+all three review fixes: typecheck, 203 focused cases and 316 affected cases pass+(five environment-gated cases remain skipped). Full core coverage, private e2e,+assertion-failing mutations and exact-head approval are still required.++Final review of `1f71fd298` identified a prerequisite: refusing an unknown+OpenCode version also prevents a clean machine from reaching its existing pane+installer. This mechanics slice therefore preserves main's legacy TUI preparation+for that case. Unknown-version launch holds belong with installer-only continuation+in the whole-launch change. A create regression now covers the absent-version+route; no claim is made that this PR completes native launch safety.++The first mutation run caught nine faults but four test oracles were inadequate+(two type errors, an early-join timeout and a reservation fixture that reached the+wrong filesystem read). Their assertions/fixture now target the intended behavior.+The unknown-version mutant is deferred with its prerequisite, leaving twelve.+The 01:04 UTC full gate passed typecheck, architecture, harnessd and all 441 hook+goldens; core reported three handoff-publication timeouts under concurrent disk+work. Its remaining tests were interrupted for the required review correction.+The private e2e run passed three eager-hook cases and failed the Codex case because+the local bundle omitted the required macOS process-control helper. The corrected+run must embed the matching locally built helper; it is not a production change.++Linux CI on `1f71fd298` found that removing the legacy null-version cache changes+the old unknown-version command trace. That policy change is deferred with the+whole-launch snapshot, keeping the launch golden unchanged in this mechanics PR.+CI also exposed a transient native directory-enumeration hold when another test+changed an ancestor under `/tmp`. The Stop/archive regression now checks that this+specific hold preserves the row and retries it at most twice; all other errors+still fail immediately. This changes no production identity rule.++At 01:15 UTC, typecheck, 201 focused native cases, architecture, harnessd at 100%+and 359 affected cases passed (five environment-gated cases skipped). All 2,393+core tests passed; the coverage gate identified one uncovered synchronous-false+installer result. The test named for synchronous/asynchronous holds now exercises+both. The no-OpenCode golden assertion also returns to its unchanged former+artifact alongside the deferred policy. No golden fixture bytes were rerecorded.+All twelve deliberate mutations failed assertions in receipt+`20261011T011530.711952Z-59124`; final core/golden gates and private e2e remain.