coverage-cases.ts 47 KB

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