compact-basic.spec.ts 87 KB

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