compact-basic.spec.ts 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  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<ContentBlock[]> {
  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
  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. // compact/* events are log-only — no surfaceOp (type system enforces this).
  372. const startRaw = startEvent as unknown as { surfaceOp?: unknown }
  373. expect(startRaw.surfaceOp).toBeUndefined()
  374. // The user/message carries the replace surfaceOp.
  375. const userMsg = events.findLast(e => e.type === 'user/message')!
  376. const surfaceUserMsg = userMsg as SurfaceEvent
  377. expect(surfaceUserMsg.surfaceOp).toEqual({ op: 'replace', start: firstSeq, end: secondSeq })
  378. expect(surfaceUserMsg.sourceEventSeqs).toContain(startEvent!.seq)
  379. expect(surfaceUserMsg.sourceEventSeqs).toContain(summaryEvent!.seq)
  380. expect(surfaceUserMsg.sourceEventSeqs).toContain(firstSeq)
  381. expect(surfaceUserMsg.sourceEventSeqs).toContain(secondSeq)
  382. // compact/end is appended AFTER the replacement (the lock brackets the whole
  383. // op), so the replacement cannot reference it — sourceEventSeqs may only
  384. // reference earlier seqs.
  385. expect(surfaceUserMsg.sourceEventSeqs).not.toContain(endEvent!.seq)
  386. expect(endEvent!.seq).toBeGreaterThan(userMsg.seq)
  387. // Surface now has: summary user/message + retained 4 nodes = 5 nodes.
  388. const newNodes = session.surface.nodes
  389. expect(newNodes.length).toBe(5)
  390. expect(newNodes[0]!.seq).toBe(userMsg.seq)
  391. // deriveMessages() produces the framed summary as a user-role message:
  392. // a checkpoint preamble + tag-wrapped summary blocks.
  393. const derived = session.deriveMessages()
  394. expect(derived.length).toBe(5)
  395. expect(derived[0]!.role).toBe('user')
  396. const framed = derived[0]!.content
  397. expect(framed[0]).toMatchObject({ type: 'text' })
  398. expect((framed[0] as { text: string }).text).toContain('<compacted-summary>')
  399. expect(framed).toContainEqual(svc.mockSummary[0])
  400. expect((framed[framed.length - 1] as { text: string }).text).toBe('</compacted-summary>')
  401. })
  402. it('throws when start or end are not surface nodes', async () => {
  403. const svc = createTestService()
  404. const session = multiTurnSession(1, 1)
  405. await expect(compactRegion(svc, session, 999, 1000, 'm'))
  406. .rejects.toThrow(/start seq 999 not found in surface/)
  407. })
  408. it('throws when start is positioned after end on the surface', async () => {
  409. const svc = createTestService()
  410. const session = multiTurnSession(2, 1)
  411. const nodes = session.surface.nodes
  412. await expect(compactRegion(svc, session, nodes[1]!.seq, nodes[0]!.seq, 'm'))
  413. .rejects.toThrow(/is after end seq .* on the surface/)
  414. })
  415. it('throws when compaction is already in progress', async () => {
  416. const svc = createTestService()
  417. const session = multiTurnSession(2, 1)
  418. const nodes = session.surface.nodes
  419. session.append('compact/start', { turn: 2 })
  420. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  421. .rejects.toThrow(/compaction already in progress/)
  422. })
  423. it('appends compact/end with error on summarize failure', async () => {
  424. const svc = createTestService()
  425. svc.summarizeError = new Error('model unavailable')
  426. const session = multiTurnSession(2, 1)
  427. const nodes = session.surface.nodes
  428. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  429. .rejects.toThrow('model unavailable')
  430. const endEvent = session.events.findLast(e => e.type === 'compact/end')
  431. expect(endEvent).toBeDefined()
  432. // multiTurnSession(2,…) closes turns 1-2 and leaves turn 3 open; compaction
  433. // stamps the open turn.
  434. expect(endEvent!.data).toMatchObject({ turn: 3, error: 'model unavailable' })
  435. // No replace-op user/message was appended (summarize failed).
  436. const userMsgsAfter = session.events.filter(e => e.type === 'user/message')
  437. const replaceMsgs = userMsgsAfter.filter((e) => {
  438. const se = e as unknown as { surfaceOp?: unknown }
  439. return se.surfaceOp !== undefined && typeof se.surfaceOp !== 'string'
  440. })
  441. expect(replaceMsgs.length).toBe(0)
  442. })
  443. it('extracts conversation text for summarization', async () => {
  444. const svc = createTestService()
  445. const session = multiTurnSession(1, 2)
  446. const nodes = session.surface.nodes
  447. await compactRegion(svc, session, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  448. expect(svc.summarizeCalls.length).toBe(1)
  449. const { text, model } = svc.summarizeCalls[0]!
  450. expect(model).toBe('m')
  451. expect(text).toContain('User: turn 1 user message 1')
  452. expect(text).toContain('Assistant: turn 1 assistant response 1')
  453. })
  454. it('frames the landed summary with a checkpoint preamble and tags, keeping raw provenance', async () => {
  455. const svc = createTestService()
  456. svc.mockSummary = [{ type: 'text', text: 'STRUCTURED SUMMARY' }]
  457. const session = multiTurnSession(3, 1)
  458. const nodes = session.surface.nodes
  459. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  460. // Provenance (compact/summary) carries the RAW, unframed summary.
  461. expect(result.summary).toEqual([{ type: 'text', text: 'STRUCTURED SUMMARY' }])
  462. const summaryEvent = session.events.findLast(e => e.type === 'compact/summary')!
  463. expect(summaryEvent.data).toMatchObject({ summary: [{ type: 'text', text: 'STRUCTURED SUMMARY' }] })
  464. // The landed surface node is framed: preamble + tag-wrapped summary.
  465. const landed = session.deriveMessages()[0]!.content
  466. expect((landed[0] as { text: string }).text).toContain('checkpoint')
  467. expect((landed[0] as { text: string }).text).toContain('<compacted-summary>')
  468. expect(landed).toContainEqual({ type: 'text', text: 'STRUCTURED SUMMARY' })
  469. expect((landed[landed.length - 1] as { text: string }).text).toBe('</compacted-summary>')
  470. })
  471. it('extracts tool-call and tool-result context', async () => {
  472. const svc = createTestService()
  473. const session = sessionWithTools()
  474. const nodes = session.surface.nodes
  475. const firstSeq = nodes[0]!.seq
  476. const lastSeq = nodes[nodes.length - 1]!.seq
  477. await compactRegion(svc, session, firstSeq, lastSeq, 'm')
  478. expect(svc.summarizeCalls.length).toBe(1)
  479. const { text } = svc.summarizeCalls[0]!
  480. expect(text).toContain('read file x')
  481. expect(text).toContain('bash')
  482. expect(text).toContain('Tool result')
  483. })
  484. })
  485. describe('BasicCompactService.compactIfNeeded', () => {
  486. it('returns null when tokens are under threshold', async () => {
  487. const svc = createTestService({ contextWindow: 128000, thresholdRatio: 0.8 })
  488. const session = multiTurnSession(1, 1)
  489. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  490. })
  491. it('compacts when tokens exceed threshold', async () => {
  492. const svc = createTestService({ contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 })
  493. const session = multiTurnSession(3, 1) // 6 surface nodes, 10 tokens each = 60
  494. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  495. expect(result).not.toBeNull()
  496. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  497. })
  498. it('returns the first compaction result when a zero-retry pass converges after the loop', async () => {
  499. // With compactionRetries=0 there is no next-loop threshold check after the
  500. // first mutation, so the success path is the post-loop `return result`.
  501. const svc = createTestService({
  502. contextWindow: 100,
  503. thresholdRatio: 0.7,
  504. retainTokens: 10,
  505. compactionRetries: 0,
  506. })
  507. const session = multiTurnSession(3, 1) // 6 derived messages = 84 estimated tokens.
  508. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  509. expect(result).not.toBeNull()
  510. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(1)
  511. expect(svc.estimateTokens(session.deriveMessages(), '')).toBeLessThan(70)
  512. })
  513. it('walks tail→head and retains nodes within token budget', async () => {
  514. const svc = createTestService({ contextWindow: 350, thresholdRatio: 0.2, retainTokens: 15 })
  515. const session = multiTurnSession(5, 1) // 10 surface nodes = ~100 tokens
  516. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  517. expect(result).not.toBeNull()
  518. const nodes = session.surface.nodes
  519. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  520. expect(result!.shadowedSeqs).not.toContain(nodes[nodes.length - 1]!.seq)
  521. })
  522. it('returns null when the whole surface fits the retain budget (over threshold by role/system overhead)', async () => {
  523. // threshold = floor(480*0.1) = 48. The 4 surface nodes weigh 10 each (raw 40
  524. // for the retention walk), but the derived estimate adds 4 role tokens per
  525. // message → 56 ≥ 48, so the threshold check passes and the walk runs. The
  526. // walk accumulates all 40 < retainTokens (45) without crossing the budget,
  527. // so keepFromIdx reaches 0 and compaction declines.
  528. const svc = createTestService({ contextWindow: 480, thresholdRatio: 0.1, retainTokens: 45 })
  529. const session = multiTurnSession(2, 1)
  530. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  531. })
  532. it('compacts a runaway turn: its early CLOSED steps summarize while recent steps stay verbatim', async () => {
  533. // The REGRESSION that motivated dropping turn-protection. A single in-flight
  534. // (open) turn has grown past the threshold on its own: several CLOSED steps,
  535. // each [assistant(tool-call), tool/result]. Retention is turn-agnostic, so
  536. // the turn's OWN early closed steps are eligible — they compact while the
  537. // recent tail stays verbatim, and the harness survives.
  538. //
  539. // On the OLD layer-2 code this test FAILS: the entire open turn was retained
  540. // verbatim (protectedIdx = first open-turn node = 0), so compactIfNeeded
  541. // returned null and shadowedSeqs would be empty — the runaway turn could
  542. // never compact and the next model call would overflow the window.
  543. const svc = createTestService({ contextWindow: 800, thresholdRatio: 0.1, retainTokens: 25 })
  544. const s = new Session(SessionId('runaway'))
  545. // ONE open turn with 5 closed steps; each step is [asst(tool-call), result].
  546. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  547. s.append('user/message', { content: [{ type: 'text', text: 'do a big multi-step task' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  548. for (let step = 1; step <= 5; step++) {
  549. s.append('step/start', { turn: 1, step })
  550. s.append('assistant/message', {
  551. turn: 1, step,
  552. content: [{ type: 'text', text: `step ${step}` }, { type: 'tool-call', id: CallId(`c${step}`), name: 'bash', arguments: '{}' }],
  553. }, { surfaceOp: 'append' })
  554. s.append('tool/call', { turn: 1, step, callId: CallId(`c${step}`), name: 'bash', arguments: '{}' })
  555. s.append('tool/result', { turn: 1, step, callId: CallId(`c${step}`), content: [{ type: 'text', text: `out ${step}` }], isError: false }, { surfaceOp: 'append' })
  556. s.append('step/end', { turn: 1, step })
  557. }
  558. // The turn stays OPEN (no turn/end) — the model is mid-turn, about to run
  559. // step 6. Surface: user + 5×[asst, result] = 11 nodes.
  560. const nodesBefore = s.surface.nodes.length
  561. expect(nodesBefore).toBe(11)
  562. const result = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  563. expect(result).not.toBeNull()
  564. // Early steps of the SAME open turn were shadowed (impossible under layer 2).
  565. expect(result!.shadowedSeqs.length).toBeGreaterThan(0)
  566. // The most-recent step's tool result is retained verbatim (still on surface).
  567. const lastResultSeq = s.events.findLast(e => e.type === 'tool/result')!.seq
  568. expect(result!.shadowedSeqs).not.toContain(lastResultSeq)
  569. expect(s.surface.nodes.some(n => n.seq === lastResultSeq)).toBe(true)
  570. // No orphaned tool-result survives (whole-step boundaries respected).
  571. expectNoOrphanToolResults(s.deriveMessages())
  572. })
  573. it('returns null for an empty surface', async () => {
  574. const svc = createTestService({ contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 })
  575. const session = new Session(SessionId('empty'))
  576. expect(await compactIfNeeded(svc, session, '', 'm', SIGNAL)).toBeNull()
  577. })
  578. it('compacts again after a prior summary node heads the surface (the summary stays eligible)', async () => {
  579. // After the first compaction lands a replacement summary node at the head,
  580. // a second compaction (still over threshold) re-consolidates it with newer
  581. // context — head-anchoring means the prior checkpoint is always re-included,
  582. // never stranded. retainTokens=25 leaves a couple of retained nodes after
  583. // the first compaction (so the surface is [summary, …retained], not just
  584. // [summary]).
  585. const svc = createTestService({ contextWindow: 800, thresholdRatio: 0.1, retainTokens: 25 })
  586. const s = multiTurnSession(4, 1) // turns 1-4 closed, turn 5 open (no surface yet)
  587. const first = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  588. expect(first).not.toBeNull()
  589. // The summary node now heads the surface with a fresh high seq.
  590. const summaryHeadSeq = s.surface.nodes[0]!.seq
  591. const turn5StartSeq = s.events.filter(e => e.type === 'turn/start').at(-1)!.seq
  592. expect(summaryHeadSeq).toBeGreaterThan(turn5StartSeq)
  593. // Append a verbatim node in the open turn (a step's output), still over
  594. // threshold, then compact again — the older summary + closed turns compact,
  595. // the fresh nodes are retained.
  596. s.append('step/start', { turn: 5, step: 1 })
  597. s.append('user/message', { content: [{ type: 'text', text: 'turn 5 work' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  598. s.append('assistant/message', { turn: 5, step: 1, content: [{ type: 'text', text: 'reply 5' }] }, { surfaceOp: 'append' })
  599. s.append('step/end', { turn: 5, step: 1 })
  600. const second = await compactIfNeeded(svc, s, '', 'm', SIGNAL)
  601. expect(second).not.toBeNull()
  602. expect(second!.shadowedSeqs.length).toBeGreaterThan(0)
  603. // The fresh open-turn nodes were NOT compacted.
  604. const turn5UserSeq = s.events.find(e => e.type === 'user/message' && e.data.content.some(b => b.type === 'text' && b.text === 'turn 5 work'))!.seq
  605. expect(second!.shadowedSeqs).not.toContain(turn5UserSeq)
  606. })
  607. it('re-compacts smaller summaries until the post-compaction surface drops below threshold', async () => {
  608. const svc = createTestService({
  609. contextWindow: 100,
  610. thresholdRatio: 0.5,
  611. retainTokens: 10,
  612. compactionRetries: 2,
  613. })
  614. svc.estimateFramedSummariesCheaply = false
  615. svc.mockSummaryQueue = [
  616. Array.from({ length: 4 }, (_, index) => ({ type: 'text', text: `first ${index}` })),
  617. [{ type: 'text', text: 'second' }],
  618. ]
  619. const session = multiTurnSession(4, 1)
  620. const result = await compactIfNeeded(svc, session, '', 'm', SIGNAL)
  621. expect(result).not.toBeNull()
  622. expect(svc.summarizeCalls).toHaveLength(2)
  623. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(2)
  624. expect(svc.estimateTokens(session.deriveMessages(), '')).toBeLessThan(50)
  625. })
  626. it('throws after the configured re-compaction attempts still leave the surface above threshold', async () => {
  627. const svc = createTestService({
  628. contextWindow: 100,
  629. thresholdRatio: 0.5,
  630. retainTokens: 10,
  631. compactionRetries: 1,
  632. })
  633. svc.estimateFramedSummariesCheaply = false
  634. svc.mockSummaryQueue = [
  635. Array.from({ length: 4 }, (_, index) => ({ type: 'text', text: `first ${index}` })),
  636. Array.from({ length: 3 }, (_, index) => ({ type: 'text', text: `second ${index}` })),
  637. ]
  638. const session = multiTurnSession(4, 1)
  639. await expect(compactIfNeeded(svc, session, '', 'm', SIGNAL))
  640. .rejects.toThrow(/still above threshold after 2 compaction attempts/)
  641. expect(svc.summarizeCalls).toHaveLength(2)
  642. })
  643. })
  644. describe('BasicCompactService replay equivalence', () => {
  645. it('produces identical deriveMessages() after seeding from compacted log', async () => {
  646. const svc = createTestService()
  647. const session = multiTurnSession(3, 1)
  648. const nodes = session.surface.nodes
  649. await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  650. const derived = session.deriveMessages()
  651. const replayed = new Session(SessionId('replay'), [...session.events])
  652. expect(replayed.deriveMessages()).toEqual(derived)
  653. })
  654. })
  655. describe('BasicCompactService blocking (compaction in progress)', () => {
  656. it('detects in-progress compaction from unmatched compact/start', async () => {
  657. const svc = createTestService()
  658. const session = multiTurnSession(1, 1)
  659. session.append('compact/start', { turn: 1 })
  660. const nodes = session.surface.nodes
  661. // Whole step (user → assistant) is a step-aligned region, so the call reaches
  662. // the in-progress check rather than being rejected for splitting a step.
  663. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  664. .rejects.toThrow(/compaction already in progress/)
  665. })
  666. it('allows compaction after compact/end is appended', async () => {
  667. const svc = createTestService()
  668. const session = multiTurnSession(2, 1)
  669. const nodes = session.surface.nodes
  670. session.append('compact/start', { turn: 1 })
  671. session.append('compact/end', { turn: 1 })
  672. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')
  673. expect(result).toBeDefined()
  674. })
  675. it('is not wedged by an orphaned compact/start from a prior (now-closed) turn', async () => {
  676. // A crash mid-compaction left a compact/start with no compact/end; the turn
  677. // it lived in was later closed (persistence repair appends turn/end). A
  678. // whole-log scan would treat that stale start as an active lock forever. The
  679. // scan is scoped to the current turn, so a NEW turn compacts normally.
  680. const svc = createTestService()
  681. const s = new Session(SessionId('stale-lock'))
  682. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  683. s.append('step/start', { turn: 1, step: 1 })
  684. s.append('user/message', { content: [{ type: 'text', text: 'turn 1' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  685. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'reply 1' }] }, { surfaceOp: 'append' })
  686. s.append('compact/start', { turn: 1 }) // ← orphaned: no matching compact/end
  687. s.append('step/end', { turn: 1, step: 1 })
  688. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) // repair closed the turn
  689. // A new open turn.
  690. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  691. const nodes = s.surface.nodes
  692. // The stale start is before the turn/end, so it is NOT seen as in-progress.
  693. const result = await compactRegion(svc, s, nodes[0]!.seq, nodes[1]!.seq, 'm')
  694. expect(result).toBeDefined()
  695. })
  696. })
  697. describe('BasicCompactService token estimation (char/4 heuristic)', () => {
  698. it('estimates text blocks with char/4 + overhead', () => {
  699. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  700. // 'this is a somewhat longer text block' = 36 → ceil(36/4)+4 = 13; 'short' = 5 → 2+4 = 6
  701. const blocks: ContentBlock[] = [
  702. { type: 'text', text: 'this is a somewhat longer text block' },
  703. { type: 'text', text: 'short' },
  704. ]
  705. expect(svc.estimateContentTokens(blocks)).toBe(19)
  706. })
  707. it('estimates reasoning blocks same as text', () => {
  708. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  709. // 'thinking about this...' = 22 → ceil(22/4)+4 = 10
  710. expect(svc.estimateContentTokens([{ type: 'reasoning', text: 'thinking about this...' }])).toBe(10)
  711. })
  712. it('estimates tool-call blocks from name + arguments', () => {
  713. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  714. // 'bash' = 4 → 1; '{"command":"ls"}' = 16 → 4; + 4 overhead = 9
  715. expect(svc.estimateContentTokens([
  716. { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{"command":"ls"}' },
  717. ])).toBe(9)
  718. })
  719. it('estimates tool-result blocks recursively', () => {
  720. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  721. // inner text 5 → 2+4 = 6; outer 6 + 4 overhead = 10
  722. expect(svc.estimateContentTokens([
  723. { type: 'tool-result', toolCallId: CallId('c1'), content: [{ type: 'text', text: 'hello' }], isError: false },
  724. ])).toBe(10)
  725. })
  726. it('returns 0 for empty content blocks', () => {
  727. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  728. expect(svc.estimateContentTokens([])).toBe(0)
  729. })
  730. it('honors a configured charsPerToken (fractional densities included)', () => {
  731. // 'this is a somewhat longer text block' = 36 chars.
  732. const blocks: ContentBlock[] = [{ type: 'text', text: 'this is a somewhat longer text block' }]
  733. // charsPerToken 2: ceil(36/2)+4 = 22 — a CJK-density config doubles the estimate.
  734. const dense = new BasicCompactService(new Context(), cfg({ auto: false, charsPerToken: 2 }))
  735. expect(dense.estimateContentTokens(blocks)).toBe(22)
  736. // Fractional density is legal: ceil(36/1.5)+4 = 28.
  737. const fractional = new BasicCompactService(new Context(), cfg({ auto: false, charsPerToken: 1.5 }))
  738. expect(fractional.estimateContentTokens(blocks)).toBe(28)
  739. // The system-prompt term scales with the same knob: 36-char prompt at density 2 → ceil(36/2) = 18.
  740. expect(dense.estimateTokens([], 'this is a somewhat longer text block')).toBe(18)
  741. })
  742. })
  743. describe('BasicCompactService HMR safety', () => {
  744. it('registers as ctx.compact', () => {
  745. const ctx = new Context()
  746. void new BasicCompactService(ctx, cfg({ auto: false }))
  747. expect(ctx.compact).toBeDefined()
  748. expect(ctx.compact).toBeInstanceOf(BasicCompactService)
  749. })
  750. it('disposing the plugin fiber unregisters ctx.compact', async () => {
  751. // Mount through the real plugin fiber (the Loader path), then dispose it and
  752. // confirm the service registration is torn down. LlmService is mounted first
  753. // so the service's `inject: ['llm']` resolves and the fiber activates. (The
  754. // sibling-fiber ctx.llm resolution this same setup also exercises is covered
  755. // under the "llm inject (real plugin-load path)" suite.)
  756. const ctx = new Context()
  757. await ctx.plugin(LlmService)
  758. const fiber = await ctx.plugin(BasicCompactService, cfg({ auto: false }))
  759. expect(ctx.get('compact')).toBeInstanceOf(BasicCompactService)
  760. await fiber.dispose()
  761. expect(ctx.get('compact')).toBeUndefined()
  762. })
  763. })
  764. describe('BasicCompactService config validation', () => {
  765. it('rejects invalid numeric config values', () => {
  766. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, contextWindow: 0 })))
  767. .toThrow(/contextWindow .* positive integer/)
  768. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, thresholdRatio: 0 }))).toThrow(/thresholdRatio .* \(0, 1\]/)
  769. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, thresholdRatio: 1.1 }))).toThrow(/thresholdRatio .* \(0, 1\]/)
  770. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, retainTokens: -1 })))
  771. .toThrow(/retainTokens .* non-negative integer/)
  772. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, maxTokens: 0 }))).toThrow(/maxTokens .* positive integer/)
  773. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, compactionRetries: -1 })))
  774. .toThrow(/compactionRetries .* non-negative integer/)
  775. expect(() => new BasicCompactService(
  776. new Context(), cfg({ auto: false, summarizationModel: 1 } as unknown as Partial<BasicCompactConfig>),
  777. )).toThrow(/summarizationModel must be a string/)
  778. expect(() => new BasicCompactService(new Context(), cfg({ auto: 'no' } as unknown as Partial<BasicCompactConfig>)))
  779. .toThrow(/auto must be a boolean/)
  780. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, charsPerToken: 0 })))
  781. .toThrow(/charsPerToken .* positive finite number/)
  782. expect(() => new BasicCompactService(new Context(), cfg({ auto: false, charsPerToken: Number.NaN })))
  783. .toThrow(/charsPerToken .* positive finite number/)
  784. })
  785. it('accepts a large retain budget because convergence is enforced dynamically', () => {
  786. expect(() => new BasicCompactService(new Context(), cfg({
  787. auto: false,
  788. contextWindow: 1000,
  789. thresholdRatio: 0.5,
  790. retainTokens: 900,
  791. }))).not.toThrow()
  792. })
  793. it('the default config is valid', () => {
  794. expect(() => new BasicCompactService(new Context(), cfg({ auto: false }))).not.toThrow()
  795. })
  796. })
  797. /** An adapter that emits a fixed summary text, for exercising the real summarize() path. */
  798. class ScriptedAdapter extends LlmAdapter {
  799. lastOptions: GenerateOptions | null = null
  800. constructor(private summaryText: string) {
  801. super()
  802. }
  803. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  804. this.lastOptions = options
  805. yield { type: 'block-start', index: 0, blockType: 'text' }
  806. yield { type: 'text-delta', index: 0, text: this.summaryText }
  807. yield { type: 'finish', reason: { kind: 'stop' } }
  808. }
  809. }
  810. /** An adapter that emits arbitrary content blocks, preserving reasoning/text shape. */
  811. class BlocksAdapter extends LlmAdapter {
  812. lastOptions: GenerateOptions | null = null
  813. constructor(private blocks: readonly ContentBlock[]) {
  814. super()
  815. }
  816. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  817. this.lastOptions = options
  818. for (const [index, block] of this.blocks.entries()) {
  819. yield { type: 'block-start', index, blockType: block.type }
  820. switch (block.type) {
  821. case 'text':
  822. yield { type: 'text-delta', index, text: block.text }
  823. break
  824. case 'reasoning':
  825. yield { type: 'reasoning-delta', index, text: block.text }
  826. break
  827. default:
  828. yield { type: 'block-end', index, block }
  829. }
  830. }
  831. yield { type: 'finish', reason: { kind: 'stop' } }
  832. }
  833. }
  834. /** Wire a real LlmService + arbitrary-block adapter into a context. */
  835. async function ctxWithBlocks(blocks: readonly ContentBlock[], model = 'test-model'): Promise<{ ctx: Context; adapter: BlocksAdapter }> {
  836. const ctx = new Context()
  837. await ctx.plugin(LlmService)
  838. const adapter = new BlocksAdapter(blocks)
  839. ctx.llm.registerAdapter([model], adapter)
  840. return { ctx, adapter }
  841. }
  842. /** Wire a real LlmService + scripted adapter into a context. */
  843. async function ctxWithModel(summaryText: string, model = 'test-model'): Promise<{ ctx: Context; adapter: ScriptedAdapter }> {
  844. const ctx = new Context()
  845. await ctx.plugin(LlmService)
  846. const adapter = new ScriptedAdapter(summaryText)
  847. ctx.llm.registerAdapter([model], adapter)
  848. return { ctx, adapter }
  849. }
  850. /** An adapter whose stream ends with a finish chunk of the given reason (no content). */
  851. class FinishOnlyAdapter extends LlmAdapter {
  852. constructor(private reason: StreamChunk & { type: 'finish' }) {
  853. super()
  854. }
  855. async * stream(): AsyncIterable<StreamChunk> {
  856. yield this.reason
  857. }
  858. }
  859. /** Wire a real LlmService + finish-only adapter into a context. */
  860. async function ctxWithFinish(reason: (StreamChunk & { type: 'finish' })['reason'], model = 'test-model'): Promise<Context> {
  861. const ctx = new Context()
  862. await ctx.plugin(LlmService)
  863. ctx.llm.registerAdapter([model], new FinishOnlyAdapter({ type: 'finish', reason }))
  864. return ctx
  865. }
  866. /** A minimal Agent stub carrying just session + options (enough for the listeners). */
  867. function stubAgent(session: Session, model?: string): Agent {
  868. return { session, options: { model } } as unknown as Agent
  869. }
  870. function compactIfNeeded(
  871. svc: BasicCompactService,
  872. session: Session,
  873. fullSystemPrompt: string,
  874. model: string,
  875. signal: AbortSignal,
  876. ) {
  877. return svc.compactIfNeeded(stubAgent(session, model), 1, 1, fullSystemPrompt, signal)
  878. }
  879. function compactRegion(
  880. svc: BasicCompactService,
  881. session: Session,
  882. start: number,
  883. end: number,
  884. model: string,
  885. signal?: AbortSignal,
  886. ) {
  887. return svc.compactRegion(session, start, end, stubAgent(session, model), 1, 1, signal)
  888. }
  889. function summarize(svc: BasicCompactService, text: string, model: string) {
  890. return svc.summarize(text, stubAgent(new Session(SessionId('summary')), model), 1, 1)
  891. }
  892. describe('BasicCompactService.summarize (real ctx.llm.stream)', () => {
  893. it('summarizes via the registered adapter and returns its content', async () => {
  894. const { ctx, adapter } = await ctxWithModel('SUMMARY TEXT')
  895. const svc = new BasicCompactService(ctx, cfg({ auto: false, maxTokens: 512 }))
  896. const summary = await summarize(svc, 'User: hi\n\nAssistant: hello', 'test-model')
  897. expect(summary).toEqual([{ type: 'text', text: 'SUMMARY TEXT' }])
  898. // The fixed system prompt and maxTokens flow through.
  899. expect(adapter.lastOptions!.system).toContain('compaction engine')
  900. expect(adapter.lastOptions!.system).toContain('## Next Step')
  901. expect(adapter.lastOptions!.maxTokens).toBe(512)
  902. expect(adapter.lastOptions!.sessionId).toBe(SessionId('summary'))
  903. expect(adapter.lastOptions!.messages[0]!.content[0]).toMatchObject({ type: 'text' })
  904. })
  905. it('uses maxTokens as the summarization provider cap', async () => {
  906. const { ctx, adapter } = await ctxWithModel('SUMMARY TEXT')
  907. const svc = new BasicCompactService(ctx, cfg({
  908. auto: false,
  909. maxTokens: 50,
  910. }))
  911. await summarize(svc, 'User: hi', 'test-model')
  912. expect(adapter.lastOptions!.maxTokens).toBe(50)
  913. })
  914. it('keeps only text blocks in the stored summary (drops reasoning and tool-call)', async () => {
  915. const { ctx } = await ctxWithBlocks([
  916. { type: 'reasoning', text: 'private chain of thought' },
  917. { type: 'text', text: 'PUBLIC SUMMARY' },
  918. // A model reply can carry a tool-call; it must not survive into the
  919. // synthesized user/message summary as an orphaned call.
  920. { type: 'tool-call', id: CallId('c1'), name: 'bash', arguments: '{}' },
  921. ])
  922. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  923. const summary = await summarize(svc, 'User: hi', 'test-model')
  924. expect(summary).toEqual([{ type: 'text', text: 'PUBLIC SUMMARY' }])
  925. })
  926. it('throws when no text block remains after filtering', async () => {
  927. const { ctx } = await ctxWithBlocks([{ type: 'reasoning', text: 'private only' }])
  928. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  929. await expect(summarize(svc, 'User: hi', 'test-model')).rejects.toThrow(/no text summary content/)
  930. })
  931. it('throws when no model is provided', async () => {
  932. const { ctx } = await ctxWithModel('x')
  933. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  934. await expect(summarize(svc, 'text', '')).rejects.toThrow(/no model available/)
  935. })
  936. it('rethrows when the stream ends with a finish-error chunk', async () => {
  937. const ctx = await ctxWithFinish({ kind: 'error', message: 'provider 401', code: 'UNAUTHORIZED' })
  938. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  939. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ message: 'provider 401', code: 'UNAUTHORIZED' })
  940. })
  941. it('rethrows a finish-error chunk without a code (code stays undefined)', async () => {
  942. const ctx = await ctxWithFinish({ kind: 'error', message: 'opaque failure' })
  943. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  944. const error = await summarize(svc, 'text', 'test-model').then(() => null, (e: unknown) => e as Error & { code?: string })
  945. expect(error?.message).toBe('opaque failure')
  946. expect(error?.code).toBeUndefined()
  947. })
  948. it('rethrows when the stream ends with a finish-aborted chunk', async () => {
  949. const ctx = await ctxWithFinish({ kind: 'aborted' })
  950. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  951. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ message: 'summarization stream aborted', code: 'ABORTED' })
  952. })
  953. it('fails closed on a max-tokens finish (an incomplete checkpoint must not commit)', async () => {
  954. const ctx = await ctxWithFinish({ kind: 'max-tokens' })
  955. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  956. await expect(summarize(svc, 'text', 'test-model')).rejects.toMatchObject({ code: 'MAX_TOKENS' })
  957. })
  958. it('compactRegion leaves the surface intact when summarization hits max-tokens', async () => {
  959. const ctx = await ctxWithFinish({ kind: 'max-tokens' })
  960. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  961. const session = multiTurnSession(2, 1)
  962. const before = [...session.surface.nodes]
  963. const nodes = session.surface.nodes
  964. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model'))
  965. .rejects.toMatchObject({ code: 'MAX_TOKENS' })
  966. // No replacement landed — the surface is byte-identical, and the lock was
  967. // released with the error (compact/end carries it).
  968. expect(session.surface.nodes).toEqual(before)
  969. const endEvent = session.events.findLast(e => e.type === 'compact/end')!
  970. const endData = endEvent.data as { error?: string }
  971. expect(endData.error).toContain('truncated')
  972. })
  973. it('compactRegion uses the real summarizer end-to-end', async () => {
  974. const { ctx } = await ctxWithModel('CONDENSED')
  975. const svc = new BasicCompactService(ctx, cfg({ auto: false }))
  976. const session = multiTurnSession(2, 1)
  977. const nodes = session.surface.nodes
  978. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  979. expect(result.summary).toEqual([{ type: 'text', text: 'CONDENSED' }])
  980. // The raw summary is wrapped in the checkpoint framing on the surface.
  981. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'CONDENSED' })
  982. })
  983. it('rejects a summary that is not smaller than the shadowed content', async () => {
  984. const svc = createTestService({ auto: false })
  985. const session = multiTurnSession(2, 1)
  986. const nodes = session.surface.nodes
  987. svc.mockSummary = Array.from({ length: 20 }, (_, index) => ({ type: 'text', text: `large ${index}` }))
  988. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  989. .rejects.toThrow(/summary is not smaller than the shadowed content/)
  990. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  991. })
  992. it('rejects when the framed checkpoint is not smaller than the shadowed content', async () => {
  993. const svc = createTestService({ auto: false })
  994. svc.estimateFramedSummariesCheaply = false
  995. const session = new Session(SessionId('framed-nonshrinking'))
  996. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  997. session.append('step/start', { turn: 1, step: 1 })
  998. session.append('user/message', { content: [{ type: 'text', text: 'tiny user' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  999. session.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'tiny assistant' }] }, { surfaceOp: 'append' })
  1000. session.append('step/end', { turn: 1, step: 1 })
  1001. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1002. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1003. const before = [...session.surface.nodes]
  1004. const nodes = session.surface.nodes
  1005. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  1006. .rejects.toThrow(/summary is not smaller than the shadowed content/)
  1007. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  1008. expect(session.surface.nodes).toEqual(before)
  1009. })
  1010. })
  1011. describe('BasicCompactService auto-compaction (agent/pre-step listener)', () => {
  1012. /** Fire the agent/pre-step serial checkpoint as the loop does. */
  1013. function firePreStep(ctx: Context, agent: Agent, step: number, fullSystemPrompt: string): Promise<unknown> {
  1014. return ctx.serial('agent/pre-step', agent, 1, step, fullSystemPrompt, SIGNAL)
  1015. }
  1016. it('compacts (mutating the surface) when over threshold', async () => {
  1017. const { ctx } = await ctxWithModel('SUMMARY')
  1018. void new BasicCompactService(ctx, cfg({ contextWindow: 200, thresholdRatio: 0.5, retainTokens: 20 }))
  1019. const session = multiTurnSession(5, 1) // 10 surface nodes
  1020. const agent = stubAgent(session, 'test-model')
  1021. const before = session.surface.nodes.length
  1022. await firePreStep(ctx, agent, 1, '')
  1023. // The surface shrank in place, and a summary checkpoint landed.
  1024. expect(session.surface.nodes.length).toBeLessThan(before)
  1025. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  1026. // The re-derived head message is the framed summary checkpoint.
  1027. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'SUMMARY' })
  1028. })
  1029. it('logs compaction details when auto-compaction returns a converged result', async () => {
  1030. const ctx = new Context()
  1031. const infos: string[] = []
  1032. ctx.logger.info = ((msg: string) => void infos.push(msg)) as typeof ctx.logger.info
  1033. void new TestCompactService(ctx, cfg({
  1034. contextWindow: 100,
  1035. thresholdRatio: 0.7,
  1036. retainTokens: 10,
  1037. compactionRetries: 0,
  1038. }))
  1039. const session = multiTurnSession(3, 1)
  1040. const agent = stubAgent(session, 'test-model')
  1041. await firePreStep(ctx, agent, 1, '')
  1042. expect(session.events.filter(e => e.type === 'compact/summary')).toHaveLength(1)
  1043. expect(infos.some(msg => msg.includes('compaction: shadowed'))).toBe(true)
  1044. expect(infos.some(msg => msg.includes('estimated tokens after compaction'))).toBe(true)
  1045. })
  1046. it('compacts mid-turn on steps after the first (the surface grows within a turn)', async () => {
  1047. const { ctx } = await ctxWithModel('SUMMARY')
  1048. void new BasicCompactService(ctx, cfg({ contextWindow: 100, thresholdRatio: 0.5, retainTokens: 10 }))
  1049. const session = multiTurnSession(3, 1) // over the 0.5 threshold
  1050. const agent = stubAgent(session, 'test-model')
  1051. // A step-2 checkpoint (a tool-heavy turn's later step) must still compact —
  1052. // the surface accumulated assistant/message + tool/result nodes since step 1.
  1053. await firePreStep(ctx, agent, 2, '')
  1054. expect(session.events.some(e => e.type === 'compact/start')).toBe(true)
  1055. })
  1056. it('does nothing when under threshold', async () => {
  1057. const { ctx } = await ctxWithModel('SUMMARY')
  1058. void new BasicCompactService(ctx, cfg({ contextWindow: 128000, thresholdRatio: 0.8 }))
  1059. const session = multiTurnSession(1, 1)
  1060. const agent = stubAgent(session, 'test-model')
  1061. await firePreStep(ctx, agent, 1, '')
  1062. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1063. })
  1064. it('leaves the surface intact when compaction fails (summarize rejects)', async () => {
  1065. // No adapter registered for this model → summarize() rejects → caught, the
  1066. // surface is untouched (the loop derives the full history).
  1067. const ctx = new Context()
  1068. await ctx.plugin(LlmService)
  1069. void new BasicCompactService(ctx, cfg({ contextWindow: 300, thresholdRatio: 0.1, retainTokens: 10 }))
  1070. const session = multiTurnSession(3, 1)
  1071. const agent = stubAgent(session, 'missing-model')
  1072. const before = session.surface.nodes.length
  1073. await firePreStep(ctx, agent, 1, '')
  1074. // No summary landed; the surface is unchanged.
  1075. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  1076. expect(session.surface.nodes.length).toBe(before)
  1077. })
  1078. it('does not register the listener when auto is false', async () => {
  1079. const { ctx } = await ctxWithModel('SUMMARY')
  1080. void new BasicCompactService(ctx, cfg({ auto: false, contextWindow: 100, thresholdRatio: 0.1, retainTokens: 5 }))
  1081. const session = multiTurnSession(3, 1)
  1082. const agent = stubAgent(session, 'test-model')
  1083. await firePreStep(ctx, agent, 1, '')
  1084. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1085. })
  1086. it('routes summarization through agent/request so router agents can choose the model', async () => {
  1087. const { ctx, adapter } = await ctxWithModel('ROUTED SUMMARY', 'routed-model')
  1088. ctx.on('agent/request', async (_agent, _turn, _step, options, next) => {
  1089. options.model = 'routed-model'
  1090. return next()
  1091. })
  1092. void new BasicCompactService(ctx, cfg({ contextWindow: 200, thresholdRatio: 0.5, retainTokens: 20 }))
  1093. const session = multiTurnSession(5, 1)
  1094. const agent = stubAgent(session)
  1095. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1096. expect(adapter.lastOptions?.model).toBe('routed-model')
  1097. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  1098. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'ROUTED SUMMARY' })
  1099. })
  1100. it('removes the auto pre-step listener when the plugin fiber is disposed', async () => {
  1101. const { ctx } = await ctxWithModel('SUMMARY')
  1102. const fiber = await ctx.plugin(BasicCompactService, cfg({
  1103. contextWindow: 200,
  1104. thresholdRatio: 0.5,
  1105. retainTokens: 20,
  1106. }))
  1107. const session = multiTurnSession(5, 1)
  1108. const agent = stubAgent(session, 'test-model')
  1109. await fiber.dispose()
  1110. await firePreStep(ctx, agent, 1, '')
  1111. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1112. expect(ctx.get('compact')).toBeUndefined()
  1113. })
  1114. })
  1115. describe('BasicCompactService._extractText branches', () => {
  1116. it('renders reasoning, context, and steering messages', async () => {
  1117. const svc = createTestService()
  1118. const s = new Session(SessionId('rich'))
  1119. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1120. s.append('step/start', { turn: 1, step: 1 })
  1121. s.append('context/message', {
  1122. content: [{ type: 'text', text: 'project context here' }],
  1123. source: { kind: 'user' },
  1124. }, { surfaceOp: 'append' })
  1125. s.append('assistant/message', {
  1126. turn: 1, step: 1,
  1127. content: [{ type: 'reasoning', text: 'thinking hard' }, { type: 'text', text: 'answer' }],
  1128. }, { surfaceOp: 'append' })
  1129. s.append('steering/message', {
  1130. turn: 1,
  1131. content: [{ type: 'text', text: 'steer this way' }],
  1132. source: { kind: 'user' },
  1133. }, { surfaceOp: 'append' })
  1134. s.append('step/end', { turn: 1, step: 1 })
  1135. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1136. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1137. const nodes = s.surface.nodes
  1138. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1139. const { text } = svc.summarizeCalls[0]!
  1140. expect(text).toContain('[Context: project context here]')
  1141. expect(text).toContain('[reasoning: thinking hard]')
  1142. expect(text).toContain('[Steering: steer this way]')
  1143. })
  1144. it('labels tool errors distinctly from tool results', async () => {
  1145. const svc = createTestService()
  1146. const s = new Session(SessionId('toolerr'))
  1147. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1148. s.append('step/start', { turn: 1, step: 1 })
  1149. s.append('user/message', { content: [{ type: 'text', text: 'run it' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1150. s.append('assistant/message', {
  1151. turn: 1, step: 1,
  1152. content: [{ type: 'tool-call', id: CallId('c9'), name: 'bash', arguments: '{}' }],
  1153. }, { surfaceOp: 'append' })
  1154. s.append('tool/call', { turn: 1, step: 1, callId: CallId('c9'), name: 'bash', arguments: '{}' })
  1155. s.append('tool/result', {
  1156. turn: 1, step: 1, callId: CallId('c9'),
  1157. content: [{ type: 'text', text: 'boom failure' }],
  1158. isError: true,
  1159. }, { surfaceOp: 'append' })
  1160. s.append('step/end', { turn: 1, step: 1 })
  1161. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1162. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1163. const nodes = s.surface.nodes
  1164. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1165. expect(svc.summarizeCalls[0]!.text).toContain('Tool error (call c9): boom failure')
  1166. })
  1167. })
  1168. describe('BasicCompactService edge cases', () => {
  1169. it('renders bare and nested tool-result placeholders and unknown blocks', async () => {
  1170. const svc = createTestService()
  1171. const s = new Session(SessionId('toolresult'))
  1172. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1173. s.append('step/start', { turn: 1, step: 1 })
  1174. // assistant/message carrying a nested tool-result block, an unknown block,
  1175. // and the tool-call that the following tool/result answers (so the surface
  1176. // is tool-pairing balanced).
  1177. s.append('assistant/message', {
  1178. turn: 1, step: 1,
  1179. content: [
  1180. { type: 'tool-result', toolCallId: CallId('n1'), content: [{ type: 'chart', data: 'x' } as unknown as ContentBlock] },
  1181. { type: 'custom-widget', payload: 'x' } as unknown as ContentBlock,
  1182. { type: 'tool-call', id: CallId('b1'), name: 'bash', arguments: '{}' },
  1183. ],
  1184. }, { surfaceOp: 'append' })
  1185. // tool/result whose content is itself only non-text → bare '[tool-result]'.
  1186. s.append('tool/call', { turn: 1, step: 1, callId: CallId('b1'), name: 'bash', arguments: '{}' })
  1187. s.append('tool/result', {
  1188. turn: 1, step: 1, callId: CallId('b1'),
  1189. content: [{ type: 'tool-result', toolCallId: CallId('inner'), content: [] }],
  1190. isError: false,
  1191. }, { surfaceOp: 'append' })
  1192. s.append('step/end', { turn: 1, step: 1 })
  1193. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1194. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1195. const nodes = s.surface.nodes
  1196. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1197. const { text } = svc.summarizeCalls[0]!
  1198. expect(text).toContain('[tool-result: [chart]]') // nested tool-result with content
  1199. expect(text).toContain('[custom-widget]') // unknown block placeholder
  1200. expect(text).toContain('Tool result (call b1): [tool-result]') // empty nested → bare placeholder
  1201. })
  1202. it('estimates unknown block types via JSON length (default branch)', () => {
  1203. const svc = new BasicCompactService(new Context(), cfg({ auto: false }))
  1204. // A block whose type is none of the known kinds — exercises the default arm.
  1205. const unknown = { type: 'custom-widget', payload: 'some data' } as unknown as ContentBlock
  1206. expect(svc.estimateContentTokens([unknown])).toBeGreaterThan(0)
  1207. })
  1208. it('auto-compaction reports bounded retry exhaustion after committing a smaller summary', async () => {
  1209. const { ctx } = await ctxWithModel('SUMMARY')
  1210. const warnings: string[] = []
  1211. ctx.logger.warn = ((msg: string) => void warnings.push(msg)) as typeof ctx.logger.warn
  1212. void new BasicCompactService(ctx, cfg({
  1213. contextWindow: 300,
  1214. thresholdRatio: 0.1,
  1215. retainTokens: 5,
  1216. compactionRetries: 0,
  1217. }))
  1218. const session = multiTurnSession(4, 1)
  1219. const agent = stubAgent(session, 'test-model')
  1220. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1221. expect(session.events.some(e => e.type === 'compact/summary')).toBe(true)
  1222. // The surface was mutated; the head message is the framed summary checkpoint.
  1223. expect(session.deriveMessages()[0]!.content).toContainEqual({ type: 'text', text: 'SUMMARY' })
  1224. expect(warnings.some(w => w.includes('still above threshold after 1 compaction attempts'))).toBe(true)
  1225. })
  1226. it('rejects compaction when no turn is open (compaction events must be turn-enclosed)', async () => {
  1227. const svc = createTestService()
  1228. // A session whose only turn has CLOSED — scanning back from the tail hits
  1229. // turn/end before any turn/start, so there is no open turn to enclose
  1230. // compaction's compact/* + replacement events, which the log contract forbids.
  1231. const s = new Session(SessionId('noturn'))
  1232. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1233. s.append('step/start', { turn: 1, step: 1 })
  1234. s.append('user/message', { content: [{ type: 'text', text: 'orphan' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1235. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'reply' }] }, { surfaceOp: 'append' })
  1236. s.append('step/end', { turn: 1, step: 1 })
  1237. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1238. const nodes = s.surface.nodes
  1239. await expect(compactRegion(svc, s, nodes[0]!.seq, nodes[1]!.seq, 'm'))
  1240. .rejects.toThrow(/no open turn/)
  1241. // The lock was never acquired — no compact/start landed.
  1242. expect(s.events.some(e => e.type === 'compact/start')).toBe(false)
  1243. })
  1244. it('rejects compaction on a session with no turn boundaries at all', async () => {
  1245. const svc = createTestService()
  1246. // No turn events whatsoever — the open-turn scan falls through to the end
  1247. // of the log and finds none, so compaction is rejected (its events have no
  1248. // turn to enclose them).
  1249. const s = new Session(SessionId('turnless'))
  1250. s.append('user/message', { content: [{ type: 'text', text: 'orphan' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1251. const nodes = s.surface.nodes
  1252. await expect(compactRegion(svc, s, nodes[0]!.seq, nodes[0]!.seq, 'm'))
  1253. .rejects.toThrow(/no open turn/)
  1254. expect(s.events.some(e => e.type === 'compact/start')).toBe(false)
  1255. })
  1256. it('compactIfNeeded returns null for empty surface even when over threshold', async () => {
  1257. const svc = createTestService({ contextWindow: 1000, thresholdRatio: 0.1, retainTokens: 5 })
  1258. const session = new Session(SessionId('empty-but-pressured'))
  1259. // No surface nodes, but a large system prompt pushes the estimate over threshold.
  1260. const bigPrompt = 'x'.repeat(800) // ceil(800/4) = 200 tokens >> threshold 100
  1261. expect(await compactIfNeeded(svc, session, bigPrompt, 'm', SIGNAL)).toBeNull()
  1262. })
  1263. it('compactRegion throws when end is not a surface node (start valid)', async () => {
  1264. const svc = createTestService()
  1265. const session = multiTurnSession(1, 1)
  1266. const nodes = session.surface.nodes
  1267. await expect(compactRegion(svc, session, nodes[0]!.seq, 9999, 'm'))
  1268. .rejects.toThrow(/end seq 9999 not found in surface/)
  1269. })
  1270. it('compactRegion stringifies a non-Error thrown by summarize', async () => {
  1271. const svc = createTestService()
  1272. // Throw a non-Error value to exercise the String(error) branch in the catch.
  1273. svc.summarizeError = 'plain string failure' as unknown as Error
  1274. const session = multiTurnSession(1, 1)
  1275. const nodes = session.surface.nodes
  1276. // Whole step (user → assistant): a step-aligned region that reaches summarize.
  1277. await expect(compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'm')).rejects.toBe('plain string failure')
  1278. const endEvent = session.events.findLast(e => e.type === 'compact/end')!
  1279. expect(endEvent.data).toMatchObject({ error: 'plain string failure' })
  1280. })
  1281. it('auto-compaction listener stringifies a non-Error and proceeds', async () => {
  1282. const { ctx } = await ctxWithModel('SUMMARY')
  1283. const warnings: string[] = []
  1284. ctx.logger.warn = ((msg: string) => void warnings.push(msg)) as typeof ctx.logger.warn
  1285. const svc = new TestCompactService(ctx, cfg({ contextWindow: 300, thresholdRatio: 0.1, retainTokens: 10 }))
  1286. svc.summarizeError = 'boom' as unknown as Error
  1287. const session = multiTurnSession(3, 1)
  1288. const agent = stubAgent(session, 'test-model')
  1289. const before = session.surface.nodes.length
  1290. await ctx.serial('agent/pre-step', agent, 1, 1, '', SIGNAL)
  1291. // The failure was swallowed; the surface is untouched and a warning logged.
  1292. expect(session.surface.nodes.length).toBe(before)
  1293. expect(session.events.some(e => e.type === 'compact/summary')).toBe(false)
  1294. expect(warnings.some(w => w.includes('compaction failed: boom'))).toBe(true)
  1295. })
  1296. it('auto-compaction listener takes the result-null branch (nothing to compact)', async () => {
  1297. const { ctx } = await ctxWithModel('SUMMARY')
  1298. // A large system prompt pushes the listener's estimate over threshold, but
  1299. // retainTokens is huge so compactIfNeeded walks everything and returns null.
  1300. // threshold = floor(2000*0.1) = 200; invariant: 5 + 150 = 155 ≤ 200.
  1301. const svc = new TestCompactService(ctx, cfg({ contextWindow: 2000, thresholdRatio: 0.1, retainTokens: 150 }))
  1302. const session = multiTurnSession(2, 1)
  1303. const agent = stubAgent(session, 'test-model')
  1304. const bigSystem = 'x'.repeat(900) // ceil(900/4)=225 > threshold 200
  1305. await ctx.serial('agent/pre-step', agent, 1, 1, bigSystem, SIGNAL)
  1306. expect(session.events.some(e => e.type === 'compact/start')).toBe(false)
  1307. expect(svc.summarizeCalls.length).toBe(0)
  1308. })
  1309. it('skips messages whose extracted text is empty across all kinds', async () => {
  1310. const svc = createTestService()
  1311. const s = new Session(SessionId('empties'))
  1312. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1313. // Step 1: an empty-text user, an empty-reasoning assistant with NO tool-call
  1314. // (balanced: nothing to answer), and empty context/steering — all extract to
  1315. // nothing and are skipped.
  1316. s.append('step/start', { turn: 1, step: 1 })
  1317. s.append('user/message', { content: [{ type: 'text', text: '' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1318. s.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'reasoning', text: '' }] }, { surfaceOp: 'append' })
  1319. s.append('context/message', { content: [], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1320. s.append('steering/message', { turn: 1, content: [{ type: 'text', text: '' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1321. s.append('step/end', { turn: 1, step: 1 })
  1322. // Step 2: a tool exchange whose tool/result has empty content → empty
  1323. // extraction → skipped. The assistant carries the matching tool-call so the
  1324. // surface stays tool-pairing balanced; its text extracts to the tool-call
  1325. // placeholder (the one surviving line).
  1326. s.append('step/start', { turn: 1, step: 2 })
  1327. s.append('assistant/message', {
  1328. turn: 1, step: 2,
  1329. content: [{ type: 'tool-call', id: CallId('z1'), name: 'bash', arguments: '{}' }],
  1330. }, { surfaceOp: 'append' })
  1331. s.append('tool/call', { turn: 1, step: 2, callId: CallId('z1'), name: 'bash', arguments: '{}' })
  1332. s.append('tool/result', { turn: 1, step: 2, callId: CallId('z1'), content: [], isError: false }, { surfaceOp: 'append' })
  1333. s.append('step/end', { turn: 1, step: 2 })
  1334. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1335. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1336. const nodes = s.surface.nodes
  1337. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1338. // Every empty-content message (user text, empty reasoning, empty-content
  1339. // tool/result, empty context, empty steering) extracted to nothing and was
  1340. // skipped — the only surviving line is the assistant's tool-call (which a
  1341. // balanced surface requires to answer the tool/result).
  1342. expect(svc.summarizeCalls[0]!.text).toBe('Assistant: [tool-call: bash({})]')
  1343. })
  1344. it('renders non-text blocks as type-tagged placeholders across all message kinds', async () => {
  1345. const svc = createTestService()
  1346. const s = new Session(SessionId('placeholders'))
  1347. // A plugin-added block type (merge-extensible ContentBlockMap) — the
  1348. // placeholder path must cover every message kind, not just assistant.
  1349. const chart = (id: string): ContentBlock => ({ type: 'chart', data: id } as unknown as ContentBlock)
  1350. s.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  1351. s.append('step/start', { turn: 1, step: 1 })
  1352. // user/message with only a plugin-added block → '[chart]' placeholder.
  1353. s.append('user/message', { content: [chart('y')], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1354. // assistant/message with a plugin-added block AND the tool-call its
  1355. // tool/result answers (so the surface is tool-pairing balanced).
  1356. s.append('assistant/message', {
  1357. turn: 1, step: 1,
  1358. content: [
  1359. chart('z'),
  1360. { type: 'tool-call', id: CallId('e1'), name: 'bash', arguments: '{}' },
  1361. ],
  1362. }, { surfaceOp: 'append' })
  1363. // tool/result with a plugin-added block → '[chart]' placeholder.
  1364. s.append('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'bash', arguments: '{}' })
  1365. s.append('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [chart('r')], isError: false }, { surfaceOp: 'append' })
  1366. // context/message and steering/message with plugin-added content.
  1367. s.append('context/message', { content: [chart('c')], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1368. s.append('steering/message', { turn: 1, content: [chart('s')], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1369. s.append('step/end', { turn: 1, step: 1 })
  1370. s.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  1371. s.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  1372. const nodes = s.surface.nodes
  1373. await compactRegion(svc, s, nodes[0]!.seq, nodes[nodes.length - 1]!.seq, 'm')
  1374. const { text } = svc.summarizeCalls[0]!
  1375. // Every non-text block surfaces as a placeholder rather than being dropped.
  1376. expect(text).toContain('User: [chart]')
  1377. expect(text).toContain('Assistant: [chart]')
  1378. expect(text).toContain('Tool result (call e1): [chart]')
  1379. expect(text).toContain('[Context: [chart]]')
  1380. expect(text).toContain('[Steering: [chart]]')
  1381. })
  1382. })
  1383. describe('BasicCompactService positional range (surface seqs are not monotonic after a replace)', () => {
  1384. it('compacts a second region after the first replace lands a high-seq summary at the head position', async () => {
  1385. // A replace inserts the new summary node (a high seq) AT the shadowed
  1386. // range's surface position, so the surface becomes
  1387. // [highSeqSummary, …olderRetainedLowerSeqs]. A second compaction over a
  1388. // range whose start node has a HIGHER seq than its end node must still
  1389. // succeed — the range is positional, not a numeric seq interval.
  1390. const svc = createTestService({ auto: false })
  1391. const session = multiTurnSession(4, 1)
  1392. // First compaction: shadow the two oldest surface nodes.
  1393. const nodes0 = session.surface.nodes
  1394. const first = await compactRegion(svc, session, nodes0[0]!.seq, nodes0[1]!.seq, 'm')
  1395. // The summary node now sits at the head with a seq HIGHER than the
  1396. // retained older nodes that follow it — the non-monotonic surface. (The
  1397. // head is the user/message replace node, appended after the compact/summary
  1398. // provenance event, so its seq is at least first.summarySeq.)
  1399. const nodes1 = session.surface.nodes
  1400. expect(nodes1[0]!.seq).toBeGreaterThanOrEqual(first.summarySeq)
  1401. expect(nodes1[0]!.seq).toBeGreaterThan(nodes1[1]!.seq)
  1402. // Second compaction: shadow [summary(head) … turn-2's step end]. The start
  1403. // seq (the head summary node) is GREATER than the end seq (an older retained
  1404. // node), so the range is a SURFACE-POSITION span, not a numeric seq interval.
  1405. // The end must land on a step boundary (turn-2's assistant message closes
  1406. // its step).
  1407. const startSeq = nodes1[0]!.seq
  1408. const endSeq = nodes1[2]!.seq
  1409. expect(startSeq).toBeGreaterThan(endSeq)
  1410. const second = await compactRegion(svc, session, startSeq, endSeq, 'm')
  1411. // Exactly the three nodes at surface positions [0..2] are shadowed, in
  1412. // surface order — the positional slice, regardless of their seq values.
  1413. expect(second.shadowedSeqs).toEqual([nodes1[0]!.seq, nodes1[1]!.seq, nodes1[2]!.seq])
  1414. // The surface still derives cleanly: a new head replace node + the rest.
  1415. const finalNodes = session.surface.nodes
  1416. expect(finalNodes[0]!.seq).toBeGreaterThanOrEqual(second.summarySeq)
  1417. expect(session.deriveMessages().length).toBe(finalNodes.length)
  1418. })
  1419. it('extracts the second-compaction transcript in surface order, not log-seq order', async () => {
  1420. const svc = createTestService({ auto: false })
  1421. const session = multiTurnSession(3, 1)
  1422. // First compaction shadows the oldest two surface nodes, landing a high-seq
  1423. // summary node at the head.
  1424. const n0 = session.surface.nodes
  1425. await compactRegion(svc, session, n0[0]!.seq, n0[1]!.seq, 'm')
  1426. // Second compaction spans [head summary … turn-2's step end]. The head's seq
  1427. // is higher than the older retained nodes' seqs, so a log-seq-order walk
  1428. // would emit the older messages BEFORE the checkpoint.
  1429. const n1 = session.surface.nodes
  1430. svc.summarizeCalls = []
  1431. await compactRegion(svc, session, n1[0]!.seq, n1[2]!.seq, 'm')
  1432. // The extracted transcript follows surface order: the checkpoint (head)
  1433. // first, then the older retained messages — matching deriveMessages().
  1434. const { text } = svc.summarizeCalls[0]!
  1435. const checkpointIdx = text.indexOf('compacted-summary')
  1436. const olderIdx = text.indexOf('turn 2 user')
  1437. expect(checkpointIdx).toBeGreaterThanOrEqual(0)
  1438. expect(olderIdx).toBeGreaterThan(checkpointIdx)
  1439. })
  1440. })
  1441. describe('BasicCompactService llm inject (real plugin-load path)', () => {
  1442. it('declares llm in static inject so a sibling fiber can resolve ctx.llm', () => {
  1443. // summarize() reads ctx.llm; the inject lets the cordis ctx proxy resolve a
  1444. // sibling LlmService when this service is mounted as its own plugin fiber.
  1445. // Asserting the declaration (and exercising the real mount below) guards the
  1446. // resolution that root-ctx unit tests cannot, since they share one fiber.
  1447. expect(BasicCompactService.inject).toContain('llm')
  1448. })
  1449. it('resolves ctx.llm and summarizes when mounted as a sibling plugin of LlmService', async () => {
  1450. const ctx = new Context()
  1451. await ctx.plugin(LlmService)
  1452. ctx.llm.registerAdapter(['test-model'], new ScriptedAdapter('CONDENSED'))
  1453. // Mount the service through its real plugin fiber (NOT new …(rootCtx)), so
  1454. // the sibling-fiber ctx.llm resolution actually exercises the inject.
  1455. const fiber = await ctx.plugin(BasicCompactService, cfg({ auto: false }))
  1456. const svc = ctx.compact as BasicCompactService
  1457. const session = multiTurnSession(2, 1)
  1458. const nodes = session.surface.nodes
  1459. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  1460. expect(result.summary).toEqual([{ type: 'text', text: 'CONDENSED' }])
  1461. // Tear the fiber down so this test owns no leaked registration; the
  1462. // dedicated cleanup assertion lives in the "HMR safety" suite.
  1463. await fiber.dispose()
  1464. expect(ctx.get('compact')).toBeUndefined()
  1465. })
  1466. })
  1467. describe('BasicCompactService under the real invariants plugin', () => {
  1468. /**
  1469. * Drive compaction through a session whose `session/event` listeners include
  1470. * the real dev-mode invariants plugin (as a real app loads it via agent-core).
  1471. * The invariants throw on append, so a passing run proves the compaction
  1472. * sequence is contract-valid: every event is turn-enclosed, and the positional
  1473. * replace op is accepted even when the surface is no longer seq-ordered.
  1474. */
  1475. async function setup(): Promise<{ ctx: Context; session: Session; svc: BasicCompactService }> {
  1476. const ctx = new Context()
  1477. await ctx.plugin(SessionStore)
  1478. await ctx.plugin(Invariants, {})
  1479. await ctx.plugin(LlmService)
  1480. ctx.llm.registerAdapter(['test-model'], new ScriptedAdapter('CONDENSED'))
  1481. await ctx.plugin(BasicCompactService, cfg({ auto: false }))
  1482. const session = ctx.sessions.create()
  1483. return { ctx, session, svc: ctx.compact as BasicCompactService }
  1484. }
  1485. /** Append one closed turn of [user, assistant] surface nodes via the store. */
  1486. function closedTurn(session: Session, turn: number): void {
  1487. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  1488. session.append('step/start', { turn, step: 1 })
  1489. session.append('user/message', { content: [{ type: 'text', text: `turn ${turn} user.${LONG_FIXTURE_TEXT}` }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  1490. session.append('assistant/message', { turn, step: 1, content: [{ type: 'text', text: `turn ${turn} assistant.${LONG_FIXTURE_TEXT}` }] }, { surfaceOp: 'append' })
  1491. session.append('step/end', { turn, step: 1 })
  1492. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  1493. }
  1494. it('runs a turn-enclosed compaction whose positional replace the invariants accept', async () => {
  1495. const { session, svc } = await setup()
  1496. closedTurn(session, 1)
  1497. closedTurn(session, 2)
  1498. // Open turn 3, as the loop has when the auto-compaction listener fires.
  1499. session.append('turn/start', { turn: 3, trigger: { kind: 'message', source: { kind: 'user' } } })
  1500. const nodes = session.surface.nodes
  1501. // No invariant throws here: compact/* + the replacement are all in turn 3.
  1502. const result = await compactRegion(svc, session, nodes[0]!.seq, nodes[1]!.seq, 'test-model')
  1503. expect(result.shadowedSeqs.length).toBe(2)
  1504. expect(session.surface.nodes[0]!.seq).toBeGreaterThan(session.surface.nodes[1]!.seq)
  1505. })
  1506. it('accepts a second compaction over the non-monotonic surface left by the first', async () => {
  1507. const { session, svc } = await setup()
  1508. closedTurn(session, 1)
  1509. closedTurn(session, 2)
  1510. closedTurn(session, 3)
  1511. session.append('turn/start', { turn: 4, trigger: { kind: 'message', source: { kind: 'user' } } })
  1512. const n0 = session.surface.nodes
  1513. await compactRegion(svc, session, n0[0]!.seq, n0[1]!.seq, 'test-model')
  1514. // Surface head now carries a higher seq than the older retained nodes. A
  1515. // second compaction spanning [head … a later closed-step end] must pass the
  1516. // invariants' positional replace check even though startSeq > endSeq.
  1517. const n1 = session.surface.nodes
  1518. expect(n1[0]!.seq).toBeGreaterThan(n1[2]!.seq)
  1519. const second = await compactRegion(svc, session, n1[0]!.seq, n1[2]!.seq, 'test-model')
  1520. expect(second.shadowedSeqs).toEqual([n1[0]!.seq, n1[1]!.seq, n1[2]!.seq])
  1521. })
  1522. })