coverage-cases.ts 46 KB

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