coverage.spec.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 LlmService from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { type SessionEvent } from '@deepseek-ai/dsh-session'
  8. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  9. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  10. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  11. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  12. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  13. import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex'
  14. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  15. const dirs: string[] = []
  16. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  17. function dir(): string { const d = mkdtempSync(join(tmpdir(), 'dsh-hx-cov-')); dirs.push(d); return d }
  18. function sh(d: string, name: string, body: string): string {
  19. const p = join(d, name); writeFileSync(p, body); chmodSync(p, 0o755); return p
  20. }
  21. function hooks(d: string, h: unknown): string {
  22. writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
  23. }
  24. async function harness(configPath: string, adapter: MockAdapter, opts: { stderrSummaryMaxChars?: number } = {}): Promise<Context> {
  25. const ctx = new Context()
  26. await ctx.plugin(LlmService); await ctx.plugin(SessionStore); await ctx.plugin(SystemPrompt)
  27. await ctx.plugin(ToolRegistry); await ctx.plugin(AgentRegistry); await ctx.plugin(AgentLoop, { agents: [] })
  28. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  29. await ctx.plugin(HooksCodex, { configPath, model: 'm', ...opts })
  30. ctx.llm.registerAdapter(['mock'], adapter)
  31. return ctx
  32. }
  33. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  34. return new Promise((resolve) => { const d = ctx.on('agent/status', (s, st) => { if (s === agent && st === 'idle') { d(); resolve() } }) })
  35. }
  36. function events(agent: ReactLoopAgent): SessionEvent[] { return [...agent.session.events] }
  37. /** Poll until `predicate` holds or the deadline passes — robust to detached
  38. * emit-listener hooks firing on a `.then` (a fixed sleep flakes under load). */
  39. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  40. const deadline = Date.now() + timeout
  41. while (!predicate()) {
  42. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  43. await new Promise(r => setTimeout(r, interval))
  44. }
  45. }
  46. describe('hooks-codex coverage — decision mapping paths', () => {
  47. it('UserPromptSubmit block (exit 2) → rejected turn; default reason on empty stderr', async () => {
  48. const d = dir()
  49. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'b.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  50. const adapter = new MockAdapter([textResponse('no')])
  51. const ctx = await harness(join(d, 'hooks.json'), adapter)
  52. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  53. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  54. expect(adapter.requests).toHaveLength(0)
  55. const te = events(agent).findLast(e => e.type === 'turn/end')
  56. expect(te?.type === 'turn/end' && te.data.reason.kind).toBe('rejected')
  57. })
  58. it('UserPromptSubmit additionalContext is injected; a no-op hook proceeds', async () => {
  59. const d = dir()
  60. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"ctx-x"}}\'\n') }] }] })
  61. const adapter = new MockAdapter([textResponse('ok')])
  62. const ctx = await harness(join(d, 'hooks.json'), adapter)
  63. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  64. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  65. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('ctx-x')
  66. })
  67. it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
  68. // Context alone is not a veto: the bridge delegates with `next()` and folds its context, so a
  69. // downstream policy listener can still block.
  70. const d = dir()
  71. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n') }] }] })
  72. const adapter = new MockAdapter([textResponse('should not run')])
  73. const ctx = await harness(join(d, 'hooks.json'), adapter)
  74. ctx.on('agent/prompt-submit', async () => ({ kind: 'block' as const, reason: 'policy veto' }))
  75. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  76. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  77. expect(adapter.requests).toHaveLength(0)
  78. expect(events(agent).some(e => e.type === 'user/message')).toBe(false)
  79. const te = events(agent).findLast(e => e.type === 'turn/end')
  80. expect(te?.type === 'turn/end' && te.data.reason).toMatchObject({ kind: 'rejected', reason: 'policy veto' })
  81. })
  82. it('folds the bridge additionalContext WITH a downstream listener that also adds context', async () => {
  83. const d = dir()
  84. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"from-bridge"}}\'\n') }] }] })
  85. const adapter = new MockAdapter([textResponse('ok')])
  86. const ctx = await harness(join(d, 'hooks.json'), adapter)
  87. ctx.on('agent/prompt-submit', async () => ({
  88. kind: 'allow' as const,
  89. content: [{ type: 'text' as const, text: 'rewritten-prompt' }],
  90. additionalContext: { content: [{ type: 'text' as const, text: 'from-downstream' }], source: { kind: 'plugin' as const, plugin: 'policy' } },
  91. }))
  92. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  93. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  94. const req = JSON.stringify(adapter.requests[0]!.messages)
  95. expect(req).toContain('from-bridge')
  96. expect(req).toContain('from-downstream')
  97. expect(req).toContain('rewritten-prompt')
  98. })
  99. it('folds the bridge PostToolUse context onto a downstream ACCEPT that replaces content', async () => {
  100. const d = dir()
  101. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n') }] }] })
  102. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  103. const ctx = await harness(join(d, 'hooks.json'), adapter)
  104. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  105. ctx.on('tools/post-execute', async () => ({ kind: 'accept' as const, content: [{ type: 'text' as const, text: 'rewritten-result' }] }))
  106. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  107. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  108. const result = events(agent).find(e => e.type === 'tool/result')
  109. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text === 'rewritten-result')).toBe(true)
  110. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  111. })
  112. it('folds the bridge PostToolUse context onto a downstream listener BLOCK', async () => {
  113. const d = dir()
  114. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n') }] }] })
  115. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  116. const ctx = await harness(join(d, 'hooks.json'), adapter)
  117. ctx.tools.register(defineTool({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  118. ctx.on('tools/post-execute', async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'downstream-block' }] }))
  119. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  120. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  121. const result = events(agent).find(e => e.type === 'tool/result')
  122. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  123. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('downstream-block'))).toBe(true)
  124. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('bridge-note')))).toBe(true)
  125. })
  126. it('SessionStart additionalContext is injected for the first request', async () => {
  127. const d = dir()
  128. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"start-ctx"}}\'\n') }] }] })
  129. const adapter = new MockAdapter([textResponse('ok')])
  130. const ctx = await harness(join(d, 'hooks.json'), adapter)
  131. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  132. await waitFor(() => events(agent).some(e => e.type === 'context/message'
  133. && e.data.content.some(b => b.type === 'text' && b.text.includes('start-ctx'))))
  134. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  135. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('start-ctx')
  136. })
  137. it('PostToolUse block (exit 2) → isError feedback; default reason', async () => {
  138. const d = dir()
  139. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'p.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  140. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  141. const ctx = await harness(join(d, 'hooks.json'), adapter)
  142. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  143. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  144. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  145. const r = events(agent).find(e => e.type === 'tool/result')
  146. expect(r?.type === 'tool/result' && r.data.isError).toBe(true)
  147. expect(r?.type === 'tool/result' && r.data.content.some(b => b.type === 'text' && b.text.includes('blocked by PostToolUse hook'))).toBe(true)
  148. })
  149. it('PostToolUse additionalContext (clean exit) is attached after the result', async () => {
  150. const d = dir()
  151. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"post-ctx"}}\'\n') }] }] })
  152. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  153. const ctx = await harness(join(d, 'hooks.json'), adapter)
  154. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  155. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  156. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  157. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('post-ctx')))).toBe(true)
  158. })
  159. it('PreToolUse for a tool call WITHOUT a command arg passes an empty command (commandOf non-object/missing arm)', async () => {
  160. const d = dir()
  161. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pre.sh', '#!/usr/bin/env bash\ncat >/dev/null\nexit 0\n') }] }] })
  162. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', {}), textResponse('done')]) // no command arg
  163. const ctx = await harness(join(d, 'hooks.json'), adapter)
  164. let ran = false
  165. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  166. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  167. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  168. expect(ran).toBe(true) // clean-exit hook allows; commandOf returned ''
  169. })
  170. it('a clean exit-0 hook records exitCode 0 and omits stderrSummary', async () => {
  171. const d = dir()
  172. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'n.sh', '#!/usr/bin/env bash\nexit 0\n') }] }] })
  173. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  174. const ctx = await harness(join(d, 'hooks.json'), adapter)
  175. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  176. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  177. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  178. const res = events(agent).find(e => e.type === 'hook/result')
  179. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(0)
  180. expect(res?.type === 'hook/result' && 'stderrSummary' in res.data).toBe(false)
  181. })
  182. it('a long stderr is truncated in the hook/result summary', async () => {
  183. const d = dir()
  184. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'l.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n') }] }] })
  185. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  186. const ctx = await harness(join(d, 'hooks.json'), adapter)
  187. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  188. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  189. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  190. const res = events(agent).find(e => e.type === 'hook/result')
  191. expect(res?.type === 'hook/result' && res.data.stderrSummary?.endsWith('…')).toBe(true)
  192. expect(res?.type === 'hook/result' && res.data.stderrSummary?.length).toBe(501) // default 500-char cap + ellipsis
  193. })
  194. it('rejects a non-positive or fractional stderrSummaryMaxChars at load', async () => {
  195. const d = dir()
  196. hooks(d, {})
  197. for (const bad of [0, -5, 1.5, Number.NaN]) {
  198. const adapter = new MockAdapter([])
  199. await expect(harness(join(d, 'hooks.json'), adapter, { stderrSummaryMaxChars: bad }))
  200. .rejects.toThrow(/hooks-codex: stderrSummaryMaxChars must be a positive integer/)
  201. }
  202. })
  203. it('the stderr summary cap is plugin config (stderrSummaryMaxChars)', async () => {
  204. const d = dir()
  205. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'l.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n') }] }] })
  206. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  207. const ctx = await harness(join(d, 'hooks.json'), adapter, { stderrSummaryMaxChars: 40 })
  208. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  209. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  210. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  211. const res = events(agent).find(e => e.type === 'hook/result')
  212. expect(res?.type === 'hook/result' && res.data.stderrSummary).toBe('x'.repeat(40) + '…')
  213. })
  214. it('warns on a skipped async hook and a direct apply() (schema bypass) runs', async () => {
  215. const d = dir()
  216. const marker = join(d, 'ran')
  217. hooks(d, { UserPromptSubmit: [{ hooks: [
  218. { type: 'command', command: 'bg.sh', async: true }, // skipped → warn
  219. { type: 'command', command: sh(d, 'h.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`) },
  220. ] }] })
  221. const warn = vi.fn()
  222. const adapter = new MockAdapter([textResponse('ok')])
  223. const ctx = new Context()
  224. await ctx.plugin(LlmService); await ctx.plugin(SessionStore); await ctx.plugin(SystemPrompt)
  225. await ctx.plugin(ToolRegistry); await ctx.plugin(AgentRegistry); await ctx.plugin(AgentLoop, { agents: [] })
  226. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  227. ctx.logger.warn = warn as never
  228. // Direct apply (schema bypass) → the `model ?? ''` fallback is exercised.
  229. HooksCodex.apply(ctx, { configPath: join(d, 'hooks.json') })
  230. ctx.llm.registerAdapter(['mock'], adapter)
  231. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  232. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  233. expect(existsSync(marker)).toBe(true)
  234. expect(warn).toHaveBeenCalledWith(expect.stringContaining('async hook'))
  235. })
  236. it('a no-op clean hook proceeds (contextFrom empty → next)', async () => {
  237. const d = dir()
  238. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'n.sh', '#!/usr/bin/env bash\nexit 0\n') }] }] })
  239. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  240. const ctx = await harness(join(d, 'hooks.json'), adapter)
  241. let ran = false
  242. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  243. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  244. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  245. expect(ran).toBe(true)
  246. })
  247. it('SessionStart with no additionalContext is a no-op (contextFrom empty)', async () => {
  248. const d = dir()
  249. // The hook touches a marker so we can wait for it to ACTUALLY FINISH before
  250. // asserting absence — a completed turn alone would not prove the detached
  251. // session-start hook ran, making the absence check a false pass.
  252. const marker = join(d, 'ss-ran')
  253. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', `#!/usr/bin/env bash\ntouch "${marker}"\nexit 0\n`) }] }] })
  254. const adapter = new MockAdapter([textResponse('ok')])
  255. const ctx = await harness(join(d, 'hooks.json'), adapter)
  256. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  257. await waitFor(() => existsSync(marker)) // the clean no-output hook has finished
  258. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  259. expect(events(agent).some(e => e.type === 'context/message')).toBe(false)
  260. })
  261. it('a throwing SessionStart inject is contained (logged)', async () => {
  262. const d = dir()
  263. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"x"}}\'\n') }] }] })
  264. const adapter = new MockAdapter([textResponse('ok')])
  265. const ctx = await harness(join(d, 'hooks.json'), adapter)
  266. const warn = vi.fn(); ctx.logger.warn = warn as never
  267. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  268. agent.inject = (() => { throw new Error('inject boom') })
  269. await waitFor(() => warn.mock.calls.some(c => String(c[0]).includes('SessionStart hook failed')))
  270. expect(warn).toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
  271. })
  272. it('a clean PreToolUse with no decision allows the tool (no deny)', async () => {
  273. const d = dir()
  274. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'ok.sh', '#!/usr/bin/env bash\nexit 0\n') }] }] })
  275. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  276. const ctx = await harness(join(d, 'hooks.json'), adapter)
  277. let ran = false
  278. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  279. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  280. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  281. expect(ran).toBe(true)
  282. })
  283. it('a non-matching regex matcher skips the hook (matchesMatcher false → continue)', async () => {
  284. const d = dir()
  285. // /^Edit$/ does not match the tool name "Bash" → the group is skipped.
  286. hooks(d, { PreToolUse: [{ matcher: '^Edit$', hooks: [{ type: 'command', command: sh(d, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  287. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  288. const ctx = await harness(join(d, 'hooks.json'), adapter)
  289. let ran = false
  290. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  291. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  292. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  293. expect(ran).toBe(true) // matcher didn't match → no hook ran → tool proceeded
  294. expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false)
  295. })
  296. it('a {"continue":false} hook is RECORDED as "stop" but does not halt the run (TODO(hook-continue-false))', async () => {
  297. // Honoring `continue:false` is deferred — the seams have no hard-halt
  298. // primitive. Assert the LOG records the halt request AND that the run is not
  299. // actually halted (the tool still runs, the turn completes).
  300. const d = dir()
  301. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', '#!/usr/bin/env bash\necho \'{"continue":false,"stopReason":"halt"}\'\n') }] }] })
  302. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  303. const ctx = await harness(join(d, 'hooks.json'), adapter)
  304. let ran = false
  305. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  306. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  307. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  308. const res = events(agent).find(e => e.type === 'hook/result')
  309. expect(res?.type === 'hook/result' && res.data.decision).toBe('stop') // recorded
  310. expect(ran).toBe(true) // NOT honored: the tool still ran (halt is deferred)
  311. })
  312. it('PreToolUse deny with EMPTY stderr uses the default reason (?? right arm)', async () => {
  313. const d = dir()
  314. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'd.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  315. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  316. const ctx = await harness(join(d, 'hooks.json'), adapter)
  317. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  318. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  319. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  320. const r = events(agent).find(e => e.type === 'tool/result')
  321. expect(r?.type === 'tool/result' && r.data.content.some(b => b.type === 'text' && b.text.includes('blocked by PreToolUse hook'))).toBe(true)
  322. })
  323. it('PostToolUse block AND additionalContext are surfaced together', async () => {
  324. const d = dir()
  325. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'bc.sh', '#!/usr/bin/env bash\necho \'{"decision":"block","reason":"bad","hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"ctx too"}}\'\n') }] }] })
  326. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  327. const ctx = await harness(join(d, 'hooks.json'), adapter)
  328. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  329. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  330. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  331. const r = events(agent).find(e => e.type === 'tool/result')
  332. expect(r?.type === 'tool/result' && r.data.isError).toBe(true)
  333. expect(r?.type === 'tool/result' && r.data.content.some(b => b.type === 'text' && b.text.includes('bad'))).toBe(true)
  334. expect(events(agent).some(e => e.type === 'context/message' && e.data.content.some(b => b.type === 'text' && b.text.includes('ctx too')))).toBe(true)
  335. })
  336. it('commandOf reads a non-string command arg as an empty command', async () => {
  337. const d = dir()
  338. // The tool-call arguments carry `command` as a NUMBER → commandOf's
  339. // `typeof command === 'string'` false arm → '' (the payload's tool_input.command).
  340. const cap = join(d, 'payload')
  341. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'cap.sh', `#!/usr/bin/env bash\ncat > "${cap}"\nexit 0\n`) }] }] })
  342. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 7 }), textResponse('done')])
  343. const ctx = await harness(join(d, 'hooks.json'), adapter)
  344. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'number' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  345. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  346. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  347. const payload = JSON.parse(readFileSync(cap, 'utf8')) as { tool_input: { command: string } }
  348. expect(payload.tool_input.command).toBe('')
  349. })
  350. it('a no-agent direct PreToolUse run uses process.cwd() and turn 0 (no session to record)', async () => {
  351. const d = dir()
  352. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'd.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  353. const ctx = await harness(join(d, 'hooks.json'), new MockAdapter([]))
  354. let ran = false
  355. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'x' }] } }))
  356. const { CallId } = await import('@deepseek-ai/dsh-llm')
  357. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'Bash', arguments: { command: 'x' } })
  358. expect(ran).toBe(false) // denied
  359. expect(result.isError).toBe(true)
  360. })
  361. it('a no-agent direct PostToolUse run attaches context with no session to record', async () => {
  362. const d = dir()
  363. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"x"}}\'\n') }] }] })
  364. const ctx = await harness(join(d, 'hooks.json'), new MockAdapter([]))
  365. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  366. const { CallId } = await import('@deepseek-ai/dsh-llm')
  367. const result = await ctx.tools.execute({ callId: CallId('c1'), name: 'Bash', arguments: { command: 'x' } })
  368. expect(result.isError).toBeFalsy()
  369. expect(result.additionalContext?.content.some(b => b.type === 'text' && b.text === 'x')).toBe(true)
  370. })
  371. it('when the bash executor REJECTS, the hook/result omits exitCode (non-blocking)', async () => {
  372. const d = dir()
  373. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'h.sh', '#!/usr/bin/env bash\nexit 0\n') }] }] })
  374. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  375. const ctx = await harness(join(d, 'hooks.json'), adapter)
  376. ctx.bash.run = (() => Promise.reject(new Error('executor down')))
  377. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  378. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  379. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  380. const res = events(agent).find(e => e.type === 'hook/result')
  381. expect(res?.type === 'hook/result' && 'exitCode' in res.data).toBe(false)
  382. })
  383. it('a blocking Stop hook with EMPTY stderr still forces continuation (no reason required)', async () => {
  384. // Regression: an exit-2 Stop hook with no stderr yields decision 'deny' +
  385. // reason undefined; the turn must STILL force-continue, not silently stop.
  386. const d = dir()
  387. const marker = join(d, 'fired')
  388. hooks(d, { Stop: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', `#!/usr/bin/env bash\nif [ -e "${marker}" ]; then exit 0; fi\ntouch "${marker}"\nexit 2\n`) }] }] })
  389. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  390. const ctx = await harness(join(d, 'hooks.json'), adapter)
  391. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  392. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  393. expect(adapter.requests).toHaveLength(2) // empty-reason block forced continuation
  394. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('blocked by Stop hook')
  395. })
  396. it('a clean UserPromptSubmit hook that prints PLAIN stdout injects it as context', async () => {
  397. // Codex feeds a SessionStart/UserPromptSubmit hook's PLAIN (non-JSON) stdout
  398. // as additionalContext (unlike CC, which needs a JSON hookSpecificOutput).
  399. const d = dir()
  400. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'ctx.sh', '#!/usr/bin/env bash\necho "extra guidance from a plain hook"\nexit 0\n') }] }] })
  401. const adapter = new MockAdapter([textResponse('ok')])
  402. const ctx = await harness(join(d, 'hooks.json'), adapter)
  403. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  404. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  405. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('extra guidance from a plain hook')
  406. })
  407. it('a NON-clean SessionStart hook (exit 2) does NOT inject its stdout as context', async () => {
  408. // SessionStart cannot block, but non-clean stdout still must not become context. The marker
  409. // waits for detached completion; `echo stale; exit 2` then proves the exit-code gate matches
  410. // the codec's structured-stdout rule.
  411. const d = dir()
  412. const marker = join(d, 'ran')
  413. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 'b.sh', `#!/usr/bin/env bash\ntouch "${marker}"\necho "stale"\nexit 2\n`) }] }] })
  414. const adapter = new MockAdapter([textResponse('ok')])
  415. const ctx = await harness(join(d, 'hooks.json'), adapter)
  416. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  417. await waitFor(() => existsSync(marker)) // the exit-2 hook has finished
  418. expect(events(agent).some(e => e.type === 'context/message'
  419. && e.data.content.some(b => b.type === 'text' && b.text.includes('stale')))).toBe(false)
  420. })
  421. it('a UserPromptSubmit hook with a non-blocking error exit (1) + stdout does NOT inject it', async () => {
  422. // Exit 1 is a non-blocking error (no decision), so the prompt is NOT blocked
  423. // and the handler falls through to the context path — the gate must still
  424. // suppress the error hook's stdout ("stale" never reaches the model).
  425. const d = dir()
  426. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'e.sh', '#!/usr/bin/env bash\necho "stale"\nexit 1\n') }] }] })
  427. const adapter = new MockAdapter([textResponse('ok')])
  428. const ctx = await harness(join(d, 'hooks.json'), adapter)
  429. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  430. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  431. expect(adapter.requests).toHaveLength(1) // exit 1 is non-blocking → the turn ran
  432. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('stale')
  433. })
  434. it('a clean SessionStart hook that prints PLAIN stdout injects it (not JSON)', async () => {
  435. const d = dir()
  436. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 'ss.sh', '#!/usr/bin/env bash\necho "session preamble"\nexit 0\n') }] }] })
  437. const adapter = new MockAdapter([textResponse('ok')])
  438. const ctx = await harness(join(d, 'hooks.json'), adapter)
  439. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  440. await waitFor(() => events(agent).some(e => e.type === 'context/message'
  441. && e.data.content.some(b => b.type === 'text' && b.text.includes('session preamble'))))
  442. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  443. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  444. })
  445. it('a clean hook that prints JSON is NOT injected as prose (plain-stdout gate)', async () => {
  446. // A structured (JSON) stdout must go through the hookSpecificOutput path, not
  447. // be dumped verbatim as context — the `!startsWith('{')` gate guards this.
  448. const d = dir()
  449. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'j.sh', '#!/usr/bin/env bash\necho \'{"unrelated":"json"}\'\nexit 0\n') }] }] })
  450. const adapter = new MockAdapter([textResponse('ok')])
  451. const ctx = await harness(join(d, 'hooks.json'), adapter)
  452. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  453. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  454. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('unrelated')
  455. })
  456. it('the PreToolUse payload carries the REAL tool name (matches the matcher subject)', async () => {
  457. // Regression: the payload once hardcoded tool_name "Bash", disagreeing with
  458. // the exec.name matcher subject — a config matcher on the real name would
  459. // then never fire. Capture the payload and assert tool_name === the real name.
  460. const d = dir()
  461. const cap = join(d, 'payload')
  462. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'cap.sh', `#!/usr/bin/env bash\ncat > "${cap}"\nexit 0\n`) }] }] })
  463. const adapter = new MockAdapter([toolCallResponse('c1', 'shell', { command: 'ls' }), textResponse('done')])
  464. const ctx = await harness(join(d, 'hooks.json'), adapter)
  465. ctx.tools.register(defineTool({ name: 'shell', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  466. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  467. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  468. const payload = JSON.parse(readFileSync(cap, 'utf8')) as { tool_name: string; tool_input: { command: string } }
  469. expect(payload.tool_name).toBe('shell')
  470. expect(payload.tool_input.command).toBe('ls')
  471. })
  472. it('a Codex matcher on the REAL tool name fires (matcher subject === payload tool_name)', async () => {
  473. // A regex matcher matching the real tool name must select the hook — proving
  474. // the matcher subject and the payload tool_name agree.
  475. const d = dir()
  476. hooks(d, { PreToolUse: [{ matcher: 'shell', hooks: [{ type: 'command', command: sh(d, 'd.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  477. const adapter = new MockAdapter([toolCallResponse('c1', 'shell', { command: 'ls' }), textResponse('done')])
  478. const ctx = await harness(join(d, 'hooks.json'), adapter)
  479. let ran = false
  480. ctx.tools.register(defineTool({ name: 'shell', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  481. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  482. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  483. expect(ran).toBe(false) // the matcher fired → the hook denied the tool
  484. expect(events(agent).some(e => e.type === 'hook/invoked' && e.data.point === 'PreToolUse')).toBe(true)
  485. })
  486. it('a hook emitting a systemMessage is warned as not-yet-surfaced', async () => {
  487. const d = dir()
  488. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'sm.sh', '#!/usr/bin/env bash\necho \'{"systemMessage":"heads up"}\'\n') }] }] })
  489. const adapter = new MockAdapter([textResponse('ok')])
  490. const ctx = await harness(join(d, 'hooks.json'), adapter)
  491. const warn = vi.fn(); ctx.logger.warn = warn as never
  492. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  493. agent.send([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  494. expect(warn).toHaveBeenCalledWith(expect.stringContaining('systemMessage'))
  495. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('heads up')
  496. })
  497. it('runs an agent-scoped hook in the session cwd, not the executor default', async () => {
  498. // Same regression as the CC bridge: the Codex bridge must thread the session
  499. // cwd as the hook workdir. Executor default = serverDir; session cwd =
  500. // sessionDir; the PreToolUse hook's `pwd` marker must land in sessionDir.
  501. const serverDir = dir()
  502. const sessionDir = dir()
  503. const marker = join(sessionDir, 'where')
  504. hooks(serverDir, { PreToolUse: [{ hooks: [{ type: 'command', command: 'pwd > where' }] }] })
  505. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  506. const ctx = new Context()
  507. await ctx.plugin(LlmService); await ctx.plugin(SessionStore); await ctx.plugin(SystemPrompt)
  508. await ctx.plugin(ToolRegistry); await ctx.plugin(AgentRegistry); await ctx.plugin(AgentLoop, { agents: [] })
  509. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  510. await ctx.plugin(HooksCodex, { configPath: join(serverDir, 'hooks.json'), model: 'm' })
  511. ctx.llm.registerAdapter(['mock'], adapter)
  512. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  513. const { SessionId } = await import('@deepseek-ai/dsh-session')
  514. const handle = await ctx.agents.create({ agentId: AgentId('a1'), sessionId: SessionId('s1'), meta: { cwd: sessionDir }, agentOptions: { model: 'mock' } })
  515. handle.agent.send([{ type: 'text', text: 'go' }])
  516. await waitForIdle(ctx, handle.agent as ReactLoopAgent)
  517. expect(existsSync(marker)).toBe(true)
  518. expect(readFileSync(marker, 'utf8').trim().endsWith(sessionDir.split('/').pop()!)).toBe(true)
  519. await handle.dispose()
  520. })
  521. })