compact-basic.spec.ts 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { BasicCompactService } from '@deepseek-ai/dsh-compact-basic'
  4. import type { BasicCompactConfig } from '@deepseek-ai/dsh-compact-basic'
  5. import type { ContentBlock, GenerateOptions, Message, StreamChunk } from '@deepseek-ai/dsh-llm'
  6. import { CallId, LlmAdapter, LlmService } from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent, SurfaceEvent } from '@deepseek-ai/dsh-session'
  9. import * as Invariants from '@deepseek-ai/dsh-invariants'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. /** A never-aborted signal for the required `compactIfNeeded`/listener arg. */
  12. const SIGNAL = new AbortController().signal
  13. /**
  14. * A BasicCompactService with summarize() stubbed (no real model call) and a
  15. * predictable token estimate, for deterministic unit tests of the algorithm.
  16. */
  17. class TestCompactService extends BasicCompactService {
  18. private readonly summaryOutputs = new WeakSet<readonly ContentBlock[]>()
  19. /** Track calls to summarize for test assertions. */
  20. summarizeCalls: { text: string; model: string }[] = []
  21. /** The fixed summary to return. */
  22. mockSummary: ContentBlock[] = [{ type: 'text', text: 'Test summary of compacted content.' }]
  23. /** Per-call summaries; when set, each summarize() call shifts one value. */
  24. mockSummaryQueue: ContentBlock[][] = []
  25. /** If set, summarize() throws this error. */
  26. summarizeError: Error | null = null
  27. override estimateContentTokens(blocks: readonly ContentBlock[]): number {
  28. if (this.summaryOutputs.has(blocks)) return blocks.length * 2
  29. // 10 tokens per block — predictable for retention/threshold math.
  30. return blocks.length * 10
  31. }
  32. override async summarize(text: string, agent: Agent): Promise<ContentBlock[]> {
  33. const model = this.config.summarizationModel || agent.options.model || ''
  34. this.summarizeCalls.push({ text, model })
  35. if (this.summarizeError) throw this.summarizeError
  36. const summary = this.mockSummaryQueue.shift() ?? this.mockSummary
  37. this.summaryOutputs.add(summary)
  38. return summary
  39. }
  40. }
  41. /** Create a test service with a throwaway context (auto disabled — no model). */
  42. function createTestService(config: BasicCompactConfig = {}): TestCompactService {
  43. return new TestCompactService(new Context(), { auto: false, ...config })
  44. }
  45. /**
  46. * Build a multi-turn session with surface markers (simulating real agent-loop
  47. * output). Compaction always runs inside an OPEN turn (the loop fires the
  48. * `agent/pre-step` seam after a turn's start and before a step's start), so by
  49. * default the session is left with a trailing open turn: turns `1..turns`
  50. * close, then one more `turn/start` opens with no matching `turn/end`. Pass
  51. * `{ leaveOpen: false }` for a fully-closed session (e.g. to assert that manual
  52. * compaction is rejected when no turn is open).
  53. */
  54. function multiTurnSession(turns: number, messagesPerTurn: number = 2, opts: { leaveOpen?: boolean } = {}): Session {
  55. const leaveOpen = opts.leaveOpen ?? true
  56. const s = new Session(SessionId('test'))
  57. for (let t = 1; t <= turns; t++) {
  58. s.append('turn/start', { turn: t, trigger: { kind: 'message', source: { kind: 'user' } } })
  59. s.append('step/start', { turn: t, step: 1 })
  60. for (let m = 0; m < messagesPerTurn; m++) {
  61. s.append('user/message', {
  62. content: [{ type: 'text', text: `turn ${t} user message ${m + 1}` }],
  63. source: { kind: 'user' },
  64. }, { surfaceOp: 'append' })
  65. s.append('assistant/message', {
  66. turn: t, step: 1,
  67. content: [{ type: 'text', text: `turn ${t} assistant response ${m + 1}` }],
  68. }, { surfaceOp: 'append' })
  69. }
  70. s.append('step/end', { turn: t, step: 1 })
  71. s.append('turn/end', { turn: t, reason: { kind: 'completed' } })
  72. }
  73. // Open one more turn so compaction's events are turn-enclosed, as they are
  74. // when the loop runs the auto-compaction listener mid-turn.
  75. if (leaveOpen) {
  76. s.append('turn/start', { turn: turns + 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  77. }
  78. return s
  79. }
  80. /** Build a session with tool calls for richer extraction tests. */
  81. function sessionWithTools(): Session {
  82. const s = new Session(SessionId('tools'))
  83. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  84. s.append('step/start', { turn: 1, step: 1 })
  85. s.append('user/message', {
  86. content: [{ type: 'text', text: 'read file x' }],
  87. source: { kind: 'user' },
  88. }, { surfaceOp: 'append' })
  89. s.append('assistant/message', {
  90. turn: 1, step: 1,
  91. content: [
  92. { type: 'text', text: 'Let me read that file.' },
  93. { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{"command":"cat x"}' },
  94. ],
  95. }, { surfaceOp: 'append' })
  96. s.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: '{"command":"cat x"}' })
  97. s.append('tool/result', {
  98. turn: 1, step: 1, callId: CallId('c1'),
  99. content: [{ type: 'text', text: 'hello world' }],
  100. isError: false,
  101. }, { surfaceOp: 'append' })
  102. s.append('assistant/message', {
  103. turn: 1, step: 1,
  104. content: [{ type: 'text', text: 'The file contains: hello world' }],
  105. }, { surfaceOp: 'append' })
  106. s.append('step/end', { turn: 1, step: 1 })
  107. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  108. // Open a trailing turn so compaction's events are turn-enclosed (as they are
  109. // when the loop runs the auto-compaction listener mid-turn).
  110. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  111. return s
  112. }
  113. /**
  114. * Build a session of `turns` turns, each a SINGLE step containing an
  115. * assistant/message that issues a tool-call plus its tool/result — the real
  116. * multi-node-step shape (a step is two surface nodes: the assistant and the
  117. * result). Each turn is preceded by a user/message. Used to exercise
  118. * step-alignment: a region boundary must not fall between the assistant and its
  119. * result.
  120. */
  121. function toolTurnSession(turns: number): Session {
  122. const s = new Session(SessionId('tools-multi'))
  123. for (let t = 1; t <= turns; t++) {
  124. s.append('turn/start', { turn: t, trigger: { kind: 'message', source: { kind: 'user' } } })
  125. s.append('user/message', {
  126. content: [{ type: 'text', text: `turn ${t} request` }],
  127. source: { kind: 'user' },
  128. }, { surfaceOp: 'append' })
  129. s.append('step/start', { turn: t, step: 1 })
  130. s.append('assistant/message', {
  131. turn: t, step: 1,
  132. content: [
  133. { type: 'text', text: `turn ${t} calling tool` },
  134. { type: 'tool-call', id: CallId(`c${t}`), name: 'bash', arguments: '{"command":"ls"}' },
  135. ],
  136. }, { surfaceOp: 'append' })
  137. s.append('tool/call', { turn: t, step: 1, callId: CallId(`c${t}`), name: 'bash', arguments: '{"command":"ls"}' })
  138. s.append('tool/result', {
  139. turn: t, step: 1, callId: CallId(`c${t}`),
  140. content: [{ type: 'text', text: `turn ${t} output` }],
  141. isError: false,
  142. }, { surfaceOp: 'append' })
  143. s.append('step/end', { turn: t, step: 1 })
  144. s.append('turn/end', { turn: t, reason: { kind: 'completed' } })
  145. }
  146. // Open a trailing turn so compaction's events are turn-enclosed.
  147. s.append('turn/start', { turn: turns + 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  148. return s
  149. }
  150. /**
  151. * Assert the derived transcript has NO orphaned tool-result: every
  152. * `tool-result` block's `toolCallId` must be matched by a preceding `tool-call`
  153. * block in an earlier (assistant) message. A dangling tool-result is exactly
  154. * what splitting a step at compaction produces, and every provider rejects it.
  155. */
  156. function expectNoOrphanToolResults(messages: Message[]): void {
  157. const seenCallIds = new Set<string>()
  158. for (const msg of messages) {
  159. for (const block of msg.content) {
  160. if (block.type === 'tool-call') seenCallIds.add(block.id)
  161. if (block.type === 'tool-result') {
  162. expect(seenCallIds.has(block.toolCallId),
  163. `orphaned tool-result for callId ${block.toolCallId} (no preceding tool-call)`).toBe(true)
  164. }
  165. }
  166. }
  167. }
  168. describe('BasicCompactService step-alignment (never split a tool-call/result pair)', () => {
  169. it('compactIfNeeded rounds the retained boundary head-ward to keep a whole step (no orphaned tool-result)', async () => {
  170. // 3 turns, each one step = { assistant(tool-call), tool/result }. Surface
  171. // (9 nodes): user1, asst1, res1, user2, asst2, res2, user3, asst3, res3 —
  172. // 10/20/10 tokens. The tail→head walk retains by whole units; the compacted
  173. // region always ends on a step boundary, so no step's tool-call is split
  174. // from its result. retainTokens=55 keeps the recent tail; the older steps
  175. // compact intact.
  176. const svc = createTestService({ contextWindow: 280, thresholdRatio: 0.5, retainTokens: 55 })
  177. const session = toolTurnSession(3)
  178. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  179. expect(result).not.toBeNull()
  180. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  181. // No dangling tool-result: every compacted/retained step stayed whole.
  182. expectNoOrphanToolResults(session.deriveMessages())
  183. // The most-recent step's result is retained verbatim (still on the surface).
  184. const lastResultSeq = session.events.findLast(e => e.type === 'tool/result')!.seq
  185. expect(result!.shadowedSeqs).not.toContain(lastResultSeq)
  186. })
  187. it('compactIfNeeded returns null when the only compactable region is an un-splittable single step', async () => {
  188. // The surface is exactly ONE step: [assistant(tool-call), tool/result]. Over
  189. // threshold (by the derived role overhead), the tail→head walk stops with the
  190. // retained boundary at the tool/result — which is NOT a step-aligned start (its
  191. // issuing assistant precedes it in the same step). Rounding head-ward to find a
  192. // clean boundary reaches index 0, so there is no step-aligned cutoff in the
  193. // compactable range: compactIfNeeded declines rather than splitting the step.
  194. const s = new Session(SessionId('one-step'))
  195. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  196. s.append('step/start', { turn: 1, step: 1 })
  197. s.append('assistant/message', {
  198. turn: 1, step: 1,
  199. content: [{ type: 'text', text: 'calling' }, { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{}' }],
  200. }, { surfaceOp: 'append' })
  201. s.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: '{}' })
  202. s.append('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'out' }], isError: false }, { surfaceOp: 'append' })
  203. s.append('step/end', { turn: 1, step: 1 })
  204. // Turn stays open.
  205. const svc = createTestService({ contextWindow: 100, thresholdRatio: 0.1, retainTokens: 5 })
  206. const result = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  207. expect(result).toBeNull()
  208. expect(s.events.some(e => e.type === 'compact/start')).toBe(false)
  209. })
  210. it('compactRegion rejects a start that splits a step (unbalanced boundary)', async () => {
  211. const svc = createTestService()
  212. const session = toolTurnSession(1)
  213. const nodes = session.surface.nodes // [user, asst(tool-call), result]
  214. const userSeq = nodes[0]!.seq
  215. const resultSeq = nodes[2]!.seq
  216. // start = the tool/result: its issuing assistant precedes it IN THE SAME STEP,
  217. // so starting here would orphan that assistant's tool-call. end is fine (user).
  218. await expect(compactRegion(svc, session, resultSeq, resultSeq, 'm'))
  219. .rejects.toThrow(/start seq .* is not a balanced boundary/)
  220. expect(userSeq).toBeLessThan(resultSeq) // sanity: ordering as expected
  221. })
  222. it('compactRegion rejects an end that splits a step (unbalanced boundary)', async () => {
  223. const svc = createTestService()
  224. const session = toolTurnSession(1)
  225. const nodes = session.surface.nodes
  226. const userSeq = nodes[0]!.seq
  227. const asstSeq = nodes[1]!.seq
  228. // end = the assistant/message: its tool/result follows IN THE SAME STEP, so
  229. // ending here would strand that result. start is fine (the pre-step user).
  230. await expect(compactRegion(svc, session, userSeq, asstSeq, 'm'))
  231. .rejects.toThrow(/end seq .* is not a balanced boundary/)
  232. })
  233. it('compactRegion rejects an end inside an open tail step', async () => {
  234. const svc = createTestService()
  235. const s = new Session(SessionId('open-tail'))
  236. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  237. s.append('user/message', { content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  238. s.append('step/start', { turn: 1, step: 1 })
  239. s.append('assistant/message', {
  240. turn: 1, step: 1,
  241. content: [{ type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{}' }],
  242. }, { surfaceOp: 'append' })
  243. const nodes = s.surface.nodes // [user, asst]
  244. const userSeq = nodes[0]!.seq
  245. const asstSeq = nodes[1]!.seq
  246. await expect(compactRegion(svc, s, userSeq, asstSeq, 'm'))
  247. .rejects.toThrow(/end seq .* is not a balanced boundary/)
  248. })
  249. it('compactRegion accepts step-aligned boundaries (pre-step user → last result of a closed step)', async () => {
  250. const svc = createTestService()
  251. const session = toolTurnSession(2)
  252. const nodes = session.surface.nodes // [user1, asst1, res1, user2, asst2, res2]
  253. const startSeq = nodes[0]!.seq // pre-step user1 (free boundary)
  254. const endSeq = nodes[2]!.seq // res1 = last node of turn 1's closed step
  255. const result = await compactRegion(svc, session, startSeq, endSeq, 'm')
  256. expect(result.shadowedRange).toEqual({ start: startSeq, end: endSeq })
  257. expectNoOrphanToolResults(session.deriveMessages())
  258. })
  259. it('compactRegion accepts a single inter-step node (start === end on a pre-step user/message)', async () => {
  260. const svc = createTestService()
  261. const session = toolTurnSession(1)
  262. const nodes = session.surface.nodes
  263. const userSeq = nodes[0]!.seq // pre-step user: free boundary both ways
  264. const result = await compactRegion(svc, session, userSeq, userSeq, 'm')
  265. expect(result.shadowedRange).toEqual({ start: userSeq, end: userSeq })
  266. })
  267. it('compactRegion accepts an injection-turn context node (no step at all)', async () => {
  268. const svc = createTestService()
  269. const s = new Session(SessionId('inject'))
  270. // An idle inject(): turn/start → context/message, NO step. A later turn is
  271. // open so compaction's events are turn-enclosed.
  272. s.append('turn/start', { turn: 1, trigger: { kind: 'injection', source: { kind: 'user' } } })
  273. s.append('context/message', { content: [{ type: 'text', text: 'ctx' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  274. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  275. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  276. const nodes = s.surface.nodes
  277. const ctxSeq = nodes[0]!.seq
  278. const result = await compactRegion(svc, s, ctxSeq, ctxSeq, 'm')
  279. expect(result.shadowedRange).toEqual({ start: ctxSeq, end: ctxSeq })
  280. })
  281. })
  282. describe('BasicCompactService.estimateEventTokens', () => {
  283. it('returns 0 for non-message events (boundary, chunk, step/end, tool/call)', () => {
  284. const svc = createTestService()
  285. expect(svc.estimateEventTokens({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } })).toBe(0)
  286. expect(svc.estimateEventTokens({ type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } })).toBe(0)
  287. expect(svc.estimateEventTokens({ type: 'assistant/chunk', seq: 2, time: 3, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'h' } } })).toBe(0)
  288. expect(svc.estimateEventTokens({ type: 'step/end', seq: 3, time: 4, data: { turn: 1, step: 1 } })).toBe(0)
  289. expect(svc.estimateEventTokens({ type: 'tool/call', seq: 4, time: 5, data: { turn: 1, step: 1, callId: CallId('c1'), name: 'read', arguments: '{}' } })).toBe(0)
  290. })
  291. it('returns estimate for message-producing events', () => {
  292. const svc = createTestService()
  293. const userEvent: SessionEvent = { type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } } }
  294. expect(svc.estimateEventTokens(userEvent)).toBe(10)
  295. const asstEvent: SessionEvent = { type: 'assistant/message', seq: 1, time: 2, data: { turn: 1, step: 1, content: [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }] } }
  296. expect(svc.estimateEventTokens(asstEvent)).toBe(20)
  297. const toolEvent: SessionEvent = { type: 'tool/result', seq: 2, time: 3, data: { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'output' }], isError: false } }
  298. expect(svc.estimateEventTokens(toolEvent)).toBe(10)
  299. })
  300. })
  301. describe('BasicCompactService.estimateTokens', () => {
  302. it('sums token estimates across messages', () => {
  303. const svc = createTestService()
  304. const messages: Message[] = [
  305. { role: 'user', content: [{ type: 'text', text: 'hello' }] },
  306. { role: 'assistant', content: [{ type: 'text', text: 'hi' }, { type: 'text', text: 'there' }] },
  307. ]
  308. // 1 block * 10 + 4 (role) + 2 blocks * 10 + 4 (role) = 10 + 4 + 20 + 4 = 38
  309. expect(svc.estimateTokens(messages)).toBe(38)
  310. })
  311. it('includes system prompt in the estimate', () => {
  312. const svc = createTestService()
  313. const messages: Message[] = [
  314. { role: 'user', content: [{ type: 'text', text: 'hi' }] },
  315. ]
  316. const systemPrompt = 'You are a helpful assistant.'
  317. // 1 block * 10 + 4 (role) + ceil(28/4) = 10 + 4 + 7 = 21
  318. expect(svc.estimateTokens(messages, systemPrompt)).toBe(21)
  319. })
  320. })
  321. describe('BasicCompactService.compactRegion', () => {
  322. it('shadows surface nodes and inserts a summary via user/message', async () => {
  323. const svc = createTestService()
  324. const session = multiTurnSession(3, 1) // 3 turns, 2 surface nodes each = 6 nodes
  325. const nodes = session.surface.nodes
  326. expect(nodes.length).toBe(6)
  327. const firstSeq = nodes[0]!.seq
  328. const secondSeq = nodes[1]!.seq
  329. const result = await compactRegion(svc, session, firstSeq, secondSeq, 'test-model')
  330. expect(result.shadowedSeqs).toEqual([firstSeq, secondSeq])
  331. expect(result.shadowedRange.start).toBe(firstSeq)
  332. expect(result.shadowedRange.end).toBe(secondSeq)
  333. expect(result.summary).toEqual(svc.mockSummary)
  334. const events = session.events
  335. const startEvent = events.findLast(e => e.type === 'compact/start')
  336. const summaryEvent = events.findLast(e => e.type === 'compact/summary')
  337. const endEvent = events.findLast(e => e.type === 'compact/end')
  338. expect(startEvent).toBeDefined()
  339. expect(summaryEvent).toBeDefined()
  340. expect(endEvent).toBeDefined()
  341. // compact/* events are log-only — no surfaceOp (type system enforces this).
  342. const startRaw = startEvent as unknown as { surfaceOp?: unknown }
  343. expect(startRaw.surfaceOp).toBeUndefined()
  344. // The user/message carries the replace surfaceOp.
  345. const userMsg = events.findLast(e => e.type === 'user/message')!
  346. const surfaceUserMsg = userMsg as SurfaceEvent
  347. expect(surfaceUserMsg.surfaceOp).toEqual({ op: 'replace', start: firstSeq, end: secondSeq })
  348. expect(surfaceUserMsg.sourceEventSeqs).toContain(startEvent!.seq)
  349. expect(surfaceUserMsg.sourceEventSeqs).toContain(summaryEvent!.seq)
  350. expect(surfaceUserMsg.sourceEventSeqs).toContain(firstSeq)
  351. expect(surfaceUserMsg.sourceEventSeqs).toContain(secondSeq)
  352. // compact/end is appended AFTER the replacement (the lock brackets the whole
  353. // op), so the replacement cannot reference it — sourceEventSeqs may only
  354. // reference earlier seqs.
  355. expect(surfaceUserMsg.sourceEventSeqs).not.toContain(endEvent!.seq)
  356. expect(endEvent!.seq).toBeGreaterThan(userMsg.seq)
  357. // Surface now has: summary user/message + retained 4 nodes = 5 nodes.
  358. const newNodes = session.surface.nodes
  359. expect(newNodes.length).toBe(5)
  360. expect(newNodes[0]!.seq).toBe(userMsg.seq)
  361. // deriveMessages() produces the framed summary as a user-role message:
  362. // a checkpoint preamble + tag-wrapped summary blocks.
  363. const derived = session.deriveMessages()
  364. expect(derived.length).toBe(5)
  365. expect(derived[0]!.role).toBe('user')
  366. const framed = derived[0]!.content
  367. expect(framed[0]).toMatchObject({ type: 'text' })
  368. expect((framed[0] as { text: string }).text).toContain('<compacted-summary>')
  369. expect(framed).toContainEqual(svc.mockSummary[0])
  370. expect((framed[framed.length - 1] as { text: string }).text).toBe('</compacted-summary>')
  371. })
  372. it('throws when start or end are not surface nodes', async () => {
  373. const svc = createTestService()
  374. const session = multiTurnSession(1, 1)
  375. await expect(compactRegion(svc, session, 999, 1000, 'm'))
  376. .rejects.toThrow(/start seq 999 not found in surface/)
  377. })
  378. it('throws when start is positioned after end on the surface', async () => {
  379. const svc = createTestService()
  380. const session = multiTurnSession(2, 1)
  381. const nodes = session.surface.nodes
  382. await expect(compactRegion(svc, session, nodes[1]!.seq, nodes[0]!.seq, 'm'))
  383. .rejects.toThrow(/is after end seq .* on the surface/)
  384. })
  385. it('throws when compaction is already in progress', async () => {
  386. const svc = createTestService()
  387. const session = multiTurnSession(2, 1)
  388. const nodes = session.surface.nodes
  389. session.append('compact/start', { turn: 2 })
  390. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  391. .rejects.toThrow(/compaction already in progress/)
  392. })
  393. it('appends compact/end with error on summarize failure', async () => {
  394. const svc = createTestService()
  395. svc.summarizeError = new Error('model unavailable')
  396. const session = multiTurnSession(2, 1)
  397. const nodes = session.surface.nodes
  398. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  399. .rejects.toThrow('model unavailable')
  400. const endEvent = session.events.findLast(e => e.type === 'compact/end')
  401. expect(endEvent).toBeDefined()
  402. // multiTurnSession(2,…) closes turns 1-2 and leaves turn 3 open; compaction
  403. // stamps the open turn.
  404. expect(endEvent!.data).toMatchObject({ turn: 3, error: 'model unavailable' })
  405. // No replace-op user/message was appended (summarize failed).
  406. const userMsgsAfter = session.events.filter(e => e.type === 'user/message')
  407. const replaceMsgs = userMsgsAfter.filter((e) => {
  408. const se = e as unknown as { surfaceOp?: unknown }
  409. return se.surfaceOp !== undefined && typeof se.surfaceOp !== 'string'
  410. })
  411. expect(replaceMsgs.length).toBe(0)
  412. })
  413. it('extracts conversation text for summarization', async () => {
  414. const svc = createTestService()
  415. const session = multiTurnSession(1, 2)
  416. const nodes = session.surface.nodes
  417. await compactRegion(svc, session, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  418. expect(svc.summarizeCalls.length).toBe(1)
  419. const { text, model } = svc.summarizeCalls[0]!
  420. expect(model).toBe('m')
  421. expect(text).toContain('User: turn 1 user message 1')
  422. expect(text).toContain('Assistant: turn 1 assistant response 1')
  423. })
  424. it('frames the landed summary with a checkpoint preamble and tags, keeping raw provenance', async () => {
  425. const svc = createTestService()
  426. svc.mockSummary = [{ type: 'text', text: 'STRUCTURED SUMMARY' }]
  427. const session = multiTurnSession(3, 1)
  428. const nodes = session.surface.nodes
  429. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  430. // Provenance (compact/summary) carries the RAW, unframed summary.
  431. expect(result.summary).toEqual([{ type: 'text', text: 'STRUCTURED SUMMARY' }])
  432. const summaryEvent = session.events.findLast(e => e.type === 'compact/summary')!
  433. expect(summaryEvent.data).toMatchObject({ summary: [{ type: 'text', text: 'STRUCTURED SUMMARY' }] })
  434. // The landed surface node is framed: preamble + tag-wrapped summary.
  435. const landed = session.deriveMessages()[0]!.content
  436. expect((landed[0] as { text: string }).text).toContain('checkpoint')
  437. expect((landed[0] as { text: string }).text).toContain('<compacted-summary>')
  438. expect(landed).toContainEqual({ type: 'text', text: 'STRUCTURED SUMMARY' })
  439. expect((landed[landed.length - 1] as { text: string }).text).toBe('</compacted-summary>')
  440. })
  441. it('extracts tool-call and tool-result context', async () => {
  442. const svc = createTestService()
  443. const session = sessionWithTools()
  444. const nodes = session.surface.nodes
  445. const firstSeq = nodes[0]!.seq
  446. const lastSeq = nodes[nodes.length - 1]!.seq
  447. await compactRegion(svc, session, firstSeq, lastSeq, 'm')
  448. expect(svc.summarizeCalls.length).toBe(1)
  449. const { text } = svc.summarizeCalls[0]!
  450. expect(text).toContain('read file x')
  451. expect(text).toContain('bash')
  452. expect(text).toContain('Tool result')
  453. })
  454. })
  455. describe('BasicCompactService.compactIfNeeded', () => {
  456. it('returns null when tokens are under threshold', async () => {
  457. const svc = createTestService({ contextWindow: 128000, thresholdRatio: 0.8 })
  458. const session = multiTurnSession(1, 1)
  459. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  460. })
  461. it('compacts when tokens exceed threshold', async () => {
  462. const svc = createTestService({ contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 })
  463. const session = multiTurnSession(3, 1) // 6 surface nodes, 10 tokens each = 60
  464. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  465. expect(result).not.toBeNull()
  466. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  467. })
  468. it('returns the first compaction result when a zero-retry pass converges after the loop', async () => {
  469. // With compactionRetries=0 there is no next-loop threshold check after the
  470. // first mutation, so the success path is the post-loop `return result`.
  471. const svc = createTestService({
  472. contextWindow: 100,
  473. thresholdRatio: 0.7,
  474. retainTokens: 10,
  475. compactionRetries: 0,
  476. })
  477. const session = multiTurnSession(3, 1) // 6 derived messages = 84 estimated tokens.
  478. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  479. expect(result).not.toBeNull()
  480. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(1)
  481. expect(svc.estimateTokens(session.deriveMessages(), '')).toBeLessThan(70)
  482. })
  483. it('walks tail→head and retains nodes within token budget', async () => {
  484. const svc = createTestService({ contextWindow: 350, thresholdRatio: 0.2, retainTokens: 15 })
  485. const session = multiTurnSession(5, 1) // 10 surface nodes = ~100 tokens
  486. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  487. expect(result).not.toBeNull()
  488. const nodes = session.surface.nodes
  489. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  490. expect(result!.shadowedSeqs).not.toContain(nodes[nodes.length - 1]!.seq)
  491. })
  492. it('returns null when the whole surface fits the retain budget (over threshold by role/system overhead)', async () => {
  493. // threshold = floor(480*0.1) = 48. The 4 surface nodes weigh 10 each (raw 40
  494. // for the retention walk), but the derived estimate adds 4 role tokens per
  495. // message → 56 ≥ 48, so the threshold check passes and the walk runs. The
  496. // walk accumulates all 40 < retainTokens (45) without crossing the budget,
  497. // so keepFromIdx reaches 0 and compaction declines.
  498. const svc = createTestService({ contextWindow: 480, thresholdRatio: 0.1, retainTokens: 45 })
  499. const session = multiTurnSession(2, 1)
  500. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  501. })
  502. it('compacts a runaway turn: its early CLOSED steps summarize while recent steps stay verbatim', async () => {
  503. // The REGRESSION that motivated dropping turn-protection. A single in-flight
  504. // (open) turn has grown past the threshold on its own: several CLOSED steps,
  505. // each [assistant(tool-call), tool/result]. Retention is turn-agnostic, so
  506. // the turn's OWN early closed steps are eligible — they compact while the
  507. // recent tail stays verbatim, and the harness survives.
  508. //
  509. // On the OLD layer-2 code this test FAILS: the entire open turn was retained
  510. // verbatim (protectedIdx = first open-turn node = 0), so compactIfNeeded
  511. // returned null and shadowedSeqs would be empty — the runaway turn could
  512. // never compact and the next model call would overflow the window.
  513. const svc = createTestService({ contextWindow: 800, thresholdRatio: 0.1, retainTokens: 25 })
  514. const s = new Session(SessionId('runaway'))
  515. // ONE open turn with 5 closed steps; each step is [asst(tool-call), result].
  516. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  517. s.append('user/message', { content: [{ type: 'text', text: 'do a big multi-step task' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  518. for (let step = 1; step <= 5; step++) {
  519. s.append('step/start', { turn: 1, step })
  520. s.append('assistant/message', {
  521. turn: 1, step,
  522. content: [{ type: 'text', text: `step ${step}` }, { type: 'tool-call', id: CallId(`c${step}`), name: 'bash', arguments: '{}' }],
  523. }, { surfaceOp: 'append' })
  524. s.append('tool/call', { turn: 1, step, callId: CallId(`c${step}`), name: 'bash', arguments: '{}' })
  525. s.append('tool/result', { turn: 1, step, callId: CallId(`c${step}`), content: [{ type: 'text', text: `out ${step}` }], isError: false }, { surfaceOp: 'append' })
  526. s.append('step/end', { turn: 1, step })
  527. }
  528. // The turn stays OPEN (no turn/end) — the model is mid-turn, about to run
  529. // step 6. Surface: user + 5×[asst, result] = 11 nodes.
  530. const nodesBefore = s.surface.nodes.length
  531. expect(nodesBefore).toBe(11)
  532. const result = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  533. expect(result).not.toBeNull()
  534. // Early steps of the SAME open turn were shadowed (impossible under layer 2).
  535. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  536. // The most-recent step's tool result is retained verbatim (still on surface).
  537. const lastResultSeq = s.events.findLast(e => e.type === 'tool/result')!.seq
  538. expect(result!.shadowedSeqs).not.toContain(lastResultSeq)
  539. expect(s.surface.nodes.some(n => n.seq === lastResultSeq)).toBe(true)
  540. // No orphaned tool-result survives (whole-step boundaries respected).
  541. expectNoOrphanToolResults(s.deriveMessages())
  542. })
  543. it('returns null for an empty surface', async () => {
  544. const svc = createTestService({ contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 })
  545. const session = new Session(SessionId('empty'))
  546. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  547. })
  548. it('compacts again after a prior summary node heads the surface (the summary stays eligible)', async () => {
  549. // After the first compaction lands a replacement summary node at the head,
  550. // a second compaction (still over threshold) re-consolidates it with newer
  551. // context — head-anchoring means the prior checkpoint is always re-included,
  552. // never stranded. retainTokens=25 leaves a couple of retained nodes after
  553. // the first compaction (so the surface is [summary, …retained], not just
  554. // [summary]).
  555. const svc = createTestService({ contextWindow: 800, thresholdRatio: 0.1, retainTokens: 25 })
  556. const s = multiTurnSession(4, 1) // turns 1-4 closed, turn 5 open (no surface yet)
  557. const first = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  558. expect(first).not.toBeNull()
  559. // The summary node now heads the surface with a fresh high seq.
  560. const summaryHeadSeq = s.surface.nodes[0]!.seq
  561. const turn5StartSeq = s.events.filter(e => e.type === 'turn/start').at(-1)!.seq
  562. expect(summaryHeadSeq).toBeGreaterThan(turn5StartSeq)
  563. // Append a verbatim node in the open turn (a step's output), still over
  564. // threshold, then compact again — the older summary + closed turns compact,
  565. // the fresh nodes are retained.
  566. s.append('step/start', { turn: 5, step: 1 })
  567. s.append('user/message', { content: [{ type: 'text', text: 'turn 5 work' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  568. s.append('assistant/message', { turn: 5, step: 1, content: [{ type: 'text', text: 'reply 5' }] }, { surfaceOp: 'append' })
  569. s.append('step/end', { turn: 5, step: 1 })
  570. const second = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  571. expect(second).not.toBeNull()
  572. expect(second!.shadowedSeqs.length).toBeGreaterThan(0)
  573. // The fresh open-turn nodes were NOT compacted.
  574. const turn5UserSeq = s.events.find(e => e.type === 'user/message' && e.data.content.some(b => b.type === 'text' && b.text === 'turn 5 work'))!.seq
  575. expect(second!.shadowedSeqs).not.toContain(turn5UserSeq)
  576. })
  577. it('re-compacts smaller summaries until the post-compaction surface drops below threshold', async () => {
  578. const svc = createTestService({
  579. contextWindow: 100,
  580. thresholdRatio: 0.5,
  581. retainTokens: 10,
  582. compactionRetries: 2,
  583. })
  584. svc.mockSummaryQueue = [
  585. Array.from({ length: 4 }, (_, index) => ({ type: 'text', text: `first ${index}` })),
  586. [{ type: 'text', text: 'second' }],
  587. ]
  588. const session = multiTurnSession(4, 1)
  589. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  590. expect(result).not.toBeNull()
  591. expect(svc.summarizeCalls).toHaveLength(2)
  592. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(2)
  593. expect(svc.estimateTokens(session.deriveMessages(), '')).toBeLessThan(50)
  594. })
  595. it('throws after the configured re-compaction attempts still leave the surface above threshold', async () => {
  596. const svc = createTestService({
  597. contextWindow: 100,
  598. thresholdRatio: 0.5,
  599. retainTokens: 10,
  600. compactionRetries: 1,
  601. })
  602. svc.mockSummaryQueue = [
  603. Array.from({ length: 4 }, (_, index) => ({ type: 'text', text: `first ${index}` })),
  604. Array.from({ length: 3 }, (_, index) => ({ type: 'text', text: `second ${index}` })),
  605. ]
  606. const session = multiTurnSession(4, 1)
  607. await expect(compactIfNeeded(svc, session, '', 'm', SIGNAL))
  608. .rejects.toThrow(/still above threshold after 2 compaction attempts/)
  609. expect(svc.summarizeCalls).toHaveLength(2)
  610. })
  611. })
  612. describe('BasicCompactService replay equivalence', () => {
  613. it('produces identical deriveMessages() after seeding from compacted log', async () => {
  614. const svc = createTestService()
  615. const session = multiTurnSession(3, 1)
  616. const nodes = session.surface.nodes
  617. await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  618. const derived = session.deriveMessages()
  619. const replayed = new Session(SessionId('replay'), [...session.events])
  620. expect(replayed.deriveMessages()).toEqual(derived)
  621. })
  622. })
  623. describe('BasicCompactService blocking (compaction in progress)', () => {
  624. it('detects in-progress compaction from unmatched compact/start', async () => {
  625. const svc = createTestService()
  626. const session = multiTurnSession(1, 1)
  627. session.append('compact/start', { turn: 1 })
  628. const nodes = session.surface.nodes
  629. // Whole step (user → assistant) is a step-aligned region, so the call reaches
  630. // the in-progress check rather than being rejected for splitting a step.
  631. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  632. .rejects.toThrow(/compaction already in progress/)
  633. })
  634. it('allows compaction after compact/end is appended', async () => {
  635. const svc = createTestService()
  636. const session = multiTurnSession(2, 1)
  637. const nodes = session.surface.nodes
  638. session.append('compact/start', { turn: 1 })
  639. session.append('compact/end', { turn: 1 })
  640. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  641. expect(result).toBeDefined()
  642. })
  643. it('is not wedged by an orphaned compact/start from a prior (now-closed) turn', async () => {
  644. // A crash mid-compaction left a compact/start with no compact/end; the turn
  645. // it lived in was later closed (persistence repair appends turn/end). A
  646. // whole-log scan would treat that stale start as an active lock forever. The
  647. // scan is scoped to the current turn, so a NEW turn compacts normally.
  648. const svc = createTestService()
  649. const s = new Session(SessionId('stale-lock'))
  650. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  651. s.append('step/start', { turn: 1, step: 1 })
  652. s.append('user/message', { content: [{ type: 'text', text: 'turn 1' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  653. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'reply 1' }] }, { surfaceOp: 'append' })
  654. s.append('compact/start', { turn: 1 }) // ← orphaned: no matching compact/end
  655. s.append('step/end', { turn: 1, step: 1 })
  656. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) // repair closed the turn
  657. // A new open turn.
  658. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  659. const nodes = s.surface.nodes
  660. // The stale start is before the turn/end, so it is NOT seen as in-progress.
  661. const result = await compactRegion(svc, s, nodes[0]!.seq, nodes[1]!.seq, 'm')
  662. expect(result).toBeDefined()
  663. })
  664. })
  665. describe('BasicCompactService token estimation (char/4 heuristic)', () => {
  666. it('estimates text blocks with char/4 + overhead', () => {
  667. const svc = new BasicCompactService(new Context(), { auto: false })
  668. // 'this is a somewhat longer text block' = 36 → ceil(36/4)+4 = 13; 'short' = 5 → 2+4 = 6
  669. const blocks: ContentBlock[] = [
  670. { type: 'text', text: 'this is a somewhat longer text block' },
  671. { type: 'text', text: 'short' },
  672. ]
  673. expect(svc.estimateContentTokens(blocks)).toBe(19)
  674. })
  675. it('estimates reasoning blocks same as text', () => {
  676. const svc = new BasicCompactService(new Context(), { auto: false })
  677. // 'thinking about this...' = 22 → ceil(22/4)+4 = 10
  678. expect(svc.estimateContentTokens([{ type: 'reasoning', text: 'thinking about this...' }])).toBe(10)
  679. })
  680. it('estimates tool-call blocks from name + arguments', () => {
  681. const svc = new BasicCompactService(new Context(), { auto: false })
  682. // 'bash' = 4 → 1; '{"command":"ls"}' = 16 → 4; + 4 overhead = 9
  683. expect(svc.estimateContentTokens([
  684. { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{"command":"ls"}' },
  685. ])).toBe(9)
  686. })
  687. it('estimates tool-result blocks recursively', () => {
  688. const svc = new BasicCompactService(new Context(), { auto: false })
  689. // inner text 5 → 2+4 = 6; outer 6 + 4 overhead = 10
  690. expect(svc.estimateContentTokens([
  691. { type: 'tool-result', toolCallId: CallId('c1'), content: [{ type: 'text', text: 'hello' }], isError: false },
  692. ])).toBe(10)
  693. })
  694. it('estimates image blocks at fixed 85 tokens', () => {
  695. const svc = new BasicCompactService(new Context(), { auto: false })
  696. expect(svc.estimateContentTokens([{ type: 'image', url: 'https://example.com/img.png' }])).toBe(85)
  697. })
  698. it('returns 0 for empty content blocks', () => {
  699. const svc = new BasicCompactService(new Context(), { auto: false })
  700. expect(svc.estimateContentTokens([])).toBe(0)
  701. })
  702. })
  703. describe('BasicCompactService HMR safety', () => {
  704. it('registers as ctx.compact', () => {
  705. const ctx = new Context()
  706. void new BasicCompactService(ctx, { auto: false })
  707. expect(ctx.compact).toBeDefined()
  708. expect(ctx.compact).toBeInstanceOf(BasicCompactService)
  709. })
  710. it('disposing the plugin fiber unregisters ctx.compact', async () => {
  711. // Mount through the real plugin fiber (the Loader path), then dispose it and
  712. // confirm the service registration is torn down. LlmService is mounted first
  713. // so the service's `inject: ['llm']` resolves and the fiber activates. (The
  714. // sibling-fiber ctx.llm resolution this same setup also exercises is covered
  715. // under the "llm inject (real plugin-load path)" suite.)
  716. const ctx = new Context()
  717. await ctx.plugin(LlmService)
  718. const fiber = await ctx.plugin(BasicCompactService, { auto: false })
  719. expect(ctx.get('compact')).toBeInstanceOf(BasicCompactService)
  720. await fiber.dispose()
  721. expect(ctx.get('compact')).toBeUndefined()
  722. })
  723. })
  724. describe('BasicCompactService config validation', () => {
  725. it('rejects invalid numeric config values', () => {
  726. expect(() => new BasicCompactService(new Context(), { auto: false, contextWindow: 0 })).toThrow(/contextWindow .* positive integer/)
  727. expect(() => new BasicCompactService(new Context(), { auto: false, thresholdRatio: 0 })).toThrow(/thresholdRatio .* \(0, 1\]/)
  728. expect(() => new BasicCompactService(new Context(), { auto: false, thresholdRatio: 1.1 })).toThrow(/thresholdRatio .* \(0, 1\]/)
  729. expect(() => new BasicCompactService(new Context(), { auto: false, retainTokens: -1 })).toThrow(/retainTokens .* non-negative integer/)
  730. expect(() => new BasicCompactService(new Context(), { auto: false, maxTokens: 0 })).toThrow(/maxTokens .* positive integer/)
  731. expect(() => new BasicCompactService(new Context(), { auto: false, compactionRetries: -1 }))
  732. .toThrow(/compactionRetries .* non-negative integer/)
  733. expect(() => new BasicCompactService(new Context(), { auto: false, summarizationModel: 1 } as unknown as BasicCompactConfig))
  734. .toThrow(/summarizationModel must be a string/)
  735. expect(() => new BasicCompactService(new Context(), { auto: 'no' } as unknown as BasicCompactConfig))
  736. .toThrow(/auto must be a boolean/)
  737. })
  738. it('accepts a large retain budget because convergence is enforced dynamically', () => {
  739. expect(() => new BasicCompactService(new Context(), {
  740. auto: false,
  741. contextWindow: 1000,
  742. thresholdRatio: 0.5,
  743. retainTokens: 900,
  744. })).not.toThrow()
  745. })
  746. it('the default config is valid', () => {
  747. expect(() => new BasicCompactService(new Context(), { auto: false })).not.toThrow()
  748. })
  749. })
  750. /** An adapter that emits a fixed summary text, for exercising the real summarize() path. */
  751. class ScriptedAdapter extends LlmAdapter {
  752. lastOptions: GenerateOptions | null = null
  753. constructor(private summaryText: string) {
  754. super()
  755. }
  756. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  757. this.lastOptions = options
  758. yield { type: 'block-start', index: 0, blockType: 'text' }
  759. yield { type: 'text-delta', index: 0, text: this.summaryText }
  760. yield { type: 'finish', reason: { kind: 'stop' } }
  761. }
  762. }
  763. /** An adapter that emits arbitrary content blocks, preserving reasoning/text shape. */
  764. class BlocksAdapter extends LlmAdapter {
  765. lastOptions: GenerateOptions | null = null
  766. constructor(private blocks: readonly ContentBlock[]) {
  767. super()
  768. }
  769. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  770. this.lastOptions = options
  771. for (const [index, block] of this.blocks.entries()) {
  772. yield { type: 'block-start', index, blockType: block.type }
  773. switch (block.type) {
  774. case 'text':
  775. yield { type: 'text-delta', index, text: block.text }
  776. break
  777. case 'reasoning':
  778. yield { type: 'reasoning-delta', index, text: block.text }
  779. break
  780. default:
  781. yield { type: 'block-end', index, block }
  782. }
  783. }
  784. yield { type: 'finish', reason: { kind: 'stop' } }
  785. }
  786. }
  787. /** Wire a real LlmService + arbitrary-block adapter into a context. */
  788. async function ctxWithBlocks(blocks: readonly ContentBlock[], model = 'test-model'): Promise<{ ctx: Context; adapter: BlocksAdapter }> {
  789. const ctx = new Context()
  790. await ctx.plugin(LlmService)
  791. const adapter = new BlocksAdapter(blocks)
  792. ctx.llm.registerAdapter([model], adapter)
  793. return { ctx, adapter }
  794. }
  795. /** Wire a real LlmService + scripted adapter into a context. */
  796. async function ctxWithModel(summaryText: string, model = 'test-model'): Promise<{ ctx: Context; adapter: ScriptedAdapter }> {
  797. const ctx = new Context()
  798. await ctx.plugin(LlmService)
  799. const adapter = new ScriptedAdapter(summaryText)
  800. ctx.llm.registerAdapter([model], adapter)
  801. return { ctx, adapter }
  802. }
  803. /** An adapter whose stream ends with a finish chunk of the given reason (no content). */
  804. class FinishOnlyAdapter extends LlmAdapter {
  805. constructor(private reason: StreamChunk & { type: 'finish' }) {
  806. super()
  807. }
  808. async * stream(): AsyncIterable<StreamChunk> {
  809. yield this.reason
  810. }
  811. }
  812. /** Wire a real LlmService + finish-only adapter into a context. */
  813. async function ctxWithFinish(reason: (StreamChunk & { type: 'finish' })['reason'], model = 'test-model'): Promise<Context> {
  814. const ctx = new Context()
  815. await ctx.plugin(LlmService)
  816. ctx.llm.registerAdapter([model], new FinishOnlyAdapter({ type: 'finish', reason }))
  817. return ctx
  818. }
  819. /** A minimal Agent stub carrying just session + options (enough for the listeners). */
  820. function stubAgent(session: Session, model?: string): Agent {
  821. return { session, options: { model } } as unknown as Agent
  822. }
  823. function compactIfNeeded(
  824. svc: BasicCompactService,
  825. session: Session,
  826. fullSystemPrompt: string,
  827. model: string,
  828. signal: AbortSignal,
  829. ) {
  830. return svc.compactIfNeeded(stubAgent(session, model), 1, 1, fullSystemPrompt, signal)
  831. }
  832. function compactRegion(
  833. svc: BasicCompactService,
  834. session: Session,
  835. start: number,
  836. end: number,
  837. model: string,
  838. signal?: AbortSignal,
  839. ) {
  840. return svc.compactRegion(session, start, end, stubAgent(session, model), 1, 1, signal)
  841. }
  842. function summarize(svc: BasicCompactService, text: string, model: string) {
  843. return svc.summarize(text, stubAgent(new Session(SessionId('summary')), model), 1, 1)
  844. }
  845. describe('BasicCompactService.summarize (real ctx.llm.stream)', () => {
  846. it('summarizes via the registered adapter and returns its content', async () => {
  847. const { ctx, adapter } = await ctxWithModel('SUMMARY TEXT')
  848. const svc = new BasicCompactService(ctx, { auto: false, maxTokens: 512 })
  849. const summary = await summarize(svc, 'User: hi\n\nAssistant: hello', 'test-model')
  850. expect(summary).toEqual([{ type: 'text', text: 'SUMMARY TEXT' }])
  851. // The fixed system prompt and maxTokens flow through.
  852. expect(adapter.lastOptions!.system).toContain('compaction engine')
  853. expect(adapter.lastOptions!.system).toContain('## Next Step')
  854. expect(adapter.lastOptions!.maxTokens).toBe(512)
  855. expect(adapter.lastOptions!.messages[0]!.content[0]).toMatchObject({ type: 'text' })
  856. })
  857. it('uses maxTokens as the summarization provider cap', async () => {
  858. const { ctx, adapter } = await ctxWithModel('SUMMARY TEXT')
  859. const svc = new BasicCompactService(ctx, {
  860. auto: false,
  861. maxTokens: 50,
  862. })
  863. await summarize(svc, 'User: hi', 'test-model')
  864. expect(adapter.lastOptions!.maxTokens).toBe(50)
  865. })
  866. it('keeps only text blocks in the stored summary (drops reasoning and tool-call)', async () => {
  867. const { ctx } = await ctxWithBlocks([
  868. { type: 'reasoning', text: 'private chain of thought' },
  869. { type: 'text', text: 'PUBLIC SUMMARY' },
  870. // A model reply can carry a tool-call; it must not survive into the
  871. // synthesized user/message summary as an orphaned call.
  872. { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{}' },
  873. ])
  874. const svc = new BasicCompactService(ctx, { auto: false })
  875. const summary = await summarize(svc, 'User: hi', 'test-model')
  876. expect(summary).toEqual([{ type: 'text', text: 'PUBLIC SUMMARY' }])
  877. })
  878. it('throws when no text block remains after filtering', async () => {
  879. const { ctx } = await ctxWithBlocks([{ type: 'reasoning', text: 'private only' }])
  880. const svc = new BasicCompactService(ctx, { auto: false })
  881. await expect(summarize(svc, 'User: hi', 'test-model')).rejects.toThrow(/no text summary content/)
  882. })
  883. it('throws when no model is provided', async () => {
  884. const { ctx } = await ctxWithModel('x')
  885. const svc = new BasicCompactService(ctx, { auto: false })
  886. await expect(summarize(svc, 'text', '')).rejects.toThrow(/no model available/)
  887. })
  888. it('rethrows when the stream ends with a finish-error chunk', async () => {
  889. const ctx = await ctxWithFinish({ kind: 'error', message: 'provider 401', code: 'UNAUTHORIZED' })
  890. const svc = new BasicCompactService(ctx, { auto: false })
  891. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ message: 'provider 401', code: 'UNAUTHORIZED' })
  892. })
  893. it('rethrows a finish-error chunk without a code (code stays undefined)', async () => {
  894. const ctx = await ctxWithFinish({ kind: 'error', message: 'opaque failure' })
  895. const svc = new BasicCompactService(ctx, { auto: false })
  896. const error = await summarize(svc, 'text', 'test-model').then(() => null, (e: unknown) => e as Error & { code?: string })
  897. expect(error?.message).toBe('opaque failure')
  898. expect(error?.code).toBeUndefined()
  899. })
  900. it('rethrows when the stream ends with a finish-aborted chunk', async () => {
  901. const ctx = await ctxWithFinish({ kind: 'aborted' })
  902. const svc = new BasicCompactService(ctx, { auto: false })
  903. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ message: 'summarization stream aborted', code: 'ABORTED' })
  904. })
  905. it('fails closed on a max-tokens finish (an incomplete checkpoint must not commit)', async () => {
  906. const ctx = await ctxWithFinish({ kind: 'max-tokens' })
  907. const svc = new BasicCompactService(ctx, { auto: false })
  908. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ code: 'MAX_TOKENS' })
  909. })
  910. it('compactRegion leaves the surface intact when summarization hits max-tokens', async () => {
  911. const ctx = await ctxWithFinish({ kind: 'max-tokens' })
  912. const svc = new BasicCompactService(ctx, { auto: false })
  913. const session = multiTurnSession(2, 1)
  914. const before = [...session.surface.nodes]
  915. const nodes = session.surface.nodes
  916. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model'))
  917. .rejects.toMatchObject({ code: 'MAX_TOKENS' })
  918. // No replacement landed — the surface is byte-identical, and the lock was
  919. // released with the error (compact/end carries it).
  920. expect(session.surface.nodes).toEqual(before)
  921. const endEvent = session.events.findLast(e => e.type === 'compact/end')!
  922. const endData = endEvent.data as { error?: string }
  923. expect(endData.error).toContain('truncated')
  924. })
  925. it('compactRegion uses the real summarizer end-to-end', async () => {
  926. const { ctx } = await ctxWithModel('CONDENSED')
  927. const svc = new BasicCompactService(ctx, { auto: false })
  928. const session = multiTurnSession(2, 1)
  929. const nodes = session.surface.nodes
  930. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  931. expect(result.summary).toEqual([{ type: 'text', text: 'CONDENSED' }])
  932. // The raw summary is wrapped in the checkpoint framing on the surface.
  933. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'CONDENSED' })
  934. })
  935. it('rejects a summary that is not smaller than the shadowed content', async () => {
  936. const svc = createTestService({ auto: false })
  937. const session = multiTurnSession(2, 1)
  938. const nodes = session.surface.nodes
  939. svc.mockSummary = Array.from({ length: 20 }, (_, index) => ({ type: 'text', text: `large ${index}` }))
  940. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  941. .rejects.toThrow(/summary is not smaller than the shadowed content/)
  942. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  943. })
  944. })
  945. describe('BasicCompactService auto-compaction (agent/pre-step listener)', () => {
  946. /** Fire the agent/pre-step serial checkpoint as the loop does. */
  947. function firePreStep(ctx: Context, agent: Agent, step: number, fullSystemPrompt: string): Promise<unknown> {
  948. return ctx.serial('agent/pre-step', agent, 1, step, fullSystemPrompt, SIGNAL)
  949. }
  950. it('compacts (mutating the surface) when over threshold', async () => {
  951. const { ctx } = await ctxWithModel('SUMMARY')
  952. void new BasicCompactService(ctx, { contextWindow: 200, thresholdRatio: 0.5, retainTokens: 20 })
  953. const session = multiTurnSession(5, 1) // 10 surface nodes
  954. const agent = stubAgent(session, 'test-model')
  955. const before = session.surface.nodes.length
  956. await firePreStep(ctx, agent, 1, '')
  957. // The surface shrank in place, and a summary checkpoint landed.
  958. expect(session.surface.nodes.length).toBeLessThan(before)
  959. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  960. // The re-derived head message is the framed summary checkpoint.
  961. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'SUMMARY' })
  962. })
  963. it('logs compaction details when auto-compaction returns a converged result', async () => {
  964. const ctx = new Context()
  965. const infos: string[] = []
  966. ctx.logger.info = ((msg: string) => void infos.push(msg)) as typeof ctx.logger.info
  967. void new TestCompactService(ctx, {
  968. contextWindow: 100,
  969. thresholdRatio: 0.7,
  970. retainTokens: 10,
  971. compactionRetries: 0,
  972. })
  973. const session = multiTurnSession(3, 1)
  974. const agent = stubAgent(session, 'test-model')
  975. await firePreStep(ctx, agent, 1, '')
  976. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(1)
  977. expect(infos.some(msg => msg.includes('compaction: shadowed'))).toBe(true)
  978. expect(infos.some(msg => msg.includes('estimated tokens after compaction'))).toBe(true)
  979. })
  980. it('compacts mid-turn on steps after the first (the surface grows within a turn)', async () => {
  981. const { ctx } = await ctxWithModel('SUMMARY')
  982. void new BasicCompactService(ctx, { contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 })
  983. const session = multiTurnSession(3, 1) // over the 0.5 threshold
  984. const agent = stubAgent(session, 'test-model')
  985. // A step-2 checkpoint (a tool-heavy turn's later step) must still compact —
  986. // the surface accumulated assistant/message + tool/result nodes since step 1.
  987. await firePreStep(ctx, agent, 2, '')
  988. expect(session.events.some(e => e.type === 'compact/start')).toBe(true)
  989. })
  990. it('does nothing when under threshold', async () => {
  991. const { ctx } = await ctxWithModel('SUMMARY')
  992. void new BasicCompactService(ctx, { contextWindow: 128000, thresholdRatio: 0.8 })
  993. const session = multiTurnSession(1, 1)
  994. const agent = stubAgent(session, 'test-model')
  995. await firePreStep(ctx, agent, 1, '')
  996. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  997. })
  998. it('leaves the surface intact when compaction fails (summarize rejects)', async () => {
  999. // No adapter registered for this model → summarize() rejects → caught, the
  1000. // surface is untouched (the loop derives the full history).
  1001. const ctx = new Context()
  1002. await ctx.plugin(LlmService)
  1003. void new BasicCompactService(ctx, { contextWindow: 300, thresholdRatio: 0.1, retainTokens: 10 })
  1004. const session = multiTurnSession(3, 1)
  1005. const agent = stubAgent(session, 'missing-model')
  1006. const before = session.surface.nodes.length
  1007. await firePreStep(ctx, agent, 1, '')
  1008. // No summary landed; the surface is unchanged.
  1009. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  1010. expect(session.surface.nodes.length).toBe(before)
  1011. })
  1012. it('does not register the listener when auto is false', async () => {
  1013. const { ctx } = await ctxWithModel('SUMMARY')
  1014. void new BasicCompactService(ctx, { auto: false, contextWindow: 100, thresholdRatio: 0.1, retainTokens: 5 })
  1015. const session = multiTurnSession(3, 1)
  1016. const agent = stubAgent(session, 'test-model')
  1017. await firePreStep(ctx, agent, 1, '')
  1018. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1019. })
  1020. it('routes summarization through agent/request so router agents can choose the model', async () => {
  1021. const { ctx, adapter } = await ctxWithModel('ROUTED SUMMARY', 'routed-model')
  1022. ctx.on('agent/request', async (_agent, _turn, _step, options, next) => {
  1023. options.model = 'routed-model'
  1024. return next()
  1025. })
  1026. void new BasicCompactService(ctx, { contextWindow: 200, thresholdRatio: 0.5, retainTokens: 20 })
  1027. const session = multiTurnSession(5, 1)
  1028. const agent = stubAgent(session)
  1029. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1030. expect(adapter.lastOptions?.model).toBe('routed-model')
  1031. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  1032. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'ROUTED SUMMARY' })
  1033. })
  1034. it('removes the auto pre-step listener when the plugin fiber is disposed', async () => {
  1035. const { ctx } = await ctxWithModel('SUMMARY')
  1036. const fiber = await ctx.plugin(BasicCompactService, {
  1037. contextWindow: 200,
  1038. thresholdRatio: 0.5,
  1039. retainTokens: 20,
  1040. })
  1041. const session = multiTurnSession(5, 1)
  1042. const agent = stubAgent(session, 'test-model')
  1043. await fiber.dispose()
  1044. await firePreStep(ctx, agent, 1, '')
  1045. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1046. expect(ctx.get('compact')).toBeUndefined()
  1047. })
  1048. })
  1049. describe('BasicCompactService._extractText branches', () => {
  1050. it('renders reasoning, context, and steering messages', async () => {
  1051. const svc = createTestService()
  1052. const s = new Session(SessionId('rich'))
  1053. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1054. s.append('step/start', { turn: 1, step: 1 })
  1055. s.append('context/message', {
  1056. content: [{ type: 'text', text: 'project context here' }],
  1057. source: { kind: 'user' },
  1058. }, { surfaceOp: 'append' })
  1059. s.append('assistant/message', {
  1060. turn: 1, step: 1,
  1061. content: [{ type: 'reasoning', text: 'thinking hard' }, { type: 'text', text: 'answer' }],
  1062. }, { surfaceOp: 'append' })
  1063. s.append('steering/message', {
  1064. turn: 1,
  1065. content: [{ type: 'text', text: 'steer this way' }],
  1066. source: { kind: 'user' },
  1067. }, { surfaceOp: 'append' })
  1068. s.append('step/end', { turn: 1, step: 1 })
  1069. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1070. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1071. const nodes = s.surface.nodes
  1072. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1073. const { text } = svc.summarizeCalls[0]!
  1074. expect(text).toContain('[Context: project context here]')
  1075. expect(text).toContain('[reasoning: thinking hard]')
  1076. expect(text).toContain('[Steering: steer this way]')
  1077. })
  1078. it('labels tool errors distinctly from tool results', async () => {
  1079. const svc = createTestService()
  1080. const s = new Session(SessionId('toolerr'))
  1081. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1082. s.append('step/start', { turn: 1, step: 1 })
  1083. s.append('user/message', { content: [{ type: 'text', text: 'run it' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1084. s.append('assistant/message', {
  1085. turn: 1, step: 1,
  1086. content: [{ type: 'tool-call', id: CallId('c9'), name: 'bash', arguments: '{}' }],
  1087. }, { surfaceOp: 'append' })
  1088. s.append('tool/call', { turn: 1, step: 1, callId: CallId('c9'), name: 'bash', arguments: '{}' })
  1089. s.append('tool/result', {
  1090. turn: 1, step: 1, callId: CallId('c9'),
  1091. content: [{ type: 'text', text: 'boom failure' }],
  1092. isError: true,
  1093. }, { surfaceOp: 'append' })
  1094. s.append('step/end', { turn: 1, step: 1 })
  1095. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1096. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1097. const nodes = s.surface.nodes
  1098. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1099. expect(svc.summarizeCalls[0]!.text).toContain('Tool error (call c9): boom failure')
  1100. })
  1101. })
  1102. describe('BasicCompactService edge cases', () => {
  1103. it('renders bare and nested tool-result placeholders and unknown blocks', async () => {
  1104. const svc = createTestService()
  1105. const s = new Session(SessionId('toolresult'))
  1106. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1107. s.append('step/start', { turn: 1, step: 1 })
  1108. // assistant/message carrying a nested tool-result block, an unknown block,
  1109. // and the tool-call that the following tool/result answers (so the surface
  1110. // is tool-pairing balanced).
  1111. s.append('assistant/message', {
  1112. turn: 1, step: 1,
  1113. content: [
  1114. { type: 'tool-result', toolCallId: CallId('n1'), content: [{ type: 'image', url: 'https://x/n.png' }] },
  1115. { type: 'custom-widget', payload: 'x' } as unknown as ContentBlock,
  1116. { type: 'tool-call', id: CallId('b1'), name: 'bash', arguments: '{}' },
  1117. ],
  1118. }, { surfaceOp: 'append' })
  1119. // tool/result whose content is itself only non-text → bare '[tool-result]'.
  1120. s.append('tool/call', { turn: 1, step: 1, callId: CallId('b1'), name: 'bash', arguments: '{}' })
  1121. s.append('tool/result', {
  1122. turn: 1, step: 1, callId: CallId('b1'),
  1123. content: [{ type: 'tool-result', toolCallId: CallId('inner'), content: [] }],
  1124. isError: false,
  1125. }, { surfaceOp: 'append' })
  1126. s.append('step/end', { turn: 1, step: 1 })
  1127. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1128. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1129. const nodes = s.surface.nodes
  1130. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1131. const { text } = svc.summarizeCalls[0]!
  1132. expect(text).toContain('[tool-result: [image]]') // nested tool-result with content
  1133. expect(text).toContain('[custom-widget]') // unknown block placeholder
  1134. expect(text).toContain('Tool result (call b1): [tool-result]') // empty nested → bare placeholder
  1135. })
  1136. it('estimates unknown block types via JSON length (default branch)', () => {
  1137. const svc = new BasicCompactService(new Context(), { auto: false })
  1138. // A block whose type is none of the known kinds — exercises the default arm.
  1139. const unknown = { type: 'custom-widget', payload: 'some data' } as unknown as ContentBlock
  1140. expect(svc.estimateContentTokens([unknown])).toBeGreaterThan(0)
  1141. })
  1142. it('auto-compaction reports bounded retry exhaustion after committing a smaller summary', async () => {
  1143. const { ctx } = await ctxWithModel('SUMMARY')
  1144. const warnings: string[] = []
  1145. ctx.logger.warn = ((msg: string) => void warnings.push(msg)) as typeof ctx.logger.warn
  1146. void new BasicCompactService(ctx, {
  1147. contextWindow: 300,
  1148. thresholdRatio: 0.1,
  1149. retainTokens: 5,
  1150. compactionRetries: 0,
  1151. })
  1152. const session = multiTurnSession(4, 1)
  1153. const agent = stubAgent(session, 'test-model')
  1154. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1155. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  1156. // The surface was mutated; the head message is the framed summary checkpoint.
  1157. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'SUMMARY' })
  1158. expect(warnings.some(w => w.includes('still above threshold after 1 compaction attempts'))).toBe(true)
  1159. })
  1160. it('rejects compaction when no turn is open (compaction events must be turn-enclosed)', async () => {
  1161. const svc = createTestService()
  1162. // A session whose only turn has CLOSED — scanning back from the tail hits
  1163. // turn/end before any turn/start, so there is no open turn to enclose
  1164. // compaction's compact/* + replacement events, which the log contract forbids.
  1165. const s = new Session(SessionId('noturn'))
  1166. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1167. s.append('step/start', { turn: 1, step: 1 })
  1168. s.append('user/message', { content: [{ type: 'text', text: 'orphan' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1169. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'reply' }] }, { surfaceOp: 'append' })
  1170. s.append('step/end', { turn: 1, step: 1 })
  1171. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1172. const nodes = s.surface.nodes
  1173. await expect(compactRegion(svc, s, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  1174. .rejects.toThrow(/no open turn/)
  1175. // The lock was never acquired — no compact/start landed.
  1176. expect(s.events.some(e => e.type === 'compact/start')).toBe(false)
  1177. })
  1178. it('rejects compaction on a session with no turn boundaries at all', async () => {
  1179. const svc = createTestService()
  1180. // No turn events whatsoever — the open-turn scan falls through to the end
  1181. // of the log and finds none, so compaction is rejected (its events have no
  1182. // turn to enclose them).
  1183. const s = new Session(SessionId('turnless'))
  1184. s.append('user/message', { content: [{ type: 'text', text: 'orphan' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1185. const nodes = s.surface.nodes
  1186. await expect(compactRegion(svc, s, nodes[0]!.seq, nodes[0]!.seq, 'm'))
  1187. .rejects.toThrow(/no open turn/)
  1188. expect(s.events.some(e => e.type === 'compact/start')).toBe(false)
  1189. })
  1190. it('compactIfNeeded returns null for empty surface even when over threshold', async () => {
  1191. const svc = createTestService({ contextWindow: 1000, thresholdRatio: 0.1, retainTokens: 5 })
  1192. const session = new Session(SessionId('empty-but-pressured'))
  1193. // No surface nodes, but a large system prompt pushes the estimate over threshold.
  1194. const bigPrompt = 'x'.repeat(800) // ceil(800/4) = 200 tokens >> threshold 100
  1195. expect(await compactIfNeeded(svc, session, bigPrompt, 'm', SIGNAL)).toBeNull()
  1196. })
  1197. it('compactRegion throws when end is not a surface node (start valid)', async () => {
  1198. const svc = createTestService()
  1199. const session = multiTurnSession(1, 1)
  1200. const nodes = session.surface.nodes
  1201. await expect(compactRegion(svc, session, nodes[0]!.seq, 9999, 'm'))
  1202. .rejects.toThrow(/end seq 9999 not found in surface/)
  1203. })
  1204. it('compactRegion stringifies a non-Error thrown by summarize', async () => {
  1205. const svc = createTestService()
  1206. // Throw a non-Error value to exercise the String(error) branch in the catch.
  1207. svc.summarizeError = 'plain string failure' as unknown as Error
  1208. const session = multiTurnSession(1, 1)
  1209. const nodes = session.surface.nodes
  1210. // Whole step (user → assistant): a step-aligned region that reaches summarize.
  1211. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')).rejects.toBe('plain string failure')
  1212. const endEvent = session.events.findLast(e => e.type === 'compact/end')!
  1213. expect(endEvent.data).toMatchObject({ error: 'plain string failure' })
  1214. })
  1215. it('auto-compaction listener stringifies a non-Error and proceeds', async () => {
  1216. const { ctx } = await ctxWithModel('SUMMARY')
  1217. const warnings: string[] = []
  1218. ctx.logger.warn = ((msg: string) => void warnings.push(msg)) as typeof ctx.logger.warn
  1219. const svc = new TestCompactService(ctx, { contextWindow: 300, thresholdRatio: 0.1, retainTokens: 10 })
  1220. svc.summarizeError = 'boom' as unknown as Error
  1221. const session = multiTurnSession(3, 1)
  1222. const agent = stubAgent(session, 'test-model')
  1223. const before = session.surface.nodes.length
  1224. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1225. // The failure was swallowed; the surface is untouched and a warning logged.
  1226. expect(session.surface.nodes.length).toBe(before)
  1227. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  1228. expect(warnings.some(w => w.includes('compaction failed: boom'))).toBe(true)
  1229. })
  1230. it('auto-compaction listener takes the result-null branch (nothing to compact)', async () => {
  1231. const { ctx } = await ctxWithModel('SUMMARY')
  1232. // A large system prompt pushes the listener's estimate over threshold, but
  1233. // retainTokens is huge so compactIfNeeded walks everything and returns null.
  1234. // threshold = floor(2000*0.1) = 200; invariant: 5 + 150 = 155 ≤ 200.
  1235. const svc = new TestCompactService(ctx, { contextWindow: 2000, thresholdRatio: 0.1, retainTokens: 150 })
  1236. const session = multiTurnSession(2, 1)
  1237. const agent = stubAgent(session, 'test-model')
  1238. const bigSystem = 'x'.repeat(900) // ceil(900/4)=225 > threshold 200
  1239. await ctx.serial('agent/pre-step', agent, 1, 1, bigSystem, SIGNAL)
  1240. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1241. expect(svc.summarizeCalls.length).toBe(0)
  1242. })
  1243. it('skips messages whose extracted text is empty across all kinds', async () => {
  1244. const svc = createTestService()
  1245. const s = new Session(SessionId('empties'))
  1246. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1247. // Step 1: an empty-text user, an empty-reasoning assistant with NO tool-call
  1248. // (balanced: nothing to answer), and empty context/steering — all extract to
  1249. // nothing and are skipped.
  1250. s.append('step/start', { turn: 1, step: 1 })
  1251. s.append('user/message', { content: [{ type: 'text', text: '' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1252. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'reasoning', text: '' }] }, { surfaceOp: 'append' })
  1253. s.append('context/message', { content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1254. s.append('steering/message', { turn: 1, content: [{ type: 'text', text: '' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1255. s.append('step/end', { turn: 1, step: 1 })
  1256. // Step 2: a tool exchange whose tool/result has empty content → empty
  1257. // extraction → skipped. The assistant carries the matching tool-call so the
  1258. // surface stays tool-pairing balanced; its text extracts to the tool-call
  1259. // placeholder (the one surviving line).
  1260. s.append('step/start', { turn: 1, step: 2 })
  1261. s.append('assistant/message', {
  1262. turn: 1, step: 2,
  1263. content: [{ type: 'tool-call', id: CallId('z1'), name: 'bash', arguments: '{}' }],
  1264. }, { surfaceOp: 'append' })
  1265. s.append('tool/call', { turn: 1, step: 2, callId: CallId('z1'), name: 'bash', arguments: '{}' })
  1266. s.append('tool/result', { turn: 1, step: 2, callId: CallId('z1'), content: [], isError: false }, { surfaceOp: 'append' })
  1267. s.append('step/end', { turn: 1, step: 2 })
  1268. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1269. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1270. const nodes = s.surface.nodes
  1271. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1272. // Every empty-content message (user text, empty reasoning, empty-content
  1273. // tool/result, empty context, empty steering) extracted to nothing and was
  1274. // skipped — the only surviving line is the assistant's tool-call (which a
  1275. // balanced surface requires to answer the tool/result).
  1276. expect(svc.summarizeCalls[0]!.text).toBe('Assistant: [tool-call: bash({})]')
  1277. })
  1278. it('renders non-text blocks as type-tagged placeholders across all message kinds', async () => {
  1279. const svc = createTestService()
  1280. const s = new Session(SessionId('placeholders'))
  1281. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1282. s.append('step/start', { turn: 1, step: 1 })
  1283. // user/message with only an image block → '[image]' placeholder.
  1284. s.append('user/message', { content: [{ type: 'image', url: 'https://x/y.png' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1285. // assistant/message with an image block AND the tool-call its tool/result
  1286. // answers (so the surface is tool-pairing balanced) → '[image]' placeholder.
  1287. s.append('assistant/message', {
  1288. turn: 1, step: 1,
  1289. content: [
  1290. { type: 'image', url: 'https://x/z.png' },
  1291. { type: 'tool-call', id: CallId('e1'), name: 'bash', arguments: '{}' },
  1292. ],
  1293. }, { surfaceOp: 'append' })
  1294. // tool/result with an image block → '[image]' placeholder.
  1295. s.append('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'bash', arguments: '{}' })
  1296. s.append('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [{ type: 'image', url: 'https://x/r.png' }], isError: false }, { surfaceOp: 'append' })
  1297. // context/message and steering/message with image content.
  1298. s.append('context/message', { content: [{ type: 'image', url: 'https://x/c.png' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1299. s.append('steering/message', { turn: 1, content: [{ type: 'image', url: 'https://x/s.png' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1300. s.append('step/end', { turn: 1, step: 1 })
  1301. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1302. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1303. const nodes = s.surface.nodes
  1304. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1305. const { text } = svc.summarizeCalls[0]!
  1306. // Every non-text block surfaces as a placeholder rather than being dropped.
  1307. expect(text).toContain('User: [image]')
  1308. expect(text).toContain('Assistant: [image]')
  1309. expect(text).toContain('Tool result (call e1): [image]')
  1310. expect(text).toContain('[Context: [image]]')
  1311. expect(text).toContain('[Steering: [image]]')
  1312. })
  1313. })
  1314. describe('BasicCompactService positional range (surface seqs are not monotonic after a replace)', () => {
  1315. it('compacts a second region after the first replace lands a high-seq summary at the head position', async () => {
  1316. // A replace inserts the new summary node (a high seq) AT the shadowed
  1317. // range's surface position, so the surface becomes
  1318. // [highSeqSummary, …olderRetainedLowerSeqs]. A second compaction over a
  1319. // range whose start node has a HIGHER seq than its end node must still
  1320. // succeed — the range is positional, not a numeric seq interval.
  1321. const svc = createTestService({ auto: false })
  1322. const session = multiTurnSession(4, 1)
  1323. // First compaction: shadow the two oldest surface nodes.
  1324. const nodes0 = session.surface.nodes
  1325. const first = await compactRegion(svc, session, nodes0[0]!.seq, nodes0[1]!.seq, 'm')
  1326. // The summary node now sits at the head with a seq HIGHER than the
  1327. // retained older nodes that follow it — the non-monotonic surface. (The
  1328. // head is the user/message replace node, appended after the compact/summary
  1329. // provenance event, so its seq is at least first.summarySeq.)
  1330. const nodes1 = session.surface.nodes
  1331. expect(nodes1[0]!.seq).toBeGreaterThanOrEqual(first.summarySeq)
  1332. expect(nodes1[0]!.seq).toBeGreaterThan(nodes1[1]!.seq)
  1333. // Second compaction: shadow [summary(head) … turn-2's step end]. The start
  1334. // seq (the head summary node) is GREATER than the end seq (an older retained
  1335. // node), so the range is a SURFACE-POSITION span, not a numeric seq interval.
  1336. // The end must land on a step boundary (turn-2's assistant message closes
  1337. // its step).
  1338. const startSeq = nodes1[0]!.seq
  1339. const endSeq = nodes1[2]!.seq
  1340. expect(startSeq).toBeGreaterThan(endSeq)
  1341. const second = await compactRegion(svc, session, startSeq, endSeq, 'm')
  1342. // Exactly the three nodes at surface positions [0..2] are shadowed, in
  1343. // surface order — the positional slice, regardless of their seq values.
  1344. expect(second.shadowedSeqs).toEqual([nodes1[0]!.seq, nodes1[1]!.seq, nodes1[2]!.seq])
  1345. // The surface still derives cleanly: a new head replace node + the rest.
  1346. const finalNodes = session.surface.nodes
  1347. expect(finalNodes[0]!.seq).toBeGreaterThanOrEqual(second.summarySeq)
  1348. expect(session.deriveMessages().length).toBe(finalNodes.length)
  1349. })
  1350. it('extracts the second-compaction transcript in surface order, not log-seq order', async () => {
  1351. const svc = createTestService({ auto: false })
  1352. const session = multiTurnSession(3, 1)
  1353. // First compaction shadows the oldest two surface nodes, landing a high-seq
  1354. // summary node at the head.
  1355. const n0 = session.surface.nodes
  1356. await compactRegion(svc, session, n0[0]!.seq, n0[1]!.seq, 'm')
  1357. // Second compaction spans [head summary … turn-2's step end]. The head's seq
  1358. // is higher than the older retained nodes' seqs, so a log-seq-order walk
  1359. // would emit the older messages BEFORE the checkpoint.
  1360. const n1 = session.surface.nodes
  1361. svc.summarizeCalls = []
  1362. await compactRegion(svc, session, n1[0]!.seq, n1[2]!.seq, 'm')
  1363. // The extracted transcript follows surface order: the checkpoint (head)
  1364. // first, then the older retained messages — matching deriveMessages().
  1365. const { text } = svc.summarizeCalls[0]!
  1366. const checkpointIdx = text.indexOf('compacted-summary')
  1367. const olderIdx = text.indexOf('turn 2 user')
  1368. expect(checkpointIdx).toBeGreaterThanOrEqual(0)
  1369. expect(olderIdx).toBeGreaterThan(checkpointIdx)
  1370. })
  1371. })
  1372. describe('BasicCompactService llm inject (real plugin-load path)', () => {
  1373. it('declares llm in static inject so a sibling fiber can resolve ctx.llm', () => {
  1374. // summarize() reads ctx.llm; the inject lets the cordis ctx proxy resolve a
  1375. // sibling LlmService when this service is mounted as its own plugin fiber.
  1376. // Asserting the declaration (and exercising the real mount below) guards the
  1377. // resolution that root-ctx unit tests cannot, since they share one fiber.
  1378. expect(BasicCompactService.inject).toContain('llm')
  1379. })
  1380. it('resolves ctx.llm and summarizes when mounted as a sibling plugin of LlmService', async () => {
  1381. const ctx = new Context()
  1382. await ctx.plugin(LlmService)
  1383. ctx.llm.registerAdapter(['test-model'], new ScriptedAdapter('CONDENSED'))
  1384. // Mount the service through its real plugin fiber (NOT new …(rootCtx)), so
  1385. // the sibling-fiber ctx.llm resolution actually exercises the inject.
  1386. const fiber = await ctx.plugin(BasicCompactService, { auto: false })
  1387. const svc = ctx.compact as BasicCompactService
  1388. const session = multiTurnSession(2, 1)
  1389. const nodes = session.surface.nodes
  1390. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  1391. expect(result.summary).toEqual([{ type: 'text', text: 'CONDENSED' }])
  1392. // Tear the fiber down so this test owns no leaked registration; the
  1393. // dedicated cleanup assertion lives in the "HMR safety" suite.
  1394. await fiber.dispose()
  1395. expect(ctx.get('compact')).toBeUndefined()
  1396. })
  1397. })
  1398. describe('BasicCompactService under the real invariants plugin', () => {
  1399. /**
  1400. * Drive compaction through a session whose `session/event` listeners include
  1401. * the real dev-mode invariants plugin (as a real app loads it via agent-core).
  1402. * The invariants throw on append, so a passing run proves the compaction
  1403. * sequence is contract-valid: every event is turn-enclosed, and the positional
  1404. * replace op is accepted even when the surface is no longer seq-ordered.
  1405. */
  1406. async function setup(): Promise<{ ctx: Context; session: Session; svc: BasicCompactService }> {
  1407. const ctx = new Context()
  1408. await ctx.plugin(SessionStore)
  1409. await ctx.plugin(Invariants, {})
  1410. await ctx.plugin(LlmService)
  1411. ctx.llm.registerAdapter(['test-model'], new ScriptedAdapter('CONDENSED'))
  1412. await ctx.plugin(BasicCompactService, { auto: false })
  1413. const session = ctx.sessions.create()
  1414. return { ctx, session, svc: ctx.compact as BasicCompactService }
  1415. }
  1416. /** Append one closed turn of [user, assistant] surface nodes via the store. */
  1417. function closedTurn(session: Session, turn: number): void {
  1418. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  1419. session.append('step/start', { turn, step: 1 })
  1420. session.append('user/message', { content: [{ type: 'text', text: `turn ${turn} user` }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1421. session.append('assistant/message', { turn, step: 1, content: [{ type: 'text', text: `turn ${turn} assistant` }] }, { surfaceOp: 'append' })
  1422. session.append('step/end', { turn, step: 1 })
  1423. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  1424. }
  1425. it('runs a turn-enclosed compaction whose positional replace the invariants accept', async () => {
  1426. const { session, svc } = await setup()
  1427. closedTurn(session, 1)
  1428. closedTurn(session, 2)
  1429. // Open turn 3, as the loop has when the auto-compaction listener fires.
  1430. session.append('turn/start', { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } })
  1431. const nodes = session.surface.nodes
  1432. // No invariant throws here: compact/* + the replacement are all in turn 3.
  1433. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  1434. expect(result.shadowedSeqs.length).toBe(2)
  1435. expect(session.surface.nodes[0]!.seq).toBeGreaterThan(session.surface.nodes[1]!.seq)
  1436. })
  1437. it('accepts a second compaction over the non-monotonic surface left by the first', async () => {
  1438. const { session, svc } = await setup()
  1439. closedTurn(session, 1)
  1440. closedTurn(session, 2)
  1441. closedTurn(session, 3)
  1442. session.append('turn/start', { turn: 4, trigger: { kind: 'message', source: { kind: 'user' } } })
  1443. const n0 = session.surface.nodes
  1444. await compactRegion(svc, session, n0[0]!.seq, n0[1]!.seq, 'test-model')
  1445. // Surface head now carries a higher seq than the older retained nodes. A
  1446. // second compaction spanning [head … a later closed-step end] must pass the
  1447. // invariants' positional replace check even though startSeq > endSeq.
  1448. const n1 = session.surface.nodes
  1449. expect(n1[0]!.seq).toBeGreaterThan(n1[2]!.seq)
  1450. const second = await compactRegion(svc, session, n1[0]!.seq, n1[2]!.seq, 'test-model')
  1451. expect(second.shadowedSeqs).toEqual([n1[0]!.seq, n1[1]!.seq, n1[2]!.seq])
  1452. })
  1453. })