compact-basic.spec.ts 81 KB

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