coverage-cases.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { mkdtempSync, rmSync, writeFileSync, chmodSync, existsSync, readFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { Context } from 'cordis'
  6. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  7. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  8. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  11. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  12. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  13. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  14. import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex'
  15. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  16. const testToolSignal = new AbortController().signal
  17. const dirs: string[] = []
  18. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  19. function dir(): string { const d = mkdtempSync(join(tmpdir(), 'dsh-hx-cov-')); dirs.push(d); return d }
  20. function sh(d: string, name: string, body: string): string {
  21. const p = join(d, name); writeFileSync(p, body); chmodSync(p, 0o755); return p
  22. }
  23. function hooks(d: string, h: unknown): string {
  24. writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
  25. }
  26. type HarnessOpts = { stderrSummaryMaxChars?: number; sessionRoot?: string }
  27. async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
  28. const ctx = new Context()
  29. await mountAgentLoopTestDependencies(ctx)
  30. if (opts.sessionRoot !== undefined) await ctx.plugin(SessionPersistenceJsonl, { root: opts.sessionRoot })
  31. await ctx.plugin(AgentLoop, { agents: [] })
  32. await ctx.plugin(LocalSubprocessService)
  33. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  34. await ctx.plugin(HooksCodex, { configPath, model: 'm', ...opts })
  35. ctx.llm.registerAdapter(['mock'], adapter)
  36. return ctx
  37. }
  38. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  39. return new Promise((resolve) => { const d = ctx.on('agent/status', (s, st) => { if (s === agent && st === 'idle') { d(); resolve() } }) })
  40. }
  41. function events(agent: Agent): SessionEvent[] { return [...agent.session.events] }
  42. /** Poll until `predicate` holds or the deadline passes — robust to detached
  43. * emit-listener hooks firing on a `.then` (a fixed sleep flakes under load). */
  44. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  45. const deadline = Date.now() + timeout
  46. while (!predicate()) {
  47. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  48. await new Promise(r => setTimeout(r, interval))
  49. }
  50. }
  51. export type CoverageGroup = 'prompt' | 'post-tool' | 'result-shape' | 'edge-paths' | 'payload'
  52. /** Register independently schedulable slices of the hooks-codex coverage matrix. */
  53. export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGroup[]): void {
  54. const selected = new Set(typeof groups === 'string' ? [groups] : groups)
  55. if (selected.has('prompt')) describe('hooks-codex coverage — prompt decision mapping', () => {
  56. it('uses the persistence locator for transcript_path and null without one', async () => {
  57. async function capture(sessionRoot?: string): Promise<{ payload: { transcript_path: string | null }; expected: string | undefined }> {
  58. const d = dir()
  59. const cap = join(d, 'payload')
  60. const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'capture.sh', `#!/usr/bin/env bash\ncat > "${cap}"\n`) }] }] })
  61. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  62. const ctx = await harness(path, adapter, { ...sessionRoot !== undefined ? { sessionRoot } : {} })
  63. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  64. const agent = ctx.agentLoop.create(SessionId('transcript'), { provider: 'mock', model: 'mock' })
  65. agent.followup([{ type: 'text', text: 'go' }])
  66. await waitForIdle(ctx, agent)
  67. return {
  68. payload: JSON.parse(readFileSync(cap, 'utf8')) as { transcript_path: string | null },
  69. expected: ctx.get('sessionPersistence')?.locate(agent.session.header)?.path,
  70. }
  71. }
  72. const located = await capture(dir())
  73. expect(located.payload.transcript_path).toBe(located.expected)
  74. expect((await capture()).payload.transcript_path).toBeNull()
  75. }, 15_000) // Two real agent/hook subprocess loops need process startup and teardown headroom.
  76. it('UserPromptSubmit block (exit 2) → rejected turn; default reason on empty stderr', async () => {
  77. const d = dir()
  78. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'b.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  79. const adapter = new MockAdapter([textResponse('no')])
  80. const ctx = await harness(join(d, 'hooks.json'), adapter)
  81. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  82. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  83. expect(adapter.requests).toHaveLength(0)
  84. const te = events(agent).findLast(e => e.type === 'turn/end')
  85. expect(te?.type === 'turn/end' && te.data.reason.kind).toBe('rejected')
  86. })
  87. it('UserPromptSubmit additionalContext is injected; a no-op hook proceeds', async () => {
  88. const d = dir()
  89. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"ctx-x"}}\'\n') }] }] })
  90. const adapter = new MockAdapter([textResponse('ok')])
  91. const ctx = await harness(join(d, 'hooks.json'), adapter)
  92. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  93. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  94. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('ctx-x')
  95. })
  96. it('a context-only UserPromptSubmit hook DELEGATES so a later listener can still block', async () => {
  97. // Context alone is not a veto: the bridge delegates with `next()` and folds its context, so a
  98. // downstream policy listener can still block.
  99. const d = dir()
  100. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"bridge ctx"}}\'\n') }] }] })
  101. const adapter = new MockAdapter([textResponse('should not run')])
  102. const ctx = await harness(join(d, 'hooks.json'), adapter)
  103. ctx.on('agent/prompt-submit', async () => ({ kind: 'block' as const, reason: 'policy veto' }))
  104. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  105. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  106. expect(adapter.requests).toHaveLength(0)
  107. expect(events(agent).some(e => e.type === 'user/message')).toBe(false)
  108. const te = events(agent).findLast(e => e.type === 'turn/end')
  109. expect(te?.type === 'turn/end' && te.data.reason).toMatchObject({ kind: 'rejected', reason: 'policy veto' })
  110. })
  111. it('preserves separate bridge and downstream prompt contexts with framing and metadata', async () => {
  112. const d = dir()
  113. hooks(d, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: sh(d, 'c.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"from-bridge"}}\'\n') }] }] })
  114. const adapter = new MockAdapter([textResponse('ok')])
  115. const ctx = await harness(join(d, 'hooks.json'), adapter)
  116. ctx.on('agent/prompt-submit', async () => ({
  117. kind: 'allow' as const,
  118. content: [{ type: 'text' as const, text: 'rewritten-prompt' }],
  119. additionalContexts: [{
  120. content: [{ type: 'text' as const, text: 'from-downstream' }],
  121. source: { kind: 'plugin' as const, plugin: 'policy' },
  122. meta: { owner: 'policy' },
  123. }],
  124. }))
  125. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  126. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  127. const req = JSON.stringify(adapter.requests[0]!.messages)
  128. expect(req).toContain('from-bridge')
  129. expect(req).toContain('from-downstream')
  130. expect(req).toContain('rewritten-prompt')
  131. const contexts = events(agent).filter(event => event.type === 'user/message' && event.data.source.kind !== 'user')
  132. expect(contexts.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  133. { kind: 'plugin', plugin: 'hooks-codex' },
  134. { kind: 'plugin', plugin: 'policy' },
  135. ])
  136. expect(contexts[1]?.type === 'user/message' && contexts[1].data.meta).toEqual({ owner: 'policy' })
  137. })
  138. })
  139. if (selected.has('post-tool')) describe('hooks-codex coverage — post-tool and session context mapping', () => {
  140. it('folds the bridge PostToolUse context onto a downstream canonical value replacement', async () => {
  141. const d = dir()
  142. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n') }] }] })
  143. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  144. const ctx = await harness(join(d, 'hooks.json'), adapter)
  145. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  146. ctx.on('tools/post-execute', async () => ({ kind: 'accept' as const, value: [{ type: 'text' as const, text: 'rewritten-result' }] }))
  147. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  148. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  149. const result = events(agent).find(e => e.type === 'tool/result')
  150. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text === 'rewritten-result')).toBe(true)
  151. 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)
  152. })
  153. it('keeps bridge and downstream PostToolUse contexts as separate sourced events', async () => {
  154. const d = dir()
  155. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n') }] }] })
  156. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  157. const ctx = await harness(join(d, 'hooks.json'), adapter)
  158. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  159. ctx.on('tools/post-execute', async () => ({
  160. kind: 'accept' as const,
  161. additionalContexts: [{
  162. content: [{ type: 'text' as const, text: 'downstream-note' }],
  163. source: { kind: 'plugin' as const, plugin: 'policy' },
  164. meta: { owner: 'policy' },
  165. }],
  166. }))
  167. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  168. agent.followup([{ type: 'text', text: 'go' }]); 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. expect(contexts[1]?.type === 'user/message' && contexts[1].data.meta).toEqual({ owner: 'policy' })
  175. })
  176. it('folds the bridge PostToolUse context onto a downstream listener BLOCK', async () => {
  177. const d = dir()
  178. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"bridge-note"}}\'\n') }] }] })
  179. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
  180. const ctx = await harness(join(d, 'hooks.json'), adapter)
  181. ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  182. ctx.on('tools/post-execute', async () => ({ kind: 'block' as const, feedback: [{ type: 'text' as const, text: 'downstream-block' }] }))
  183. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  184. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  185. const result = events(agent).find(e => e.type === 'tool/result')
  186. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  187. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('downstream-block'))).toBe(true)
  188. 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)
  189. })
  190. it('SessionStart additionalContext is injected for the first request', async () => {
  191. const d = dir()
  192. hooks(d, { SessionStart: [{ hooks: [{ type: 'command', command: sh(d, 's.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"start-ctx"}}\'\n') }] }] })
  193. const adapter = new MockAdapter([textResponse('ok')])
  194. const ctx = await harness(join(d, 'hooks.json'), adapter)
  195. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  196. await waitFor(() => events(agent).some(e => e.type === 'user/message'
  197. && e.data.content.some(b => b.type === 'text' && b.text.includes('start-ctx'))))
  198. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  199. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('start-ctx')
  200. })
  201. it('PostToolUse block (exit 2) → isError feedback; default reason', async () => {
  202. const d = dir()
  203. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'p.sh', '#!/usr/bin/env bash\nexit 2\n') }] }] })
  204. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  205. const ctx = await harness(join(d, 'hooks.json'), adapter)
  206. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  207. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  208. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  209. const r = events(agent).find(e => e.type === 'tool/result')
  210. expect(r?.type === 'tool/result' && r.data.isError).toBe(true)
  211. expect(r?.type === 'tool/result' && r.data.content.some(b => b.type === 'text' && b.text.includes('blocked by PostToolUse hook'))).toBe(true)
  212. })
  213. it('PostToolUse additionalContext (clean exit) is attached after the result', async () => {
  214. const d = dir()
  215. hooks(d, { PostToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pc.sh', '#!/usr/bin/env bash\necho \'{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"post-ctx"}}\'\n') }] }] })
  216. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  217. const ctx = await harness(join(d, 'hooks.json'), adapter)
  218. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  219. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  220. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  221. 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)
  222. })
  223. })
  224. if (selected.has('result-shape')) describe('hooks-codex coverage — hook result shape and configuration', () => {
  225. it('PreToolUse for a tool call WITHOUT a command arg passes an empty command (commandOf non-object/missing arm)', async () => {
  226. const d = dir()
  227. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'pre.sh', '#!/usr/bin/env bash\ncat >/dev/null\nexit 0\n') }] }] })
  228. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', {}), textResponse('done')]) // no command arg
  229. const ctx = await harness(join(d, 'hooks.json'), adapter)
  230. let ran = false
  231. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: {}, async execute() { ran = true; return [{ type: 'text', text: 'ok' }] } }))
  232. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  233. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  234. expect(ran).toBe(true) // clean-exit hook allows; commandOf returned ''
  235. })
  236. it('a clean exit-0 hook records exitCode 0 and omits stderrSummary', async () => {
  237. const d = dir()
  238. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'n.sh', '#!/usr/bin/env bash\nexit 0\n') }] }] })
  239. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  240. const ctx = await harness(join(d, 'hooks.json'), adapter)
  241. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  242. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  243. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  244. const res = events(agent).find(e => e.type === 'hook/result')
  245. expect(res?.type === 'hook/result' && res.data.exitCode).toBe(0)
  246. expect(res?.type === 'hook/result' && 'stderrSummary' in res.data).toBe(false)
  247. })
  248. it('a long stderr is truncated in the hook/result summary', async () => {
  249. const d = dir()
  250. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'l.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n') }] }] })
  251. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  252. const ctx = await harness(join(d, 'hooks.json'), adapter)
  253. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  254. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  255. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  256. const res = events(agent).find(e => e.type === 'hook/result')
  257. expect(res?.type === 'hook/result' && res.data.stderrSummary?.endsWith('…')).toBe(true)
  258. expect(res?.type === 'hook/result' && res.data.stderrSummary?.length).toBe(501) // default 500-char cap + ellipsis
  259. })
  260. it('rejects a non-positive or fractional stderrSummaryMaxChars at load', async () => {
  261. const d = dir()
  262. hooks(d, {})
  263. for (const bad of [0, -5, 1.5, Number.NaN]) {
  264. const adapter = new MockAdapter([])
  265. await expect(harness(join(d, 'hooks.json'), adapter, { stderrSummaryMaxChars: bad }))
  266. .rejects.toThrow(/hooks-codex: stderrSummaryMaxChars must be a positive integer/)
  267. }
  268. })
  269. it('the stderr summary cap is plugin config (stderrSummaryMaxChars)', async () => {
  270. const d = dir()
  271. hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'l.sh', '#!/usr/bin/env bash\nprintf "x%.0s" {1..600} >&2\nexit 2\n') }] }] })
  272. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'x' }), textResponse('done')])
  273. const ctx = await harness(join(d, 'hooks.json'), adapter, { stderrSummaryMaxChars: 40 })
  274. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  275. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  276. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  277. const res = events(agent).find(e => e.type === 'hook/result')
  278. expect(res?.type === 'hook/result' && res.data.stderrSummary).toBe('x'.repeat(40) + '…')
  279. })
  280. it('warns on a skipped async hook and a direct apply() (schema bypass) runs', async () => {
  281. const d = dir()
  282. const marker = join(d, 'ran')
  283. hooks(d, { UserPromptSubmit: [{ hooks: [
  284. { type: 'command', command: 'bg.sh', async: true }, // skipped → warn
  285. { type: 'command', command: sh(d, 'h.sh', `#!/usr/bin/env bash\ntouch "${marker}"\n`) },
  286. ] }] })
  287. const warn = vi.fn()
  288. const adapter = new MockAdapter([textResponse('ok')])
  289. const ctx = new Context()
  290. await mountAgentLoopTestDependencies(ctx)
  291. await ctx.plugin(AgentLoop, { agents: [] })
  292. await ctx.plugin(LocalSubprocessService)
  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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  299. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  311. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  324. await waitFor(() => existsSync(marker)) // the clean no-output hook has finished
  325. agent.followup([{ type: 'text', text: 'go' }]); 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 = 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  349. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  361. agent.followup([{ type: 'text', text: 'go' }]); 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 seams 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  376. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  388. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  389. const r = events(agent).find(e => e.type === 'tool/result')
  390. expect(r?.type === 'tool/result' && r.data.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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  399. agent.followup([{ type: 'text', text: 'go' }]); await waitForIdle(ctx, agent)
  400. const r = events(agent).find(e => e.type === 'tool/result')
  401. expect(r?.type === 'tool/result' && r.data.isError).toBe(true)
  402. expect(r?.type === 'tool/result' && r.data.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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  415. agent.followup([{ type: 'text', text: 'go' }]); 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 { CallId } = await import('@deepseek-ai/dsh-llm')
  426. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('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 { CallId } = await import('@deepseek-ai/dsh-llm')
  436. const result = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('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.bash.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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  448. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  463. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  475. agent.followup([{ type: 'text', text: 'go' }]); 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 = 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  501. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  511. await waitFor(() => events(agent).some(e => e.type === 'user/message'
  512. && e.data.content.some(b => b.type === 'text' && b.text.includes('session preamble'))))
  513. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  524. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  538. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  553. agent.followup([{ type: 'text', text: 'go' }]); 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 = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  564. agent.followup([{ type: 'text', text: 'go' }]); 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(AgentLoop, { agents: [] })
  580. await ctx.plugin(LocalSubprocessService)
  581. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000, cwd: serverDir })
  582. await ctx.plugin(HooksCodex, { configPath: join(serverDir, 'hooks.json'), model: 'm' })
  583. ctx.llm.registerAdapter(['mock'], adapter)
  584. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { return [{ type: 'text', text: 'ok' }] } }))
  585. const { SessionId } = await import('@deepseek-ai/dsh-session')
  586. const handle = await ctx.agents.create({ sessionId: SessionId('s1'), meta: { cwd: sessionDir }, agentOptions: { provider: 'mock', model: 'mock' } })
  587. handle.agent.followup([{ type: 'text', text: 'go' }])
  588. await waitForIdle(ctx, handle.agent)
  589. expect(existsSync(marker)).toBe(true)
  590. expect(readFileSync(marker, 'utf8').trim().endsWith(sessionDir.split('/').pop()!)).toBe(true)
  591. await handle.dispose()
  592. })
  593. })
  594. }