1
0

coverage-cases.ts 47 KB

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