fix(hooks): drain detached hook runs on bridge dispose
The emit-shaped hook points (SessionStart, SubagentStart, SubagentStop) run fire-and-forget: no seam awaits the run chain, so disposing a bridge could strand a live hook process and let a late continuation inject into a disposed context. The floating continuation also made the coverage gate racy: the only coverage of the SubagentStart continuation's no-context branch arm rode on an un-awaited .then, and on a loaded CI runner the fork's per-file coverage snapshot beat it — master run 28798191671 failed the 100% branch gate on hooks-claude/src/index.ts at 99.03% (uncovered line 336) with the identical tree passing the PR run three minutes earlier. New shared primitive createDetachedRuns() in dsh-hook-protocol: a bridge tracks each detached run chain, passes the tracker's abort signal to runHook, and registers drain() as its effect disposer — drain aborts still-running hook processes (a kill via the bash seam, not a wait out to the 10-minute default hook timeout), then resolves once every chain has settled. fiber.dispose() resolving now means the bridge's detached work is quiescent (docs/defensive-patterns.md). The subagent marker test disposes the bridge as its sync point, so the formerly racy branch arm is executed deterministically before the file's coverage snapshot; new tests pin abort-on-dispose promptness for both bridges and the tracker's settle/drain contract in hook-protocol.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { mkdtempSync, rmSync, writeFileSync, chmodSync } from 'node:fs'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { Context } from 'cordis'
|
||||
@@ -62,6 +62,15 @@ function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
|
||||
}
|
||||
function events(agent: ReactLoopAgent): SessionEvent[] { return [...agent.session.events] }
|
||||
|
||||
/** Poll `predicate` until true or the deadline passes (detached hook effects can't be awaited directly). */
|
||||
async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
|
||||
const deadline = Date.now() + timeout
|
||||
while (!predicate()) {
|
||||
if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
|
||||
await new Promise(r => setTimeout(r, interval))
|
||||
}
|
||||
}
|
||||
|
||||
describe('hooks-codex bridge', () => {
|
||||
it('a PreToolUse hook (exit 2) denies a tool the regex matcher matches as a substring', async () => {
|
||||
const dir = configDir()
|
||||
@@ -159,6 +168,35 @@ describe('hooks-codex bridge', () => {
|
||||
expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false) // no hook ran
|
||||
})
|
||||
|
||||
it('disposing the bridge aborts a still-running SessionStart hook and drains to quiescence', async () => {
|
||||
const dir = configDir()
|
||||
const marker = join(dir, 'started')
|
||||
// Touch the marker FIRST so the test can tell "the hook is genuinely
|
||||
// mid-run", then sleep far past the suite timeout: dispose resolving at all
|
||||
// proves the drain KILLED the process (the tracker's abort signal wired
|
||||
// through this bridge's runPoint) instead of awaiting its exit.
|
||||
const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\ntouch "${marker}"\nsleep 30\n`)
|
||||
writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(LlmService)
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(ToolRegistry)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(AgentLoop, { agents: [] })
|
||||
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
|
||||
const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
|
||||
ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
|
||||
const warn = vi.fn()
|
||||
ctx.logger.warn = warn as never
|
||||
ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) // fires agent/session-start
|
||||
await waitFor(() => existsSync(marker))
|
||||
await fiber.dispose()
|
||||
// The aborted run resolves as a non-blocking error (runHook never rejects),
|
||||
// so the drained continuation must NOT have logged a failure.
|
||||
expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
|
||||
})
|
||||
|
||||
it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
|
||||
expect('default' in HooksCodex).toBe(false)
|
||||
expect(HooksCodex.name).toBe('hooks-codex')
|
||||
|
||||
Reference in New Issue
Block a user