coverage-cases.ts 47 KB

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