coverage.spec.ts 40 KB

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