compact-basic.spec.ts 83 KB

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