coverage-cases.ts 47 KB

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