compact-basic.spec.ts 88 KB

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