coverage-cases.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { mkdtempSync, rmSync, writeFileSync, chmodSync, existsSync, readFileSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { Context } from 'cordis'
  7. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  8. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  9. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  12. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  15. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  16. import SubagentService, { SubagentRunId } from '@deepseek-ai/dsh-subagent'
  17. import * as HooksClaude from '@deepseek-ai/dsh-hooks-claude'
  18. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  19. const testToolSignal = new AbortController().signal
  20. /** Targeted branch coverage for the CC bridge: option arms, warn paths, no-agent
  21. * fallbacks, contextFrom-empty, and the detached-listener catch handlers. */
  22. const dirs: string[] = []
  23. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  24. function subagentCarrier(ctx: Context) {
  25. return scopeTarget(ctx as unknown as SubagentService, undefined)
  26. }
  27. function dir(): string { const d = mkdtempSync(join(tmpdir(), 'dsh-hc-cov-')); dirs.push(d); return d }
  28. function sh(d: string, name: string, body: string): string {
  29. const p = join(d, name); writeFileSync(p, body); chmodSync(p, 0o755); return p
  30. }
  31. function hooks(d: string, h: unknown): string {
  32. writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
  33. }
  34. type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxChars?: number; sessionRoot?: string }
  35. async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
  36. const ctx = new Context()
  37. await mountAgentLoopTestDependencies(ctx)
  38. if (opts.sessionRoot !== undefined) await ctx.plugin(SessionPersistenceJsonl, { root: opts.sessionRoot })
  39. await ctx.plugin(AgentLoop, { agents: [] })
  40. await ctx.plugin(LocalSubprocessService)
  41. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  42. await ctx.plugin(HooksClaude, { configPath, ...opts })
  43. ctx.llm.registerAdapter(['mock'], adapter)
  44. return ctx
  45. }
  46. function waitForIdle(_ctx: Context, agent: Agent): Promise<void> {
  47. return agent.whenIdle()
  48. }
  49. function events(agent: Agent): SessionEvent[] { return [...agent.session.events] }
  50. /** Poll until `predicate` holds or the deadline passes — robust to detached
  51. * emit-listener hooks firing on a `.then` (a fixed sleep flakes under load). */
  52. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  53. const deadline = Date.now() + timeout
  54. while (!predicate()) {
  55. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  56. await new Promise(r => setTimeout(r, interval))
  57. }
  58. }
  59. export type CoverageGroup = 'config' | 'stop' | 'context' | 'edge-paths'
  60. /** Register independently schedulable slices of the hooks-claude coverage matrix. */
  61. export function defineCoverageCases(group: CoverageGroup): void {
  62. if (group === 'config') describe('hooks-claude coverage — config option arms + substitution + skip warning', () => {
  63. it('uses the persistence locator for transcript_path and an empty string without one', async () => {
  64. async function capture(sessionRoot?: string): Promise<{ payload: { transcript_path: string }; expected: string | undefined }> {
  65. const d = dir()
  66. const cap = join(d, 'payload')
  67. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'capture.sh', `#!/usr/bin/env bash\ncat > "${cap}"\n`) }] }] })
  68. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  69. const ctx = await harness(path, adapter, { ...sessionRoot !== undefined ? { sessionRoot } : {} })
  70. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  71. const agent = ctx.agentLoop.create(SessionId('transcript'), { provider: 'mock', model: 'mock' })
  72. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  73. await waitForIdle(ctx, agent)
  74. return {
  75. payload: JSON.parse(readFileSync(cap, 'utf8')) as { transcript_path: string },
  76. expected: ctx.get('sessionPersistence')?.locate(agent.session.header)?.path,
  77. }
  78. }
  79. const located = await capture(dir())
  80. expect(located.payload.transcript_path).toBe(located.expected)
  81. expect((await capture()).payload.transcript_path).toBe('')
  82. }, 15_000) // Two real agent/hook subprocess loops need process startup and teardown headroom.
  83. it('honors pluginRoot + projectDir substitution and warns on a skipped non-command hook', async () => {
  84. const d = dir()
  85. // ${CLAUDE_PLUGIN_ROOT} resolves to d; the script writes its own cwd-independent marker.
  86. const marker = join(d, 'ran')
  87. sh(d, 'h.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`)
  88. const path = hooks(d, {
  89. PreToolUse: [{ hooks: [
  90. { type: 'prompt', prompt: 'skipme' }, // skipped → warn loop
  91. { type: 'command', command: '${CLAUDE_PLUGIN_ROOT}/h.sh' }, // substituted
  92. ] }],
  93. })
  94. const warn = vi.fn()
  95. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  96. const ctx = await harness(path, adapter, { pluginRoot: d, projectDir: d })
  97. ctx.logger.warn = warn as never
  98. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  99. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  100. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  101. await waitForIdle(ctx, agent)
  102. expect(existsSync(marker)).toBe(true) // substituted command ran
  103. })
  104. it('warns and honors updatedInput as a no-op (input rewrite deferred)', async () => {
  105. const d = dir()
  106. const s = sh(d, 'u.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","updatedInput":{"command":"rewritten"}}}\'\n')
  107. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  108. const warn = vi.fn()
  109. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { command: 'original' }), textResponse('done')])
  110. const ctx = await harness(path, adapter)
  111. ctx.logger.warn = warn as never
  112. let sawArgs: unknown
  113. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: { command: { type: 'string' } }, async execute(args) { sawArgs = args; return [{ type: 'text', text: 'ok' }] } }))
  114. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  115. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  116. await waitForIdle(ctx, agent)
  117. // updatedInput is NOT honored — the tool ran with the ORIGINAL args.
  118. expect((sawArgs as { command?: string }).command).toBe('original')
  119. expect(warn).toHaveBeenCalledWith(expect.stringContaining('updatedInput'))
  120. })
  121. })
  122. if (group === 'config') describe('hooks-claude coverage — empty/no-op outcomes and no-agent paths', () => {
  123. it('a clean exit-0 hook with no output is a no-op (contextFrom empty → next())', async () => {
  124. const d = dir()
  125. const s = sh(d, 'noop.sh', '#!/usr/bin/env bash\nexit 0\n')
  126. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  127. const adapter = new MockAdapter([textResponse('ran')])
  128. const ctx = await harness(path, adapter)
  129. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  130. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  131. await waitForIdle(ctx, agent)
  132. // The prompt proceeded unchanged; no injected context.
  133. expect(adapter.requests).toHaveLength(1)
  134. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user')).toBe(false)
  135. })
  136. it('a PreToolUse hook fires for a no-agent direct tool call (no session/turn to record into)', async () => {
  137. const d = dir()
  138. const s = sh(d, 'deny.sh', '#!/usr/bin/env bash\necho "no" >&2\nexit 2\n')
  139. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  140. const ctx = await harness(path, new MockAdapter([]))
  141. let ran = false
  142. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'x' }] } }))
  143. const { CallId } = await import('@deepseek-ai/dsh-llm')
  144. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'echo', arguments: {} })
  145. expect(ran).toBe(false)
  146. expect(result.isError).toBe(true)
  147. })
  148. it('a long stderr is truncated in the hook/result summary', async () => {
  149. const d = dir()
  150. const s = sh(d, 'long.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n')
  151. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  152. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  153. const ctx = await harness(path, adapter)
  154. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  155. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  156. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  157. await waitForIdle(ctx, agent)
  158. const res = events(agent).find(e => e.type === 'hook/result')
  159. expect(res?.type === 'hook/result' && res.data.stderrSummary?.endsWith('…')).toBe(true)
  160. expect(res?.type === 'hook/result' && res.data.stderrSummary?.length).toBe(501) // default 500-char cap + ellipsis
  161. })
  162. it('rejects a non-positive or fractional stderrSummaryMaxChars at load', async () => {
  163. const d = dir()
  164. const path = hooks(d, {})
  165. for (const bad of [0, -5, 1.5, Number.NaN]) {
  166. const adapter = new MockAdapter([])
  167. await expect(harness(path, adapter, { stderrSummaryMaxChars: bad }))
  168. .rejects.toThrow(/hooks-claude: stderrSummaryMaxChars must be a positive integer/)
  169. }
  170. })
  171. it('the stderr summary cap is plugin config (stderrSummaryMaxChars)', async () => {
  172. const d = dir()
  173. const s = sh(d, 'long.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n')
  174. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  175. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  176. const ctx = await harness(path, adapter, { stderrSummaryMaxChars: 40 })
  177. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  178. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  179. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  180. await waitForIdle(ctx, agent)
  181. const res = events(agent).find(e => e.type === 'hook/result')
  182. expect(res?.type === 'hook/result' && res.data.stderrSummary).toBe('x'.repeat(40) + '…')
  183. })
  184. })
  185. if (group === 'stop') describe('hooks-claude coverage — Stop continuation + subagent inject/catch', () => {
  186. it('a Stop hook that blocks (exit 2) forces the turn to continue (CC dialect)', async () => {
  187. const d = dir()
  188. const marker = join(d, 'fired')
  189. const s = sh(d, 'stop.sh', `#!/usr/bin/env bash\nif [ -e "${marker}" ]; then exit 0; fi\ntouch "${marker}"\necho "continue please" >&2\nexit 2\n`)
  190. const path = hooks(d, { Stop: [{ hooks: [{ type: 'command', command: s }] }] })
  191. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  192. const ctx = await harness(path, adapter)
  193. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  194. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  195. await waitForIdle(ctx, agent)
  196. expect(adapter.requests).toHaveLength(2)
  197. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('continue please')
  198. })
  199. it('a Stop hook that blocks with EMPTY stderr still forces continuation (no reason required)', async () => {
  200. // A blocking Stop hook with no stderr yields `deny` without a reason. The block still forces
  201. // continuation; the script self-limits to one block to avoid a loop.
  202. const d = dir()
  203. const marker = join(d, 'fired')
  204. const s = sh(d, 'stop.sh', `#!/usr/bin/env bash\nif [ -e "${marker}" ]; then exit 0; fi\ntouch "${marker}"\nexit 2\n`)
  205. const path = hooks(d, { Stop: [{ hooks: [{ type: 'command', command: s }] }] })
  206. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  207. const ctx = await harness(path, adapter)
  208. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  209. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  210. await waitForIdle(ctx, agent)
  211. // A second model request ran → the empty-reason block forced continuation.
  212. expect(adapter.requests).toHaveLength(2)
  213. // The steering carried the fallback reason (no stderr to use).
  214. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('blocked by Stop hook')
  215. })
  216. it('SubagentStart additionalContext is injected into a REGISTERED live child', async () => {
  217. const d = dir()
  218. const s = sh(d, 'sa.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":"child guidance"}}\'\n')
  219. const path = hooks(d, { SubagentStart: [{ hooks: [{ type: 'command', command: s }] }] })
  220. const ctx = await harness(path, new MockAdapter([]))
  221. const injected: string[] = []
  222. const child = {
  223. id: SessionId('child-x'),
  224. inject: (input: { content: Array<{ type: string; text?: string }> }) => {
  225. injected.push(input.content.map(block => block.text ?? '').join(''))
  226. },
  227. session: { id: SessionId('child-x'), header: { id: 'child-x' } },
  228. } as unknown as Parameters<typeof ctx.agents.register>[0]
  229. ctx.agents.register(child)
  230. ctx.emit(subagentCarrier(ctx), 'subagent/start', { runId: SubagentRunId('run-x'), provider: 'p', id: SessionId('child-x'), local: true })
  231. await waitFor(() => injected.includes('child guidance'))
  232. expect(injected).toContain('child guidance')
  233. })
  234. it('a throwing SubagentStart/SubagentStop hook run is contained (logged)', async () => {
  235. const d = dir()
  236. // A hook command that does not exist makes runHook resolve a non-blocking
  237. // error (not a throw), so to hit the .catch we make the .then throw: register
  238. // a child whose inject throws for SubagentStart.
  239. const s = sh(d, 'sa.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":"x"}}\'\n')
  240. const path = hooks(d, { SubagentStart: [{ hooks: [{ type: 'command', command: s }] }] })
  241. const ctx = await harness(path, new MockAdapter([]))
  242. const warn = vi.fn(); ctx.logger.warn = warn as never
  243. const child = { id: SessionId('child-y'), inject: () => { throw new Error('inject boom') }, session: { id: SessionId('child-y'), header: { id: 'child-y' } } } as unknown as Parameters<typeof ctx.agents.register>[0]
  244. ctx.agents.register(child)
  245. ctx.emit(subagentCarrier(ctx), 'subagent/start', { runId: SubagentRunId('run-y'), provider: 'p', id: SessionId('child-y'), local: true })
  246. await waitFor(() => warn.mock.calls.some(c => String(c[0]).includes('SubagentStart hook failed')))
  247. expect(warn).toHaveBeenCalledWith(expect.stringContaining('SubagentStart hook failed'))
  248. })
  249. })
  250. if (group === 'stop') describe('hooks-claude coverage — default reasons + sparse payloads', () => {
  251. it('PreToolUse deny with EMPTY stderr uses the default reason', async () => {
  252. const d = dir()
  253. const s = sh(d, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n') // exit 2, no stderr
  254. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  255. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  256. const ctx = await harness(path, adapter)
  257. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'x' }] } }))
  258. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  259. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  260. await waitForIdle(ctx, agent)
  261. const result = events(agent).find(e => e.type === 'tool/result')
  262. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('blocked by PreToolUse hook'))).toBe(true)
  263. })
  264. it('PostToolUse deny with EMPTY stderr + no context uses the default feedback', async () => {
  265. const d = dir()
  266. const s = sh(d, 'block.sh', '#!/usr/bin/env bash\nexit 2\n')
  267. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  268. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  269. const ctx = await harness(path, adapter)
  270. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  271. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  272. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  273. await waitForIdle(ctx, agent)
  274. const result = events(agent).find(e => e.type === 'tool/result')
  275. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('blocked by PostToolUse hook'))).toBe(true)
  276. })
  277. it('SubagentStop with no registered child runs the hook cleanly (fire-and-forget)', async () => {
  278. const d = dir()
  279. // The agents registry has no entry for the id, so the child lookup yields
  280. // undefined and the payload falls back to base(undefined) — assert the
  281. // observe-only SubagentStop run still executes the hook without crashing.
  282. const marker = join(d, 'stopran')
  283. const s = sh(d, 'stop.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`)
  284. const path = hooks(d, { SubagentStop: [{ hooks: [{ type: 'command', command: s }] }] })
  285. const ctx = await harness(path, new MockAdapter([]))
  286. ctx.emit(subagentCarrier(ctx), 'subagent/end', { runId: SubagentRunId('run-z'), provider: 'p', id: SessionId('child-z'), local: false, stopReason: 'completed' })
  287. await waitFor(() => existsSync(marker))
  288. expect(existsSync(marker)).toBe(true)
  289. })
  290. })
  291. if (group === 'edge-paths') describe('hooks-claude coverage — more default/sparse arms', () => {
  292. it('UserPromptSubmit deny with EMPTY stderr uses the default block reason', async () => {
  293. const d = dir()
  294. const s = sh(d, 'block.sh', '#!/usr/bin/env bash\nexit 2\n')
  295. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  296. const adapter = new MockAdapter([textResponse('no')])
  297. const ctx = await harness(path, adapter)
  298. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  299. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  300. await waitForIdle(ctx, agent)
  301. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  302. })
  303. it('a PreToolUse ask with NO reason omits the reason (false arm)', async () => {
  304. const d = dir()
  305. const s = sh(d, 'ask.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask"}}\'\n')
  306. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  307. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  308. const ctx = await harness(path, adapter)
  309. let ran = false
  310. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'x' }] } }))
  311. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  312. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  313. await waitForIdle(ctx, agent)
  314. // ask (no reason) → degrades to deny with the registry's generic message.
  315. expect(ran).toBe(false)
  316. expect(events(agent).some(e => e.type === 'tool/result' && e.data.message.content[0].isError)).toBe(true)
  317. })
  318. it('a recorded clean exit-0 hook with no stderr omits exitCode-extra/stderrSummary fields', async () => {
  319. const d = dir()
  320. const s = sh(d, 'noop.sh', '#!/usr/bin/env bash\nexit 0\n')
  321. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  322. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  323. const ctx = await harness(path, adapter)
  324. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  325. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  326. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  327. await waitForIdle(ctx, agent)
  328. const res = events(agent).find(e => e.type === 'hook/result')
  329. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(0)
  330. expect(res?.type === 'hook/result' && 'stderrSummary' in res.data).toBe(false)
  331. })
  332. })
  333. if (group === 'edge-paths') describe('hooks-claude coverage — schema-bypass apply + unspawnable hook', () => {
  334. it('a direct apply() (schema bypass) with only configPath runs', async () => {
  335. const d = dir()
  336. const marker = join(d, 'ran')
  337. const s = sh(d, 'h.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`)
  338. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  339. const adapter = new MockAdapter([textResponse('ok')])
  340. const ctx = new Context()
  341. await mountAgentLoopTestDependencies(ctx)
  342. await ctx.plugin(AgentLoop, { agents: [] })
  343. await ctx.plugin(LocalSubprocessService)
  344. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  345. // Direct apply with only configPath — bypasses schemastery's defaults, so
  346. // the bridge must run on the raw minimal config (the per-hook timeout is
  347. // the protocol lib's reference default, not a config knob).
  348. HooksClaude.apply(ctx, { configPath: join(d, 'hooks.json') })
  349. ctx.llm.registerAdapter(['mock'], adapter)
  350. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  351. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  352. await waitForIdle(ctx, agent)
  353. expect(existsSync(marker)).toBe(true)
  354. })
  355. it('a non-zero non-2 hook exit (e.g. a command-not-found 127) is a non-blocking error; the tool still runs', async () => {
  356. const d = dir()
  357. // `bash -c` of a missing program exits 127 — a non-blocking error (not 0, not
  358. // 2 → no decision), so the tool proceeds; the hook/result records exit 127.
  359. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: '/nonexistent/definitely/not/a/command' }] }] })
  360. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  361. const ctx = await harness(path, adapter)
  362. let ran = false
  363. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  364. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  365. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  366. await waitForIdle(ctx, agent)
  367. expect(ran).toBe(true)
  368. const res = events(agent).find(e => e.type === 'hook/result')
  369. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(127)
  370. })
  371. it('a PostToolUse deny with empty stderr + no context uses the default feedback (no context arm)', async () => {
  372. const d = dir()
  373. const s = sh(d, 'block.sh', '#!/usr/bin/env bash\nexit 2\n')
  374. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  375. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  376. const ctx = await harness(path, adapter)
  377. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  378. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  379. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  380. await waitForIdle(ctx, agent)
  381. const result = events(agent).find(e => e.type === 'tool/result')
  382. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  383. })
  384. })
  385. if (group === 'context') describe('hooks-claude coverage — continue:false, context arm, no-cwd', () => {
  386. it('a {"continue":false} hook is RECORDED as decision "stop" but does not halt the run (TODO(hook-continue-false))', async () => {
  387. // The seams cannot yet honor `continue:false` as a hard halt. The log must still record the
  388. // stop decision while execution and the turn continue normally.
  389. const d = dir()
  390. const s = sh(d, 'stop.sh', '#!/usr/bin/env bash\necho \'{"continue":false,"stopReason":"halt"}\'\n')
  391. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  392. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  393. const ctx = await harness(path, adapter)
  394. let ran = false
  395. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  396. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  397. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  398. await waitForIdle(ctx, agent)
  399. const res = events(agent).find(e => e.type === 'hook/result')
  400. expect(res?.type === 'hook/result' && res.data.decision).toBe('stop') // recorded
  401. expect(ran).toBe(true) // NOT honored: the tool still ran (halt is deferred)
  402. const turnEnd = events(agent).findLast(e => e.type === 'turn/end')
  403. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed') // ran to completion
  404. })
  405. it('a PostToolUse hook that BOTH blocks AND attaches additionalContext', async () => {
  406. const d = dir()
  407. const s = sh(d, 'b.sh', '#!/usr/bin/env bash\necho \'{"decision":"block","reason":"bad","hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"context too"}}\'\n')
  408. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  409. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  410. const ctx = await harness(path, adapter)
  411. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  412. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  413. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  414. await waitForIdle(ctx, agent)
  415. const result = events(agent).find(e => e.type === 'tool/result')
  416. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  417. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('bad'))).toBe(true)
  418. // additionalContext also injected (the block + context arm).
  419. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user' && e.data.content.some(b => b.type === 'text' && b.text.includes('context too')))).toBe(true)
  420. })
  421. it('a PreToolUse hook whose hookSpecificOutput names a DIFFERENT event does NOT deny the tool', async () => {
  422. // The block's hookEventName (UserPromptSubmit) mismatches the firing event
  423. // (PreToolUse), so its permissionDecision:"deny" is discarded — the tool runs.
  424. const d = dir()
  425. const s = sh(d, 'x.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","permissionDecision":"deny"}}\'\n')
  426. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  427. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  428. const ctx = await harness(path, adapter)
  429. let ran = false
  430. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  431. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  432. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  433. await waitForIdle(ctx, agent)
  434. expect(ran).toBe(true) // the mismatched deny was discarded → the tool ran
  435. })
  436. it('defaults CLAUDE_PROJECT_DIR to the session workspace when no projectDir is configured', async () => {
  437. // The default ACP wiring sets no projectDir. A stock CC hook that references
  438. // $CLAUDE_PROJECT_DIR (shell expansion) must still get the session workspace,
  439. // not an empty string. The hook echoes the var as additionalContext.
  440. const d = dir()
  441. const workspace = dir()
  442. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\nprintf \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"dir=%s"}}\' "$CLAUDE_PROJECT_DIR"\n')
  443. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  444. const adapter = new MockAdapter([textResponse('ran')])
  445. const ctx = await harness(path, adapter) // NB: no projectDir
  446. // The factory create() path honors meta.cwd (the plain agentLoop.create() does not).
  447. const { SessionId } = await import('@deepseek-ai/dsh-session')
  448. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: workspace }, agentOptions: { provider: 'mock', model: 'mock' } })
  449. handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  450. await waitForIdle(ctx, handle.agent)
  451. expect(events(handle.agent).some(e => e.type === 'user/message'
  452. && e.data.content.some(b => b.type === 'text' && b.text.includes(`dir=${workspace}`)))).toBe(true)
  453. await handle.dispose()
  454. })
  455. it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
  456. // A context-only hook delegates with `next()` and folds its context, so a downstream policy
  457. // listener can still veto the prompt.
  458. const d = dir()
  459. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n')
  460. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  461. const adapter = new MockAdapter([textResponse('should not run')])
  462. const ctx = await harness(path, adapter)
  463. // A later listener that blocks every prompt (registered AFTER the bridge).
  464. ctx.on('agent/prompt-submit', async () => ({ kind: 'block' as const, reason: 'policy veto' }))
  465. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  466. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  467. await waitForIdle(ctx, agent)
  468. // the downstream block won: the model was never called, no user/message was
  469. // recorded, and the (sole, fully-blocked) prompt closed the turn `rejected`
  470. expect(adapter.requests).toHaveLength(0)
  471. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user')).toBe(false)
  472. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  473. })
  474. it('preserves separate bridge and downstream prompt contexts with framing and metadata', async () => {
  475. // Both the bridge hook and a later prompt-submit listener attach context; the
  476. // request must see both as separately sourced durable events.
  477. const d = dir()
  478. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"from-bridge"}}\'\n')
  479. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  480. const adapter = new MockAdapter([textResponse('ok')])
  481. const ctx = await harness(path, adapter)
  482. ctx.on('agent/prompt-submit', async () => ({
  483. kind: 'allow' as const,
  484. content: [{ type: 'text' as const, text: 'rewritten-prompt' }],
  485. additionalContexts: [createUserMessage({
  486. content: [{ type: 'text' as const, text: 'from-downstream' }],
  487. source: { kind: 'plugin' as const, plugin: 'policy' },
  488. })],
  489. }))
  490. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  491. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  492. await waitForIdle(ctx, agent)
  493. const req = JSON.stringify(adapter.requests[0]!.messages)
  494. expect(req).toContain('from-bridge')
  495. expect(req).toContain('from-downstream')
  496. expect(req).toContain('rewritten-prompt') // downstream content rewrite preserved
  497. // the original prompt was replaced by the downstream rewrite
  498. const userMsg = events(agent).find(e => e.type === 'user/message')
  499. expect(userMsg?.type === 'user/message' && userMsg.data.content.some(b => b.type === 'text' && b.text === 'rewritten-prompt')).toBe(true)
  500. const contexts = events(agent).filter(event => event.type === 'user/message' && event.data.source.kind !== 'user')
  501. expect(contexts.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  502. { kind: 'plugin', plugin: 'hooks-claude' },
  503. { kind: 'plugin', plugin: 'policy' },
  504. ])
  505. })
  506. it('folds the bridge PostToolUse context onto a downstream canonical value replacement', async () => {
  507. // The bridge hook adds context; a later post-execute listener accepts with a
  508. // canonical replacement. Both the replacement and the bridge context survive.
  509. const d = dir()
  510. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  511. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  512. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  513. const ctx = await harness(path, adapter)
  514. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  515. ctx.on('tools/post-execute', async () => ({ kind: 'accept' as const, value: [{ type: 'text' as const, text: 'rewritten-result' }] }))
  516. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  517. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  518. await waitForIdle(ctx, agent)
  519. const result = events(agent).find(e => e.type === 'tool/result')
  520. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text === 'rewritten-result')).toBe(true)
  521. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  522. })
  523. it('keeps bridge and downstream PostToolUse contexts as separate sourced events', async () => {
  524. const d = dir()
  525. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  526. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  527. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  528. const ctx = await harness(path, adapter)
  529. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  530. ctx.on('tools/post-execute', async () => ({
  531. kind: 'accept' as const,
  532. additionalContexts: [createUserMessage({
  533. content: [{ type: 'text' as const, text: 'downstream-note' }],
  534. source: { kind: 'plugin' as const, plugin: 'policy' },
  535. })],
  536. }))
  537. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  538. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  539. await waitForIdle(ctx, agent)
  540. const contexts = events(agent).filter(event => event.type === 'user/message' && event.data.source.kind !== 'user')
  541. expect(contexts.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  542. { kind: 'plugin', plugin: 'hooks-claude' },
  543. { kind: 'plugin', plugin: 'policy' },
  544. ])
  545. })
  546. it('folds the bridge PostToolUse context onto a downstream listener BLOCK', async () => {
  547. // The bridge hook only adds context; a later post-execute listener blocks the
  548. // result. The block wins AND carries the bridge context (concatContext on the
  549. // block arm).
  550. const d = dir()
  551. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  552. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  553. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  554. const ctx = await harness(path, adapter)
  555. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  556. ctx.on('tools/post-execute', async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'downstream-block' }] }))
  557. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  558. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  559. await waitForIdle(ctx, agent)
  560. const result = events(agent).find(e => e.type === 'tool/result')
  561. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  562. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('downstream-block'))).toBe(true)
  563. // the bridge's context still landed (folded onto the block)
  564. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  565. })
  566. })
  567. if (group === 'edge-paths') describe('hooks-claude coverage — executor reject + no-open-turn', () => {
  568. it('when the bash executor REJECTS a hook run, the hook/result omits exitCode (non-blocking)', async () => {
  569. const d = dir()
  570. const s = sh(d, 'h.sh', '#!/usr/bin/env bash\nexit 0\n')
  571. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  572. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  573. const ctx = await harness(path, adapter)
  574. // Force the executor to reject (an infrastructure fault) so runHook's catch
  575. // yields a HookOutput with exitCode undefined → the `exitCode` spread false arm.
  576. const bash = ctx.bash
  577. bash.run = (() => Promise.reject(new Error('executor down')))
  578. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  579. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  580. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  581. await waitForIdle(ctx, agent)
  582. const res = events(agent).find(e => e.type === 'hook/result')
  583. expect(res?.type === 'hook/result' && 'exitCode' in res.data).toBe(false)
  584. })
  585. })
  586. if (group === 'edge-paths') describe('hooks-claude coverage — detached-listener catch handlers', () => {
  587. it('a throwing SessionStart inject is contained (logged, agent still runs)', async () => {
  588. const d = dir()
  589. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"x"}}\'\n')
  590. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  591. const adapter = new MockAdapter([textResponse('ok')])
  592. const ctx = await harness(path, adapter)
  593. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  594. // Make inject throw, forcing the SessionStart .catch path.
  595. const original = agent.inject.bind(agent)
  596. let threw = false
  597. agent.inject = (() => { threw = true; throw new Error('inject boom') })
  598. await waitFor(() => threw)
  599. expect(threw).toBe(true)
  600. agent.inject = original
  601. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  602. await waitForIdle(ctx, agent)
  603. expect(adapter.requests).toHaveLength(1) // loop survived the thrown inject
  604. })
  605. })
  606. if (group === 'stop') describe('hooks-claude coverage — hook runs in the session cwd, not the server cwd', () => {
  607. it('runs an agent-scoped hook in the session workspace even when the executor default differs', async () => {
  608. // The server launch directory and session cwd deliberately differ. The marker proves the
  609. // bridge passes `session/new.cwd` instead of falling back to the executor default.
  610. const serverDir = dir()
  611. const sessionDir = dir()
  612. const marker = join(sessionDir, 'where')
  613. // The hook is invoked with cwd = session dir, so a relative marker path lands there.
  614. hooks(serverDir, { PreToolUse: [{ hooks: [{ type: 'command', command: 'pwd > where' }] }] })
  615. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  616. const ctx = new Context()
  617. await mountAgentLoopTestDependencies(ctx)
  618. await ctx.plugin(AgentLoop, { agents: [] })
  619. // Executor default cwd = serverDir (deliberately NOT the session cwd).
  620. await ctx.plugin(LocalSubprocessService)
  621. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  622. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  623. ctx.llm.registerAdapter(['mock'], adapter)
  624. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  625. const { SessionId } = await import('@deepseek-ai/dsh-session')
  626. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: sessionDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  627. handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  628. await waitForIdle(ctx, handle.agent)
  629. expect(existsSync(marker)).toBe(true) // the marker landed in the SESSION dir
  630. const { readFileSync } = await import('node:fs')
  631. const where = readFileSync(marker, 'utf8').trim()
  632. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  633. expect(where.endsWith(sessionDir.split('/').pop()!)).toBe(true)
  634. await handle.dispose()
  635. })
  636. it('runs a SubagentStop hook in the CHILD session workspace, not the server cwd', async () => {
  637. // `SubagentStop` recovers the child at `subagent/end`; a relative marker proves `runPoint`
  638. // receives that agent and runs in the child's cwd rather than the executor default.
  639. const serverDir = dir()
  640. const childDir = dir()
  641. const marker = join(childDir, 'stopwhere')
  642. hooks(serverDir, { SubagentStop: [{ hooks: [{ type: 'command', command: 'pwd > stopwhere' }] }] })
  643. const ctx = new Context()
  644. await mountAgentLoopTestDependencies(ctx)
  645. await ctx.plugin(AgentLoop, { agents: [] })
  646. // Executor default cwd = serverDir (deliberately NOT the child session cwd).
  647. await ctx.plugin(LocalSubprocessService)
  648. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  649. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  650. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  651. const { SessionId } = await import('@deepseek-ai/dsh-session')
  652. const childHandle = await ctx.agents.create({ sessionId: SessionId('child-stop-session'), meta: { cwd: childDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  653. ctx.emit(subagentCarrier(ctx), 'subagent/end', { runId: SubagentRunId('run-stop'), provider: 'inproc', id: childHandle.agent.id, local: true, stopReason: 'completed' })
  654. await waitFor(() => existsSync(marker))
  655. expect(existsSync(marker)).toBe(true) // the marker landed in the CHILD dir
  656. const { readFileSync } = await import('node:fs')
  657. const where = readFileSync(marker, 'utf8').trim()
  658. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  659. expect(where.endsWith(childDir.split('/').pop()!)).toBe(true)
  660. await childHandle.dispose()
  661. })
  662. })
  663. if (group === 'config') describe('hooks-claude coverage — systemMessage is warned, not surfaced', () => {
  664. it('a hook emitting a systemMessage is logged as not-yet-surfaced', async () => {
  665. const d = dir()
  666. const s = sh(d, 'sm.sh', '#!/usr/bin/env bash\necho \'{"systemMessage":"heads up"}\'\n')
  667. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  668. const adapter = new MockAdapter([textResponse('ok')])
  669. const ctx = await harness(path, adapter)
  670. const warn = vi.fn(); ctx.logger.warn = warn as never
  671. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  672. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  673. await waitForIdle(ctx, agent)
  674. expect(warn).toHaveBeenCalledWith(expect.stringContaining('systemMessage'))
  675. // Not surfaced: the systemMessage text never reaches the model request.
  676. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('heads up')
  677. })
  678. })
  679. if (group === 'edge-paths') describe('hooks-claude coverage — SessionStart timing is best-effort (no-wait)', () => {
  680. it('does NOT crash or block when the prompt is sent immediately (context is best-effort, may miss the first request)', async () => {
  681. // Session-start injection is detached, so an immediate prompt need not observe it. Assert only
  682. // the guaranteed behavior—no crash and a completed turn—without pre-waiting away the race.
  683. const d = dir()
  684. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"late ctx"}}\'\n')
  685. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  686. const adapter = new MockAdapter([textResponse('ok')])
  687. const ctx = await harness(path, adapter)
  688. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  689. // Send immediately — do NOT wait for the session-start inject.
  690. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  691. await waitForIdle(ctx, agent)
  692. expect(adapter.requests).toHaveLength(1) // the turn ran regardless of hook timing
  693. })
  694. })
  695. }