compact-basic.spec.ts 71 KB

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