compact-basic.spec.ts 70 KB

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