coverage.spec.ts 41 KB

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