bridge.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { Context, type Fiber } from 'cordis'
  6. import Loader from '@cordisjs/plugin-loader'
  7. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  8. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  11. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  12. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  13. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  14. import SubagentService, { SubagentRunId } from '@deepseek-ai/dsh-subagent'
  15. import * as HooksClaude from '@deepseek-ai/dsh-hooks-claude'
  16. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  17. /**
  18. * Full-loop bridge tests: a scripted mock MODEL drives the REAL agent loop + REAL
  19. * bash executor, and the REAL `dsh-hooks-claude` bridge runs REAL shell hook
  20. * scripts written to a temp dir — only the model is mocked (the "prefer the real
  21. * implementation" rule). Each test writes a `hooks.json` + executable scripts,
  22. * loads the bridge pointed at them, and asserts the hook's effect on the loop.
  23. */
  24. const dirs: string[] = []
  25. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  26. function subagentCarrier(ctx: Context) {
  27. return scopeTarget(ctx as unknown as SubagentService, undefined)
  28. }
  29. /** Write a hooks.json + named executable scripts into a fresh temp dir. */
  30. function writeConfig(hooks: unknown, scripts: Record<string, string> = {}): string {
  31. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  32. dirs.push(dir)
  33. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks }))
  34. for (const [name, body] of Object.entries(scripts)) {
  35. const path = join(dir, name)
  36. writeFileSync(path, body)
  37. chmodSync(path, 0o755)
  38. }
  39. return dir
  40. }
  41. async function harness(configDir: string, adapter: MockAdapter): Promise<Context> {
  42. return (await harnessWithFiber(configDir, adapter)).ctx
  43. }
  44. /** {@link harness}, also exposing the bridge's fiber for tests that dispose it. */
  45. async function harnessWithFiber(configDir: string, adapter: MockAdapter): Promise<{ ctx: Context; hooks: Fiber }> {
  46. const ctx = new Context()
  47. await mountAgentLoopTestDependencies(ctx)
  48. await ctx.plugin(AgentLoop, { agents: [] })
  49. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  50. const hooks = await ctx.plugin(HooksClaude, { configPath: join(configDir, 'hooks.json') })
  51. ctx.llm.registerAdapter(['mock'], adapter)
  52. return { ctx, hooks }
  53. }
  54. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  55. return new Promise((resolve) => {
  56. const dispose = ctx.on('agent/status', (subject, status) => {
  57. if (subject === agent && status === 'idle') { dispose(); resolve() }
  58. })
  59. })
  60. }
  61. function events(agent: Agent): SessionEvent[] {
  62. return [...agent.session.events]
  63. }
  64. /**
  65. * Poll `predicate` until it returns true or the deadline passes. Detached
  66. * emit-listener hooks (session-start, subagent) fire on a `.then` the test can't
  67. * await directly; polling for the observable EFFECT is robust under load, where a
  68. * single fixed sleep flakes ("async state is not synchronous state").
  69. */
  70. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  71. const deadline = Date.now() + timeout
  72. while (!predicate()) {
  73. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  74. await new Promise(r => setTimeout(r, interval))
  75. }
  76. }
  77. describe('hooks-claude bridge — UserPromptSubmit', () => {
  78. it('a UserPromptSubmit hook that exits 2 blocks the prompt (rejected turn)', async () => {
  79. // The UserPromptSubmit hook exits 2 (blocking) with a reason on stderr.
  80. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  81. dirs.push(dir)
  82. const block = join(dir, 'block.sh')
  83. writeFileSync(block, '#!/usr/bin/env bash\necho "prompt denied by policy" >&2\nexit 2\n')
  84. chmodSync(block, 0o755)
  85. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: block }] }] } }))
  86. const adapter = new MockAdapter([textResponse('should not run')])
  87. const ctx = await harness(dir, adapter)
  88. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  89. agent.followup([{ type: 'text', text: 'do something' }])
  90. await waitForIdle(ctx, agent)
  91. // The prompt was blocked: model never called, turn ended rejected.
  92. expect(adapter.requests).toHaveLength(0)
  93. const turnEnd = events(agent).findLast(e => e.type === 'turn/end')
  94. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('rejected')
  95. // The hook ran and was recorded.
  96. expect(events(agent).some(e => e.type === 'hook/invoked' && e.data.point === 'UserPromptSubmit')).toBe(true)
  97. expect(events(agent).some(e => e.type === 'hook/result' && e.data.decision === 'block')).toBe(true)
  98. })
  99. it('a UserPromptSubmit hook printing additionalContext injects it for the model', async () => {
  100. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  101. dirs.push(dir)
  102. const ctxScript = join(dir, 'ctx.sh')
  103. writeFileSync(ctxScript, '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"remember: be brief"}}\'\n')
  104. chmodSync(ctxScript, 0o755)
  105. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: ctxScript }] }] } }))
  106. const adapter = new MockAdapter([textResponse('ok')])
  107. const ctx = await harness(dir, adapter)
  108. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  109. agent.followup([{ type: 'text', text: 'go' }])
  110. await waitForIdle(ctx, agent)
  111. // The injected context reached the model and is recorded with the plugin source.
  112. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('remember: be brief')
  113. const ctxMsg = events(agent).find(e => e.type === 'user/message' && e.data.source.kind !== 'user')
  114. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'hooks-claude' })
  115. })
  116. })
  117. describe('hooks-claude bridge — PreToolUse', () => {
  118. it('a matching PreToolUse hook that exits 2 denies the tool (isError result), tool never runs', async () => {
  119. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  120. dirs.push(dir)
  121. const deny = join(dir, 'deny.sh')
  122. writeFileSync(deny, '#!/usr/bin/env bash\necho "danger tool blocked" >&2\nexit 2\n')
  123. chmodSync(deny, 0o755)
  124. // Matcher "danger" (literal) selects only the danger tool.
  125. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'danger', hooks: [{ type: 'command', command: deny }] }] } }))
  126. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('done')])
  127. const ctx = await harness(dir, adapter)
  128. let ran = false
  129. ctx.tools.register(defineContentToolFixture({ name: 'danger', description: 'd', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] } }))
  130. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  131. agent.followup([{ type: 'text', text: 'use danger' }])
  132. await waitForIdle(ctx, agent)
  133. expect(ran).toBe(false)
  134. const result = events(agent).find(e => e.type === 'tool/result')
  135. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  136. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('danger tool blocked'))).toBe(true)
  137. })
  138. it('a PreToolUse hook whose matcher does NOT match leaves the tool alone', async () => {
  139. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  140. dirs.push(dir)
  141. const deny = join(dir, 'deny.sh')
  142. writeFileSync(deny, '#!/usr/bin/env bash\nexit 2\n')
  143. chmodSync(deny, 0o755)
  144. // Matcher only targets "danger" — the "safe" tool is untouched.
  145. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'danger', hooks: [{ type: 'command', command: deny }] }] } }))
  146. const adapter = new MockAdapter([toolCallResponse('c1', 'safe', {}), textResponse('done')])
  147. const ctx = await harness(dir, adapter)
  148. let ran = false
  149. ctx.tools.register(defineContentToolFixture({ name: 'safe', description: 's', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ran ok' }] } }))
  150. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  151. agent.followup([{ type: 'text', text: 'use safe' }])
  152. await waitForIdle(ctx, agent)
  153. expect(ran).toBe(true)
  154. const result = events(agent).find(e => e.type === 'tool/result')
  155. expect(result?.type === 'tool/result' && result.data.isError).toBe(false)
  156. })
  157. })
  158. describe('hooks-claude bridge — PostToolUse', () => {
  159. it('a PostToolUse hook that blocks (exit 2) turns the result into an isError with feedback', async () => {
  160. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  161. dirs.push(dir)
  162. const block = join(dir, 'block.sh')
  163. writeFileSync(block, '#!/usr/bin/env bash\necho "output rejected, retry" >&2\nexit 2\n')
  164. chmodSync(block, 0o755)
  165. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { PostToolUse: [{ hooks: [{ type: 'command', command: block }] }] } }))
  166. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  167. const ctx = await harness(dir, adapter)
  168. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'raw output' }] } }))
  169. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  170. agent.followup([{ type: 'text', text: 'go' }])
  171. await waitForIdle(ctx, agent)
  172. const result = events(agent).find(e => e.type === 'tool/result')
  173. // PostToolUse blocks AFTER the tool ran: the result is rewritten to isError + feedback.
  174. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  175. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('output rejected, retry'))).toBe(true)
  176. })
  177. it('a PostToolUse hook printing additionalContext attaches it after the tool result', async () => {
  178. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  179. dirs.push(dir)
  180. const s = join(dir, 'ctx.sh')
  181. writeFileSync(s, '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"note: tool was slow"}}\'\n')
  182. chmodSync(s, 0o755)
  183. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] } }))
  184. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  185. const ctx = await harness(dir, adapter)
  186. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  187. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  188. agent.followup([{ type: 'text', text: 'go' }])
  189. await waitForIdle(ctx, agent)
  190. const log = events(agent)
  191. const resultIdx = log.findIndex(e => e.type === 'tool/result')
  192. const ctxIdx = log.findIndex(e => e.type === 'user/message' && e.data.source.kind !== 'user')
  193. expect(ctxIdx).toBeGreaterThan(resultIdx) // context appended AFTER the tool result
  194. const ctxMsg = log[ctxIdx]
  195. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.content.some(b => b.type === 'text' && b.text.includes('tool was slow'))).toBe(true)
  196. })
  197. it('a PreToolUse permissionDecision:ask degrades to ask (the tool is gated, not run)', async () => {
  198. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  199. dirs.push(dir)
  200. const s = join(dir, 'ask.sh')
  201. writeFileSync(s, '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"needs approval"}}\'\n')
  202. chmodSync(s, 0o755)
  203. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] } }))
  204. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  205. const ctx = await harness(dir, adapter)
  206. let ran = false
  207. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'x' }] } }))
  208. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  209. agent.followup([{ type: 'text', text: 'go' }])
  210. await waitForIdle(ctx, agent)
  211. // `ask` degrades to deny today (FIXME permissions): the tool does not run and the result is isError.
  212. expect(ran).toBe(false)
  213. const result = events(agent).find(e => e.type === 'tool/result')
  214. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  215. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('needs approval'))).toBe(true)
  216. })
  217. })
  218. describe('hooks-claude bridge — SessionStart', () => {
  219. it('a SessionStart hook injects additionalContext the first request sees', async () => {
  220. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  221. dirs.push(dir)
  222. const s = join(dir, 'start.sh')
  223. writeFileSync(s, '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"project uses tabs"}}\'\n')
  224. chmodSync(s, 0o755)
  225. // matcher 'startup' selects the startup source.
  226. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: { SessionStart: [{ matcher: 'startup', hooks: [{ type: 'command', command: s }] }] } }))
  227. const adapter = new MockAdapter([textResponse('ok')])
  228. const ctx = await harness(dir, adapter)
  229. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  230. // session-start fires async (detached .then → agent.inject); wait for the
  231. // injected context/message to actually land before sending, rather than a
  232. // fixed sleep that flakes under load.
  233. await waitFor(() => events(agent).some(e => e.type === 'user/message'
  234. && e.data.content.some(b => b.type === 'text' && b.text.includes('project uses tabs'))))
  235. agent.followup([{ type: 'text', text: 'go' }])
  236. await waitForIdle(ctx, agent)
  237. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('project uses tabs')
  238. })
  239. })
  240. describe('hooks-claude bridge — SubagentStart / SubagentStop (observe)', () => {
  241. it('runs SubagentStart and SubagentStop hooks when the subagent lifecycle events fire', async () => {
  242. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  243. dirs.push(dir)
  244. // Each hook touches a marker file so we can assert it ran (these events are
  245. // observe-only — there is no decision to assert, only the side effect).
  246. const startMarker = join(dir, 'start-ran')
  247. const stopMarker = join(dir, 'stop-ran')
  248. const startHook = join(dir, 'start.sh')
  249. const stopHook = join(dir, 'stop.sh')
  250. writeFileSync(startHook, `#!/usr/bin/env bash\ntouch "${startMarker}"\n`)
  251. writeFileSync(stopHook, `#!/usr/bin/env bash\ntouch "${stopMarker}"\n`)
  252. chmodSync(startHook, 0o755)
  253. chmodSync(stopHook, 0o755)
  254. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: {
  255. SubagentStart: [{ hooks: [{ type: 'command', command: startHook }] }],
  256. SubagentStop: [{ hooks: [{ type: 'command', command: stopHook }] }],
  257. } }))
  258. const adapter = new MockAdapter([])
  259. const { ctx, hooks } = await harnessWithFiber(dir, adapter)
  260. // Drive the observe-only lifecycle events directly (no real child needed — the
  261. // bridge just listens). No child agent is registered, so SubagentStart's
  262. // child lookup yields undefined and it simply runs the hook.
  263. ctx.emit(subagentCarrier(ctx), 'subagent/start', { runId: SubagentRunId('run-1'), provider: 'inproc', id: SessionId('child-1'), local: false })
  264. ctx.emit(subagentCarrier(ctx), 'subagent/end', { runId: SubagentRunId('run-1'), provider: 'inproc', id: SessionId('child-1'), local: false, stopReason: 'completed', lastAssistantMessage: [{ type: 'text', text: 'done' }] })
  265. // Both hooks run async (detached .then); poll for their marker files rather
  266. // than a fixed sleep that flakes under load.
  267. await waitFor(() => existsSync(startMarker) && existsSync(stopMarker))
  268. expect(existsSync(startMarker)).toBe(true)
  269. expect(existsSync(stopMarker)).toBe(true)
  270. // The markers prove the hook PROCESSES ran, not that the detached `.then`
  271. // continuations did (`touch` lands before the process exits). Dispose drains
  272. // them, so the no-context arm of the SubagentStart continuation — covered
  273. // only here — executes before this file's coverage snapshot instead of
  274. // racing it (the arm went uncovered on a loaded CI runner and failed the
  275. // per-file 100% branch gate).
  276. await hooks.dispose()
  277. })
  278. it('disposing the bridge aborts a still-running hook and drains to quiescence', async () => {
  279. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-claude-'))
  280. dirs.push(dir)
  281. const pidFile = join(dir, 'pid')
  282. const marker = join(dir, 'started')
  283. const slowHook = join(dir, 'slow.sh')
  284. // Record the hook shell's PID and touch the marker FIRST so the test can
  285. // tell "the hook is genuinely mid-run", then sleep far past the suite
  286. // timeout. Dispose must KILL the process (the tracker's abort signal), not
  287. // await its exit or its 10-minute default hook timeout.
  288. writeFileSync(slowHook, `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  289. chmodSync(slowHook, 0o755)
  290. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks: {
  291. SubagentStart: [{ hooks: [{ type: 'command', command: slowHook }] }],
  292. } }))
  293. const { ctx, hooks } = await harnessWithFiber(dir, new MockAdapter([]))
  294. const warn = vi.fn()
  295. ctx.logger.warn = warn as never
  296. ctx.emit(subagentCarrier(ctx), 'subagent/start', { runId: SubagentRunId('run-1'), provider: 'inproc', id: SessionId('child-1'), local: false })
  297. await waitFor(() => existsSync(marker))
  298. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  299. await hooks.dispose()
  300. // Quiescence, not just promptness: the drain resolves only after the run
  301. // settled, and the run settles only after the killed process was reaped —
  302. // so by the time dispose returns, the PID must be GONE (kill(pid, 0)
  303. // throws ESRCH). An untracked fire-and-forget regression would leave the
  304. // process alive (or unreaped) and fail this deterministically.
  305. expect(() => process.kill(pid, 0)).toThrow()
  306. // The aborted run resolves as a non-blocking error (runHook never rejects),
  307. // so the drained continuation must NOT have logged a failure.
  308. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SubagentStart hook failed'))
  309. })
  310. })
  311. describe('hooks-claude bridge — load resilience', () => {
  312. it('a missing config file registers no hooks and does not crash the loop', async () => {
  313. const adapter = new MockAdapter([textResponse('fine')])
  314. const ctx = new Context()
  315. await mountAgentLoopTestDependencies(ctx)
  316. await ctx.plugin(AgentLoop, { agents: [] })
  317. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  318. await ctx.plugin(HooksClaude, { configPath: '/nonexistent/hooks.json' })
  319. ctx.llm.registerAdapter(['mock'], adapter)
  320. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  321. agent.followup([{ type: 'text', text: 'go' }])
  322. await waitForIdle(ctx, agent)
  323. // The turn ran normally — no hooks, no crash.
  324. expect(adapter.requests).toHaveLength(1)
  325. })
  326. it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
  327. // A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose it
  328. // would veto the prompt (0 model requests) and log a hook/invoked. Build the
  329. // ctx WITHOUT the harness's own bridge mount so this is the ONLY mount, then
  330. // dispose it — a leaked listener fails the test (a no-op `true` hook would
  331. // pass even leaked, so it proved nothing).
  332. const dir = writeConfig({ UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'exit 2' }] }] })
  333. const adapter = new MockAdapter([textResponse('ok')])
  334. const ctx = new Context()
  335. await mountAgentLoopTestDependencies(ctx)
  336. await ctx.plugin(AgentLoop, { agents: [] })
  337. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  338. const fiber = await ctx.plugin(HooksClaude, { configPath: join(dir, 'hooks.json') })
  339. await fiber.dispose()
  340. ctx.llm.registerAdapter(['mock'], adapter)
  341. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  342. agent.followup([{ type: 'text', text: 'go' }])
  343. await waitForIdle(ctx, agent)
  344. expect(adapter.requests).toHaveLength(1) // not blocked → the listener is gone
  345. expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false) // no hook ran
  346. })
  347. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
  348. // Postmortem 0001 guard: this plugin HAS `inject = ['bash']`, so a stray
  349. // `export default apply` would collapse the module via `unwrapExports`
  350. // (`exports.default ?? exports`), DROP `inject`, and crash at load with
  351. // "cannot get property … without inject". Guard the shape directly.
  352. expect('default' in HooksClaude).toBe(false)
  353. expect(HooksClaude.name).toBe('hooks-claude')
  354. expect(HooksClaude.inject).toEqual(['bash'])
  355. const loader = Object.create(Loader.prototype) as Loader
  356. const unwrapped = loader.unwrapExports(HooksClaude) as Record<string, unknown>
  357. expect(unwrapped).toBe(HooksClaude)
  358. expect(unwrapped.name).toBe('hooks-claude')
  359. expect(unwrapped.inject).toEqual(['bash'])
  360. expect(typeof unwrapped.apply).toBe('function')
  361. })
  362. })