coverage-cases.ts 48 KB

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