Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): keep file ops from the folded compaction tail

xpeng5278-web01712462eefd
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index eab8cb2e0..3348eaa79 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -660,7 +660,10 @@ own collector, which recognizes the lowercase spellings `read` / `write` /
preparation (`withPiFileOpToolNames`): nothing stored changes, and every other
tool name is left spelled the way we register it. Without that conversion a
checkpoint's `readFiles` / `modifiedFiles` and the `<read-files>` section of a
-summary were always empty (D618).
+summary were always empty (D618). Codex-shaped compaction folds pi's retained
+tail into that same summary, and the runtime records file operations from the
+folded tail as well, so a file touched only inside the recent-token window
+still appears in the checkpoint lists and summary tags.
A delegate (§5f) runs the same derivation against its own resolved model and
compacts at its own turn boundaries, without a durable checkpoint chain of
diff --git a/packages/agent-runtime/src/pi-runtime-compaction-plan.ts b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
index 0e80fc118..aab1450d5 100644
--- a/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
+++ b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
@@ -113,7 +113,11 @@ function createFileOperations(): FileOperations {
return { read: new Set(), written: new Set(), edited: new Set() };
}
-function collectMessageFileOperations(message: AgentMessage, fileOps: FileOperations): void {
+/** Record one assistant message's Read/Write/Edit paths. Mutates `fileOps`. */
+export function collectMessageFileOperations(
+ message: AgentMessage,
+ fileOps: FileOperations,
+): void {
if (message.role !== "assistant" || !Array.isArray(message.content)) return;
for (const block of message.content) {
if (!block || block.type !== "toolCall") continue;
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 1142fdc78..ff92c5cb0 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -7418,6 +7418,180 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
await runtime.dispose();
});
+ /**
+ * Read of `src/a.ts`, then Edit of `src/b.ts`, then a trailing user message.
+ * A large `keepRecentTokens` parks the calls in pi's retained tail; a tiny
+ * one leaves them in `messagesToSummarize`. Codex folds both ranges into the
+ * summary, so the file lists have to agree.
+ */
+ function recentFileOperationEntries() {
+ const readAssistant = {
+ ...assistant,
+ content: [
+ {
+ type: "toolCall" as const,
+ id: "read-a",
+ name: "Read",
+ arguments: { path: "src/a.ts" },
+ },
+ ],
+ stopReason: "toolUse" as const,
+ };
+ const readResult = {
+ ...toolResult,
+ toolCallId: "read-a",
+ toolName: "Read",
+ content: [{ type: "text" as const, text: "contents of a" }],
+ };
+ const editAssistant = {
+ ...assistant,
+ timestamp: 3,
+ content: [
+ {
+ type: "toolCall" as const,
+ id: "edit-b",
+ name: "Edit",
+ arguments: { path: "src/b.ts" },
+ },
+ ],
+ stopReason: "toolUse" as const,
+ };
+ const editResult = {
+ ...toolResult,
+ toolCallId: "edit-b",
+ toolName: "Edit",
+ timestamp: 4,
+ content: [{ type: "text" as const, text: "edited b" }],
+ };
+ return [
+ {
+ type: "message",
+ id: "user-1",
+ seq: 0,
+ parentId: null,
+ timestamp: Date.parse("2026-07-28T00:00:00Z"),
+ message: { role: "user", content: "update the files", timestamp: 1 },
+ },
+ {
+ type: "message",
+ id: "read-assistant",
+ seq: 1,
+ parentId: "user-1",
+ timestamp: Date.parse("2026-07-28T00:00:01Z"),
+ message: readAssistant,
+ },
+ {
+ type: "message",
+ id: "read-a",
+ seq: 2,
+ parentId: "read-assistant",
+ timestamp: Date.parse("2026-07-28T00:00:02Z"),
+ message: readResult,
+ },
+ {
+ type: "message",
+ id: "edit-assistant",
+ seq: 3,
+ parentId: "read-a",
+ timestamp: Date.parse("2026-07-28T00:00:03Z"),
+ message: editAssistant,
+ },
+ {
+ type: "message",
+ id: "edit-b",
+ seq: 4,
+ parentId: "edit-assistant",
+ timestamp: Date.parse("2026-07-28T00:00:04Z"),
+ message: editResult,
+ },
+ {
+ type: "message",
+ id: "user-next",
+ seq: 5,
+ parentId: "edit-b",
+ timestamp: Date.parse("2026-07-28T00:00:05Z"),
+ message: { role: "user", content: "next", timestamp: 5 },
+ },
+ ];
+ }
+
+ function summarizedToolCalls(messages: any[]) {
+ return messages.flatMap((message) =>
+ Array.isArray(message.content)
+ ? message.content
+ .filter((block: any) => block.type === "toolCall")
+ .map((block: any) => ({ name: block.name, path: block.arguments.path }))
+ : [],
+ );
+ }
+
+ function prepareRecentFileOperations(
+ runtime: DesktopAgentRuntime,
+ keepRecentTokens: number,
+ ) {
+ (runtime as any).fullEntries = recentFileOperationEntries();
+ const entries = (runtime as any).entriesWithCompaction();
+ const budget = (runtime as any).contextBudget(
+ entries.map((entry: any) => entry.message),
+ );
+ return (runtime as any).prepareCompactionInput(
+ entries,
+ { ...budget, keepRecentTokens },
+ 20_000,
+ "completed_turn",
+ );
+ }
+
+ it("records file operations from tool calls folded out of the retained tail", async () => {
+ const runtime = createRuntime();
+ // Larger than the whole history, so pi leaves the Read/Edit calls in
+ // `retainedTail`. The shaped preparation still summarizes them.
+ const preparation = prepareRecentFileOperations(runtime, 1_000_000);
+
+ expect(preparation.ok).toBe(true);
+ expect(summarizedToolCalls(preparation.value.messagesToSummarize)).toEqual([
+ { name: "read", path: "src/a.ts" },
+ { name: "edit", path: "src/b.ts" },
+ ]);
+ expect([...preparation.value.fileOps.read]).toEqual(["src/a.ts"]);
+ expect([...preparation.value.fileOps.edited]).toEqual(["src/b.ts"]);
+ expect([...preparation.value.fileOps.written]).toEqual([]);
+
+ (runtime as any).models = {
+ completeSimple: async () =>
+ assistantMessage({ content: [{ type: "text", text: "Older work." }] }),
+ };
+ const summary = await (runtime as any).generateCompaction(
+ preparation.value,
+ new AbortController().signal,
+ );
+ expect(summary.ok).toBe(true);
+ expect(summary.value.summary).toContain(
+ "<modified-files>\nsrc/b.ts\n</modified-files>",
+ );
+ expect(summary.value.details.modifiedFiles).toEqual(["src/b.ts"]);
+ await runtime.dispose();
+ });
+
+ it("does not duplicate file operations already collected before the fold", async () => {
+ const runtime = createRuntime();
+ // The trailing user message is the only thing that fits, so the calls stay
+ // in pi's `messagesToSummarize` and are collected before the fold.
+ const preparation = prepareRecentFileOperations(runtime, 1);
+
+ expect(preparation.ok).toBe(true);
+ expect(summarizedToolCalls(preparation.value.messagesToSummarize)).toEqual([
+ { name: "read", path: "src/a.ts" },
+ { name: "edit", path: "src/b.ts" },
+ ]);
+ expect([...preparation.value.fileOps.read]).toEqual(["src/a.ts"]);
+ expect([...preparation.value.fileOps.edited]).toEqual(["src/b.ts"]);
+ expect([...preparation.value.fileOps.written]).toEqual([]);
+ expect(preparation.value.fileOps.read.size).toBe(1);
+ expect(preparation.value.fileOps.edited.size).toBe(1);
+ await runtime.dispose();
+ });
+
it("retains only the active user message and truncates it at the retention cap", async () => {
const runtime = createRuntime();
// Historical user messages are summarized. The active prompt is retained
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 2b6a4ea02..5e6dcecc3 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -153,7 +153,10 @@ import {
} from "./agent-messages.js";
import { withExplicitRequired } from "./tool-schema.js";
import { buildSessionContext } from "./session-context.js";
-import { prepareCompaction } from "./pi-runtime-compaction-plan.js";
+import {
+ collectMessageFileOperations,
+ prepareCompaction,
+} from "./pi-runtime-compaction-plan.js";
import { compact } from "./pi-runtime-compaction-summary.js";
import {
ESTIMATED_TEXT_CHARS_PER_TOKEN,
@@ -7046,8 +7049,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
*
* pi's cut point is still what marks the boundary, but the split it produces
* is folded back together (see `codexShapedPreparation`), so
- * `budget.keepRecentTokens` no longer decides what survives — it only decides
- * which messages pi attributes file operations to.
+ * `budget.keepRecentTokens` no longer decides what survives. File operations
+ * are collected from that whole folded range, including the retained tail.
*/
private prepareCompactionInput(
entries: Entry[],
@@ -7118,6 +7121,18 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
...preparation.turnPrefixMessages,
...preparation.retainedTail,
];
+ // pi records file operations for `messagesToSummarize` and, on a split
+ // turn, `turnPrefixMessages`. The tail is summarized too — including the
+ // suffix a split left uncollected — so copy the sets and record it there.
+ // The sets pi returned stay unchanged.
+ const fileOps: CompactionPreparation["fileOps"] = {
+ read: new Set(preparation.fileOps.read),
+ written: new Set(preparation.fileOps.written),
+ edited: new Set(preparation.fileOps.edited),
+ };
+ for (const message of preparation.retainedTail) {
+ collectMessageFileOperations(message, fileOps);
+ }
const latestUser = messagesToSummarize
.filter((message): message is UserMessage => message.role === "user")
.at(-1);
@@ -7130,6 +7145,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
turnPrefixMessages: [],
isSplitTurn: false,
retainedTail: selectRetainedUserMessages(candidates, retainedUserTokens),
+ fileOps,
};
}