integration.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /**
  2. * End-to-end tool-registry tests against the real local backend. The policy deployment verifies
  3. * observed-state and guarded mutation; the bare deployment proves unconditional tools have no
  4. * policy-service dependency. Assertions read files back byte-for-byte rather than trusting tool
  5. * messages.
  6. */
  7. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  8. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
  9. import { tmpdir } from 'node:os'
  10. import { join } from 'node:path'
  11. import { Context } from 'cordis'
  12. import { CallId } from '@deepseek-ai/dsh-llm'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  15. import { LocalFileSystem } from '@deepseek-ai/dsh-fs-local'
  16. import * as FsPolicy from '@deepseek-ai/dsh-fs-policy'
  17. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  18. const testToolSignal = new AbortController().signal
  19. let dir: string
  20. let ctx: Context
  21. let fiber: Awaited<ReturnType<Context['plugin']>>
  22. // No header cwd: sessionCwd returns undefined and the provider's configured test dir applies.
  23. const session = { header: {} }
  24. let callCounter = 0
  25. function call(name: string, args: unknown) {
  26. return ctx.tools.execute({
  27. signal: testToolSignal,
  28. callId: CallId(`call-${++callCounter}`),
  29. name,
  30. arguments: args,
  31. agent: { session } as never,
  32. })
  33. }
  34. function text(result: { content: { type: string; text?: string }[] }): string {
  35. return result.content.filter(b => b.type === 'text').map(b => b.text).join('')
  36. }
  37. afterEach(async () => {
  38. await fiber.dispose()
  39. await rm(dir, { recursive: true, force: true })
  40. })
  41. // --------------------------------------------------------------------------
  42. // DEFAULT deployment: the policy gate plugin is loaded.
  43. // --------------------------------------------------------------------------
  44. describe('default deployment (with dsh-fs-policy)', () => {
  45. beforeEach(async () => {
  46. dir = await mkdtemp(join(tmpdir(), 'dsh-tool-fs-'))
  47. ctx = new Context()
  48. await ctx.plugin(SystemPrompt)
  49. await ctx.plugin(ToolRegistry)
  50. await ctx.plugin(LocalFileSystem, { cwd: dir })
  51. await ctx.plugin(FsPolicy)
  52. fiber = await ctx.plugin(ToolFs)
  53. })
  54. describe('write → disk', () => {
  55. it('creates a file with exactly the requested bytes', async () => {
  56. const result = await call('write', { file_path: 'new.txt', content: 'line one\nline two\n' })
  57. expect(result.isError).toBe(false)
  58. expect(await readFile(join(dir, 'new.txt'), 'utf8')).toBe('line one\nline two\n')
  59. })
  60. it('rejects overwriting an existing file without reading it first', async () => {
  61. await writeFile(join(dir, 'a.txt'), 'original')
  62. const result = await call('write', { file_path: 'a.txt', content: 'clobber' })
  63. expect(result.isError).toBe(true)
  64. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  65. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('original')
  66. })
  67. it('allows overwriting after a read', async () => {
  68. await writeFile(join(dir, 'a.txt'), 'original')
  69. expect((await call('read', { file_path: 'a.txt' })).isError).toBe(false)
  70. const result = await call('write', { file_path: 'a.txt', content: 'replaced' })
  71. expect(result.isError).toBe(false)
  72. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('replaced')
  73. })
  74. it('rejects a full overwrite when the file changed since the read (stale)', async () => {
  75. await writeFile(join(dir, 'a.txt'), 'original')
  76. await call('read', { file_path: 'a.txt' })
  77. await writeFile(join(dir, 'a.txt'), 'changed-externally') // out-of-band change
  78. const result = await call('write', { file_path: 'a.txt', content: 'replaced' })
  79. expect(result.isError).toBe(true)
  80. expect(result.error).toMatchObject({ info: { code: 'FS_STALE_VERSION' } })
  81. })
  82. })
  83. describe('read', () => {
  84. it('returns line-numbered content', async () => {
  85. await writeFile(join(dir, 'a.txt'), 'alpha\nbeta')
  86. const result = await call('read', { file_path: 'a.txt' })
  87. expect(text(result)).toContain('1: alpha')
  88. expect(text(result)).toContain('2: beta')
  89. expect(text(result)).toContain('(End of file - total 2 lines)')
  90. })
  91. it('reports a binary file as an error', async () => {
  92. await writeFile(join(dir, 'bin'), Buffer.from([0x00, 0x01, 0x02]))
  93. const result = await call('read', { file_path: 'bin' })
  94. expect(result.isError).toBe(true)
  95. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_TEXT' } })
  96. })
  97. it('paginates a multi-line file with offset/limit', async () => {
  98. await writeFile(join(dir, 'a.txt'), 'one\ntwo\nthree\nfour')
  99. const result = await call('read', { file_path: 'a.txt', offset: 2, limit: 2 })
  100. expect(text(result)).toContain('2: two')
  101. expect(text(result)).toContain('3: three')
  102. expect(text(result)).toContain('(Showing lines 2-3 of 4. Use offset=4 to continue.)')
  103. })
  104. })
  105. describe('edit → disk', () => {
  106. it('applies a unique literal replacement after a read', async () => {
  107. await writeFile(join(dir, 'a.txt'), 'hello world')
  108. await call('read', { file_path: 'a.txt' })
  109. const result = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  110. expect(result.isError).toBe(false)
  111. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('hello there')
  112. })
  113. it('rejects an edit before any read, leaving the file untouched', async () => {
  114. await writeFile(join(dir, 'a.txt'), 'hello world')
  115. const result = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  116. expect(result.isError).toBe(true)
  117. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  118. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('hello world')
  119. })
  120. it('lets a WINDOWED read authorize an edit when the file is unchanged (freshness, not full-view)', async () => {
  121. // A file with more lines than the read window; read only the first line.
  122. const lines = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`)
  123. await writeFile(join(dir, 'a.txt'), lines.join('\n'))
  124. const read = await call('read', { file_path: 'a.txt', offset: 1, limit: 1 })
  125. expect(read.isError).toBe(false)
  126. expect(text(read)).toContain('(Showing lines 1-1 of 20')
  127. // Editing a line OUTSIDE the window is authorized because the file is unchanged.
  128. const result = await call('edit', { file_path: 'a.txt', old_string: 'line 12', new_string: 'LINE 12' })
  129. expect(result.isError).toBe(false)
  130. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe(lines.map(l => l === 'line 12' ? 'LINE 12' : l).join('\n'))
  131. })
  132. it('rejects an edit when the file changed since the windowed read (stale before matching)', async () => {
  133. await writeFile(join(dir, 'a.txt'), 'hello world')
  134. await call('read', { file_path: 'a.txt', offset: 1, limit: 1 })
  135. await writeFile(join(dir, 'a.txt'), 'goodbye') // out-of-band change removes 'world'
  136. const result = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  137. expect(result.isError).toBe(true)
  138. expect(result.error).toMatchObject({ info: { code: 'FS_STALE_VERSION' } })
  139. })
  140. it('rejects an ambiguous match without replace_all', async () => {
  141. await writeFile(join(dir, 'a.txt'), 'a a a')
  142. await call('read', { file_path: 'a.txt' })
  143. const result = await call('edit', { file_path: 'a.txt', old_string: 'a', new_string: 'b' })
  144. expect(result.isError).toBe(true)
  145. expect(result.error).toMatchObject({ info: { code: 'FS_AMBIGUOUS_EDIT' } })
  146. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('a a a')
  147. })
  148. it('replaces all matches with replace_all', async () => {
  149. await writeFile(join(dir, 'a.txt'), 'a a a')
  150. await call('read', { file_path: 'a.txt' })
  151. const result = await call('edit', { file_path: 'a.txt', old_string: 'a', new_string: 'b', replace_all: true })
  152. expect(result.isError).toBe(false)
  153. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('b b b')
  154. })
  155. it('supports a full write→edit cycle without an intervening read', async () => {
  156. await call('write', { file_path: 'a.txt', content: 'one two' })
  157. const result = await call('edit', { file_path: 'a.txt', old_string: 'two', new_string: 'three' })
  158. expect(result.isError).toBe(false)
  159. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('one three')
  160. })
  161. })
  162. describe('the gate records only through the events (no method coupling)', () => {
  163. it('a direct ctx.fs.readText records no observed-state, so a later edit rejects', async () => {
  164. await writeFile(join(dir, 'a.txt'), 'hello world')
  165. // Reach AROUND the tool — an explicit escape hatch for non-tool consumers.
  166. await ctx.fs.readText(await ctx.fs.resolve('a.txt'))
  167. // The model-facing edit still rejects: the read did not emit fs/observed.
  168. const result = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  169. expect(result.isError).toBe(true)
  170. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  171. })
  172. })
  173. describe('stat budget', () => {
  174. it('read stats once; write and edit never stat in the tool (the gate stats zero too)', async () => {
  175. await writeFile(join(dir, 'a.txt'), 'hello world')
  176. const statSpy = vi.spyOn(ctx.fs, 'stat')
  177. // read: exactly one stat (type + size routing + observed version).
  178. await call('read', { file_path: 'a.txt' })
  179. expect(statSpy).toHaveBeenCalledTimes(1)
  180. // edit (guarded, after the read): the gate supplies vObserved; the tool
  181. // does not stat to manufacture a basis. CAS happens in editText's lock.
  182. statSpy.mockClear()
  183. const edited = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  184. expect(edited.isError).toBe(false)
  185. expect(statSpy).not.toHaveBeenCalled()
  186. // write (guarded replace, after the edit refreshed observed state): zero stat.
  187. statSpy.mockClear()
  188. const written = await call('write', { file_path: 'a.txt', content: 'fresh' })
  189. expect(written.isError).toBe(false)
  190. expect(statSpy).not.toHaveBeenCalled()
  191. statSpy.mockRestore()
  192. })
  193. })
  194. })
  195. // --------------------------------------------------------------------------
  196. // BARE deployment: the tool suite WITHOUT the policy gate.
  197. // --------------------------------------------------------------------------
  198. describe('bare provider (no dsh-fs-policy)', () => {
  199. beforeEach(async () => {
  200. dir = await mkdtemp(join(tmpdir(), 'dsh-tool-fs-bare-'))
  201. ctx = new Context()
  202. await ctx.plugin(SystemPrompt)
  203. await ctx.plugin(ToolRegistry)
  204. await ctx.plugin(LocalFileSystem, { cwd: dir })
  205. fiber = await ctx.plugin(ToolFs)
  206. })
  207. it('read works (it never needed policy)', async () => {
  208. await writeFile(join(dir, 'a.txt'), 'alpha\nbeta')
  209. const result = await call('read', { file_path: 'a.txt' })
  210. expect(result.isError).toBe(false)
  211. expect(text(result)).toContain('1: alpha')
  212. })
  213. it('write unconditionally creates a new file', async () => {
  214. const result = await call('write', { file_path: 'new.txt', content: 'fresh' })
  215. expect(result.isError).toBe(false)
  216. expect(await readFile(join(dir, 'new.txt'), 'utf8')).toBe('fresh')
  217. })
  218. it('write unconditionally OVERWRITES an existing unread file', async () => {
  219. await writeFile(join(dir, 'a.txt'), 'original')
  220. const result = await call('write', { file_path: 'a.txt', content: 'clobbered' })
  221. expect(result.isError).toBe(false)
  222. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('clobbered')
  223. })
  224. it('edit unconditionally edits an UNREAD existing file', async () => {
  225. await writeFile(join(dir, 'a.txt'), 'hello world')
  226. const result = await call('edit', { file_path: 'a.txt', old_string: 'world', new_string: 'there' })
  227. expect(result.isError).toBe(false)
  228. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('hello there')
  229. })
  230. it('edit of a MISSING target reports FS_STALE_VERSION even on the unguarded path', async () => {
  231. const result = await call('edit', { file_path: 'missing.txt', old_string: 'a', new_string: 'b' })
  232. expect(result.isError).toBe(true)
  233. expect(result.error).toMatchObject({ info: { code: 'FS_STALE_VERSION' } })
  234. })
  235. it('edit still enforces literal-match codes (FS_EDIT_NOT_FOUND), unrelated to freshness', async () => {
  236. await writeFile(join(dir, 'a.txt'), 'hello world')
  237. const result = await call('edit', { file_path: 'a.txt', old_string: 'absent', new_string: 'x' })
  238. expect(result.isError).toBe(true)
  239. expect(result.error).toMatchObject({ info: { code: 'FS_EDIT_NOT_FOUND' } })
  240. })
  241. it('neither write nor edit stats in the tool on the bare path', async () => {
  242. await writeFile(join(dir, 'a.txt'), 'hello world')
  243. const statSpy = vi.spyOn(ctx.fs, 'stat')
  244. expect((await call('write', { file_path: 'a.txt', content: 'x y' })).isError).toBe(false)
  245. expect((await call('edit', { file_path: 'a.txt', old_string: 'y', new_string: 'z' })).isError).toBe(false)
  246. expect(statSpy).not.toHaveBeenCalled()
  247. statSpy.mockRestore()
  248. })
  249. })
  250. // Per-session cwd: a relative file_path resolves against the calling session's workspace
  251. // (`exec.agent.session.header.cwd`), not the backend's config.cwd, so the
  252. // caller-selected session workspace wins, matching dsh-tool-bash.
  253. describe('per-session cwd', () => {
  254. let sessionDir: string
  255. beforeEach(async () => {
  256. dir = await mkdtemp(join(tmpdir(), 'dsh-tool-fs-cfg-'))
  257. sessionDir = await mkdtemp(join(tmpdir(), 'dsh-tool-fs-session-'))
  258. ctx = new Context()
  259. await ctx.plugin(SystemPrompt)
  260. await ctx.plugin(ToolRegistry)
  261. await ctx.plugin(LocalFileSystem, { cwd: dir }) // config.cwd = dir, NOT sessionDir
  262. await ctx.plugin(FsPolicy)
  263. fiber = await ctx.plugin(ToolFs)
  264. })
  265. afterEach(async () => { await rm(sessionDir, { recursive: true, force: true }) })
  266. const callIn = (sessionObj: object, name: string, args: unknown) =>
  267. ctx.tools.execute({
  268. signal: testToolSignal,
  269. callId: CallId(`call-${++callCounter}`),
  270. name,
  271. arguments: args,
  272. agent: { session: sessionObj } as never,
  273. })
  274. it('writes a relative path into the SESSION cwd, not config.cwd', async () => {
  275. const result = await callIn({ header: { cwd: sessionDir } }, 'write', { file_path: 'note.txt', content: 'hi' })
  276. expect(result.isError).toBe(false)
  277. // Verify the WORLD: the file is in the session dir, and NOT in config.cwd.
  278. expect(await readFile(join(sessionDir, 'note.txt'), 'utf8')).toBe('hi')
  279. await expect(readFile(join(dir, 'note.txt'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
  280. })
  281. it('read + edit both resolve against the session cwd (end-to-end)', async () => {
  282. // ONE session object across both calls — observed-state keys by owner
  283. // identity, so read must record under the same owner the edit reads.
  284. const session = { header: { cwd: sessionDir } }
  285. await writeFile(join(sessionDir, 'code.txt'), 'alpha')
  286. expect((await callIn(session, 'read', { file_path: 'code.txt' })).isError).toBe(false)
  287. const edited = await callIn(session, 'edit', { file_path: 'code.txt', old_string: 'alpha', new_string: 'beta' })
  288. expect(edited.isError).toBe(false)
  289. expect(await readFile(join(sessionDir, 'code.txt'), 'utf8')).toBe('beta')
  290. })
  291. })
  292. // --------------------------------------------------------------------------
  293. // Abort-through-the-tool, tool-tier concurrency, and the fs/observed contract —
  294. // all through ctx.tools.execute() against the REAL backend + policy.
  295. // --------------------------------------------------------------------------
  296. describe('signal, concurrency, and the fs/observed contract', () => {
  297. beforeEach(async () => {
  298. dir = await mkdtemp(join(tmpdir(), 'dsh-tool-fs-'))
  299. ctx = new Context()
  300. await ctx.plugin(SystemPrompt)
  301. await ctx.plugin(ToolRegistry)
  302. await ctx.plugin(LocalFileSystem, { cwd: dir })
  303. await ctx.plugin(FsPolicy)
  304. fiber = await ctx.plugin(ToolFs)
  305. })
  306. const session = { header: {} }
  307. const callSig = (signal: AbortSignal, name: string, args: unknown) =>
  308. ctx.tools.execute({ callId: CallId(`c-${++callCounter}`), name, arguments: args, agent: { session } as never, signal })
  309. const callOwned = (name: string, args: unknown) =>
  310. ctx.tools.execute({ signal: testToolSignal, callId: CallId(`c-${++callCounter}`), name, arguments: args, agent: { session } as never })
  311. it('a pre-aborted registry call skips read/write/edit with ABORTED_BEFORE_DISPATCH', async () => {
  312. await writeFile(join(dir, 'a.txt'), 'hello')
  313. const read = await callSig(AbortSignal.abort(), 'read', { file_path: 'a.txt' })
  314. expect(read.isError).toBe(true)
  315. expect(read.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } })
  316. const write = await callSig(AbortSignal.abort(), 'write', { file_path: 'new.txt', content: 'x' })
  317. expect(write.isError).toBe(true)
  318. expect(write.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } })
  319. await expect(readFile(join(dir, 'new.txt'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
  320. // Read first (un-aborted, SAME session owner) so the edit clears the
  321. // observation gate; then the registry skips the aborted edit before its body.
  322. expect((await callOwned('read', { file_path: 'a.txt' })).isError).toBe(false)
  323. const edit = await callSig(AbortSignal.abort(), 'edit', { file_path: 'a.txt', old_string: 'hello', new_string: 'bye' })
  324. expect(edit.isError).toBe(true)
  325. expect(edit.error).toMatchObject({ info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH } })
  326. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('hello') // unchanged
  327. })
  328. it('two concurrent edits of the same file, same session: one wins, one FS_STALE_VERSION', async () => {
  329. await writeFile(join(dir, 'a.txt'), 'base value here')
  330. // One read establishes the observed version both edits guard against; then
  331. // race two edits so both carry the SAME observed version (the barrier).
  332. expect((await callOwned('read', { file_path: 'a.txt' })).isError).toBe(false)
  333. const [one, two] = await Promise.all([
  334. callOwned('edit', { file_path: 'a.txt', old_string: 'base', new_string: 'ONE', replaceAll: false }),
  335. callOwned('edit', { file_path: 'a.txt', old_string: 'value', new_string: 'TWO', replaceAll: false }),
  336. ])
  337. const errors = [one, two].filter(r => r.isError)
  338. expect(errors).toHaveLength(1)
  339. expect(errors[0]?.error).toMatchObject({ info: { code: 'FS_STALE_VERSION' } })
  340. // The world is consistent: exactly one edit landed.
  341. const onDisk = await readFile(join(dir, 'a.txt'), 'utf8')
  342. expect(onDisk === 'ONE value here' || onDisk === 'base TWO here').toBe(true)
  343. })
  344. it('a stale observed version from an older read fails closed at edit CAS', async () => {
  345. await writeFile(join(dir, 'a.txt'), 'older content\n')
  346. const target = await ctx.fs.resolve('a.txt')
  347. const firstInfo = await ctx.fs.stat(target)
  348. if (!firstInfo) throw new Error('expected first stat')
  349. expect((await callOwned('read', { file_path: 'a.txt' })).isError).toBe(false)
  350. await writeFile(join(dir, 'a.txt'), 'newer current content\n')
  351. const secondInfo = await ctx.fs.stat(target)
  352. if (!secondInfo) throw new Error('expected second stat')
  353. expect(secondInfo.version).not.toBe(firstInfo.version)
  354. expect((await callOwned('read', { file_path: 'a.txt' })).isError).toBe(false)
  355. // Reproduce an older concurrent read winning the observation race.
  356. ctx.emit('fs/observed', target, firstInfo.version, { agent: { session } })
  357. const edit = await callOwned('edit', {
  358. file_path: 'a.txt',
  359. old_string: 'newer',
  360. new_string: 'edited',
  361. })
  362. expect(edit.isError).toBe(true)
  363. expect(edit.error).toMatchObject({ info: { code: 'FS_STALE_VERSION' } })
  364. expect(await readFile(join(dir, 'a.txt'), 'utf8')).toBe('newer current content\n')
  365. })
  366. it('a throwing fs/observed listener surfaces as isError, but the mutation already hit disk', async () => {
  367. // fs/observed is a plain ctx.emit after the write succeeded; a throwing listener cannot
  368. // roll the write back — it only turns the tool result into isError.
  369. ctx.on('fs/observed', () => { throw new Error('recording bug') })
  370. const result = await callOwned('write', { file_path: 'w.txt', content: 'durable' })
  371. expect(result.isError).toBe(true)
  372. expect(await readFile(join(dir, 'w.txt'), 'utf8')).toBe('durable')
  373. })
  374. })