coverage-cases.ts 46 KB

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