compact-basic.spec.ts 68 KB

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