coverage-cases.ts 47 KB

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