integration.spec.ts 20 KB

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