compaction.e2e.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 <= 4; i++) {
  43. await writeFile(join(workdir, `file${i}.txt`), `This is file number ${i}. `.repeat(50))
  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. persona: SYSTEM_PROMPT,
  52. compact: {
  53. contextWindow: 2000,
  54. thresholdRatio: 0.5,
  55. retainTokens: 400,
  56. summarizationModel: '',
  57. maxTokens: 1024,
  58. compactionRetries: 1,
  59. },
  60. persistenceRoot: join(workdir, '.sessions'),
  61. })
  62. const agent = ctx.agentLoop.create(AgentId('e2e-compaction'), { model: 'deepseek-v4-flash' })
  63. agent.send([{
  64. type: 'text',
  65. text: 'Read file1.txt, file2.txt, file3.txt, and file4.txt one at a '
  66. + 'time using cat (a separate bash command for each). After reading all four, tell me how '
  67. + 'many files you read and the number mentioned in file1.txt.',
  68. }])
  69. await waitForIdle(ctx, agent)
  70. const events = [...agent.session.events]
  71. // A compaction ran: the start…end bracket landed in the real log.
  72. const starts = events.filter(e => e.type === 'compact/start')
  73. const ends = events.filter(e => e.type === 'compact/end')
  74. expect(starts.length).toBeGreaterThan(0)
  75. expect(ends.length).toBe(starts.length) // every start was released
  76. // It succeeded at least once: a compact/summary provenance event and a
  77. // replace-op user/message (the surface mutation) both landed.
  78. const summaries = events.filter(e => e.type === 'compact/summary')
  79. expect(summaries.length).toBeGreaterThan(0)
  80. const replaceNode = events.find((e) => {
  81. const se = e as unknown as { type: string; surfaceOp?: unknown }
  82. return se.type === 'user/message' && typeof se.surfaceOp === 'object' && se.surfaceOp !== null
  83. })
  84. expect(replaceNode).toBeDefined()
  85. // The summary shadowed real older nodes (the surface shrank vs. the raw
  86. // message-producing event count).
  87. const summaryData = summaries[0]!.data as { shadowedSeqs: number[] }
  88. expect(summaryData.shadowedSeqs.length).toBeGreaterThan(0)
  89. // The conversation survived compaction: the agent produced a final answer
  90. // that reflects the work (it read four files).
  91. const answer = finalText(events).toLowerCase()
  92. expect(answer.length).toBeGreaterThan(0)
  93. expect(answer).toMatch(/\b(4|four)\b/)
  94. }, 240_000)
  95. })