coverage-cases.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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. envelope: 'raw' as const,
  479. meta: { owner: 'policy' },
  480. }],
  481. }))
  482. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  483. agent.send([{ type: 'text', text: 'go' }])
  484. await waitForIdle(ctx, agent)
  485. const req = JSON.stringify(adapter.requests[0]!.messages)
  486. expect(req).toContain('from-bridge')
  487. expect(req).toContain('from-downstream')
  488. expect(req).toContain('rewritten-prompt') // downstream content rewrite preserved
  489. // the original prompt was replaced by the downstream rewrite
  490. const userMsg = events(agent).find(e => e.type === 'user/message')
  491. expect(userMsg?.type === 'user/message' && userMsg.data.content.some(b => b.type === 'text' && b.text === 'rewritten-prompt')).toBe(true)
  492. const contexts = events(agent).filter(event => event.type === 'context/message')
  493. expect(contexts.map(event => event.type === 'context/message' && event.data.source)).toEqual([
  494. { kind: 'plugin', plugin: 'hooks-claude' },
  495. { kind: 'plugin', plugin: 'policy' },
  496. ])
  497. expect(contexts[1]?.type === 'context/message' && contexts[1].data.envelope).toBe('raw')
  498. expect(contexts[1]?.type === 'context/message' && contexts[1].data.meta).toEqual({ owner: 'policy' })
  499. })
  500. it('folds the bridge PostToolUse context onto a downstream ACCEPT that replaces content', async () => {
  501. // The bridge hook adds context; a later post-execute listener accepts with a
  502. // content rewrite. Both the rewrite and the bridge context survive.
  503. const d = dir()
  504. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  505. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  506. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  507. const ctx = await harness(path, adapter)
  508. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  509. ctx.on('tools/post-execute', async () => ({ kind: 'accept' as const, content: [{ type: 'text' as const, text: 'rewritten-result' }] }))
  510. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  511. agent.send([{ type: 'text', text: 'go' }])
  512. await waitForIdle(ctx, agent)
  513. const result = events(agent).find(e => e.type === 'tool/result')
  514. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text === 'rewritten-result')).toBe(true)
  515. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  516. })
  517. it('keeps bridge and downstream PostToolUse contexts as separate sourced events', async () => {
  518. const d = dir()
  519. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  520. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  521. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  522. const ctx = await harness(path, adapter)
  523. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  524. ctx.on('tools/post-execute', async () => ({
  525. kind: 'accept' as const,
  526. additionalContexts: [{
  527. content: [{ type: 'text' as const, text: 'downstream-note' }],
  528. source: { kind: 'plugin' as const, plugin: 'policy' },
  529. envelope: 'raw' as const,
  530. meta: { owner: 'policy' },
  531. }],
  532. }))
  533. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  534. agent.send([{ type: 'text', text: 'go' }])
  535. await waitForIdle(ctx, agent)
  536. const contexts = events(agent).filter(event => event.type === 'context/message')
  537. expect(contexts.map(event => event.type === 'context/message' && event.data.source)).toEqual([
  538. { kind: 'plugin', plugin: 'hooks-claude' },
  539. { kind: 'plugin', plugin: 'policy' },
  540. ])
  541. expect(contexts[1]?.type === 'context/message' && contexts[1].data.envelope).toBe('raw')
  542. expect(contexts[1]?.type === 'context/message' && contexts[1].data.meta).toEqual({ owner: 'policy' })
  543. })
  544. it('folds the bridge PostToolUse context onto a downstream listener BLOCK', async () => {
  545. // The bridge hook only adds context; a later post-execute listener blocks the
  546. // result. The block wins AND carries the bridge context (concatContext on the
  547. // block arm).
  548. const d = dir()
  549. const s = sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n')
  550. const path = hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  551. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  552. const ctx = await harness(path, adapter)
  553. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  554. ctx.on('tools/post-execute', async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'downstream-block' }] }))
  555. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  556. agent.send([{ type: 'text', text: 'go' }])
  557. await waitForIdle(ctx, agent)
  558. const result = events(agent).find(e => e.type === 'tool/result')
  559. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  560. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('downstream-block'))).toBe(true)
  561. // the bridge's context still landed (folded onto the block)
  562. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  563. })
  564. })
  565. if (group === 'edge-paths') describe('hooks-claude coverage — executor reject + no-open-turn', () => {
  566. it('when the bash executor REJECTS a hook run, the hook/result omits exitCode (non-blocking)', async () => {
  567. const d = dir()
  568. const s = sh(d, 'h.sh', '#!/usr/bin/env bash\nexit 0\n')
  569. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: s }] }] })
  570. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  571. const ctx = await harness(path, adapter)
  572. // Force the executor to reject (an infrastructure fault) so runHook's catch
  573. // yields a HookOutput with exitCode undefined → the `exitCode` spread false arm.
  574. const bash = ctx.bash
  575. bash.run = (() => Promise.reject(new Error('executor down')))
  576. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  577. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  578. agent.send([{ type: 'text', text: 'go' }])
  579. await waitForIdle(ctx, agent)
  580. const res = events(agent).find(e => e.type === 'hook/result')
  581. expect(res?.type === 'hook/result' && 'exitCode' in res.data).toBe(false)
  582. })
  583. })
  584. if (group === 'edge-paths') describe('hooks-claude coverage — detached-listener catch handlers', () => {
  585. it('a throwing SessionStart inject is contained (logged, agent still runs)', async () => {
  586. const d = dir()
  587. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"x"}}\'\n')
  588. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  589. const adapter = new MockAdapter([textResponse('ok')])
  590. const ctx = await harness(path, adapter)
  591. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  592. // Make inject throw, forcing the SessionStart .catch path.
  593. const original = agent.inject.bind(agent)
  594. let threw = false
  595. agent.inject = (() => { threw = true; throw new Error('inject boom') })
  596. await waitFor(() => threw)
  597. expect(threw).toBe(true)
  598. agent.inject = original
  599. agent.send([{ type: 'text', text: 'go' }])
  600. await waitForIdle(ctx, agent)
  601. expect(adapter.requests).toHaveLength(1) // loop survived the thrown inject
  602. })
  603. })
  604. if (group === 'stop') describe('hooks-claude coverage — hook runs in the session cwd, not the server cwd', () => {
  605. it('runs an agent-scoped hook in the session workspace even when the executor default differs', async () => {
  606. // The server launch directory and session cwd deliberately differ. The marker proves the
  607. // bridge passes `session/new.cwd` instead of falling back to the executor default.
  608. const serverDir = dir()
  609. const sessionDir = dir()
  610. const marker = join(sessionDir, 'where')
  611. // The hook is invoked with cwd = session dir, so a relative marker path lands there.
  612. hooks(serverDir, { PreToolUse: [{ hooks: [{ type: 'command', command: 'pwd > where' }] }] })
  613. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  614. const ctx = new Context()
  615. await mountAgentLoopTestDependencies(ctx)
  616. await ctx.plugin(AgentLoop, { agents: [] })
  617. // Executor default cwd = serverDir (deliberately NOT the session cwd).
  618. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  619. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  620. ctx.llm.registerAdapter(['mock'], adapter)
  621. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  622. const { SessionId } = await import('@deepseek-ai/dsh-session')
  623. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: sessionDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  624. handle.agent.send([{ type: 'text', text: 'go' }])
  625. await waitForIdle(ctx, handle.agent)
  626. expect(existsSync(marker)).toBe(true) // the marker landed in the SESSION dir
  627. const { readFileSync } = await import('node:fs')
  628. const where = readFileSync(marker, 'utf8').trim()
  629. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  630. expect(where.endsWith(sessionDir.split('/').pop()!)).toBe(true)
  631. await handle.dispose()
  632. })
  633. it('runs a SubagentStop hook in the CHILD session workspace, not the server cwd', async () => {
  634. // `SubagentStop` recovers the child at `subagent/end`; a relative marker proves `runPoint`
  635. // receives that agent and runs in the child's cwd rather than the executor default.
  636. const serverDir = dir()
  637. const childDir = dir()
  638. const marker = join(childDir, 'stopwhere')
  639. hooks(serverDir, { SubagentStop: [{ hooks: [{ type: 'command', command: 'pwd > stopwhere' }] }] })
  640. const ctx = new Context()
  641. await mountAgentLoopTestDependencies(ctx)
  642. await ctx.plugin(AgentLoop, { agents: [] })
  643. // Executor default cwd = serverDir (deliberately NOT the child session cwd).
  644. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  645. await ctx.plugin(HooksClaude, { configPath: join(serverDir, 'hooks.json') })
  646. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  647. // Register a live child on its own session cwd; emit subagent/end with its id.
  648. const { SessionId } = await import('@deepseek-ai/dsh-session')
  649. const childHandle = await ctx.agents.create({ sessionId: SessionId('child-stop-session'), meta: { cwd: childDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  650. ctx.emit('subagent/end', { runId: SubagentRunId('run-stop'), provider: 'inproc', id: childHandle.agent.id, local: true, stopReason: 'completed' })
  651. await waitFor(() => existsSync(marker))
  652. expect(existsSync(marker)).toBe(true) // the marker landed in the CHILD dir
  653. const { readFileSync } = await import('node:fs')
  654. const where = readFileSync(marker, 'utf8').trim()
  655. // `pwd` may resolve symlinks (/var → /private/var etc.), so compare basenames.
  656. expect(where.endsWith(childDir.split('/').pop()!)).toBe(true)
  657. await childHandle.dispose()
  658. })
  659. })
  660. if (group === 'config') describe('hooks-claude coverage — systemMessage is warned, not surfaced', () => {
  661. it('a hook emitting a systemMessage is logged as not-yet-surfaced', async () => {
  662. const d = dir()
  663. const s = sh(d, 'sm.sh', '#!/usr/bin/env bash\necho \'{"systemMessage":"heads up"}\'\n')
  664. const path = hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: s }] }] })
  665. const adapter = new MockAdapter([textResponse('ok')])
  666. const ctx = await harness(path, adapter)
  667. const warn = vi.fn(); ctx.logger.warn = warn as never
  668. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  669. agent.send([{ type: 'text', text: 'go' }])
  670. await waitForIdle(ctx, agent)
  671. expect(warn).toHaveBeenCalledWith(expect.stringContaining('systemMessage'))
  672. // Not surfaced: the systemMessage text never reaches the model request.
  673. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('heads up')
  674. })
  675. })
  676. if (group === 'edge-paths') describe('hooks-claude coverage — SessionStart timing is best-effort (no-wait)', () => {
  677. it('does NOT crash or block when the prompt is sent immediately (context is best-effort, may miss the first request)', async () => {
  678. // Session-start injection is detached, so an immediate prompt need not observe it. Assert only
  679. // the guaranteed behavior—no crash and a completed turn—without pre-waiting away the race.
  680. const d = dir()
  681. const s = sh(d, 'start.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"late ctx"}}\'\n')
  682. const path = hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: s }] }] })
  683. const adapter = new MockAdapter([textResponse('ok')])
  684. const ctx = await harness(path, adapter)
  685. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  686. // Send immediately — do NOT wait for the session-start inject.
  687. agent.send([{ type: 'text', text: 'go' }])
  688. await waitForIdle(ctx, agent)
  689. expect(adapter.requests).toHaveLength(1) // the turn ran regardless of hook timing
  690. })
  691. })
  692. }