coverage-cases.ts 50 KB

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