Skip to content

Commit 5000f32

Browse files
zw-xyskvincentkoc
andauthored
fix(compaction): annotate partial summaries with chunk order and source time range (#100684)
* fix(compaction): annotate partial summaries with chunk order and source time range labels In summarizeInStages, partial summaries are wrapped into synthetic AgentMessage objects before the final merge pass. Previously each synthetic message used Date.now() as its timestamp and no ordering metadata was embedded in the content. Since serializeConversation (in agent-core) only preserves text content and discards timestamps, the LLM merger could not distinguish which summary chunk represented older vs newer history, making the "PRIORITIZE recent context" merge instruction ineffective. Fix: 1. Embed a chronological label with source time range in each summary content text (e.g. "[Chunk 1 - oldest messages [2026-07-05 14:00]]"). 2. Extract actual timestamp ranges from original chunk messages via new extractChunkTimeRange() helper. 3. Assign ascending timestamps from a single Date.now() capture so relative order is preserved for code paths reading timestamp field. 4. Update test to verify merge messages receive the labels. 5. Add real behavior proof script (proof/issue-100636-chunk-labels.ts) with 10/10 verification checks. Fixes #100636 * fix(compaction): stabilize chunk time labels --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent c9abc75 commit 5000f32

2 files changed

Lines changed: 58 additions & 7 deletions

File tree

‎src/agents/compaction.identifier-preservation.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ vi.mock("./sessions/index.js", async () => {
1515

1616
const mockGenerateSummary = vi.mocked(agentSessions.generateSummary);
1717
type SummarizeInStagesInput = Parameters<typeof import("./compaction.js").summarizeInStages>[0];
18+
const MESSAGE_TIME_BASE_MS = Date.UTC(2026, 0, 1);
1819

1920
const { buildCompactionSummarizationInstructions, summarizeInStages } =
2021
await import("./compaction.js");
@@ -23,7 +24,7 @@ function makeMessage(index: number, size = 1200): AgentMessage {
2324
return {
2425
role: "user",
2526
content: `m${index}-${"x".repeat(size)}`,
26-
timestamp: index,
27+
timestamp: MESSAGE_TIME_BASE_MS + index * 60_000,
2728
};
2829
}
2930

@@ -113,6 +114,14 @@ describe("compaction identifier-preservation instructions", () => {
113114
"Preserve all opaque identifiers exactly as written",
114115
);
115116
}
117+
118+
type SyntheticMergeMessage = { role: "user"; content: string; timestamp: number };
119+
const mergeMessages = mockGenerateSummary.mock.calls[2]![0] as SyntheticMergeMessage[];
120+
expect(mergeMessages.map((message) => message.content)).toEqual([
121+
"[Chunk 1 — oldest messages [2026-01-01 00:01 — 2026-01-01 00:02 UTC]]\nsummary",
122+
"[Chunk 2 — most recent messages [2026-01-01 00:03 — 2026-01-01 00:04 UTC]]\nsummary",
123+
]);
124+
expect(mergeMessages[1]!.timestamp).toBe(mergeMessages[0]!.timestamp + 1);
116125
});
117126

118127
it("avoids duplicate additional-focus headers in split+merge path", async () => {

‎src/agents/compaction.ts‎

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
* Summarization and fallback helpers for transcript compaction.
33
*/
44
import type { AgentCompactionIdentifierPolicy } from "../config/types.agent-defaults.js";
5+
import { isAbortError } from "../infra/abort-signal.js";
56
import { formatErrorMessage } from "../infra/errors.js";
67
import { retryAsync } from "../infra/retry.js";
7-
import { isAbortError } from "../infra/abort-signal.js";
88
import { createSubsystemLogger } from "../logging/subsystem.js";
99
import {
1010
buildOversizedFallbackPlanWithWorker,
@@ -338,6 +338,31 @@ export async function summarizeWithFallback(params: {
338338
);
339339
}
340340

341+
/** Extracts a compact timestamp range from a chunk of messages for merge metadata. */
342+
function extractChunkTimeRange(chunk: AgentMessage[]): string {
343+
let earliest: number | undefined;
344+
let latest: number | undefined;
345+
for (const message of chunk) {
346+
const timestamp = message.timestamp;
347+
if (
348+
typeof timestamp !== "number" ||
349+
timestamp <= 0 ||
350+
!Number.isFinite(new Date(timestamp).getTime())
351+
) {
352+
continue;
353+
}
354+
earliest = earliest === undefined ? timestamp : Math.min(earliest, timestamp);
355+
latest = latest === undefined ? timestamp : Math.max(latest, timestamp);
356+
}
357+
if (earliest === undefined || latest === undefined) {
358+
return "";
359+
}
360+
const format = (timestamp: number) =>
361+
new Date(timestamp).toISOString().replace("T", " ").slice(0, 16);
362+
const range = earliest === latest ? format(earliest) : `${format(earliest)} — ${format(latest)}`;
363+
return ` [${range} UTC]`;
364+
}
365+
341366
/** Summarizes history in multiple stages when a single pass would be too large. */
342367
export async function summarizeInStages(params: {
343368
messages: AgentMessage[];
@@ -386,11 +411,28 @@ export async function summarizeInStages(params: {
386411
return partialSummaries[0];
387412
}
388413

389-
const summaryMessages: AgentMessage[] = partialSummaries.map((summary) => ({
390-
role: "user",
391-
content: summary,
392-
timestamp: Date.now(),
393-
}));
414+
// Capture once so timestamps are strictly monotonic across
415+
// all synthetic messages regardless of how long the map iteration takes.
416+
const now = Date.now();
417+
const summaryMessages: AgentMessage[] = partialSummaries.map((summary, index) => {
418+
// serializeConversation preserves content but not timestamps, so chronology
419+
// must be explicit in the text consumed by the merge model.
420+
const chunk = plan.chunks[index];
421+
const timeRange = extractChunkTimeRange(chunk);
422+
const label =
423+
index === 0
424+
? `[Chunk 1 — oldest messages${timeRange}]`
425+
: index === partialSummaries.length - 1
426+
? `[Chunk ${partialSummaries.length} — most recent messages${timeRange}]`
427+
: `[Chunk ${index + 1}/${partialSummaries.length}${timeRange}]`;
428+
return {
429+
role: "user",
430+
content: `${label}\n${summary}`,
431+
// Ascending timestamps preserve chronological order for any code
432+
// path that reads the AgentMessage timestamp field directly.
433+
timestamp: now - (partialSummaries.length - 1 - index),
434+
};
435+
});
394436

395437
const custom = params.customInstructions?.trim();
396438
const mergeInstructions = custom

0 commit comments

Comments
 (0)