coverage-cases.ts 44 KB

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