coverage-cases.ts 50 KB

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