compact-basic.spec.ts 83 KB

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