compact-basic.spec.ts 79 KB

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