coverage-cases.ts 50 KB

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