Skip to content

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.

Keep daemon readiness independent of native hook maintenance (#1166)

Deec66139d032d3
diff --git a/cli/e2e/eagerHooks.e2e.ts b/cli/e2e/eagerHooks.e2e.ts
index d28336e53..8f4ec7c14 100644
--- a/cli/e2e/eagerHooks.e2e.ts
+++ b/cli/e2e/eagerHooks.e2e.ts
@@ -33,6 +33,40 @@ it('refuses a native hook destination outside the test, including the OpenCode s
expect(() => assertHooksContained(d.root, d.env)).toThrow('supported hook engines')
})
+it('becomes ready and serves control while startup hook preparation is still waiting', async () => {
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: bundle, env: { HARNESS_CONNECTIONS_PORT: '0' } })
+ onTestFailed(() => console.log(d.log()))
+ const binary = join(d.root, 'bin', 'opencode'), entered = join(d.root, 'startup-probe'), release = join(d.root, 'release-probe')
+ d.env.OPENCODE_PATH = binary
+ d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')
+ d.env.HOOK_INSTALL_ENGINES = 'opencode'
+ writeFileSync(binary, `#!${process.execPath}
+const fs = require('node:fs');
+if (!process.argv.includes('--version')) process.exit(2);
+fs.writeFileSync(${JSON.stringify(entered)}, String(process.pid));
+const timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(timer); console.log('opencode v2.0.18'); } }, 10);
+`, { mode: 0o755 })
+ try {
+ await d.start()
+ const pid = await until('the unreleased startup probe to enter', () => {
+ try {
+ const value = Number(readFileSync(entered, 'utf8'))
+ return Number.isSafeInteger(value) && value > 1 ? value : null
+ } catch { return null }
+ }, 3_000, 10)
+ const alive = () => { try { process.kill(pid, 0); return true } catch { return false } }
+ // Waiting for the bounded probe's timeout is still waiting for a dependency.
+ // The former startup only became ready after killing this unreleased child.
+ expect(alive()).toBe(true)
+ const c = client = await LocalClient.connect(d)
+ expect((await c.request('agents_list', { includeStopped: true }, 1_500)).agents).toEqual([])
+ expect(alive()).toBe(true)
+ expect(d.coresStarted()).toBe(1)
+ } finally { writeFileSync(release, '') }
+ await until('the startup hook to finish after its probe is released', () =>
+ existsSync(join(d.root, 'opencode', 'plugins', 'launcher-register', 'tui.js')), 10_000)
+}, 30_000)
+
it('keeps Stop and agent listing responsive while a native launch version probe waits', async () => {
const d = daemon = await IsolatedDaemon.create({ scriptPath: bundle, env: { HARNESS_CONNECTIONS_PORT: '0' } })
onTestFailed(() => console.log(d.log()))
@@ -156,7 +190,9 @@ it.each(['create', 'fork'] as const)('keeps a post-rc held %s with its original
// Only the new pane's rc file changes this private config, after preparation.
// Native probes have no TMUX_PANE. This forces the real final guard to hold.
const config = join(d.engineConfig.codexHome, 'config.toml'), trigger = join(d.root, 'change-once')
- const original = readFileSync(config)
+ const original = await until('startup hook preparation to create the private Codex config', () => {
+ try { return readFileSync(config) } catch { return null }
+ }, 10_000)
writeFileSync(trigger, '')
writeFileSync(join(d.env.HOME!, '.bashrc'), `if [ -n "$TMUX_PANE" ] && [ -f ${shellSingleQuote(trigger)} ]; then printf '\\n# changed by private pane fixture\\n' >> ${shellSingleQuote(config)}; /bin/rm ${shellSingleQuote(trigger)}; fi\n`)
const response = await c.request(operation === 'create' ? 'agent_create' : 'agent_fork', operation === 'create'
@@ -213,11 +249,6 @@ console.log('┃'); setInterval(() => {}, 1000);
`, { mode: 0o755 })
await d.start()
expect(d.log()).not.toContain('[fixture] legacy hooks stalled')
- for (const file of ['cursor/hooks.json', 'opencode/plugins/launcher-register/tui.js', 'kilo/plugin/launcher-register.js',
- 'pi/agent/extensions/launcher-register.ts', 'amp/plugins/launcher-register.ts', 'hermes/config.yaml',
- 'devin/config.json', 'commandcode/settings.json', 'grok/hooks/harness.json', 'agy/hooks.json', 'copilot/hooks/harness.json']) {
- expect(readFileSync(join(root, file), 'utf8'), file).toContain(String(d.port))
- }
const c = client = await LocalClient.connect(d)
const row = async (id: string) => ((await c.request('agents_list', { includeStopped: true })).agents as Array<Record<string, any>>).find(one => one.id === id)
const active = (id: string) => until('a native process to bind without optional hooks', async () => {
@@ -229,7 +260,17 @@ console.log('┃'); setInterval(() => {}, 1000);
expect(result.error, JSON.stringify(result)).toBeUndefined()
return active(result.agent.id)
}
+ // Readiness must permit a cold launch while startup maintenance is still finishing.
const native = await create('opencode')
+ const hookFiles = ['cursor/hooks.json', 'opencode/plugins/launcher-register/tui.js', 'kilo/plugin/launcher-register.js',
+ 'pi/agent/extensions/launcher-register.ts', 'amp/plugins/launcher-register.ts', 'hermes/config.yaml',
+ 'devin/config.json', 'commandcode/settings.json', 'grok/hooks/harness.json', 'agy/hooks.json', 'copilot/hooks/harness.json']
+ await until('all selected native hooks to finish after readiness', () => hookFiles.every(file => {
+ try { return readFileSync(join(root, file), 'utf8').includes(String(d.port)) } catch { return false }
+ }), 10_000)
+ for (const file of hookFiles) {
+ expect(readFileSync(join(root, file), 'utf8'), file).toContain(String(d.port))
+ }
const sibling = await create(engine)
const started = c.next(frame => frame.type === 'turn_started' && frame.agentId === sibling.id, 30_000)
c.send('message', { agentId: sibling.id, content: '!slow 8000' }); await started
diff --git a/cli/e2e/opencodeLaunchCost.e2e.ts b/cli/e2e/opencodeLaunchCost.e2e.ts
index 746419819..f9ad12a1a 100644
--- a/cli/e2e/opencodeLaunchCost.e2e.ts
+++ b/cli/e2e/opencodeLaunchCost.e2e.ts
@@ -48,7 +48,7 @@ console.log('┃'); setInterval(() => {}, 1000);
const cwd = join(d.projectsDir, String(i)); mkdirSync(cwd)
const before = sample(d.corePid()!), start = performance.now()
const result = await client.request('agent_create', { engine: 'opencode', cwd }, 30000)
- expect(result.error).toBeUndefined()
+ expect(result.error, `${which}: ${JSON.stringify(result)}\n${d.output}`).toBeUndefined()
const after = sample(d.corePid()!)
launches.push({ phase: i ? 'warm' : 'cold', requestMs: performance.now() - start, coreCpuMs: after.cpuMs - before.cpuMs, rssMiB: after.rssMiB })
}
diff --git a/cli/scripts/handoff-2026-10-08/mutate-hook-readiness.py b/cli/scripts/handoff-2026-10-08/mutate-hook-readiness.py
new file mode 100644
index 000000000..b407f0dbb
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-hook-readiness.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Check startup wiring mutations 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'
+hooks = 'src/core/engines/hooks.ts'
+golden = 'src/core/engines/hookStartup.golden.spec.ts'
+ready = " coreLink.ready()\n console.log('[cli] ready')\n"
+start = " installedHooks = env.DISABLE_HOOK_INSTALL ? undefined\n : installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })\n"
+before_ready = ready + " // Each launch confirms its own hooks. Startup never waits on any vendor's disk or probe.\n" + start
+blocked_ready = start + " await installedHooks?.settled\n" + ready
+mutations = [
+ ('wrong hook port', hooks, 'hooks.install(port, nativeOptions)', 'hooks.install(port + 1, nativeOptions)', golden, ''),
+ ('omit native vendors', hooks, 'of OTHER_INSTALLERS)', 'of OTHER_INSTALLERS.slice(0, 0))', golden, ''),
+ ('ignore selected vendors', hooks, 'if (options.only && !options.only.has(vendor)) return', 'if (false) return', golden, ''),
+ ('retain writes after shutdown', hooks, 'close: adoptions.close', 'close: () => {}', 'src/core/engines/hooks.spec.ts', 'returns shutdown authority'),
+ ('collide with startup maintenance', 'src/engines/nativeHooks.ts', 'if (previous && (previous.settling || previous.major !== undefined', 'if (previous && false && (previous.settling || previous.major !== undefined', 'src/engines/nativeHookPreparation.spec.ts', 'waits for startup maintenance'),
+ ('separate aliased destinations', 'src/engines/nativeHooks.ts', 'const reservation = JSON.stringify(routes.keys)', 'const reservation = root', 'src/engines/nativeHookPreparation.spec.ts', 'through alias paths'),
+ ('unbounded preparation callers', 'src/engines/nativeHooks.ts', 'if (group.users >= 16) return false', 'if (false) return false', 'src/engines/nativeHookPreparation.spec.ts', 'bounds launch callers'),
+ ('discard help after a core stall', 'src/engines/nativeLaunch.ts', "env: nativeProcessEnvironment(environment), encoding: 'utf8', killSignal: 'SIGKILL', maxBuffer:", "env: nativeProcessEnvironment(environment), encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer:", 'src/engines/nativeLaunch.probe.spec.ts', 'complete permission answer'),
+ ('retain inherited probe pipes', 'src/engines/nativeLaunch.ts', 'child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy()', 'void child', 'src/engines/nativeLaunch.probe.spec.ts', 'inherited output pipes'),
+ ('release unsettled probe capacity', 'src/engines/nativeLaunch.ts', '// An uninterruptible child retains its slot until the actual callback.\n answer(null)', '// Incorrectly free a slot while its child can still run.\n probes--; answer(null)', 'src/engines/nativeLaunch.spec.ts', 'retaining its slot'),
+ ('await hooks before readiness', 'src/core/main.ts', before_ready, blocked_ready, 'e2e/eagerHooks.e2e.ts', 'becomes ready and serves control'),
+]
+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')
+for key in ('TMUX', 'TMUX_PANE', 'RECORD_HOOK_STARTUP_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=''):
+ argv = ['node', 'node_modules/vitest/vitest.mjs', 'run']
+ if any(spec.startswith('e2e/') for spec in specs):
+ argv += ['--config', 'vitest.e2e.config.ts']
+ argv += [*specs, '--maxWorkers=1']
+ if pattern:
+ argv += ['-t', pattern]
+ return subprocess.run(argv, cwd=cli, env=environment, text=True, capture_output=True, timeout=120)
+
+
+for specs, pattern in [(sorted({item[4] for item in mutations if not item[4].startswith('e2e/')}), ''),
+ (['e2e/eagerHooks.e2e.ts'], 'becomes ready and serves control')]:
+ baseline = run(specs, pattern)
+ assert baseline.returncode == 0, 'Unchanged baseline failed.\n' + baseline.stdout + baseline.stderr
+print('Unchanged baseline passed', flush=True)
+failures = []
+for label, relative, before, after, spec, pattern in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == 1, (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/engines/__fixtures__/hook-startup.golden.json b/cli/src/core/engines/__fixtures__/hook-startup.golden.json
new file mode 100644
index 000000000..f9e4b2e57
--- /dev/null
+++ b/cli/src/core/engines/__fixtures__/hook-startup.golden.json
@@ -0,0 +1,534 @@
+{
+ "linux": {
+ "all vendors": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [],
+ "messages": []
+ },
+ "selected vendors": {
+ "calls": [
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [],
+ "messages": []
+ },
+ "adopted homes": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "/fixture/own-claude"
+ ],
+ [
+ "claude",
+ 4242,
+ "/fixture/saved-claude"
+ ],
+ [
+ "codex",
+ 4242,
+ "/fixture/saved-codex"
+ ],
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "/fixture/shell-codex"
+ ]
+ ],
+ "warnings": [
+ "[hooks] home adoption held · Waiting for hook installation in an adopted home."
+ ],
+ "messages": [
+ "[hooks] Claude Code hooks installed in its adopted home",
+ "[hooks] Claude Code hooks installed in its adopted home",
+ "[hooks] Codex hooks installed in its adopted home",
+ "[hooks] Codex hooks installed in its adopted home",
+ "[hooks] home adoption recovered"
+ ]
+ },
+ "one unavailable vendor": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [
+ "[hooks] cursor install skipped · native hook preparation is unavailable"
+ ],
+ "messages": []
+ }
+ },
+ "darwin": {
+ "all vendors": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [],
+ "messages": []
+ },
+ "selected vendors": {
+ "calls": [
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [],
+ "messages": []
+ },
+ "adopted homes": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "/fixture/own-claude"
+ ],
+ [
+ "claude",
+ 4242,
+ "/fixture/saved-claude"
+ ],
+ [
+ "codex",
+ 4242,
+ "/fixture/saved-codex"
+ ],
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "/fixture/shell-codex"
+ ]
+ ],
+ "warnings": [
+ "[hooks] home adoption held · Waiting for hook installation in an adopted home."
+ ],
+ "messages": [
+ "[hooks] Claude Code hooks installed in its adopted home",
+ "[hooks] Claude Code hooks installed in its adopted home",
+ "[hooks] Codex hooks installed in its adopted home",
+ "[hooks] Codex hooks installed in its adopted home",
+ "[hooks] home adoption recovered"
+ ]
+ },
+ "one unavailable vendor": {
+ "calls": [
+ [
+ "claude",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "codex",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "cursor",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "opencode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "kilo",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "pi",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "amp",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "hermes",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "devin",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "commandcode",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "grok",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "agy",
+ 4242,
+ "<default-home>"
+ ],
+ [
+ "copilot",
+ 4242,
+ "<default-home>"
+ ]
+ ],
+ "warnings": [
+ "[hooks] cursor install skipped · native hook preparation is unavailable"
+ ],
+ "messages": []
+ }
+ }
+}
diff --git a/cli/src/core/engines/hookStartup.golden.spec.ts b/cli/src/core/engines/hookStartup.golden.spec.ts
new file mode 100644
index 000000000..adad8e35e
--- /dev/null
+++ b/cli/src/core/engines/hookStartup.golden.spec.ts
@@ -0,0 +1,75 @@
+/** Former startup coordination, recorded from main before readiness stops waiting
+ * for hook preparation. Native file contents have their own installer goldens.
+ * This record pins the core's vendor/port/home dispatch and independent refusals.
+ * All files and installers are fixtures; no host binary or engine home is used. */
+import { readFileSync, writeFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { afterEach, expect, it, vi } from 'vitest'
+import { installEngineHooks } from './hooks.js'
+
+const world = vi.hoisted(() => {
+ const state = { calls: [] as unknown[][], homes: { claude: [] as string[], codex: [] as string[] }, failed: '' }
+ const install = (engine: string, port: number, home?: string) => {
+ state.calls.push([engine, port, home ?? '<default-home>'])
+ return Promise.resolve(engine !== state.failed)
+ }
+ return { state, install }
+})
+vi.mock('../../engines/hooks.js', () => ({ engineHooks: {
+ claude: { install: (port: number) => world.install('claude', port), installIn: (port: number, home: string) => world.install('claude', port, home) },
+ codex: { install: (port: number) => world.install('codex', port), installIn: (port: number, home: string) => world.install('codex', port, home) },
+} }))
+vi.mock('../../engines/nativeHooks.js', () => ({
+ installCursorHooks: (port: number) => world.install('cursor', port),
+ installOpencodePlugin: (port: number) => world.install('opencode', port),
+ installKiloPlugin: (port: number) => world.install('kilo', port),
+ installPiExtension: (port: number) => world.install('pi', port),
+ installAmpPlugin: (port: number) => world.install('amp', port),
+ installHermesHooks: (port: number) => world.install('hermes', port),
+ installDevinHooks: (port: number) => world.install('devin', port),
+ installCommandCodeHooks: (port: number) => world.install('commandcode', port),
+ installGrokHooks: (port: number) => world.install('grok', port),
+ installAgyHooks: (port: number) => world.install('agy', port),
+ installCopilotHooks: (port: number) => world.install('copilot', port),
+}))
+vi.mock('../../lib/engineHomes.js', () => ({
+ recoverEngineHomes: () => world.state.homes,
+ confirmHomes: (environment: NodeJS.ProcessEnv) => ({ claude: environment.CLAUDE_CONFIG_DIR ?? null, codex: environment.CODEX_HOME ?? null }),
+}))
+
+const artifact = fileURLToPath(new URL('./__fixtures__/hook-startup.golden.json', import.meta.url))
+afterEach(() => vi.restoreAllMocks())
+
+it('preserves the original vendor, adopted-home and refusal coordination', async () => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const record: Record<string, unknown> = {}
+ try {
+ for (const platform of ['linux', 'darwin']) {
+ Object.defineProperty(process, 'platform', { ...originalPlatform, value: platform })
+ const cases: Record<string, unknown> = {}
+ for (const name of ['all vendors', 'selected vendors', 'adopted homes', 'one unavailable vendor']) {
+ world.state.calls = []
+ world.state.homes = name === 'adopted homes' ? { claude: ['/fixture/saved-claude'], codex: ['/fixture/saved-codex'] } : { claude: [], codex: [] }
+ world.state.failed = name === 'one unavailable vendor' ? 'cursor' : ''
+ const warnings: string[] = [], messages: string[] = []
+ vi.spyOn(console, 'warn').mockImplementation(value => { warnings.push(String(value)) })
+ vi.spyOn(console, 'log').mockImplementation(value => { messages.push(String(value)) })
+ const installed = await installEngineHooks(4242, {
+ environment: name === 'adopted homes' ? { CLAUDE_CONFIG_DIR: '/fixture/own-claude' } : {},
+ loginShell: Promise.resolve(name === 'adopted homes' ? { CODEX_HOME: '/fixture/shell-codex' } : {}),
+ ...(name === 'selected vendors' ? { only: new Set(['codex', 'opencode', 'hermes']) } : {}),
+ })
+ // A synchronous controller may expose completion separately once startup
+ // no longer waits on it. The recorded observations stay unchanged.
+ await (installed as { settled?: Promise<void> }).settled
+ await Promise.resolve()
+ installed.close()
+ cases[name] = { calls: world.state.calls, warnings: warnings.sort(), messages: messages.sort() }
+ vi.restoreAllMocks()
+ }
+ record[platform] = cases
+ }
+ } finally { Object.defineProperty(process, 'platform', originalPlatform) }
+ if (process.env.RECORD_HOOK_STARTUP_GOLDEN === '1') writeFileSync(artifact, JSON.stringify(record, null, 2) + '\n')
+ expect(record).toEqual(JSON.parse(readFileSync(artifact, 'utf8')))
+})
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index 90b235d1c..1d9986af1 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -365,12 +365,14 @@ describe('installing every engine\'s hooks', () => {
hooks.installDevinHooks, hooks.installCommandCodeHooks, hooks.installGrokHooks, hooks.installAgyHooks,
hooks.installCopilotHooks,
]
+ const startupArgs = (install: unknown) => install === hooks.installOpencodePlugin || install === hooks.installHermesHooks
+ ? [4242, undefined, { current: expect.any(Function) }] : [4242, { current: expect.any(Function) }]
beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}) })
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); loading.stalled = false })
it('points all thirteen at the bound port without loading optional code', async () => {
await installEngineHooks(4242)
- for (const install of installs) expect(install).toHaveBeenCalledWith(4242)
+ for (const install of installs) expect(install).toHaveBeenCalledWith(...startupArgs(install))
expect(console.warn).not.toHaveBeenCalled()
expect(loadEngine).not.toHaveBeenCalled()
})
@@ -388,20 +390,36 @@ describe('installing every engine\'s hooks', () => {
let finish!: () => void
vi.mocked(hooks.installOpencodePlugin).mockImplementationOnce(() => new Promise<boolean>(done => { finish = () => done(true) }))
let completed = false
- const pending = installEngineHooks(4242).then(value => { completed = true; return value })
- expect(hooks.installCopilotHooks).toHaveBeenCalledWith(4242)
+ const installed = installEngineHooks(4242)
+ const pending = installed.settled.then(() => { completed = true })
+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(...startupArgs(hooks.installCopilotHooks))
await Promise.resolve()
expect(completed).toBe(false)
finish()
- const installed = await pending
+ await pending
installed.close()
expect(completed).toBe(true)
})
+ it('returns shutdown authority while all thirteen native preparations are still waiting', async () => {
+ const writes: Array<{ current: () => boolean; finish: (ready: boolean) => void }> = []
+ for (const install of installs) (install as Mock).mockImplementationOnce((...args: unknown[]) => {
+ const { current } = args.at(-1) as { current: () => boolean }
+ return new Promise<boolean>(finish => { writes.push({ current, finish }) })
+ })
+ const installed = installEngineHooks(4242, { environment: {} })
+ expect(writes).toHaveLength(13)
+ expect(writes.every(write => write.current())).toBe(true)
+ installed.close()
+ expect(writes.every(write => !write.current())).toBe(true)
+ for (const write of writes) write.finish(false)
+ await installed.settled
+ })
+
it('contains an asynchronous native installer rejection', async () => {
vi.mocked(hooks.installOpencodePlugin).mockRejectedValueOnce(new Error('probe unavailable'))
const installed = await installEngineHooks(4242)
- expect(hooks.installCopilotHooks).toHaveBeenCalledWith(4242)
+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(...startupArgs(hooks.installCopilotHooks))
expect(console.warn).toHaveBeenCalledWith('[hooks] opencode install skipped · probe unavailable')
installed.close()
})
@@ -424,7 +442,7 @@ describe('installing every engine\'s hooks', () => {
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)
+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(...startupArgs(hooks.installCopilotHooks))
installed.close()
})
@@ -446,33 +464,34 @@ describe('installing every engine\'s hooks', () => {
}
})
- it('installs synchronously in the original order before returning the completion promise', async () => {
+ it('starts in the original order and exposes completion separately from the controller', async () => {
const order: string[] = []
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
+ await done.settled
+ done.close()
expect(order).toEqual(installs.map((_, index) => String(index)))
})
it('only the engines asked for (HOOK_INSTALL_ENGINES), the homes they moved included', async () => {
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.install).toHaveBeenCalledWith(...startupArgs(engineHooks.codex.install))
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.
expect(loadEngine).not.toHaveBeenCalled()
await installEngineHooks(4242, { only: new Set(['kilo']), environment: {} })
- expect(hooks.installKiloPlugin).toHaveBeenCalledWith(4242)
+ expect(hooks.installKiloPlugin).toHaveBeenCalledWith(...startupArgs(hooks.installKiloPlugin))
expect(hooks.installCursorHooks).not.toHaveBeenCalled()
})
it.each([false, true])('installs every vendor with optional imports unavailable (stalled=%s)', async (stalled) => {
loading.stalled = stalled
await installEngineHooks(4242, { environment: {} })
- for (const install of installs) expect(install).toHaveBeenCalledWith(4242)
+ for (const install of installs) expect(install).toHaveBeenCalledWith(...startupArgs(install))
expect(loadEngine).not.toHaveBeenCalled()
expect(console.warn).not.toHaveBeenCalled()
})
@@ -536,7 +555,7 @@ describe('installing every engine\'s hooks', () => {
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)
+ for (const install of installs) expect(install).toHaveBeenCalledWith(...startupArgs(install))
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await vi.advanceTimersByTimeAsync(1_000)
expect(log).toHaveBeenCalledWith('[hooks] home adoption recovered')
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index b5e1f6631..52d4d7bcf 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 { NativeHookOptions } from '../../engines/kit/nativeLocations.js'
import type { OpencodeLaunchSnapshot } from '../../engines/launchControl.js'
import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
@@ -227,15 +228,15 @@ 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 | boolean | Promise<unknown>]> = [
+const OTHER_INSTALLERS: Array<[string, (port: number, options: NativeHookOptions) => void | boolean | Promise<unknown>]> = [
['cursor', nativeHooks.installCursorHooks],
- ['opencode', nativeHooks.installOpencodePlugin],
+ ['opencode', (port, options) => nativeHooks.installOpencodePlugin(port, undefined, options)],
['kilo', nativeHooks.installKiloPlugin],
['pi', nativeHooks.installPiExtension],
// A self-update refreshes plugin files here; running engine processes pick them up according to each
// vendor's own plugin reload lifecycle.
['amp', nativeHooks.installAmpPlugin],
- ['hermes', nativeHooks.installHermesHooks],
+ ['hermes', (port, options) => nativeHooks.installHermesHooks(port, undefined, options)],
['devin', nativeHooks.installDevinHooks],
['commandcode', nativeHooks.installCommandCodeHooks],
['grok', nativeHooks.installGrokHooks],
@@ -250,11 +251,12 @@ const OTHER_INSTALLERS: Array<[string, (port: number) => void | boolean | Promis
* files owned by thirteen different CLIs, and one that is malformed, read-only or mid-write is not
* a reason for the other twelve to go uninstalled — let alone for the daemon not to come up.
*
- * Claude Code's and Codex's first, then the other engines, all in line before any restored pane starts.
- * An unavailable interpreter cannot delay this step. A vendor whose settings throw is named and skipped;
- * durable launch holds for preparation failures are a separate behavior change. Never rejects.
+ * Core starts this after readiness. Every launch separately confirms the hooks it
+ * needs; an unrelated vendor's disk or version probe cannot delay control. The
+ * controller is returned immediately so shutdown can revoke every pending write.
+ * `settled` observes this initial pass, never readiness. It does not reject.
*/
-export async function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): Promise<{ close(): void }> {
+export function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): { close(): void; settled: Promise<void> } {
const pending: Promise<void>[] = []
const hookStep = (vendor: string, install: () => void | boolean | Promise<unknown>): void => {
if (options.only && !options.only.has(vendor)) return
@@ -288,8 +290,8 @@ export async function installEngineHooks(port: number, options: InstallEngineHoo
})
adoptions.submit(options.environment ?? process.env)
void options.loginShell?.then(adoptions.submit, error => console.warn(`[hooks] login-shell homes unavailable · ${error instanceof Error ? error.message : error}`))
- for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port))
- for (const [vendor, install] of OTHER_INSTALLERS) hookStep(vendor, () => install(port))
- await Promise.all(pending)
- return { close: adoptions.close }
+ const nativeOptions = { current: adoptions.current }
+ for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port, nativeOptions))
+ for (const [vendor, install] of OTHER_INSTALLERS) hookStep(vendor, () => install(port, nativeOptions))
+ return { close: adoptions.close, settled: Promise.all(pending).then(() => {}) }
}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index f479e265e..ad3d1cb69 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1914,9 +1914,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
localClient: () => ({ kind: 'desktop', name: terminalHintMachineName().slice(0, 64), machineId: backend.machineId }),
})
localWsServerRef = localWsServer
- // Every engine's hooks, pointed at the port the local server actually bound (core/engines/hooks.ts).
- const installedHooks = env.DISABLE_HOOK_INSTALL ? undefined
- : await installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })
+ // Teardown owns the controller as soon as the background pass starts after readiness.
+ let installedHooks: ReturnType<typeof installEngineHooks> | undefined
// Each transcript line, through its engine's normalizer, into the funnel (core/transcripts/ingest.ts).
const ingest = createIngest({
@@ -2646,6 +2645,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
daemonBoot.openRequests = null
coreLink.ready()
console.log('[cli] ready')
+ // Each launch confirms its own hooks. Startup never waits on any vendor's disk or probe.
+ installedHooks = env.DISABLE_HOOK_INSTALL ? undefined
+ : installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })
// Ready first, never after a service: the agents the boot held for one are launched now, in the background.
void heldLaunches.restoreHeld()
externalResumes.open()
diff --git a/cli/src/engines/kit/nativeInstall.spec.ts b/cli/src/engines/kit/nativeInstall.spec.ts
index a318a56a9..3b802e850 100644
--- a/cli/src/engines/kit/nativeInstall.spec.ts
+++ b/cli/src/engines/kit/nativeInstall.spec.ts
@@ -7,15 +7,23 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { EngineInstallRecipe } from '../../lib/engineInstall.js'
import { createNativeInstallations, NATIVE_INSTALL_WORKER } from './nativeInstall.js'
-const fixture = vi.hoisted(() => ({ failSync: false, argv: [] as string[], onSync: undefined as undefined | (() => number | void) }))
+const fixture = vi.hoisted(() => ({ failSync: false, argv: [] as string[], onSync: undefined as undefined | (() => number | void), onDirectoryOpen: undefined as undefined | (() => void) }))
vi.mock('../../lib/engineLaunch.js', () => ({ buildEngineInstallationArgv: () => fixture.argv }))
-vi.mock('node:fs', async original => ({ ...await original<typeof import('node:fs')>(),
- fsync: (_fd: number, done: (error: Error | null) => void) => {
- const delay = fixture.onSync?.()
- const finish = () => done(fixture.failSync ? Error('fixture unavailable disk') : null)
- if (delay) setTimeout(finish, delay); else queueMicrotask(finish)
- },
-}))
+vi.mock('node:fs', async original => {
+ const actual = await original<typeof import('node:fs')>()
+ return { ...actual,
+ opendirSync: (...args: Parameters<typeof actual.opendirSync>) => {
+ const directory = actual.opendirSync(...args)
+ fixture.onDirectoryOpen?.()
+ return directory
+ },
+ fsync: (_fd: number, done: (error: Error | null) => void) => {
+ const delay = fixture.onSync?.()
+ const finish = () => done(fixture.failSync ? Error('fixture unavailable disk') : null)
+ if (delay) setTimeout(finish, delay); else queueMicrotask(finish)
+ },
+ }
+})
const hash = (text: string) => createHash('sha256').update(text).digest('hex')
const recipe: EngineInstallRecipe = { command: 'fixture-only', source: 'fixture', executable: { names: ['fixture'] } }
let root: string, directory: string, environment: Record<string, string>
@@ -24,7 +32,7 @@ beforeEach(() => {
directory = join(root, 'claims')
const home = join(root, 'home'); mkdirSync(home, { mode: 0o700 })
environment = { HOME: home, PATH: '/usr/bin:/bin' }
- fixture.failSync = false; fixture.onSync = undefined
+ fixture.failSync = false; fixture.onSync = undefined; fixture.onDirectoryOpen = undefined
fixture.argv = [process.execPath, '-e', `require('node:fs').appendFileSync(${JSON.stringify(join(root, 'installed'))}, 'one\\n')`]
})
afterEach(() => { rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks() })
@@ -132,21 +140,46 @@ it('settles a durable non-dispatch cancellation through the ready-executable sta
const file = join(directory, '00000000.json')
fixture.onSync = () => { if (existsSync(file)) fixture.failSync = true }
const original = controller()
- await original.ensure('opencode', recipe, environment, 'original', () => true)
- expect(original.dispatch).not.toHaveBeenCalled()
+ await vi.waitFor(async () => {
+ expect(await original.ensure('opencode', recipe, environment, 'original', () => true)).toMatchObject({ complete: false })
+ expect(original.dispatch).not.toHaveBeenCalled()
+ expect(existsSync(file)).toBe(true)
+ expect(fixture.failSync).toBe(true)
+ })
+ const claimBytes = readFileSync(file, 'utf8'), claim = JSON.parse(claimBytes)
fixture.failSync = false
const witness = `${directory}.00000000.dispatch`
fixture.onSync = () => { if (existsSync(witness)) fixture.failSync = true }
const other = controller()
- await other.ensure('codex', recipe, environment, 'other', () => true)
+ // Linux CI's parallel fixtures can change an ancestor during enumeration.
+ // That is a real hold; keep each disk fault armed until its stage is reached.
+ fixture.onDirectoryOpen = () => {
+ fixture.onDirectoryOpen = undefined
+ writeFileSync(join(root, 'sibling'), 'changed during inspection')
+ }
+ expect(await other.ensure('codex', recipe, environment, 'other', () => true)).toMatchObject({ complete: false })
+ expect(fixture.onDirectoryOpen).toBeUndefined()
+ expect(existsSync(witness)).toBe(false)
+ expect(fixture.failSync).toBe(false)
expect(other.dispatch).not.toHaveBeenCalled()
- expect(JSON.parse(readFileSync(witness, 'utf8')).kind).toBe('cancelled')
+ await vi.waitFor(async () => {
+ expect(await other.ensure('codex', recipe, environment, 'other', () => true)).toMatchObject({ complete: false })
+ expect(other.dispatch).not.toHaveBeenCalled()
+ expect(JSON.parse(readFileSync(witness, 'utf8'))).toEqual({ token: claim.token, claim: hash(claimBytes), kind: 'cancelled' })
+ expect(fixture.failSync).toBe(true)
+ })
+ expect(readFileSync(file, 'utf8')).toBe(claimBytes)
+ const witnessBytes = readFileSync(witness, 'utf8')
expect(existsSync(`${file}.result`)).toBe(false)
fixture.onSync = undefined; fixture.failSync = false
const recovered = controller()
- expect(await recovered.status('opencode', 'original', () => true)).toMatchObject({ complete: false })
- expect(JSON.parse(readFileSync(`${file}.result`, 'utf8')).notDispatched).toBe(true)
- expect(await recovered.status('opencode', 'original', () => true)).toBeNull()
+ await vi.waitFor(async () => {
+ expect(await recovered.status('opencode', 'original', () => true)).toMatchObject({ complete: false })
+ expect(JSON.parse(readFileSync(`${file}.result`, 'utf8')).notDispatched).toBe(true)
+ })
+ await vi.waitFor(async () => { expect(await recovered.status('opencode', 'original', () => true)).toBeNull() })
+ expect(readFileSync(file, 'utf8')).toBe(claimBytes)
+ expect(readFileSync(witness, 'utf8')).toBe(witnessBytes)
expect(recovered.dispatch).not.toHaveBeenCalled()
})
@@ -161,7 +194,24 @@ it('does not replay a dispatch whose reply was lost', async () => {
it.each(['changed owner', 'foreign result', 'failed installer', 'unsafe result', 'orphan result', 'malformed result', 'contradictory result'])('holds %s without dispatch or a false completion', async kind => {
const install = controller()
- await install.ensure('opencode', recipe, environment, 'request', () => true)
+ if (kind === 'failed installer') fixture.onDirectoryOpen = () => {
+ fixture.onDirectoryOpen = undefined
+ writeFileSync(join(root, 'sibling'), 'changed during enumeration')
+ }
+ if (kind === 'failed installer') {
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({
+ complete: false, detail: 'Waiting to confirm durable engine installation ownership.',
+ })
+ expect(fixture.onDirectoryOpen).toBeUndefined()
+ expect(install.dispatch).not.toHaveBeenCalled()
+ expect(existsSync(join(directory, '00000000.json'))).toBe(false)
+ }
+ // The failure injection below requires an actually dispatched fixture claim,
+ // not an earlier safe hold caused by unrelated directory churn.
+ await vi.waitFor(async () => {
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(install.dispatch).toHaveBeenCalledOnce()
+ }, { timeout: 3_000 })
const file = join(directory, '00000000.json')
if (kind === 'changed owner') writeFileSync(file, readFileSync(file, 'utf8') + ' ')
else if (kind === 'orphan result') writeFileSync(join(directory, '00000001.json.result'), '{}', { mode: 0o600 })
diff --git a/cli/src/engines/nativeHookPreparation.spec.ts b/cli/src/engines/nativeHookPreparation.spec.ts
index b4e3c2e8b..d9ea08435 100644
--- a/cli/src/engines/nativeHookPreparation.spec.ts
+++ b/cli/src/engines/nativeHookPreparation.spec.ts
@@ -99,9 +99,9 @@ it('does not join installation for a different executable identity on the same p
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)
+ // The new executable waits for the old attempt to release its destinations,
+ // then obtains its own fresh proof instead of joining the old publication.
+ expect(await second).toBe(true)
})
it('keeps mixed foreign commands when refreshing Claude and Codex hooks', async () => {
@@ -402,3 +402,78 @@ it.each(['deadline', 'owner', 'executable'] as const)('checks %s after the last
{ timeoutMs: 10, current: () => owner, confirmed })).toBe(false)
expect(confirmed).not.toHaveBeenCalled()
})
+
+
+it.each(['direct', 'alias'] as const)('waits for startup maintenance before proving concurrent OpenCode launches through %s paths', async route => {
+ const { root, install, tui } = await fixture()
+ const alias = join(root, 'selected-config'); symlinkSync(root, alias)
+ const environment = route === 'alias' ? { HOME: join(root, 'HOME'), OPENCODE_PLUGIN_DIR: join(alias, 'plugin') } : undefined
+ probe.major = 2
+ let release!: () => void, began!: () => void
+ const disk = new Promise<void>(done => { release = done }), started = new Promise<void>(done => { began = done })
+ probe.beforeSync = async () => { probe.beforeSync = undefined; began(); await disk }
+ const maintenance = install(4242)
+ await started
+ const confirmed = vi.fn(), siblingConfirmed = vi.fn()
+ let answered = false
+ const snapshot = { command: '/fixture/opencode', identity: 'launch-executable', major: 2, current: () => true }
+ const launch = install(4242, snapshot, { environment, confirmed }).finally(() => { answered = true })
+ const sibling = install(4242, snapshot, { environment, confirmed: siblingConfirmed })
+ try {
+ for (let n = 0; n < 80; n++) await Promise.resolve()
+ expect(answered).toBe(false)
+ expect(confirmed).not.toHaveBeenCalled()
+ } finally { release() }
+ expect(await maintenance).toBe(false)
+ expect(await launch).toBe(true)
+ expect(await sibling).toBe(true)
+ expect(siblingConfirmed).toHaveBeenCalledOnce()
+ expect(siblingConfirmed.mock.calls[0][0].current()).toBe(true)
+ expect(confirmed).toHaveBeenCalledOnce()
+ expect(confirmed.mock.calls[0][0].current()).toBe(true)
+ expect(readFileSync(tui, 'utf8')).toContain('4242')
+})
+
+it.each(['owner', 'executable', 'deadline'] as const)('keeps %s authority while waiting for startup maintenance', async reason => {
+ const { install, tui } = await fixture()
+ probe.major = 2
+ let release!: () => void, began!: () => void, owner = true, executable = true
+ const disk = new Promise<void>(done => { release = done }), started = new Promise<void>(done => { began = done })
+ probe.beforeSync = async () => { probe.beforeSync = undefined; began(); await disk }
+ const maintenance = install(4242)
+ await started
+ const confirmed = vi.fn()
+ const launch = install(4242, { command: '/fixture/opencode', identity: 'launch-executable', major: 2, current: () => executable },
+ { current: () => owner, confirmed, timeoutMs: reason === 'deadline' ? 30 : 5_000 })
+ if (reason === 'owner') owner = false
+ if (reason === 'executable') executable = false
+ try {
+ if (reason === 'deadline') expect(await launch).toBe(false)
+ } finally { release() }
+ expect(await launch).toBe(false)
+ expect(await maintenance).toBe(false)
+ expect(confirmed).not.toHaveBeenCalled()
+ expect(() => readFileSync(tui)).toThrow()
+})
+
+
+it('bounds launch callers waiting for startup maintenance and recovers after overflow', async () => {
+ const { install } = await fixture()
+ probe.major = 2
+ let release!: () => void, began!: () => void
+ const disk = new Promise<void>(done => { release = done }), started = new Promise<void>(done => { began = done })
+ probe.beforeSync = async () => { probe.beforeSync = undefined; began(); await disk }
+ const maintenance = install(4242)
+ await started
+ const snapshot = { command: '/fixture/opencode', identity: 'launch-executable', major: 2, current: () => true }
+ const launches = Array.from({ length: 15 }, () => install(4242, snapshot))
+ let overflowReply: boolean | undefined
+ const overflow = install(4242, snapshot).then(reply => { overflowReply = reply })
+ try {
+ await vi.waitFor(() => expect(overflowReply).toBe(false), { timeout: 500 })
+ } finally { release(); await Promise.all([maintenance, ...launches, overflow]) }
+ await overflow
+ expect(await maintenance).toBe(false)
+ expect(await Promise.all(launches)).toEqual(Array(15).fill(true))
+ expect(await install(4242, snapshot)).toBe(true)
+})
diff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.ts
index 7fdcca7ad..b9f40b283 100644
--- a/cli/src/engines/nativeHooks.ts
+++ b/cli/src/engines/nativeHooks.ts
@@ -39,8 +39,18 @@ export const installHermesHooks = (port: number, selectedHome?: string, options?
{ ...options, createMissing: !!selectedHome && !!options?.environment })
/** Install both discovery surfaces for v1; v2 must not load our incompatible v1 export. */
-interface OpencodeInstallation { port: number; executable?: string; major?: number | null; done: Promise<boolean>; proofs: HookPreparationProof[] }
+interface OpencodeInstallation { port: number; executable?: string; major?: number | null; settling?: boolean; done: Promise<boolean>; proofs: HookPreparationProof[] }
const opencodeInstallations = new Map<string, { current: OpencodeInstallation; users: number }>()
+async function waitForInstallation(installation: OpencodeInstallation, deadline: number): Promise<boolean | null> {
+ const remaining = deadline - performance.now()
+ if (remaining <= 0) return null
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([installation.done, new Promise<null>(done => {
+ timer = setTimeout(() => done(null), remaining)
+ })])
+ } finally { clearTimeout(timer) }
+}
export async function installOpencodePlugin(port: number, snapshot?: OpencodeLaunchSnapshot, options: NativeHookOptions = {}): Promise<boolean> {
const deadline = performance.now() + (options.timeoutMs ?? OPENCODE_VERSION.timeoutMs)
const root = options.environment ? nativeHookLocations(options.environment).OPENCODE_PLUGIN_DIR : dirname(OPENCODE_LEGACY_PLUGIN.file)
@@ -50,10 +60,17 @@ export async function installOpencodePlugin(port: number, snapshot?: OpencodeLau
let routes: ReturnType<typeof hookPreparationRoutes>
try { routes = hookPreparationRoutes([legacyRule.file, tuiRule.file]) } catch { return false }
const installation: OpencodeInstallation = { port, executable: snapshot?.identity, done: Promise.resolve(false), proofs: [] }
- if (opencodeInstallations.size >= 128 && !opencodeInstallations.has(root)) return false
- const group = opencodeInstallations.get(root) ?? { current: installation, users: 0 }
+ // Parent aliases can give startup and a captured launch different spellings
+ // for the same pair. Each caller still retains its own original route proof.
+ const reservation = JSON.stringify(routes.keys)
+ if (opencodeInstallations.size >= 128 && !opencodeInstallations.has(reservation)) return false
+ const previous = opencodeInstallations.get(reservation)?.current
+ const group = opencodeInstallations.get(reservation) ?? { current: installation, users: 0 }
+ // Include callers waiting before the lower-level disk reservation. Overflow
+ // cannot supersede an admitted owner or grow an unbounded promise chain.
+ if (group.users >= 16) return false
group.current = installation; group.users++
- opencodeInstallations.set(root, group)
+ opencodeInstallations.set(reservation, group)
try {
installation.done = (async () => {
const values = pluginValues(port)
@@ -62,6 +79,17 @@ export async function installOpencodePlugin(port: number, snapshot?: OpencodeLau
// 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 !== group.current || snapshot?.current() === false) return false
+ // Readiness can precede the maintenance write. A launch has a captured
+ // executable; maintenance does not, so their publications cannot be joined.
+ // Revoke the older owner through group.current, let its disk work settle,
+ // then inspect and prove this launch's own outputs within the same deadline.
+ if (previous && (previous.settling || previous.major !== undefined
+ && (previous.port !== port || previous.executable !== installation.executable || previous.major !== major))) {
+ installation.settling = true
+ const settled = await waitForInstallation(previous, deadline)
+ installation.settling = false
+ if (settled === null || installation !== group.current || snapshot?.current() === false || options.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.
@@ -90,14 +118,9 @@ export async function installOpencodePlugin(port: number, snapshot?: OpencodeLau
// A port change or continuing churn cannot make this caller wait forever.
const remaining = deadline - performance.now()
if (current.port !== port || current.executable !== installation.executable || snapshot?.current() === false || options.current?.() === false || remaining <= 0) return false
- let timer: ReturnType<typeof setTimeout> | undefined
- try {
- const result = await Promise.race([current.done, new Promise<'timeout'>(done => {
- timer = setTimeout(() => done('timeout'), remaining)
- })])
- if (result === 'timeout') return false
- installed = result
- } finally { clearTimeout(timer) }
+ const result = await waitForInstallation(current, deadline)
+ if (result === null) return false
+ installed = result
}
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
@@ -107,5 +130,5 @@ export async function installOpencodePlugin(port: number, snapshot?: OpencodeLau
try { routes.verify(); return proof.current() } catch { return false }
} })
return true
- } finally { if (--group.users === 0) opencodeInstallations.delete(root) }
+ } finally { if (--group.users === 0) opencodeInstallations.delete(reservation) }
}
diff --git a/cli/src/engines/nativeLaunch.probe.spec.ts b/cli/src/engines/nativeLaunch.probe.spec.ts
new file mode 100644
index 000000000..ab8538c92
--- /dev/null
+++ b/cli/src/engines/nativeLaunch.probe.spec.ts
@@ -0,0 +1,79 @@
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { inspectNativeLaunch } from './nativeLaunch.js'
+
+const fixture = vi.hoisted(() => ({ calls: 0, stall: false, pipes: false, pipeCount: 0, root: '', children: [] as import('node:child_process').ChildProcess[] }))
+vi.mock('./kit/launchExecutable.js', () => ({
+ captureLaunchExecutable: async () => ({ state: 'ready',
+ executable: { command: '/fixture/permission-engine', identity: 'fixture', current: () => true },
+ environment: { HOME: '/fixture/home', PATH: '/fixture/bin' },
+ }),
+ LAUNCH_LOCATION_VARIABLES: ['HOME', 'PATH'],
+}))
+vi.mock('node:child_process', async original => {
+ const actual = await original<typeof import('node:child_process')>()
+ return { ...actual, execFile: (file: string, args: string[], options: object, done: (...values: any[]) => void) => {
+ expect(file).toBe('/fixture/permission-engine')
+ expect(args).toEqual(['--help'])
+ const index = fixture.calls++
+ if (fixture.pipes) fixture.pipeCount++
+ // No engine, shell or owner's files: a private Node child prints its complete help.
+ const inheritedPipe = `
+ const fs=require('node:fs'), release=${JSON.stringify(join(fixture.root, 'release'))}, ended=${JSON.stringify(join(fixture.root, 'ended-' + index))};
+ const exit=()=>{fs.writeFileSync(ended,'done');process.exit(0)};
+ setInterval(()=>{if(fs.existsSync(release))exit()},25);setTimeout(exit,15000);
+ `
+ const script = fixture.pipes ? `
+ const child=require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify(inheritedPipe)}],{stdio:['ignore',1,2]});
+ process.stdout.write('Usage: fixture\\n --permission-mode\\n');process.exit(0);
+ ` : 'process.stdout.write("Usage: fixture\\n --permission-mode\\n")'
+ const child = actual.execFile(process.execPath, ['-e', script], options, done)
+ fixture.children.push(child)
+ // Same check-phase stall as e2e/stall.e2e.ts. Node's native timeout loses
+ // unread output here even though the child already exited successfully.
+ if (fixture.stall) setImmediate(() => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5_400) })
+ return child
+ } }
+})
+beforeEach(() => {
+ fixture.calls = 0; fixture.stall = false; fixture.pipes = false; fixture.pipeCount = 0; fixture.children = []
+ fixture.root = mkdtempSync(join(tmpdir(), 'native-probe-'))
+})
+afterEach(async () => {
+ writeFileSync(join(fixture.root, 'release'), 'release private descendants')
+ for (const child of fixture.children) if (child.exitCode === null) child.kill('SIGKILL')
+ if (fixture.pipeCount) await vi.waitFor(() => {
+ for (let index = 0; index < fixture.pipeCount; index++) expect(existsSync(join(fixture.root, 'ended-' + index))).toBe(true)
+ }, { timeout: 3000 })
+ rmSync(fixture.root, { recursive: true, force: true })
+})
+
+it('keeps a complete permission answer across a core stall without refusing or repeating the probe', async () => {
+ fixture.stall = true
+ const prepared = await inspectNativeLaunch('claude', { permissionMode: 'auto' })
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw Error(prepared.detail)
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('supported')
+ expect(fixture.calls).toBe(1)
+ expect(fixture.children[0]?.killed).toBe(false)
+}, 15_000)
+
+it('holds inherited output pipes within a bound and recovers probe capacity after closing only its own streams', async () => {
+ const prepared = await inspectNativeLaunch('claude')
+ if (!prepared.ok) throw Error(prepared.detail)
+ fixture.pipes = true
+ const pending = Array.from({ length: 8 }, () => prepared.launch.permission({ permissionMode: 'auto' }))
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('unknown')
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const answers = await Promise.race([Promise.all(pending), new Promise<'unsettled'>(done => { timer = setTimeout(() => done('unsettled'), 7000) })])
+ clearTimeout(timer)
+ expect(answers).toEqual(Array(8).fill('unknown'))
+ // Each native wrapper exited 0; the inherited pipes alone held its close.
+ for (const child of fixture.children) { expect(child.exitCode).toBe(0); expect(child.killed).toBe(false) }
+ await new Promise<void>(done => setImmediate(done))
+ fixture.pipes = false
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('supported')
+ expect(fixture.calls).toBe(9)
+}, 15_000)
diff --git a/cli/src/engines/nativeLaunch.spec.ts b/cli/src/engines/nativeLaunch.spec.ts
index 4bdc7f7e4..e3346a887 100644
--- a/cli/src/engines/nativeLaunch.spec.ts
+++ b/cli/src/engines/nativeLaunch.spec.ts
@@ -13,7 +13,7 @@ vi.mock('node:child_process', () => ({ execFile: (command: string, args: string[
fixture.calls.push(command); fixture.environments.push(_options.env)
const settle = () => done(fixture.failed ? Error('Private probe unavailable') : null, args[0] === '--version' ? fixture.version : fixture.help)
if (fixture.stalled) fixture.pending.push(settle); else queueMicrotask(settle)
- return { stdin: { end: vi.fn() } }
+ return { stdin: { end: vi.fn(), destroy: vi.fn() } }
} }))
vi.mock('./hooks.js', () => ({ engineHooks: { claude: { installIn: vi.fn(async () => fixture.hooks) }, codex: { installIn: vi.fn(async () => fixture.hooks) } } }))
vi.mock('./nativeHooks.js', () => Object.fromEntries(['installOpencodePlugin', 'installHermesHooks', 'installCursorHooks',
@@ -154,6 +154,30 @@ it('bounds actual probe concurrency and recovers after the children settle', asy
expect(answers.filter(answer => !answer.ok)).toHaveLength(2)
expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: true })
})
+
+it('answers an expired probe while retaining its slot until the actual child settles', async () => {
+ vi.useFakeTimers()
+ fixture.stalled = true
+ try {
+ const running = Array.from({ length: 8 }, () => inspectNativeLaunch('opencode'))
+ await vi.waitFor(() => expect(fixture.pending).toHaveLength(8))
+ await vi.advanceTimersByTimeAsync(5_251)
+ expect((await Promise.all(running)).every(answer => !answer.ok)).toBe(true)
+ const overflow = inspectNativeLaunch('opencode')
+ await vi.advanceTimersByTimeAsync(0)
+ // Inspect admission before awaiting: incorrectly released capacity must fail
+ // this assertion, rather than hanging on the unplanned ninth fake child.
+ expect(fixture.calls).toHaveLength(8)
+ expect(await overflow).toMatchObject({ ok: false, unavailable: 'native' })
+ for (const settle of fixture.pending.splice(0)) settle()
+ fixture.stalled = false
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: true })
+ expect(fixture.calls).toHaveLength(9)
+ } finally {
+ for (const settle of fixture.pending.splice(0)) settle()
+ fixture.stalled = false; vi.useRealTimers()
+ }
+})
it('retries unknown permission answers and matches only complete flag tokens', async () => {
const prepared = await inspectNativeLaunch('opencode')
if (!prepared.ok) throw Error(prepared.detail)
@@ -163,6 +187,15 @@ it('retries unknown permission answers and matches only complete flag tokens', a
expect(await prepared.launch.permission({ bypassPermission: true })).toBe('unsupported')
})
+it('holds an empty help reply without caching an unsupported permission flag', async () => {
+ const prepared = await inspectNativeLaunch('claude')
+ if (!prepared.ok) throw Error(prepared.detail)
+ fixture.help = ' \n'
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('unknown')
+ fixture.help = '--permission-mode'
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('supported')
+})
+
it('does not restore a daemon location that the captured shell unset', async () => {
vi.stubEnv('OPENCODE_CONFIG_DIR', '/fixture/daemon-config')
vi.stubEnv('FIXTURE_NATIVE_CREDENTIAL', 'private-value')
diff --git a/cli/src/engines/nativeLaunch.ts b/cli/src/engines/nativeLaunch.ts
index 717f84a08..e206df042 100644
--- a/cli/src/engines/nativeLaunch.ts
+++ b/cli/src/engines/nativeLaunch.ts
@@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto'
import { isAbsolute, join } from 'node:path'
import { permissionFlagToVerify, type PermissionLaunchChoice } from '../lib/engineLaunch.js'
import type { EngineInstallRecipe } from '../lib/engineInstall.js'
+import { patientDeadline } from '../lib/patientExec.js'
import { engineHooks } from './hooks.js'
import * as hooks from './nativeHooks.js'
import { captureLaunchExecutable, LAUNCH_LOCATION_VARIABLES } from './kit/launchExecutable.js'
@@ -47,12 +48,33 @@ async function read(executable: string, args: readonly string[], environment: Re
if (probes >= 8) return null
probes++
return new Promise(done => {
+ let settled = false, expired = false, answered = false
+ let cancelDeadline = () => {}
+ let drain: ReturnType<typeof setTimeout> | undefined
+ const answer = (output: string | null) => { if (!answered) { answered = true; done(output) } }
+ let child: ReturnType<typeof execFile>
try {
- const child = execFile(executable, [...args], {
- env: nativeProcessEnvironment(environment), encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
- }, (error, output) => { probes--; done(error ? null : output) })
- child.stdin?.end()
- } catch { probes--; done(null) }
+ // Node's timeout can discard unread output after a core stall, then
+ // report exit 0. Keep its pipes and use discovery's patient deadline.
+ child = execFile(executable, [...args], {
+ env: nativeProcessEnvironment(environment), encoding: 'utf8', killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
+ }, (error, output) => {
+ settled = true; probes--; cancelDeadline(); clearTimeout(drain)
+ answer(error || expired ? null : output)
+ })
+ } catch { probes--; answer(null); return }
+ if (!settled) cancelDeadline = patientDeadline(5_000, () => {
+ expired = true
+ // An exited wrapper may leave a descendant holding its pipes. Signal
+ // only our still-live child, then close our pipe ends after a short drain.
+ try { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') } catch { /* The reply still holds. */ }
+ drain = setTimeout(() => {
+ child.stdin?.destroy(); child.stdout?.destroy(); child.stderr?.destroy()
+ // An uninterruptible child retains its slot until the actual callback.
+ answer(null)
+ }, 250)
+ })
+ child.stdin?.end()
})
}
@@ -145,7 +167,7 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLau
if (known) return known
const observedRevision = revision
const help = await read(executable.command, ['--help'], selectedEnvironment)
- if (help === null || !current() || observedRevision !== revision) return 'unknown'
+ if (!help?.trim() || !current() || observedRevision !== revision) return 'unknown'
const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const answer = new RegExp(`(?:^|[^A-Za-z0-9-])${escaped}(?![A-Za-z0-9-])`).test(help) ? 'supported' : 'unsupported'
permissions.set(flag, answer)
diff --git a/cli/src/engines/otherHooks.golden.spec.ts b/cli/src/engines/otherHooks.golden.spec.ts
index 80be31bbe..49807e6ee 100644
--- a/cli/src/engines/otherHooks.golden.spec.ts
+++ b/cli/src/engines/otherHooks.golden.spec.ts
@@ -270,7 +270,10 @@ async function install(vendor: Vendor, port: number): Promise<Run> {
const spies = [vi.spyOn(console, 'log').mockImplementation(capture('log')), vi.spyOn(console, 'error').mockImplementation(capture('error')),
vi.spyOn(console, 'warn').mockImplementation(capture('warn'))]
let threw: string | null = null
- try { await installEngineHooks(port, { only: new Set([vendor]), environment: {} }) }
+ try {
+ const installed = await installEngineHooks(port, { only: new Set([vendor]), environment: {} }) as { close(): void; settled?: Promise<void> }
+ try { await installed.settled } finally { installed.close() }
+ }
catch (error) { threw = describeError(error) } finally { for (const spy of spies) spy.mockRestore() }
return { logs, threw }
}
diff --git a/cli/src/lib/registry.homes.spec.ts b/cli/src/lib/registry.homes.spec.ts
index f6635130d..3419e6418 100644
--- a/cli/src/lib/registry.homes.spec.ts
+++ b/cli/src/lib/registry.homes.spec.ts
@@ -3,7 +3,16 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
-const fault = vi.hoisted(() => ({ beforeVerify: undefined as (() => void) | undefined, captures: 0 }))
+const fault = vi.hoisted(() => ({ beforeVerify: undefined as (() => void) | undefined, captures: 0,
+ onDirectoryOpen: undefined as (() => void) | undefined }))
+vi.mock('node:fs', async original => {
+ const actual = await original<typeof import('node:fs')>()
+ return { ...actual, opendirSync: (...args: Parameters<typeof actual.opendirSync>) => {
+ const directory = actual.opendirSync(...args)
+ fault.onDirectoryOpen?.()
+ return directory
+ } }
+})
vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
function observeHomeReads(): void { vi.doMock('./engineHomes.js', async original => {
const actual = await original<typeof import('./engineHomes.js')>()
@@ -18,7 +27,7 @@ vi.mock('./processLiveness.js', async original => ({ ...await original<object>()
processLockIdentity: () => ({ startMarker: 'fixture-start', generationMarker: 'fixture-generation' }), lockOwnerAlive: () => true,
}))
let root: string | undefined
-afterEach(() => { fault.beforeVerify = undefined; fault.captures = 0; vi.doUnmock('./engineHomes.js'); vi.unstubAllEnvs(); vi.resetModules(); if (root) rmSync(root, { recursive: true, force: true }) })
+afterEach(() => { fault.beforeVerify = undefined; fault.onDirectoryOpen = undefined; fault.captures = 0; vi.doUnmock('./engineHomes.js'); vi.unstubAllEnvs(); vi.resetModules(); if (root) rmSync(root, { recursive: true, force: true }) })
it('repairs a child-overwritten parent from an adopted Codex home before the login shell is read', async () => {
// Found by QA on a quiet machine: restart searched only the default home and discarded this parent binding.
@@ -43,9 +52,22 @@ it('repairs a child-overwritten parent from an adopted Codex home before the log
}]), { mode: 0o600 })
vi.resetModules()
const { registry } = await import('./registry.js')
+ fault.onDirectoryOpen = () => {
+ fault.onDirectoryOpen = undefined
+ writeFileSync(join(root!, 'sibling'), 'changed during enumeration')
+ }
registry.load()
- expect(registry.get(parentId)?.transcriptPath).toBe(parent)
- expect(JSON.parse(readFileSync(join(root, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parent)
+ expect(fault.onDirectoryOpen).toBeUndefined()
+ expect(registry.get(parentId)).toMatchObject({ transcriptPath: child, identityHold: expect.stringContaining('ancestor changed') })
+ expect(JSON.parse(readFileSync(join(root, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(child)
+ // A changed ancestor is incomplete evidence, even when another CI fixture
+ // caused it. The preserved binding can be repaired by the next fresh read.
+ await vi.waitFor(() => {
+ registry.load()
+ expect(registry.get(parentId)?.transcriptPath).toBe(parent)
+ expect(registry.get(parentId)?.identityHold).toBeUndefined()
+ expect(JSON.parse(readFileSync(join(root!, 'registry.json'), 'utf8'))[0].transcriptPath).toBe(parent)
+ }, { timeout: 3_000 })
})
diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.ts
index 0fa5fec47..ec0afd589 100644
--- a/cli/src/startupOrder.spec.ts
+++ b/cli/src/startupOrder.spec.ts
@@ -125,6 +125,13 @@ describe('the core\'s start-up order (core/main.ts)', () => {
}
})
+ it('starts native hook maintenance after readiness without awaiting its completion', () => {
+ const source = code(SOURCE)
+ expect(source).not.toMatch(/await\s+installEngineHooks\(/)
+ expect(source.indexOf('installEngineHooks(hookPort')).toBeGreaterThan(source.indexOf('coreLink.ready()'))
+ expect(source).toContain('installedHooks?.close()')
+ })
+
it('keeps the prologue itself incapable of throwing', () => {
// Stronger than listing today's hazards: this is what catches the NEXT line somebody adds on top.
const source = code(SOURCE)
@@ -253,6 +260,8 @@ describe('the core\'s request gate (core/main.ts)', () => {
// Readiness never waits on a service: held agents and saved manual requests
// start their dependency recovery only after the master knows core is ready.
expect(tail).toEqual(['backend.openRequests()', 'daemonBoot.openRequests = null', 'coreLink.ready()', "console.log('[cli] ready')",
+ 'installedHooks = env.DISABLE_HOOK_INSTALL ? undefined',
+ ': installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })',
'void heldLaunches.restoreHeld()', 'externalResumes.open()', 'launches.open()'])
expect(logged).toBeGreaterThan(ready)
})
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index aee1b5112..7a3b560be 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -28,7 +28,7 @@ This is the remaining completion scope as of October 9, after the six extraction
## Remaining blockers
1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [landed](2026-10-10-saved-binding-evidence.md). Atomic registration and live hook ownership are [landed](2026-10-10-native-hook-admission.md). Stop/Resume/Close transcript authority is [landed as #1139](2026-10-10-control-transcript-authority.md); reviewed history deletion is [landed as #1144](2026-10-10-native-history-consumers.md); [Change agent handoff authority](2026-10-10-native-handoff-authority.md) is landed as #1145 (`ea4e800b5`, October 10 15:13:53 UTC). Restart-persistent hook delivery, remaining saved-home consumers and legacy native-client acknowledgement/order still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.
-2. **Complete native launch preparation.** Probe executable/version facts asynchronously with a deadline and one confirmed executable snapshot per launch. The [asynchronous version-probe change](2026-10-10-native-version-probes.md) covers bounded subprocesses and concurrent observations/installers; the whole-launch snapshot, unknown-result policy and durable hook preparation remain open. Failed hook writes/removals hold launch, preserve foreign configuration and are checked consistently by create, fork, restart, retarget, restore and upgrades. Do not memoize an unavailable version as a permanent answer.
+2. **Complete native launch preparation.** The [durable hook mechanics and whole-launch integration](2026-10-11-native-launch-preparation.md) landed as #1158 and #1160 (`740fb5286`, October 11 at 06:12:15 UTC). Create, fork, restart, retarget, restore and external takeover retain captured executable/environment, permission, hook and final dispatch evidence. Missing or uncertain installers hold dependent launches; immutable generated configuration preserves foreign and borrowed data. Native and grid goldens remain unchanged; 28 wiring mutations, full Linux/macOS e2e and 100% core/harnessd/resume coverage passed. [Startup hook maintenance after readiness](2026-10-11-hook-readiness.md) is implemented and under final validation. Durable manual lifecycle intent remains group 3; it is not completed by the native preparation boundary.
3. **Durable manual lifecycle intent and mutation authority.** The live-core mutation and ownership boundary is [landed as #1155](2026-10-10-native-mutation-authority.md), `71f42b852`, October 10 at 17:46:46 UTC: unconfirmed OpenCode v2 writes are reconciled read-only across requests; unavailable catalogs cannot authorize a mutation; immutable ownership fences native/tmux effects; partial effects are reported truthfully. The same change prevents an unbound fork from claiming its parent's conversation at discovery or Stop. Preserve create/fork/restart/retarget requests across unavailable services and daemon restart, including durable uncertain native receipts. Publish generated configuration atomically after dependencies are ready. Cover v1 missing-row/rollback cases. The [durable launch design](../design/2026-10-10-durable-launch-intents.md) records the implemented model-admission slice and the remaining lifecycle boundary.
4. **Close, turns and input stay in core.** Audit OpenCode v2 Close checkpointing against its current conversation store; unavailable checkpoint/activity evidence keeps the live session with its reason. Finish per-engine Stop/turn facts, authority across asynchronous drains, Cursor pending-task persistence, agy backstop control, input verification declarations, and Pi header/argv and unwritten-conversation handling.
5. **Final architecture acceptance.** Exercise startup, discovery, binding, launch, resume, Stop, hook admission, turn closing and Close with required services absent, stalled, disconnected and recovered. Verify readiness remains independent, pending work survives without partial writes or archival, and stale completions cannot affect a replacement session. Run the relevant coverage gates, unchanged goldens and assertion-failing wiring mutations, affected private e2e/chaos lanes, and matched runtime-cost measurements. Obtain independent review and merge every completed change.
diff --git a/docs/research/2026-10-11-hook-readiness-cost.json b/docs/research/2026-10-11-hook-readiness-cost.json
new file mode 100644
index 000000000..1e7cee8ea
--- /dev/null
+++ b/docs/research/2026-10-11-hook-readiness-cost.json
@@ -0,0 +1,99 @@
+{
+ "nativeHooks": true,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "tmux": "tmux 3.5a",
+ "samples": [
+ {
+ "bundle": "baseline",
+ "readyMs": 3435.8510210000004,
+ "atReady": {
+ "cpuMs": 590,
+ "rssMiB": 89.703125
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 615.5347500000003,
+ "coreCpuMs": 100,
+ "rssMiB": 90.99609375
+ },
+ {
+ "phase": "warm",
+ "requestMs": 426.92185599999993,
+ "coreCpuMs": 60,
+ "rssMiB": 93.06640625
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 1316.6243560000003,
+ "atReady": {
+ "cpuMs": 380,
+ "rssMiB": 82.46875
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 1172.0456189999995,
+ "coreCpuMs": 150,
+ "rssMiB": 88.08984375
+ },
+ {
+ "phase": "warm",
+ "requestMs": 339.5589570000002,
+ "coreCpuMs": 80,
+ "rssMiB": 89.37890625
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 1423.3268260000004,
+ "atReady": {
+ "cpuMs": 400,
+ "rssMiB": 79.4765625
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 1472.9003919999996,
+ "coreCpuMs": 170,
+ "rssMiB": 85.953125
+ },
+ {
+ "phase": "warm",
+ "requestMs": 342.3992299999991,
+ "coreCpuMs": 100,
+ "rssMiB": 86.72265625
+ }
+ ]
+ },
+ {
+ "bundle": "baseline",
+ "readyMs": 3186.5190760000005,
+ "atReady": {
+ "cpuMs": 570,
+ "rssMiB": 85.578125
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 405.82368400000087,
+ "coreCpuMs": 100,
+ "rssMiB": 87.0859375
+ },
+ {
+ "phase": "warm",
+ "requestMs": 416.4405889999998,
+ "coreCpuMs": 50,
+ "rssMiB": 88.26953125
+ }
+ ]
+ }
+ ],
+ "baseline": "6d9b787dd664388ab9279a947bd3417360a0c8f9",
+ "candidate": "bf9c0247879eaf28301b87637fadb3dd816d390f",
+ "receipt": "20261011T071228.478825Z-34936"
+}
diff --git a/docs/research/2026-10-11-hook-readiness.md b/docs/research/2026-10-11-hook-readiness.md
new file mode 100644
index 000000000..46051b72d
--- /dev/null
+++ b/docs/research/2026-10-11-hook-readiness.md
@@ -0,0 +1,142 @@
+# Native hook maintenance after daemon readiness
+
+Startup awaited the initial native hook installer pass before it opened the request
+gate and reported readiness. A bounded OpenCode version probe still delayed every
+session until that probe completed or timed out. This violated the daemon completion
+bar even though the installer no longer depended on an optional worker.
+
+Core now starts hook maintenance after opening requests and reporting readiness to
+the master. Each launch independently confirms the required native hooks through
+its original ownership and executable snapshot. Startup maintenance returns its
+shutdown controller immediately. The same revocation predicate reaches all thirteen
+native installers, so teardown does not need to await a pending disk operation to
+revoke permission for its later writes. Existing adopted-home retries keep their
+own shutdown fence.
+
+`settled` observes the initial installer pass for tests; readiness never awaits it.
+Failures remain independently reported for each engine. A launch that needs an
+unavailable hook remains held with its reason.
+
+The former vendor, port, selected-engine, adopted-home and refusal coordination was
+recorded from main `16569f3d2` in the separate golden-only commit `43c76ff1c`, before
+changing startup. The golden pins both Linux and macOS platform values and uses
+fixture installers and paths. Its artifact remains unchanged.
+
+The private daemon regression keeps an OpenCode startup probe alive behind a
+test-owned release file. The daemon must report readiness and answer agent-list
+requests while that exact child is still waiting. Releasing it then completes the
+hook installation. The former implementation becomes ready only after its deadline
+kills the child, so it fails this assertion.
+
+Initial focused validation passed types, architecture, startup ordering and 79 tests, with
+100% per-file statement, branch, function and line coverage of the hook coordinator.
+Receipt: `20261011T053403.766571Z-65433`. Final receipts and exact-head independent review are recorded in the PR. No release
+is authorized.
+
+The first full private hook lane (`20261011T060712.803551Z-48168`) passed seven
+of eight cases, including the blocked-installer readiness case and all-vendor
+Stop/resume without the optional hooks chunk. The post-rc create fixture read
+its private Codex configuration immediately after readiness, before background
+maintenance had created it. The fixture now waits for that file before taking
+its fault-injection snapshot. All hold, crash and no-replay assertions are unchanged.
+Both create and fork cases passed in `20261011T060955.203043Z-61813`.
+
+All five startup wiring mutations passed in `20261011T061203.293017Z-72305`:
+unchanged baselines were green, and each broken implementation failed assertions.
+The readiness mutant restores the real awaited startup path in a freshly built
+bundle. Final dependency #1160 landed as `740fb5286`; merging it into this branch
+changed no CLI source or fixture bytes.
+
+The matched workload exposed an immediate-launch race after readiness: OpenCode
+maintenance and the captured launch could revoke one another's file reservation.
+Different preparations now wait for the previous disk attempt to settle, within
+the launch's original deadline, then obtain their own fresh proof. Identical
+canonical destination pairs coordinate across parent aliases; each caller retains
+its original route evidence. At most sixteen callers can wait on one pair, and
+backpressure cannot supersede a caller already admitted. Different or partial
+destination sets cannot borrow another preparation's proof. Owner, executable,
+route and deadline checks remain required after every wait.
+
+The regression failed on the former coordination before this correction. Review
+then found the alias and waiting-capacity gaps; both have dedicated regressions.
+The all-vendor private acceptance now launches OpenCode immediately after readiness,
+before waiting for background hook files. It retains every Stop/resume assertion.
+Final affected validation `20261011T063338.662745Z-68201` passed types, 157 unit and
+golden checks, and all eight private daemon cases. Core's 2,503 tests and master's
+265 tests (one platform skip) passed all four 100% per-file coverage gates in
+`20261011T061515.849504Z-86437`; the final PR carries any subsequent affected checks.
+The earlier `20261011T061414.664196Z-81910` orchestration failed during merge conflict
+cleanup and a temporary npm executable issue; it is not a passing suite.
+
+## Failure-driven acceptance corrections
+
+The first full Linux/macOS acceptance run, `38118774703`, found one production
+failure in the unchanged stall lane. After a 7.9-second core pause, Node's native
+subprocess timeout discarded a completed permission probe's unread output and
+returned exit zero with empty stdout. Launch preparation cached that as an
+unsupported flag and refused Claude creation. A private real-child regression
+reproduced the false refusal before correction (`20261011T065951.966421Z-85384`).
+
+Native launch probes now use discovery's bounded patient deadline. A completed
+answer survives a core pause; empty help remains unknown and is never cached as
+unsupported. A genuinely expired probe returns unknown. After a 250 ms drain it
+closes its own pipe ends, so an exited wrapper's descendant cannot hold its reply
+or all eight probe slots indefinitely. It signals only its still-live child;
+an uninterruptible child retains capacity until actual settlement. The existing
+four-window deadline bound remains, rather than treating it as a wall-clock limit.
+Private real-process tests cover both the pause and inherited pipes, and a held
+child test covers reply/slot separation. Types and 56 affected checks passed in
+`20261011T070638.819101Z-12098`; final PR evidence includes the preserved SIGKILL
+setting for output-limit kills. The original stall e2e assertions are unchanged.
+The final mutation pass caught ten of eleven defects by assertions; the deliberately
+released probe slot instead hung its fake ninth child. The capacity test now checks
+child admission before awaiting that reply, so this defect must fail an explicit
+assertion as required. No production code changed in that correction.
+
+Linux unit CI also exposed an installer fixture assumption: ancestor churn can
+legitimately hold enumeration before the intended fsync fault is reached. A
+one-shot private sibling mutation reproduced the exact missing-witness failure
+(`20261011T065353.731186Z-60572`). The fixture now keeps each fault armed and retries
+to that milestone, retaining exact claim/witness, absent-result and no-dispatch
+assertions (`20261011T065501.793176Z-65267`). Production ownership fences are unchanged.
+The legacy installer-output golden now awaits `settled` and closes its controller
+in `finally`; its artifact and all 340 assertions are unchanged
+(`20261011T064546.689940Z-26598`).
+
+## Matched startup workload
+
+[Raw samples](2026-10-11-hook-readiness-cost.json) retain four alternating runs of
+main and this change on the same private macOS workload, pinned Node 22.23.2 and
+tmux 3.5a, with all thirteen installers enabled. Each run starts a cold daemon and
+immediately creates two fake OpenCode sessions. No user homes, daemon or tmux server
+are involved. Two samples per tree are descriptive, not a performance threshold.
+
+| Median | Main | Readiness change |
+| --- | ---: | ---: |
+| Ready (ms) | 3,311 | 1,370 |
+| Core CPU at ready (ms) | 580 | 390 |
+| Core RSS at ready (MiB) | 87.6 | 81.0 |
+| First launch request (ms) | 511 | 1,322 |
+| Warm launch request (ms) | 422 | 341 |
+| Ready plus first launch (ms) | 3,822 | 2,692 |
+
+The first launch owns the preparation wait that formerly delayed every request.
+Warm launches retain fresh proof checks. Main advanced with the Agent Messages
+cleanup in #1165 while validation ran. The final comparison uses fresh bundles of
+main `6d9b787dd` and merged candidate `bf9c02478`, including the alias, caller-limit
+and native-probe corrections. Baseline construction passed in
+`20261011T071120.736472Z-30164` (15.6 seconds); candidate construction and all four
+matched samples passed in `20261011T071228.478825Z-34936` (15.7 and 16.4 seconds,
+respectively). No other local heavy checks ran during measurement. The earlier
+comparison against main `740fb5286` also passed in `20261011T070759.147272Z-17321`;
+it is superseded by the comparison above. The initial cost receipts `20261011T062124.649240Z-13284` and
+`20261011T062250.241018Z-19378` failed on the collision; the corrected workload passed
+in `20261011T062724.898061Z-40203` without changing its launch assertions.
+
+This readiness slice began with the main golden at 05:16 UTC on October 11.
+Implementation, failure diagnosis and local validation overlapped through 07:08 UTC.
+Integration of the new main and its matched cost comparison ran from 07:10 through
+07:13 UTC; individual receipts retain test durations. Independent review ran alongside checks.
+CI waiting and merge duration are recorded separately in the PR; publication is zero.
+The original daemon request began October 8 at 23:26:41 UTC, not at this slice's first
+workflow.
diff --git a/docs/research/2026-10-11-native-launch-preparation.md b/docs/research/2026-10-11-native-launch-preparation.md
index b2b672e12..2d696e260 100644
--- a/docs/research/2026-10-11-native-launch-preparation.md
+++ b/docs/research/2026-10-11-native-launch-preparation.md
@@ -1,7 +1,7 @@
# Native launch preparation
Status: hook durability mechanics landed as #1158 (`eef21b18b`, October 11
-at 01:30 UTC). Whole-launch integration is in reviewed PR #1160, awaiting final-head CI and merge. They are part of
+at 01:30 UTC). Whole-launch integration landed as #1160 (`740fb5286`, October 11 at 06:12:15 UTC). 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.
@@ -394,3 +394,17 @@ with review and validation. The final validation receipts above occupy
05:45–06:04; the full remote run overlaps that interval. They are not added together
as total elapsed time. Merge and publication remain zero at this checkpoint. No
release is authorized.
+
+### Whole-launch landing
+
+[PR #1160](https://github.com/autonomous-ai/openharness/pull/1160) merged as
+`740fb5286e3764cb9ee17642bf1dd98c47eb58ec` at 06:12:15 UTC. Independent review
+approved exact head `757702c3c3f85d99039ea0e25c83f4cfa31aea0b` against
+`16569f3d27e1b51352904aded33e71971b7e2724`. Final automatic
+[CI 38116964017](https://github.com/autonomous-ai/openharness/actions/runs/38116964017)
+passed every head check, including `ci/required`. The merge helper verified the
+reviewed and tested trees match the squash result. Receipt
+`20261011T061203.067283Z-merge-1160` records the authorized merge; merge validation
+occupied 06:12:03–06:12:15, following the overlapping implementation/validation
+intervals above. No release occurred. Startup maintenance after readiness remains
+the separate next change.