compaction.e2e.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, describe, expect, it } from 'vitest'
  5. import type { Context } from 'cordis'
  6. import { AgentId } from '@deepseek-ai/dsh-agent'
  7. import { codingHarness, finalText, SYSTEM_PROMPT, waitForIdle } from './harness.ts'
  8. /**
  9. * The compaction smoke test: a real model runs a multi-step bash task with a
  10. * deliberately tiny context window, so the auto-compaction listener fires
  11. * MID-SESSION and summarizes the older history into a checkpoint. This is the
  12. * first end-to-end exercise of the compaction seam (it is wired nowhere else),
  13. * and the runaway-survival regression net — it proves a session that grows past
  14. * the window keeps running rather than overflowing. Key-gated.
  15. *
  16. * Verifies the WORLD, not the agent's self-report: a compact/start…end pair
  17. * landed in the real session log, the surface actually shrank (a replace node
  18. * exists and shadowed older nodes), and the agent still produced a final answer
  19. * after compaction (so the summarized history did not break the conversation).
  20. *
  21. * FIXME(compaction-snapshot): this key-gated e2e is the ONLY coverage of runaway
  22. * compaction — there is no keyless full-transcript snapshot of it. dsh-llm-replay
  23. * reconstructs one model call per (turn, step) from `assistant/chunk` events, but
  24. * `summarize()` assembles its stream into a local BlockAssembler and appends no
  25. * `assistant/chunk`, so the interleaved summarization call is unreplayable. A
  26. * snapshot needs replay-harness work to serve that call; deferred as a follow-up.
  27. */
  28. let workdir: string | undefined
  29. let ctx: Context | undefined
  30. afterEach(async () => {
  31. await ctx?.fiber.dispose()
  32. ctx = undefined
  33. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  34. workdir = undefined
  35. })
  36. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compacts mid-flight and keeps running', () => {
  37. it('summarizes older history into a checkpoint without breaking the task', async () => {
  38. workdir = await mkdtemp(join(tmpdir(), 'dsh-compaction-'))
  39. // A handful of files for the model to read, so multiple bash steps
  40. // accumulate surface nodes (tool calls + results) and grow the history past
  41. // the (deliberately tiny) window.
  42. for (let i = 1; i <= 6; i++) {
  43. await writeFile(join(workdir, `file${i}.txt`), `This is file number ${i}. `.repeat(40))
  44. }
  45. // Tiny window so a couple of steps crosses the threshold. The generation
  46. // cap is deliberately larger than the final checkpoint because
  47. // reasoning-capable APIs count reasoning tokens against the provider output
  48. // budget even though those blocks are stripped before the checkpoint is
  49. // stored.
  50. ctx = await codingHarness(workdir, {
  51. compact: {
  52. contextWindow: 2400,
  53. thresholdRatio: 0.5,
  54. retainTokens: 500,
  55. summarizationModel: '',
  56. maxTokens: 2048,
  57. compactionRetries: 1,
  58. },
  59. persistenceRoot: './.sessions',
  60. })
  61. const agent = ctx.agentLoop.create(AgentId('e2e-compaction'), {
  62. model: 'deepseek-v4-flash',
  63. systemPrompt: SYSTEM_PROMPT,
  64. })
  65. agent.send([{
  66. type: 'text',
  67. text: 'Read file1.txt, file2.txt, file3.txt, file4.txt, file5.txt, and file6.txt one at a '
  68. + 'time using cat (a separate bash command for each). After reading all six, tell me how '
  69. + 'many files you read and the number mentioned in file1.txt.',
  70. }])
  71. await waitForIdle(ctx, agent)
  72. const events = [...agent.session.events]
  73. // A compaction ran: the start…end bracket landed in the real log.
  74. const starts = events.filter(e => e.type === 'compact/start')
  75. const ends = events.filter(e => e.type === 'compact/end')
  76. expect(starts.length).toBeGreaterThan(0)
  77. expect(ends.length).toBe(starts.length) // every start was released
  78. // It succeeded at least once: a compact/summary provenance event and a
  79. // replace-op user/message (the surface mutation) both landed.
  80. const summaries = events.filter(e => e.type === 'compact/summary')
  81. expect(summaries.length).toBeGreaterThan(0)
  82. const replaceNode = events.find((e) => {
  83. const se = e as unknown as { type: string; surfaceOp?: unknown }
  84. return se.type === 'user/message' && typeof se.surfaceOp === 'object' && se.surfaceOp !== null
  85. })
  86. expect(replaceNode).toBeDefined()
  87. // The summary shadowed real older nodes (the surface shrank vs. the raw
  88. // message-producing event count).
  89. const summaryData = summaries[0]!.data as { shadowedSeqs: number[] }
  90. expect(summaryData.shadowedSeqs.length).toBeGreaterThan(0)
  91. // The conversation survived compaction: the agent produced a final answer
  92. // that reflects the work (it read six files).
  93. const answer = finalText(events).toLowerCase()
  94. expect(answer.length).toBeGreaterThan(0)
  95. expect(answer).toMatch(/\b(6|six)\b/)
  96. }, 240_000)
  97. })