compact-basic.spec.ts 81 KB

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