@vellumai/assistant 0.10.7-dev.202607082226.4246ddb → 0.10.7-dev.202607090051.7372e8a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/openapi.yaml +42 -0
  2. package/package.json +1 -1
  3. package/src/__tests__/attachments-store.test.ts +3 -1
  4. package/src/__tests__/compaction-direct.test.ts +47 -0
  5. package/src/__tests__/compaction-summary-head-persisted-count.test.ts +438 -0
  6. package/src/__tests__/compactor-fixed-boundary.test.ts +355 -0
  7. package/src/__tests__/compactor-low-watermark-cut.test.ts +8 -2
  8. package/src/__tests__/compactor-web-search-strip.test.ts +21 -4
  9. package/src/__tests__/context-window-manager-compact-retry.test.ts +118 -0
  10. package/src/__tests__/conversation-summarize-route.test.ts +452 -0
  11. package/src/__tests__/conversation-summarize-up-to.test.ts +736 -0
  12. package/src/__tests__/db-processing-resume-attempts-migration.test.ts +116 -0
  13. package/src/__tests__/interrupted-turn-reconciler.test.ts +133 -0
  14. package/src/__tests__/openai-provider.test.ts +11 -0
  15. package/src/__tests__/openrouter-provider-only.test.ts +11 -0
  16. package/src/__tests__/summarize-boundary.test.ts +167 -0
  17. package/src/__tests__/vercel-ai-gateway-provider.test.ts +12 -0
  18. package/src/cli/commands/plugins.ts +2 -1
  19. package/src/config/call-site-defaults.ts +5 -1
  20. package/src/config/default-profile-catalog.ts +4 -3
  21. package/src/config/feature-flag-registry.json +8 -0
  22. package/src/config/schemas/conversations.ts +1 -1
  23. package/src/context/compactor.ts +230 -38
  24. package/src/daemon/conversation-process.ts +45 -2
  25. package/src/daemon/conversation-runtime-assembly.ts +47 -0
  26. package/src/daemon/conversation.ts +152 -37
  27. package/src/daemon/interrupted-turn-reconciler.ts +134 -0
  28. package/src/daemon/lifecycle.ts +49 -17
  29. package/src/daemon/summarize-boundary.ts +62 -0
  30. package/src/persistence/conversation-crud.ts +48 -1
  31. package/src/persistence/migrations/322-add-processing-resume-attempts.ts +31 -0
  32. package/src/persistence/schema/conversations.ts +10 -0
  33. package/src/persistence/steps.ts +2 -0
  34. package/src/plugins/defaults/compaction/compact.ts +13 -0
  35. package/src/plugins/defaults/compaction/window-manager.ts +207 -43
  36. package/src/plugins/defaults/image-fallback/__tests__/vision-recovery.test.ts +268 -0
  37. package/src/plugins/defaults/image-fallback/hooks/post-model-call.ts +80 -0
  38. package/src/plugins/defaults/image-fallback/hooks/stop.ts +23 -0
  39. package/src/plugins/defaults/image-fallback/src/recovery-state.ts +49 -0
  40. package/src/plugins/defaults/image-fallback/src/vision-error.ts +19 -0
  41. package/src/plugins/defaults/index.ts +16 -6
  42. package/src/providers/__tests__/retry-callsite.test.ts +86 -0
  43. package/src/providers/openai/__tests__/chat-completions-provider-reasoning.test.ts +112 -0
  44. package/src/providers/openai/chat-completions-provider.ts +58 -6
  45. package/src/providers/retry.ts +22 -1
  46. package/src/runtime/routes/canned-message-complete.ts +82 -0
  47. package/src/runtime/routes/channel-metadata.ts +49 -0
  48. package/src/runtime/routes/conversation-management-routes.ts +147 -2
  49. package/src/runtime/routes/conversation-routes.ts +15 -125
package/openapi.yaml CHANGED
@@ -9303,6 +9303,48 @@ paths:
9303
9303
  - ok
9304
9304
  - updated
9305
9305
  additionalProperties: false
9306
+ /v1/conversations/summarize:
9307
+ post:
9308
+ operationId: conversations_summarize_post
9309
+ summary: Summarize a conversation up to a message
9310
+ description:
9311
+ Replace the conversation's context before the given message with a generated summary. The boundary snaps to
9312
+ the start of the turn containing beforeMessageId; that turn and everything after stay verbatim. Messages are
9313
+ never deleted.
9314
+ tags:
9315
+ - conversations
9316
+ requestBody:
9317
+ required: true
9318
+ content:
9319
+ application/json:
9320
+ schema:
9321
+ type: object
9322
+ properties:
9323
+ conversationId:
9324
+ type: string
9325
+ beforeMessageId:
9326
+ type: string
9327
+ description: Summarize all messages before this one
9328
+ required:
9329
+ - conversationId
9330
+ - beforeMessageId
9331
+ responses:
9332
+ "202":
9333
+ description: Successful response
9334
+ content:
9335
+ application/json:
9336
+ schema:
9337
+ type: object
9338
+ properties:
9339
+ accepted:
9340
+ type: boolean
9341
+ const: true
9342
+ conversationId:
9343
+ type: string
9344
+ required:
9345
+ - accepted
9346
+ - conversationId
9347
+ additionalProperties: false
9306
9348
  /v1/conversations/switch:
9307
9349
  post:
9308
9350
  operationId: conversations_switch_post
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.7-dev.202607082226.4246ddb",
3
+ "version": "0.10.7-dev.202607090051.7372e8a",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -192,6 +192,8 @@ describe("uploadAttachment", () => {
192
192
  expect(() => uploadAttachment("ok.txt", "text/plain", "AAA")).not.toThrow();
193
193
  });
194
194
 
195
+ // Inserting the 100 MB payload into SQLite can take several seconds on
196
+ // slow CI runners, so this test needs more than the default 5s timeout.
195
197
  test("accepts payload exactly at MAX_UPLOAD_BYTES", () => {
196
198
  // MAX_UPLOAD_BYTES (100 MB) is divisible by 3, so (MAX/3)*4 base64 chars
197
199
  // decodes to exactly MAX bytes with no padding.
@@ -201,7 +203,7 @@ describe("uploadAttachment", () => {
201
203
  expect(() =>
202
204
  uploadAttachment("exact.bin", "application/octet-stream", exactData),
203
205
  ).not.toThrow();
204
- });
206
+ }, 30_000);
205
207
  });
206
208
 
207
209
  // ---------------------------------------------------------------------------
@@ -143,4 +143,51 @@ describe("defaultCompact", () => {
143
143
  actorTrustClass: "guardian",
144
144
  });
145
145
  });
146
+
147
+ test("forwards fixedTailStartIndex to the manager", async () => {
148
+ // GIVEN a manager and a fixed-boundary compaction context
149
+ const observed = registerManager("conv-fixed", makeResult());
150
+
151
+ // WHEN defaultCompact runs with a fixed tail boundary
152
+ await defaultCompact({
153
+ conversationId: "conv-fixed",
154
+ messages: [] as never,
155
+ force: true,
156
+ fixedTailStartIndex: 4,
157
+ });
158
+
159
+ // THEN the manager received the boundary in its options bag
160
+ expect(observed).toHaveLength(1);
161
+ expect(observed[0]!.options).toEqual({
162
+ force: true,
163
+ fixedTailStartIndex: 4,
164
+ });
165
+ });
166
+
167
+ test("rejects overflowSignal combined with fixedTailStartIndex", async () => {
168
+ // GIVEN a manager that records any compaction entry point
169
+ const calls: string[] = [];
170
+ fakeContextWindowManagers.set("conv-conflict", {
171
+ maybeCompact: async () => {
172
+ calls.push("maybeCompact");
173
+ return makeResult();
174
+ },
175
+ recoverContextOverflow: async () => {
176
+ calls.push("recoverContextOverflow");
177
+ return makeResult();
178
+ },
179
+ });
180
+
181
+ // WHEN defaultCompact runs with both an overflow signal and a fixed boundary
182
+ // THEN the request is rejected before reaching the manager
183
+ await expect(
184
+ defaultCompact({
185
+ conversationId: "conv-conflict",
186
+ messages: [] as never,
187
+ overflowSignal: { actualTokens: 250_000, isInteractive: true },
188
+ fixedTailStartIndex: 4,
189
+ }),
190
+ ).rejects.toThrow(/mutually exclusive/);
191
+ expect(calls).toEqual([]);
192
+ });
146
193
  });
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Persisted-count accounting when a synthetic context-summary message heads
3
+ * the history.
4
+ *
5
+ * The summary head (minted by `createContextSummaryMessage` on reload/fork
6
+ * inheritance, or by a prior compaction pass in the same process) has no DB
7
+ * row, so `compactedPersistedMessages` must exclude it — otherwise every
8
+ * compaction over an already-summarized history advances the persisted
9
+ * `contextCompactedMessageCount` one row too far and silently drops the
10
+ * first kept message on the next reload.
11
+ *
12
+ * Runs the real compactor arithmetic through `ContextWindowManager` with a
13
+ * canned provider response — only the provider call is seeded.
14
+ */
15
+ import { describe, expect, mock, test } from "bun:test";
16
+
17
+ function makeLoggerStub(): Record<string, unknown> {
18
+ const stub: Record<string, unknown> = {};
19
+ for (const m of [
20
+ "info",
21
+ "warn",
22
+ "error",
23
+ "debug",
24
+ "trace",
25
+ "fatal",
26
+ "silent",
27
+ "child",
28
+ ]) {
29
+ stub[m] = m === "child" ? () => makeLoggerStub() : () => {};
30
+ }
31
+ return stub;
32
+ }
33
+
34
+ mock.module("../util/logger.js", () => ({
35
+ getLogger: () => makeLoggerStub(),
36
+ }));
37
+
38
+ mock.module("../daemon/conversation-registry.js", () => ({
39
+ findConversationOrSubagent: () => ({
40
+ systemPrompt: "you are a test assistant",
41
+ }),
42
+ }));
43
+
44
+ mock.module("../config/loader.js", () => ({
45
+ getConfig: () => ({
46
+ compaction: { enabled: true, autoThreshold: 0.7, prompt: null },
47
+ }),
48
+ }));
49
+
50
+ mock.module("../persistence/conversation-crud.js", () => ({
51
+ setConversationProcessingStartedAt: () => {},
52
+ isConversationProcessing: () => false,
53
+ getMessages: () => [],
54
+ }));
55
+
56
+ mock.module("../persistence/attachments-store.js", () => ({
57
+ getAttachmentMetadataForMessage: () => [],
58
+ getAttachmentContent: () => null,
59
+ }));
60
+
61
+ mock.module("../persistence/llm-request-log-store.js", () => ({
62
+ recordRequestLog: () => {},
63
+ }));
64
+
65
+ import {
66
+ ContextWindowManager,
67
+ createContextSummaryMessage,
68
+ } from "../plugins/defaults/compaction/window-manager.js";
69
+ import { repairHistory } from "../plugins/defaults/history-repair/terminal.js";
70
+ import type { Message, Provider } from "../providers/types.js";
71
+
72
+ function turnTimestamp(turn: number): string {
73
+ const minute = String(turn % 60).padStart(2, "0");
74
+ return `2026-05-21 (Thursday) 10:${minute}:00 -05:00 (America/Chicago)`;
75
+ }
76
+
77
+ function userTurn(turn: number, body: string): Message {
78
+ return {
79
+ role: "user",
80
+ content: [
81
+ {
82
+ type: "text",
83
+ text: `<turn_context>\ncurrent_time: ${turnTimestamp(
84
+ turn,
85
+ )}\n</turn_context>\n[U${turn}] ${body}`,
86
+ },
87
+ ],
88
+ };
89
+ }
90
+
91
+ function assistantTurn(turn: number, body: string): Message {
92
+ return {
93
+ role: "assistant",
94
+ content: [{ type: "text", text: `[A${turn}] ${body}` }],
95
+ };
96
+ }
97
+
98
+ /** Fixed-boundary responses carry no `<tail_start>` — the caller owns the cut. */
99
+ const FIXED_RESPONSE = `<compaction_result>
100
+ <summary>
101
+ Alice and Bob's earlier discussion, remembered in my own voice.
102
+ </summary>
103
+ <key_state>
104
+ - Nothing critical pending.
105
+ </key_state>
106
+ </compaction_result>`;
107
+
108
+ function responseWithTailStart(tailTurn: number, preview: string): string {
109
+ return `<compaction_result>
110
+ <summary>
111
+ Alice and Bob's earlier discussion, remembered in my own voice.
112
+ </summary>
113
+ <key_state>
114
+ - Nothing critical pending.
115
+ </key_state>
116
+ <tail_start timestamp="${turnTimestamp(tailTurn)}" preview="${preview}" />
117
+ </compaction_result>`;
118
+ }
119
+
120
+ /** Provider that answers each call with the next queued response. */
121
+ function makeProvider(responses: string[]): Provider {
122
+ const queue = [...responses];
123
+ return {
124
+ name: "mock-provider",
125
+ sendMessage: async () => {
126
+ const response = queue.shift();
127
+ if (response === undefined) {
128
+ throw new Error("Provider called more times than responses queued");
129
+ }
130
+ return {
131
+ content: [{ type: "text", text: response }],
132
+ model: "mock-model",
133
+ usage: { inputTokens: 100, outputTokens: 50 },
134
+ stopReason: "end_turn",
135
+ };
136
+ },
137
+ };
138
+ }
139
+
140
+ function buildManager(provider: Provider): ContextWindowManager {
141
+ return new ContextWindowManager({
142
+ provider,
143
+ config: {
144
+ enabled: true,
145
+ maxInputTokens: 200_000,
146
+ targetBudgetRatio: 0.3,
147
+ compactThreshold: 0.8,
148
+ summaryBudgetRatio: 0.05,
149
+ overflowRecovery: {
150
+ enabled: true,
151
+ safetyMarginRatio: 0.05,
152
+ maxAttempts: 3,
153
+ interactiveLatestTurnCompression: "summarize",
154
+ nonInteractiveLatestTurnCompression: "summarize",
155
+ },
156
+ },
157
+ conversationId: "conv-test",
158
+ });
159
+ }
160
+
161
+ /**
162
+ * The in-memory view of a conversation with 10 persisted rows whose first 3
163
+ * are already compacted: a rehydrated summary head followed by rows 3..9.
164
+ * History index = 1 + (row - 3); row 7 lives at index 5.
165
+ */
166
+ function historyWithSummaryHead(): Message[] {
167
+ return [
168
+ createContextSummaryMessage("Prior summary covering rows 0-2."),
169
+ userTurn(3, "Alice asks about onboarding"),
170
+ assistantTurn(4, "assistant replies"),
171
+ userTurn(5, "Alice follows up"),
172
+ assistantTurn(6, "assistant replies again"),
173
+ userTurn(7, "Alice changes topic"),
174
+ assistantTurn(8, "assistant answers the new topic"),
175
+ userTurn(9, "Alice wraps up"),
176
+ ];
177
+ }
178
+
179
+ describe("compactedPersistedMessages excludes the synthetic summary head", () => {
180
+ test("fixed boundary over a rehydrated summary head", async () => {
181
+ // GIVEN 10 persisted rows with contextCompactedMessageCount 3 and a
182
+ // summary head, and the user picking row 7 ("summarize up to here") —
183
+ // history index 5
184
+ const messages = historyWithSummaryHead();
185
+ const manager = buildManager(makeProvider([FIXED_RESPONSE]));
186
+
187
+ // WHEN the fixed-boundary pass runs
188
+ const result = await manager.maybeCompact(messages, undefined, {
189
+ fixedTailStartIndex: 5,
190
+ });
191
+
192
+ // THEN the head is folded into the summary but not counted as a DB row:
193
+ // the persisted count advances 3 → 3 + 4 = 7 (rows 3..6), never 8
194
+ expect(result.compacted).toBe(true);
195
+ expect(result.compactedMessages).toBe(5);
196
+ expect(result.compactedPersistedMessages).toBe(4);
197
+ expect(result.preservedTailMessages).toBe(3);
198
+ });
199
+
200
+ test("model-chosen tail over a rehydrated summary head", async () => {
201
+ // GIVEN the same history, compacting via the model-chosen `<tail_start>`
202
+ // pointing at row 7 (history index 5)
203
+ const messages = historyWithSummaryHead();
204
+ const manager = buildManager(
205
+ makeProvider([responseWithTailStart(7, "Alice changes topic")]),
206
+ );
207
+
208
+ // WHEN a forced auto-path pass runs
209
+ const result = await manager.maybeCompact(messages, undefined, {
210
+ force: true,
211
+ });
212
+
213
+ // THEN the shared arithmetic excludes the head on this path too
214
+ expect(result.compacted).toBe(true);
215
+ expect(result.compactedMessages).toBe(5);
216
+ expect(result.compactedPersistedMessages).toBe(4);
217
+ });
218
+
219
+ test("second in-process pass over a compaction-minted summary head", async () => {
220
+ // GIVEN a history already compacted once in this process — its head is
221
+ // the summary message the compactor itself minted, not a reload artifact
222
+ const manager = buildManager(
223
+ makeProvider([FIXED_RESPONSE, FIXED_RESPONSE]),
224
+ );
225
+ const first = await manager.maybeCompact(
226
+ historyWithSummaryHead(),
227
+ undefined,
228
+ { fixedTailStartIndex: 5 },
229
+ );
230
+ expect(first.compacted).toBe(true);
231
+ // [minted summary, row 7, row 8, row 9]
232
+ expect(first.messages.length).toBe(4);
233
+
234
+ // WHEN a second fixed-boundary pass cuts at row 9 (history index 3, a
235
+ // clean user boundary the tool-pairing walk leaves in place)
236
+ const second = await manager.maybeCompact(first.messages, undefined, {
237
+ fixedTailStartIndex: 3,
238
+ });
239
+
240
+ // THEN only rows 7-8 count as compacted-persisted — the minted head does not
241
+ expect(second.compacted).toBe(true);
242
+ expect(second.compactedMessages).toBe(3);
243
+ expect(second.compactedPersistedMessages).toBe(2);
244
+ });
245
+
246
+ test("repaired history — the structural marker catches a rebuilt rehydrated head", async () => {
247
+ // GIVEN the same rehydrated history after the per-turn history-repair
248
+ // pass, which copies content into fresh message wrappers — WeakSet
249
+ // identity is lost and only the `<context_summary>` marker remains
250
+ const { messages } = repairHistory(historyWithSummaryHead());
251
+ expect(messages.length).toBe(8);
252
+ const manager = buildManager(makeProvider([FIXED_RESPONSE]));
253
+
254
+ // WHEN a fixed-boundary pass runs over the repaired array
255
+ const result = await manager.maybeCompact(messages, undefined, {
256
+ fixedTailStartIndex: 5,
257
+ });
258
+
259
+ // THEN the head is still excluded from the persisted count
260
+ expect(result.compacted).toBe(true);
261
+ expect(result.compactedMessages).toBe(5);
262
+ expect(result.compactedPersistedMessages).toBe(4);
263
+ });
264
+
265
+ test("repaired history — a compactor-minted head is excluded on the next pass", async () => {
266
+ // GIVEN a history compacted once in this process, then run through
267
+ // history repair (the per-turn default) before the next compaction —
268
+ // the compactor-minted head must carry the structural marker or this
269
+ // pass counts it as a persisted row
270
+ const manager = buildManager(
271
+ makeProvider([FIXED_RESPONSE, FIXED_RESPONSE]),
272
+ );
273
+ const first = await manager.maybeCompact(
274
+ historyWithSummaryHead(),
275
+ undefined,
276
+ { fixedTailStartIndex: 5 },
277
+ );
278
+ expect(first.compacted).toBe(true);
279
+ const { messages: repaired } = repairHistory(first.messages);
280
+ // [minted summary, row 7, row 8, row 9] — alternating roles, no merges
281
+ expect(repaired.length).toBe(4);
282
+
283
+ // WHEN a second fixed-boundary pass cuts at row 9 (history index 3)
284
+ const second = await manager.maybeCompact(repaired, undefined, {
285
+ fixedTailStartIndex: 3,
286
+ });
287
+
288
+ // THEN only rows 7-8 count as compacted-persisted
289
+ expect(second.compacted).toBe(true);
290
+ expect(second.compactedMessages).toBe(3);
291
+ expect(second.compactedPersistedMessages).toBe(2);
292
+ });
293
+
294
+ test("fork-inherited prefix is not double-counted with the summary head", async () => {
295
+ // GIVEN a forked conversation whose seeded non-persisted prefix (2)
296
+ // already includes its inherited summary head
297
+ const messages: Message[] = [
298
+ createContextSummaryMessage("Inherited summary from the parent."),
299
+ assistantTurn(0, "inherited assistant context with no DB row"),
300
+ userTurn(1, "Alice's first persisted message"),
301
+ assistantTurn(2, "assistant replies"),
302
+ userTurn(3, "Alice follows up"),
303
+ assistantTurn(4, "assistant replies again"),
304
+ ];
305
+ const manager = buildManager(makeProvider([FIXED_RESPONSE]));
306
+ manager.seedNonPersistedPrefix(2);
307
+
308
+ // WHEN a fixed-boundary pass compacts past the whole inherited prefix
309
+ const result = await manager.maybeCompact(messages, undefined, {
310
+ fixedTailStartIndex: 4,
311
+ });
312
+
313
+ // THEN the prefix is subtracted once (the seed subsumes its own head):
314
+ // compactable = [summary, inherited, row, row] → 2 persisted rows
315
+ expect(result.compacted).toBe(true);
316
+ expect(result.compactedMessages).toBe(4);
317
+ expect(result.compactedPersistedMessages).toBe(2);
318
+ });
319
+
320
+ test("partially consumed fork prefix — a later pass counts minted head plus remaining seed", async () => {
321
+ // GIVEN a fork whose seeded 2-message prefix was only partially consumed:
322
+ // the first pass folds just the inherited summary head, leaving one
323
+ // seeded message behind a freshly minted head
324
+ const messages: Message[] = [
325
+ createContextSummaryMessage("Inherited summary from the parent."),
326
+ userTurn(0, "inherited user context with no DB row"),
327
+ userTurn(1, "Alice's first persisted message"),
328
+ assistantTurn(2, "assistant replies"),
329
+ userTurn(3, "Alice follows up"),
330
+ assistantTurn(4, "assistant replies again"),
331
+ ];
332
+ const manager = buildManager(
333
+ makeProvider([FIXED_RESPONSE, FIXED_RESPONSE]),
334
+ );
335
+ manager.seedNonPersistedPrefix(2);
336
+ // Cut at the inherited user message (index 1) — a user boundary the
337
+ // tool-pairing back-walk leaves in place
338
+ const first = await manager.maybeCompact(messages, undefined, {
339
+ fixedTailStartIndex: 1,
340
+ });
341
+ expect(first.compacted).toBe(true);
342
+ expect(first.compactedMessages).toBe(1);
343
+ expect(first.compactedPersistedMessages).toBe(0);
344
+ // [minted summary, inherited user message, rows 1-4]
345
+ expect(first.messages.length).toBe(6);
346
+
347
+ // WHEN a second pass compacts past both the minted head and the
348
+ // remaining seeded message (cut at row 3 — history index 4)
349
+ const second = await manager.maybeCompact(first.messages, undefined, {
350
+ fixedTailStartIndex: 4,
351
+ });
352
+
353
+ // THEN the non-persisted lead is minted head + remaining seed = 2, so
354
+ // exactly rows 1-2 count as persisted — a max() of the two spans would
355
+ // under-count the lead and drop a kept row on reload
356
+ expect(second.compacted).toBe(true);
357
+ expect(second.compactedMessages).toBe(4);
358
+ expect(second.compactedPersistedMessages).toBe(2);
359
+ });
360
+
361
+ test("a pass that compacts only the minted head leaves the remaining seed intact", async () => {
362
+ // GIVEN a fork in the disjoint regime — [minted head, remaining seed,
363
+ // rows] — with exactly one seeded message left
364
+ const messages: Message[] = [
365
+ createContextSummaryMessage("Inherited summary from the parent."),
366
+ userTurn(0, "inherited user context with no DB row"),
367
+ userTurn(1, "Alice's first persisted message"),
368
+ assistantTurn(2, "assistant replies"),
369
+ userTurn(3, "Alice follows up"),
370
+ assistantTurn(4, "assistant replies again"),
371
+ ];
372
+ const manager = buildManager(
373
+ makeProvider([FIXED_RESPONSE, FIXED_RESPONSE, FIXED_RESPONSE]),
374
+ );
375
+ manager.seedNonPersistedPrefix(2);
376
+ // First pass consumes the seed's inherited summary head, entering the
377
+ // disjoint regime with 1 seeded message behind a freshly minted head
378
+ const first = await manager.maybeCompact(messages, undefined, {
379
+ fixedTailStartIndex: 1,
380
+ });
381
+ expect(first.compacted).toBe(true);
382
+ expect(manager.nonPersistedPrefixCount).toBe(1);
383
+
384
+ // WHEN a pass compacts ONLY the minted head (cut at the seeded user
385
+ // message, history index 1) — no seed message is folded away
386
+ const second = await manager.maybeCompact(first.messages, undefined, {
387
+ fixedTailStartIndex: 1,
388
+ });
389
+
390
+ // THEN the head position is not charged against the seed
391
+ expect(second.compacted).toBe(true);
392
+ expect(second.compactedMessages).toBe(1);
393
+ expect(second.compactedPersistedMessages).toBe(0);
394
+ expect(manager.nonPersistedPrefixCount).toBe(1);
395
+
396
+ // AND the next pass still counts minted head + surviving seed as the
397
+ // non-persisted lead: compacting [head, seed, rows 1-2] (cut at row 3,
398
+ // history index 4) yields exactly 2 persisted rows — an over-consumed
399
+ // seed would report 3 and slice a kept row out on reload
400
+ const third = await manager.maybeCompact(second.messages, undefined, {
401
+ fixedTailStartIndex: 4,
402
+ });
403
+ expect(third.compacted).toBe(true);
404
+ expect(third.compactedMessages).toBe(4);
405
+ expect(third.compactedPersistedMessages).toBe(2);
406
+ expect(manager.nonPersistedPrefixCount).toBe(0);
407
+ });
408
+
409
+ test("emergency compaction over a rehydrated summary head", async () => {
410
+ // GIVEN a mid-turn overflow history led by a rehydrated summary head,
411
+ // with the last tool pair anchoring the emergency split at index 2
412
+ const messages: Message[] = [
413
+ createContextSummaryMessage("Prior summary covering rows 0-2."),
414
+ userTurn(3, "Alice asks for a command run"),
415
+ {
416
+ role: "assistant",
417
+ content: [{ type: "tool_use", id: "X", name: "Bash", input: {} }],
418
+ },
419
+ {
420
+ role: "user",
421
+ content: [{ type: "tool_result", tool_use_id: "X", content: "ok" }],
422
+ },
423
+ ];
424
+ // The emergency prompt requests no `<tail_start>` — the canned response
425
+ // mirrors a prompt-following model and must still parse.
426
+ const manager = buildManager(makeProvider([FIXED_RESPONSE]));
427
+
428
+ // WHEN emergency compaction runs
429
+ const result = await manager.emergencyCompact(messages, {
430
+ previousEstimatedInputTokens: 190_000,
431
+ });
432
+
433
+ // THEN the compacted prefix [head, row 3] counts one persisted row
434
+ expect(result.compacted).toBe(true);
435
+ expect(result.compactedMessages).toBe(2);
436
+ expect(result.compactedPersistedMessages).toBe(1);
437
+ });
438
+ });