Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI, bug] compaction: anchor summaries to kept-tail state and stop re-summarizing file lists (#2385)

Seth Karten27f32ddb7e99
diff --git a/packages/coding-agent/.changes/compaction-anchor-file-lists.md b/packages/coding-agent/.changes/compaction-anchor-file-lists.md
new file mode 100644
index 0000000000..4d32d740e5
--- /dev/null
+++ b/packages/coding-agent/.changes/compaction-anchor-file-lists.md
@@ -0,0 +1,2 @@
+- Fixed compaction summaries drifting behind the retained conversation: the summarizer now receives the newest kept-tail assistant text as a `<recent-state-anchor>` and the in-context `[compaction-summary]` prefix states that the retained messages below are authoritative.
+- Fixed compaction file lists compounding through repeated summaries: `<read-files>`/`<modified-files>` blocks are stripped from the previous summary before the update prompt (entry details plus the fresh append remain the single source), and the combined file lists are capped at 6000 characters, dropping read-only entries first.
diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts
index c3a0acafed..a8216fe6d2 100644
--- a/packages/coding-agent/src/core/compaction/compaction.ts
+++ b/packages/coding-agent/src/core/compaction/compaction.ts
@@ -26,6 +26,7 @@ import {
formatFileOperations,
SUMMARIZATION_SYSTEM_PROMPT,
serializeConversation,
+ stripFileListBlocks,
} from "./utils.js";
/** Details stored in CompactionEntry.details for file tracking */
export interface CompactionDetails {
@@ -520,6 +521,9 @@ export function buildSummarizationPrompt(customInstructions?: string, previousSu
/**
* Generate a summary of the conversation using the LLM.
* If previousSummary is provided, uses the update prompt to merge.
+ * If recentStateAnchor is provided (newest retained assistant text), the
+ * prompt marks it as the current state so the summary cannot lag behind the
+ * kept tail.
*/
export async function generateSummary(
currentMessages: AgentMessage[],
@@ -533,6 +537,7 @@ export async function generateSummary(
thinkingLevel?: ThinkingLevel,
retry?: ProviderRetryPolicy,
sessionId?: string,
+ recentStateAnchor?: string,
): Promise<SummarySlice> {
const maxTokens = Math.floor(0.8 * reserveTokens);
@@ -544,6 +549,9 @@ export async function generateSummary(
if (previousSummary) {
promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
}
+ if (recentStateAnchor) {
+ promptText += `<recent-state-anchor>\nNewest assistant message that stays retained below the summary. The conversation to summarize is older than this anchor; the retained messages below are authoritative, so treat this anchor, not the conversation above, as the current state.\n\n${recentStateAnchor}\n</recent-state-anchor>\n\n`;
+ }
promptText += basePrompt;
const summarizationMessages = [
@@ -590,8 +598,10 @@ export interface CompactionPreparation {
/** Whether this is a split turn (cut point in middle of turn) */
isSplitTurn: boolean;
tokensBefore: number;
- /** Summary from previous compaction, for iterative update */
+ /** Summary from previous compaction, for iterative update (file-list blocks stripped) */
previousSummary?: string;
+ /** Newest retained assistant text; anchors the summary to kept-tail state */
+ recentStateAnchor?: string;
/** File operations extracted from messagesToSummarize */
fileOps: FileOperations;
/** Compaction settions from settings.jsonl */
@@ -618,7 +628,10 @@ export function prepareCompaction(
let boundaryStart = 0;
if (prevCompactionIndex >= 0) {
const prevCompaction = pathEntries[prevCompactionIndex] as CompactionEntry;
- previousSummary = prevCompaction.summary;
+ // File-list blocks never reach the update prompt: they are re-appended
+ // mechanically below and compound when the model re-summarizes them.
+ const strippedSummary = stripFileListBlocks(prevCompaction.summary);
+ previousSummary = strippedSummary.length > 0 ? strippedSummary : undefined;
const firstKeptEntryIndex = pathEntries.findIndex((entry) => entry.id === prevCompaction.firstKeptEntryId);
boundaryStart = firstKeptEntryIndex >= 0 ? firstKeptEntryIndex : prevCompactionIndex + 1;
}
@@ -647,6 +660,11 @@ export function prepareCompaction(
}
}
+ // Recency anchor: the summarizer sees only messages before the cut, so its
+ // summary would describe pre-tail state. The newest retained assistant
+ // text is the state the next turn actually sees; pass it to the summarizer.
+ const recentStateAnchor = extractRecentStateAnchor(pathEntries, cutPoint.firstKeptEntryIndex, pathEntries.length);
+
// Avoid a compaction that would summarize no history.
if (messagesToSummarize.length === 0 && turnPrefixMessages.length === 0 && !previousSummary) {
return undefined;
@@ -666,10 +684,39 @@ export function prepareCompaction(
isSplitTurn: cutPoint.isSplitTurn,
tokensBefore,
previousSummary,
+ recentStateAnchor,
fileOps,
settings,
};
}
+
+/**
+ * Maximum characters kept from the retained tail for the recency anchor.
+ * The end of a message holds the newest state, so long text keeps its tail.
+ */
+const RECENT_STATE_ANCHOR_MAX_CHARS = 2000;
+
+/**
+ * Extract the newest retained assistant text (the recency anchor) from the
+ * kept tail [keptStart, keptEnd). Returns undefined when the tail has no
+ * assistant text; long text is tail-truncated to the anchor budget.
+ */
+function extractRecentStateAnchor(entries: SessionEntry[], keptStart: number, keptEnd: number): string | undefined {
+ for (let i = keptEnd - 1; i >= keptStart; i--) {
+ const msg = getMessageFromEntryForCompaction(entries[i]);
+ if (!msg || msg.role !== "assistant" || !("content" in msg) || !Array.isArray(msg.content)) continue;
+ const text = msg.content
+ .filter((block): block is { type: "text"; text: string } => block.type === "text")
+ .map((block) => block.text)
+ .join("\n")
+ .trim();
+ if (!text) continue;
+ return text.length > RECENT_STATE_ANCHOR_MAX_CHARS
+ ? text.slice(text.length - RECENT_STATE_ANCHOR_MAX_CHARS)
+ : text;
+ }
+ return undefined;
+}
const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
Summarize the prefix to provide context for the retained suffix:
@@ -716,6 +763,7 @@ export async function compact(
isSplitTurn,
tokensBefore,
previousSummary,
+ recentStateAnchor,
fileOps,
settings,
} = preparation;
@@ -739,6 +787,7 @@ export async function compact(
thinkingLevel,
retry,
sessionId,
+ recentStateAnchor,
),
)
: Promise.resolve<SummarySlice>({ summary: "No prior history." }),
@@ -772,6 +821,7 @@ export async function compact(
thinkingLevel,
retry,
sessionId,
+ recentStateAnchor,
),
);
slices.push(result);
diff --git a/packages/coding-agent/src/core/compaction/utils.ts b/packages/coding-agent/src/core/compaction/utils.ts
index aa811c8506..e953e617ac 100644
--- a/packages/coding-agent/src/core/compaction/utils.ts
+++ b/packages/coding-agent/src/core/compaction/utils.ts
@@ -79,10 +79,27 @@ function extractFileOpsFromToolResult(message: AgentMessage, fileOps: FileOperat
*/
const FILE_LIST_MAX_ENTRIES = 200;
+/**
+ * Maximum combined characters the two file blocks may add to a summary.
+ * Repeated compactions merge lists carried in the previous entry's details,
+ * so without a character cap the appended block grows without bound.
+ */
+const FILE_LIST_MAX_COMBINED_CHARS = 6000;
+
+function fileListChars(readFiles: string[], modifiedFiles: string[]): number {
+ let chars = 0;
+ for (const file of readFiles) chars += file.length + 1;
+ for (const file of modifiedFiles) chars += file.length + 1;
+ return chars;
+}
+
/**
* Compute final file lists from file operations.
* Returns readFiles (files only read, not modified) and modifiedFiles.
- * Both lists are capped at FILE_LIST_MAX_ENTRIES (sorted, then truncated).
+ * Both lists are capped at FILE_LIST_MAX_ENTRIES (sorted, then truncated) and
+ * at FILE_LIST_MAX_COMBINED_CHARS combined characters: read-only entries are
+ * least valuable and drop first (from the alphabetical end), then modified
+ * entries drop only after the read-only list is empty.
*/
export function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {
const modified = new Set([...fileOps.edited, ...fileOps.written]);
@@ -91,7 +108,34 @@ export function computeFileLists(fileOps: FileOperations): { readFiles: string[]
.sort()
.slice(0, FILE_LIST_MAX_ENTRIES);
const modifiedFiles = [...modified].sort().slice(0, FILE_LIST_MAX_ENTRIES);
- return { readFiles: readOnly, modifiedFiles };
+ const readFiles = readOnly.slice();
+ while (readFiles.length > 0 && fileListChars(readFiles, modifiedFiles) > FILE_LIST_MAX_COMBINED_CHARS) {
+ readFiles.pop();
+ }
+ while (
+ modifiedFiles.length > 0 &&
+ readFiles.length === 0 &&
+ fileListChars(readFiles, modifiedFiles) > FILE_LIST_MAX_COMBINED_CHARS
+ ) {
+ modifiedFiles.pop();
+ }
+ return { readFiles, modifiedFiles };
+}
+
+/**
+ * Remove <read-files>/<modified-files> blocks from a stored summary.
+ *
+ * The blocks are re-appended mechanically after every summarization (see
+ * computeFileLists/formatFileOperations) and carried in the compaction entry's
+ * details. Feeding stale blocks back into the update prompt makes the model
+ * re-summarize them, so lists compound across repeated compactions. Strip
+ * them before a previous summary reaches the summarizer; the details plus the
+ * fresh append remain the single source of truth.
+ */
+const FILE_LIST_BLOCK_PATTERN = /(?:\n*)<(read-files|modified-files)>[\s\S]*?<\/\1>/g;
+
+export function stripFileListBlocks(summary: string): string {
+ return summary.replace(FILE_LIST_BLOCK_PATTERN, "").trimEnd();
}
/**
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index 50270e113d..3ded6ee3a1 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -18,7 +18,8 @@ import { isSessionSlashCommandName, parseSessionSlashCommand, type SessionSlashC
export const COMPACTION_SUMMARY_PREFIX = `[compaction-summary]
-The conversation history before this point was compacted into the following summary:
+The conversation history before this point was compacted into the following summary.
+The retained messages below are authoritative; this summary may lag behind them.
<summary>
`;
diff --git a/packages/coding-agent/test/compaction.test.ts b/packages/coding-agent/test/compaction.test.ts
index c966e135bf..4978fbc3db 100644
--- a/packages/coding-agent/test/compaction.test.ts
+++ b/packages/coding-agent/test/compaction.test.ts
@@ -301,6 +301,47 @@ describe("prepareCompaction with previous compaction", () => {
});
});
+describe("prepareCompaction recency anchor", () => {
+ // A long user message crosses the tiny keep-recent budget, so the cut
+ // lands on it: a deterministic user-message cut with no split turn.
+ const longUserText = `user tail ${"x".repeat(400)}`;
+ const anchoredPreparation = (previousSummary: string, tailTexts: string[]) => {
+ const u2 = createMessageEntry(createUserMessage("user msg 2"));
+ const entries = [
+ createMessageEntry(createUserMessage("user msg 1")),
+ createMessageEntry(createAssistantMessage("assistant msg 1", createMockUsage(5000, 1000))),
+ u2,
+ createMessageEntry(createAssistantMessage("assistant msg 2", createMockUsage(6000, 2000))),
+ createCompactionEntry(previousSummary, u2.id),
+ createMessageEntry(createUserMessage(longUserText)),
+ ...tailTexts.map((text) => createMessageEntry(createAssistantMessage(text, createMockUsage(7000, 3000)))),
+ ];
+ return prepareCompaction(entries, { ...DEFAULT_COMPACTION_SETTINGS, keepRecentTokens: 10 });
+ };
+
+ it.each([
+ {
+ name: "anchors to the newest kept-tail assistant text, skipping empty ones",
+ previousSummary: "First summary",
+ tailTexts: ["", "older kept text", "newest kept text"],
+ anchor: "newest kept text",
+ keptSummary: "First summary",
+ },
+ {
+ name: "drops the previous summary entirely when it contained only file blocks",
+ previousSummary: "<read-files>\nold/a.ts\n</read-files>\n\n<modified-files>\nold/b.ts\n</modified-files>",
+ tailTexts: [],
+ anchor: undefined,
+ keptSummary: undefined,
+ },
+ ])("$name", ({ previousSummary, tailTexts, anchor, keptSummary }) => {
+ const preparation = anchoredPreparation(previousSummary, tailTexts);
+ expect(preparation).toBeDefined();
+ expect(preparation!.recentStateAnchor).toBe(anchor);
+ expect(preparation!.previousSummary).toBe(keptSummary);
+ });
+});
+
// ============================================================================
// Integration tests with real session data
// ============================================================================