coverage-cases.ts 47 KB

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