compact-basic.spec.ts 87 KB

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