compact-basic.spec.ts 83 KB

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