coverage-cases.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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 '@deepseek-ai/cordis'
  7. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  8. import JsonlSessionPersistence 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 LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  15. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  16. import SubagentRuntime, { SubagentRunId } from '@deepseek-ai/dsh-subagent'
  17. import * as HooksClaude from '@deepseek-ai/dsh-hooks-claude-code'
  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 SubagentRuntime, 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(JsonlSessionPersistence, { root: opts.sessionRoot })
  39. await ctx.plugin(AgentLoop, { agents: [] })
  40. await ctx.plugin(LocalSubprocessRuntime)
  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-code coverage matrix. */
  61. export function defineCoverageCases(group: CoverageGroup): void {
  62. if (group === 'config') describe('hooks-claude-code 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. }, 15_000) // Real agent and hook subprocess startup can exceed Vitest's default under coverage concurrency.
  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-code 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-code: 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-code 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-code 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-code 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).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
  302. || e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
  303. .toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
  304. })
  305. it('a PreToolUse ask with NO reason omits the reason (false arm)', async () => {
  306. const d = dir()
  307. const s = sh(d, 'ask.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask"}}\'\n')
  308. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  309. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  310. const ctx = await harness(path, adapter)
  311. let ran = false
  312. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'x' }] } }))
  313. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  314. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  315. await waitForIdle(ctx, agent)
  316. // ask (no reason) → degrades to deny with the registry's generic message.
  317. expect(ran).toBe(false)
  318. expect(events(agent).some(e => e.type === 'tool/result' && e.data.message.content[0].isError)).toBe(true)
  319. })
  320. it('a recorded clean exit-0 hook with no stderr omits exitCode-extra/stderrSummary fields', async () => {
  321. const d = dir()
  322. const s = sh(d, 'noop.sh', '#!/usr/bin/env bash\nexit 0\n')
  323. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  324. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  325. const ctx = await harness(path, adapter)
  326. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  327. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  328. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  329. await waitForIdle(ctx, agent)
  330. const res = events(agent).find(e => e.type === 'hook/result')
  331. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(0)
  332. expect(res?.type === 'hook/result' && 'stderrSummary' in res.data).toBe(false)
  333. })
  334. })
  335. if (group === 'edge-paths') describe('hooks-claude-code coverage — schema-bypass apply + unspawnable hook', () => {
  336. it('a direct apply() (schema bypass) with only configPath runs', async () => {
  337. const d = dir()
  338. const marker = join(d, 'ran')
  339. const s = sh(d, 'h.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`)
  340. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  341. const adapter = new MockAdapter([textResponse('ok')])
  342. const ctx = new Context()
  343. await mountAgentLoopTestDependencies(ctx)
  344. await ctx.plugin(AgentLoop, { agents: [] })
  345. await ctx.plugin(LocalSubprocessRuntime)
  346. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  347. // Direct apply with only configPath — bypasses schemastery's defaults, so
  348. // the bridge must run on the raw minimal config (the per-hook timeout is
  349. // the protocol lib's reference default, not a config knob).
  350. HooksClaude.apply(ctx, { configPath: join(d, 'hooks.json') })
  351. ctx.llm.registerAdapter(['mock'], adapter)
  352. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  353. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  354. await waitForIdle(ctx, agent)
  355. expect(existsSync(marker)).toBe(true)
  356. })
  357. 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 () => {
  358. const d = dir()
  359. // `bash -c` of a missing program exits 127 — a non-blocking error (not 0, not
  360. // 2 → no decision), so the tool proceeds; the hook/result records exit 127.
  361. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: '/nonexistent/definitely/not/a/command' }] }] })
  362. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  363. const ctx = await harness(path, adapter)
  364. let ran = false
  365. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  366. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  367. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  368. await waitForIdle(ctx, agent)
  369. expect(ran).toBe(true)
  370. const res = events(agent).find(e => e.type === 'hook/result')
  371. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(127)
  372. })
  373. it('a PostToolUse deny with empty stderr + no context uses the default feedback (no context arm)', async () => {
  374. const d = dir()
  375. const s = sh(d, 'block.sh', '#!/usr/bin/env bash\nexit 2\n')
  376. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  377. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  378. const ctx = await harness(path, adapter)
  379. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  380. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  381. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  382. await waitForIdle(ctx, agent)
  383. const result = events(agent).find(e => e.type === 'tool/result')
  384. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  385. })
  386. })
  387. if (group === 'context') describe('hooks-claude-code coverage — continue:false, context arm, no-cwd', () => {
  388. it('a {"continue":false} hook is RECORDED as decision "stop" but does not halt the run (TODO(hook-continue-false))', async () => {
  389. // The extension points cannot yet honor `continue:false` as a hard halt. The log must still record the
  390. // stop decision while execution and the turn continue normally.
  391. const d = dir()
  392. const s = sh(d, 'stop.sh', '#!/usr/bin/env bash\necho \'{"continue":false,"stopReason":"halt"}\'\n')
  393. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  394. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  395. const ctx = await harness(path, adapter)
  396. let ran = false
  397. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  398. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  399. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  400. await waitForIdle(ctx, agent)
  401. const res = events(agent).find(e => e.type === 'hook/result')
  402. expect(res?.type === 'hook/result' && res.data.decision).toBe('stop') // recorded
  403. expect(ran).toBe(true) // NOT honored: the tool still ran (halt is deferred)
  404. const turnEnd = events(agent).findLast(e => e.type === 'turn/end')
  405. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed') // ran to completion
  406. })
  407. it('a PostToolUse hook that BOTH blocks AND attaches additionalContext', async () => {
  408. const d = dir()
  409. const s = sh(d, 'b.sh', '#!/usr/bin/env bash\necho \'{"decision":"block","reason":"bad","hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"context too"}}\'\n')
  410. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  411. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  412. const ctx = await harness(path, adapter)
  413. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  414. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  415. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  416. await waitForIdle(ctx, agent)
  417. const result = events(agent).find(e => e.type === 'tool/result')
  418. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  419. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('bad'))).toBe(true)
  420. // additionalContext also injected (the block + context arm).
  421. 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)
  422. })
  423. it('a PreToolUse hook whose hookSpecificOutput names a DIFFERENT event does NOT deny the tool', async () => {
  424. // The block's hookEventName (UserPromptSubmit) mismatches the firing event
  425. // (PreToolUse), so its permissionDecision:"deny" is discarded — the tool runs.
  426. const d = dir()
  427. const s = sh(d, 'x.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","permissionDecision":"deny"}}\'\n')
  428. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  429. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  430. const ctx = await harness(path, adapter)
  431. let ran = false
  432. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  433. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  434. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  435. await waitForIdle(ctx, agent)
  436. expect(ran).toBe(true) // the mismatched deny was discarded → the tool ran
  437. })
  438. it('defaults CLAUDE_PROJECT_DIR to the session workspace when no projectDir is configured', async () => {
  439. // The default ACP wiring sets no projectDir. A stock CC hook that references
  440. // $CLAUDE_PROJECT_DIR (shell expansion) must still get the session workspace,
  441. // not an empty string. The hook echoes the var as additionalContext.
  442. const d = dir()
  443. const workspace = dir()
  444. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\nprintf \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"dir=%s"}}\' "$CLAUDE_PROJECT_DIR"\n')
  445. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  446. const adapter = new MockAdapter([textResponse('ran')])
  447. const ctx = await harness(path, adapter) // NB: no projectDir
  448. // The factory create() path honors meta.cwd (the plain agentLoop.create() does not).
  449. const { SessionId } = await import('@deepseek-ai/dsh-session')
  450. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: workspace }, agentOptions: { provider: 'mock', model: 'mock' } })
  451. handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  452. await waitForIdle(ctx, handle.agent)
  453. expect(events(handle.agent).some(e => e.type === 'user/message'
  454. && e.data.content.some(b => b.type === 'text' && b.text.includes(`dir=${workspace}`)))).toBe(true)
  455. await handle.dispose()
  456. })
  457. it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
  458. // A context-only hook delegates with `next()` and folds its context, so a downstream policy
  459. // listener can still veto the prompt.
  460. const d = dir()
  461. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n')
  462. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  463. const adapter = new MockAdapter([textResponse('should not run')])
  464. const ctx = await harness(path, adapter)
  465. // A later listener that blocks every prompt (registered AFTER the bridge).
  466. ctx.on('agent/pre-step', async () => ({
  467. kind: 'reject' as const,
  468. }))
  469. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  470. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  471. await waitForIdle(ctx, agent)
  472. // the downstream block won: the model was never called, no user/message was
  473. // recorded, and the (sole, fully-blocked) prompt closed the turn `rejected`
  474. expect(adapter.requests).toHaveLength(0)
  475. expect(events(agent).some(e => e.type === 'user/message' && e.data.source.kind !== 'user')).toBe(false)
  476. expect(events(agent).filter(e => e.type === 'turn/start' || e.type === 'hook/invoked'
  477. || e.type === 'hook/result' || e.type === 'turn/end').map(e => e.type))
  478. .toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
  479. })
  480. it('preserves separate bridge and downstream prompt contexts with framing and metadata', async () => {
  481. // Both the bridge hook and a later pre-step listener attach context; the
  482. // request must see both as separately sourced durable events.
  483. const d = dir()
  484. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"from-bridge"}}\'\n')
  485. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  486. const adapter = new MockAdapter([textResponse('ok')])
  487. const ctx = await harness(path, adapter)
  488. ctx.on('agent/pre-step', async ({ messages }) => ({
  489. kind: 'enter' as const,
  490. messages: [{
  491. ...messages[0]!,
  492. content: [{ type: 'text' as const, text: 'rewritten-prompt' }],
  493. }, createUserMessage({
  494. content: [{ type: 'text' as const, text: 'from-downstream' }],
  495. source: { kind: 'plugin' as const, plugin: 'policy' },
  496. })],
  497. }))
  498. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  499. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  500. await waitForIdle(ctx, agent)
  501. const req = JSON.stringify(adapter.requests[0]!.messages)
  502. expect(req).toContain('from-bridge')
  503. expect(req).toContain('from-downstream')
  504. expect(req).toContain('rewritten-prompt') // downstream content rewrite preserved
  505. // the original prompt was replaced by the downstream rewrite
  506. const userMsg = events(agent).find(e => e.type === 'user/message')
  507. expect(userMsg?.type === 'user/message' && userMsg.data.content.some(b => b.type === 'text' && b.text === 'rewritten-prompt')).toBe(true)
  508. const contexts = events(agent).filter(event => event.type === 'user/message' && event.data.source.kind !== 'user')
  509. expect(contexts.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  510. { kind: 'plugin', plugin: 'policy' },
  511. { kind: 'plugin', plugin: 'hooks-claude-code' },
  512. ])
  513. })
  514. it('folds the bridge PostToolUse context onto a downstream canonical value replacement', async () => {
  515. // The bridge hook adds context; a later post-execute listener accepts with a
  516. // canonical replacement. Both the replacement and the bridge context survive.
  517. const d = dir()
  518. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  519. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  520. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  521. const ctx = await harness(path, adapter)
  522. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  523. ctx.on('tools/post-execute', async () => ({ kind: 'accept' as const, value: [{ type: 'text' as const, text: 'rewritten-result' }] }))
  524. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  525. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  526. await waitForIdle(ctx, agent)
  527. const result = events(agent).find(e => e.type === 'tool/result')
  528. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text === 'rewritten-result')).toBe(true)
  529. 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)
  530. })
  531. it('keeps bridge and downstream PostToolUse contexts as separate sourced events', async () => {
  532. const d = dir()
  533. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  534. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  535. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  536. const ctx = await harness(path, adapter)
  537. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  538. ctx.on('tools/post-execute', async () => ({
  539. kind: 'accept' as const,
  540. additionalContexts: [createUserMessage({
  541. content: [{ type: 'text' as const, text: 'downstream-note' }],
  542. source: { kind: 'plugin' as const, plugin: 'policy' },
  543. })],
  544. }))
  545. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  546. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  547. await waitForIdle(ctx, agent)
  548. const contexts = events(agent).filter(event => event.type === 'user/message' && event.data.source.kind !== 'user')
  549. expect(contexts.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  550. { kind: 'plugin', plugin: 'hooks-claude-code' },
  551. { kind: 'plugin', plugin: 'policy' },
  552. ])
  553. })
  554. it('folds the bridge PostToolUse context onto a downstream listener BLOCK', async () => {
  555. // The bridge hook only adds context; a later post-execute listener blocks the
  556. // result. The block wins AND carries the bridge context (concatContext on the
  557. // block arm).
  558. const d = dir()
  559. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  560. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  561. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  562. const ctx = await harness(path, adapter)
  563. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  564. ctx.on('tools/post-execute', async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'downstream-block' }] }))
  565. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  566. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  567. await waitForIdle(ctx, agent)
  568. const result = events(agent).find(e => e.type === 'tool/result')
  569. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  570. expect(result?.type === 'tool/result' && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('downstream-block'))).toBe(true)
  571. // the bridge's context still landed (folded onto the block)
  572. 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)
  573. })
  574. })
  575. if (group === 'edge-paths') describe('hooks-claude-code coverage — executor reject + no-open-turn', () => {
  576. it('when the bash executor REJECTS a hook run, the hook/result omits exitCode (non-blocking)', async () => {
  577. const d = dir()
  578. const s = sh(d, 'h.sh', '#!/usr/bin/env bash\nexit 0\n')
  579. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  580. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  581. const ctx = await harness(path, adapter)
  582. // Force the executor to reject (an infrastructure fault) so runHook's catch
  583. // yields a HookOutput with exitCode undefined → the `exitCode` spread false arm.
  584. const bash = ctx.shell
  585. bash.run = (() => Promise.reject(new Error('executor down')))
  586. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  587. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  588. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  589. await waitForIdle(ctx, agent)
  590. const res = events(agent).find(e => e.type === 'hook/result')
  591. expect(res?.type === 'hook/result' && 'exitCode' in res.data).toBe(false)
  592. })
  593. })
  594. if (group === 'edge-paths') describe('hooks-claude-code coverage — detached-listener catch handlers', () => {
  595. it('a throwing SessionStart inject is contained (logged, agent still runs)', async () => {
  596. const d = dir()
  597. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"x"}}\'\n')
  598. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  599. const adapter = new MockAdapter([textResponse('ok')])
  600. const ctx = await harness(path, adapter)
  601. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  602. // Make inject throw, forcing the SessionStart .catch path.
  603. const original = agent.inject.bind(agent)
  604. let threw = false
  605. agent.inject = (() => { threw = true; throw new Error('inject boom') })
  606. await waitFor(() => threw)
  607. expect(threw).toBe(true)
  608. agent.inject = original
  609. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  610. await waitForIdle(ctx, agent)
  611. expect(adapter.requests).toHaveLength(1) // loop survived the thrown inject
  612. })
  613. })
  614. if (group === 'stop') describe('hooks-claude-code coverage — hook runs in the session cwd, not the server cwd', () => {
  615. it('runs an agent-scoped hook in the session workspace even when the executor default differs', async () => {
  616. // The server launch directory and session cwd deliberately differ. The marker proves the
  617. // bridge passes `session/new.cwd` instead of falling back to the executor default.
  618. const serverDir = dir()
  619. const sessionDir = dir()
  620. const marker = join(sessionDir, 'where')
  621. // The hook is invoked with cwd = session dir, so a relative marker path lands there.
  622. hooks(serverDir, { PreToolUse: [{ hooks: [{ type: 'command', command: 'pwd > where' }] }] })
  623. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  624. const ctx = new Context()
  625. await mountAgentLoopTestDependencies(ctx)
  626. await ctx.plugin(AgentLoop, { agents: [] })
  627. // Executor default cwd = serverDir (deliberately NOT the session cwd).
  628. await ctx.plugin(LocalSubprocessRuntime)
  629. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  630. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  631. ctx.llm.registerAdapter(['mock'], adapter)
  632. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  633. const { SessionId } = await import('@deepseek-ai/dsh-session')
  634. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: sessionDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  635. handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  636. await waitForIdle(ctx, handle.agent)
  637. expect(existsSync(marker)).toBe(true) // the marker landed in the SESSION dir
  638. const { readFileSync } = await import('node:fs')
  639. const where = readFileSync(marker, 'utf8').trim()
  640. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  641. expect(where.endsWith(sessionDir.split('/').pop()!)).toBe(true)
  642. await handle.dispose()
  643. })
  644. it('runs a SubagentStop hook in the CHILD session workspace, not the server cwd', async () => {
  645. const serverDir = dir()
  646. const childDir = dir()
  647. const marker = join(childDir, 'stopwhere')
  648. const payload = join(childDir, 'stoppayload')
  649. hooks(serverDir, { SubagentStop: [{ hooks: [{ type: 'command', command: 'cat > stoppayload.tmp; mv stoppayload.tmp stoppayload; pwd > stopwhere' }] }] })
  650. const ctx = new Context()
  651. await mountAgentLoopTestDependencies(ctx)
  652. await ctx.plugin(AgentLoop, { agents: [] })
  653. // Executor default cwd = serverDir (deliberately NOT the child session cwd).
  654. await ctx.plugin(LocalSubprocessRuntime)
  655. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  656. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  657. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  658. const { SessionId } = await import('@deepseek-ai/dsh-session')
  659. const childHandle = await ctx.agents.create({ sessionId: SessionId('child-stop-session'), meta: { cwd: childDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  660. const runId = SubagentRunId('run-stop')
  661. const identity = { runId, provider: 'inproc', id: childHandle.agent.id, local: true }
  662. // Start is the registry-backed capture edge; end deliberately follows
  663. // handle disposal, matching continuable Activation settlement.
  664. ctx.emit(subagentCarrier(ctx), 'subagent/start', identity)
  665. await childHandle.dispose()
  666. expect(ctx.agents.get(childHandle.agent.id)).toBeUndefined()
  667. ctx.emit(subagentCarrier(ctx), 'subagent/end', { ...identity, stopReason: 'completed' })
  668. await waitFor(() => existsSync(marker))
  669. expect(existsSync(marker)).toBe(true) // the marker landed in the CHILD dir
  670. const where = readFileSync(marker, 'utf8').trim()
  671. const input = JSON.parse(readFileSync(payload, 'utf8')) as { cwd: string; session_id: string }
  672. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  673. expect(where.endsWith(childDir.split('/').pop()!)).toBe(true)
  674. expect(input).toMatchObject({ cwd: childDir, session_id: childHandle.agent.id })
  675. })
  676. })
  677. if (group === 'config') describe('hooks-claude-code coverage — systemMessage is warned, not surfaced', () => {
  678. it('a hook emitting a systemMessage is logged as not-yet-surfaced', async () => {
  679. const d = dir()
  680. const s = sh(d, 'sm.sh', '#!/usr/bin/env bash\necho \'{"systemMessage":"heads up"}\'\n')
  681. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  682. const adapter = new MockAdapter([textResponse('ok')])
  683. const ctx = await harness(path, adapter)
  684. const warn = vi.fn(); ctx.logger.warn = warn as never
  685. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  686. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  687. await waitForIdle(ctx, agent)
  688. expect(warn).toHaveBeenCalledWith(expect.stringContaining('systemMessage'))
  689. // Not surfaced: the systemMessage text never reaches the model request.
  690. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('heads up')
  691. })
  692. })
  693. if (group === 'edge-paths') describe('hooks-claude-code coverage — SessionStart timing is best-effort (no-wait)', () => {
  694. it('does NOT crash or block when the prompt is sent immediately (context is best-effort, may miss the first request)', async () => {
  695. // Session-start injection is detached, so an immediate prompt need not observe it. Assert only
  696. // the guaranteed behavior—no crash and a completed turn—without pre-waiting away the race.
  697. const d = dir()
  698. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"late ctx"}}\'\n')
  699. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  700. const adapter = new MockAdapter([textResponse('ok')])
  701. const ctx = await harness(path, adapter)
  702. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  703. // Send immediately — do NOT wait for the session-start inject.
  704. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  705. await waitForIdle(ctx, agent)
  706. expect(adapter.requests).toHaveLength(1) // the turn ran regardless of hook timing
  707. })
  708. })
  709. }