compact-basic.spec.ts 83 KB

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