Repository navigation
Keep the messages a compaction summarizes as files the agent can search - #1334
AshishKumar4 wants to merge 20 commits into
Conversation
A compaction leaves the model a summary and nothing to check it against. It now writes the messages it summarizes as files in one git commit on top of the last checkpoint's, and names the commit on the checkpoint. readFile and grep read it under the reserved name EARLIER_MESSAGES, which validateBindingName refuses, so no binding takes it and no other tool resolves it. The files hold what was said and none of the chat's code, so a revert's refold keeps the commit. Anthropic's compaction block replaces the summary message, which carries the note that names the files, so on that path the summary is asked to end with it.
validateBindingName() refused the name, and it also runs where names are read, so a chat that already had a binding called EARLIER_MESSAGES lost it. The name is now refused to a new chat binding only, and a binding that already took it keeps resolving as it did, which is the rule GIT follows. The constant moves beside GIT_BINDING_NAME.
…IT is kept out The name was refused only where the agent names a binding. A gadget's default binding, a spawner's env or a generated name could still take it in a new chat, and readFile and grep then read that workpiece under the name the chat's earlier messages are read under. It is now reserved in the three places GIT is. An entry that arrives with the name is renamed, and a chat that already has such a binding keeps it.
Keeping the summarized messages could cost a chat its compaction in two ways. The write ran first, inside the compaction's `try`, so a write that failed was a compaction that failed: an ordinary turn logged it, ran on, and tried again on the next turn while the prompt grew. And on Anthropic's native path the request's instructions gained a sentence, so that the summary would name the files, which made the request one that no test had sent to Anthropic. CI's compaction eval showed the cost on claude-sonnet-5-5: no checkpoint, and 361k prompt tokens by turn 22 where main compacts to 56k by turn 11. The run kept no Worker log, so which step failed is not known, and its branch carried other changes to the prompt. The unit tests could not tell either: they script the model, and a scripted model summarizes whatever it is asked. The write now follows the summary and is best effort. A failed write is logged, and the checkpoint names the commit of the one before it. A summary that fails leaves no commit behind. Every request on the native path is the one main sends: the instructions are unchanged, and the summary message that a block replaces carries no note, since it is only weighed for the next boundary. A test holds the instructions to that. A model that reads Anthropic's block is therefore not told about the files.
A stored tool result can hold a NUL, as the output of code that prints binary data does. Copied into the message's file, it made the file binary: grep skipped the whole message and readFile refused its lines. The file now shows a NUL as `\0`.
The search test said that nothing in the prompt held the summarized text, and looked only at the system message of the request that followed the search. It now looks at the whole request before the search. The file test said the files hold none of the code. They hold the code a tool ran, and the test's name now says what they leave out.
…les can hold The comment on earlierMessageFiles said the files hold none of the chat's code. They hold each tool call's stored result, which can quote a file.
…on summarized The unit tests compact with /compact, against a scripted model handle. This test runs the whole Workshop under workerd: a chat passes its budget and compacts as its next turn starts, and the scripted agent's grep under EARLIER_MESSAGES returns the first turn.
A compaction that fails on an ordinary turn does not fail the turn, and the reason goes only to the Worker's log, which an eval run does not keep. CI's compaction eval showed a chat that never compacted and nothing about why. A run's errors now list what the Workshop logged under agent.compaction.*, each line once. Trials of one model share a Workshop, and so share these lines.
…e the files existed The note that names the earlier-message files was left out only where Anthropic's block replaces the summary message. A checkpoint with files and no block still sent it: after a compaction that fell back to a transcript summary, one made with unread attachments, or one made before the chat moved to Claude. The next native compaction request then carried the note, though the reason to keep it out, that a request Anthropic answers without a summary costs the chat its compaction, holds for that request too. The note is now sent only to a model Anthropic cannot compact for. A test compacts two chats through Claude, one whose checkpoint names files and one whose does not, and holds the two requests equal. The test that pinned the wording of the instructions now says what it protected: the request names no files.
…erved names The name was reserved in a chat's scope and seeds only. A new gadget binding or a spawner's env could still take it, and every chat seeded from one then renamed it to EARLIER_MESSAGES_2, so code or a prompt that said env.EARLIER_MESSAGES no longer matched what the agent had. RESERVED_BINDING_NAMES now holds both names, and each place that refused GIT reads it: bindWorkpiece, renameBinding, validateSpawnerBinding, a chat's scope, its seed and its generated names. The constant for the name moves beside the files it names, so that the code that renders them can use it. fallbackBindingName's comment goes back to what it said: its catch handles validateBindingName alone, and a reserved name is refused by isTaken.
…sults A search of the files stored its matches as the call's result, and the next compaction wrote that result into the step's file. A later search then matched the copy beside the message, and each compaction added copies. A grep of the files is now kept without its result. A writeFile or editFile call recorded with no workpiece was also written as "workpiece: undefined". A field with no value is now left out.
A chat binding that took the name EARLIER_MESSAGES before it was reserved keeps resolving as that binding, so readFile and grep read the binding and never the files. The chat still wrote the files at each compaction, and its summary message still said they could be read under the name. Such a chat now writes none, so its checkpoint names no commit and its summary carries no note.
…g they stay and how they grow Deleting a chat removes the checkpoints that name the commit and leaves the commit, its trees and its blobs in the git store. deleteChat's comment said it deletes the chat's messages, and nothing said the copies stay. The guide, the checkpoint's doc and that comment now say so, with the case of a compaction that writes as its chat is deleted. The list of roots a future GC must keep gains the commit. The doc of earlierMessageFiles said the files hold no file a tool wrote. They keep the code executeCode ran, which can hold one. It also did not say that reverts, merges and a person's own edits are left out. The tree stays flat. Each compaction's root tree names every file so far, at about 25 stored bytes a file, and reaches the 2 MB of one row at 80,000 files. The guide gives the measurements and why the layout can change later with no migration.
Trials of one model share a Workshop, and each listed every compaction failure in its log, its own or not. A trial also listed any event whose name began with agent.compaction., failure or not. A trial now lists the lines that name its workspace and one of the two failure events. The session exposes its workspace's id for that.
Preview:
|
|
|
||
| // Delete the chat's messages and the attachment content referenced by them. Attachment metadata | ||
| // is canonical in each message's ChatAttachmentRef, so no separate attachment index is needed. | ||
| // The copies of messages that compactions kept as files stay in the git store, where nothing |
There was a problem hiding this comment.
Tie archived transcript text to the chat's lifetime. The retention note in packages/workshop-backend/AGENTS.md says "Without the commit's id the files cannot be
read." But an archive readFile stamps its blob OID (agent.ts:3796), getChatHistory() returns that stamp unchanged (overseer.ts:14887, :7108), and workspace readBlob() only needs the OID (:14838). An editor who cached a tool-call record can therefore fetch that message from the server after deleteChat(), without ever knowing the commit ID. Keep the archive and its replay references in chat-scoped storage that deletion clears, or make archive objects and replay stamps private and revoke their read path on deletion. A regression test should retain the handle across deletion and check that it stops resolving.
| // event, each in quotes, as the Workshop's logger prints them. | ||
| compactionFailures: () => workshop.server.getLogs().flatMap(({ message }) => | ||
| message.includes(`'${session.workspaceId}'`) && | ||
| COMPACTION_FAILURE_EVENTS.some(event => message.includes(`'${event}'`)) ? [message] : []), |
There was a problem hiding this comment.
Keep raw provider errors out of eval artifacts. This copies the entire warning, including error and errorStack, into the trial result. requestAnthropicCompaction() wraps the SDK's errorMessage in AgentTurnError (anthropic-compaction.ts:117–119); the installed pi-ai dist/utils/error-body.js explicitly notes that Anthropic's SDK folds the provider response body into that message. The PR eval workflow uploads the resulting JSON (.github/workflows/workshop-evals-pr.yml:210–232). packages/observability/AGENTS.md says "Never log secrets, prompts, headers,
tokens, or request/response bodies." Record bounded, Workshop-owned failure codes and safe scalars such as HTTP status rather than exporting the warning text.
| ? {workpiece: call.input.workpiece, filename: call.input.filename} : call.input) | ||
| .filter(([, value]) => value !== undefined); | ||
| let searchedThese = call.toolName === "grep" && | ||
| call.input.workpiece?.replace(/^env\./, "") === EARLIER_MESSAGES_BINDING_NAME; |
There was a problem hiding this comment.
A malformed grep call drops the whole archive span. agent.ts:4719–4739 persists the original model arguments even when tool validation rejected them; pi-ai validates a copy. An object-valued workpiece therefore reaches this formatter on an errored call. ?. only guards null and undefined, so .replace() throws before the call.error branch. earlierMessageFiles() then aborts the batch, and the checkpoint advances without archiving any valid message in that span. Guard the persisted input shape and type before checking the workpiece name; add a case with a rejected call between valid messages.
| // leaves no commit behind. A chat whose binding took the name before it was reserved keeps | ||
| // none: its tools read the binding, and the note would be false. | ||
| let earlierMessages = checkpoint?.earlierMessagesCommit; | ||
| if (!chatBindings.has(EARLIER_MESSAGES_BINDING_NAME)) { |
There was a problem hiding this comment.
Account for legacy requests that already claimed this name. A pending connection request created before the reservation puts its name in claimedNames, not chatBindings (agent.ts:3275–3287). /compact can still archive the turns before that request. If the user then accepts it, the request retains the original name (overseer.ts:14668–14675), so the summary advertises EARLIER_MESSAGES while both file tools resolve it to the connection. Treat an outstanding legacy claim as a conflict before creating or advertising the archive, and cover compaction followed by late acceptance.
| // result, which the next search would find beside the messages it quotes. | ||
| function formatEarlierToolCall(call: AiToolCall): string { | ||
| // (A call recorded before tools took a workpiece has none to show.) | ||
| let fields = Object.entries(call.toolName === "writeFile" || call.toolName === "editFile" |
There was a problem hiding this comment.
A repeated literal search finds its own earlier query. The result text is omitted, but all input fields are written before that check, so grep for zebra-42 writes a searchable pattern: zebra-42 line. After compaction the same query returns the original message plus another hit for each archived search. The existing repeat-search test uses zebra-\d+, which cannot match its own pattern text. Omit the query from the searchable representation of archive lookups and exercise a repeated literal query.
|
Review: 5 findings. Posted all five findings in the inline review. |
A call its tool's schema refuses is stored with the arguments the model sent: pi checks a copy. So a stored `input` can be null, text or a list, and a field of it can have any type. The renderer of the earlier-message files assumed a checked input. A grep whose `workpiece` was an object threw in it, the write for the whole span failed, and the checkpoint was recorded with no files for any message of that span. The renderer now treats an input that is no object as having no fields, and tells a search of the files only by a workpiece that is text. One test has a model send such a call between two messages and finds the first of them after the compaction. Another renders calls stored with null, text and a list.
A search of the files was written without its result and with its query. A search for literal words therefore found, after the next compaction, the `pattern:` line of each earlier search for them, beside the message that held them. The test for this used a pattern that cannot match its own text, and so missed it. A search of the files is now written as its name and workpiece alone, with no query, path, result or error. The test searches for literal words.
A connection request made before EARLIER_MESSAGES was reserved holds the name in the chat's scope while it is pending, and makes it a binding when it is accepted. A compaction in between wrote the files and said in its summary that they could be read under the name. After the acceptance both tools read the connection, so the note was false and the files out of reach. A pending request that holds the name now counts as a binding of it: the compaction writes no files and its summary carries no note. The test compacts while the request is pending and then accepts it.
A trial's result listed each compaction failure as the Workshop's whole log line, with the error's message and stack. For a request a provider refused, that message is the provider's response body, and CI uploads the result. A trial now lists the event, with the HTTP status of a refused request, or with the sentence the Workshop itself writes when a compaction gets no summary. The Workshop logs that status on agent.compaction.failed, as it does on agent.run.failed. Any other error's text stays in the Worker's log.
…sages The guide said that without the commit's id the files cannot be read. One file can: a readFile of the files stamps the file's blob id on its tool call, getChatHistory() returns that call to build clients, and readBlob() gives a build session any blob by id. A build client that kept the id can fetch that file after the chat is deleted. It was not sent the file's text with the id, and could read the same message in the chat until then. The guide, the checkpoint's doc and deleteChat's comment now say what a deletion leaves, who can fetch what, and that a committed file an agent read and an attachment outlive their chat on main in the same way. The guide also says that a pending request holding the name keeps a chat from writing files, and what is written of a search of the files.
| // A NUL would make the file binary, which grep skips and readFile refuses to show. | ||
| let text = parts.filter(part => part !== "").join("\n\n").replaceAll("\0", "\\0"); | ||
| if (text !== "") { | ||
| files.set(`${String(message.sequence).padStart(8, "0")}-${role}.md`, `${text}\n`); |
There was a problem hiding this comment.
Keep private chat text out of the workspace-wide Git lookup. The sequence and role are only in the path; a plain message becomes a Git blob containing just its text and a newline. Gadget code has env.GIT, and git-cache.ts:1578–1589 distinguishes a locally held blob from an unknown object without checking chat access. That lets code with no chat access confirm a predictable private reply, such as a yes/no decision. docs/sharing.md:14–15 reserves chat access for build; this inference is possible even while the chat is live and no readFile has stamped the blob. Store the archive behind the chat-scoped lookup rather than registering its plaintext blobs in the workspace Git store.
| chatId?: number): void { | ||
| validateBindingName(name); | ||
| if (name === "GADGET" || name === GIT_BINDING_NAME) { | ||
| if (name === "GADGET" || RESERVED_BINDING_NAMES.includes(name)) { |
There was a problem hiding this comment.
Preserve published blueprints that use this binding name. Blueprint exports preserve the original env key (overseer.ts:10451–10464), and newWorkspaceFromBlueprint() restores it verbatim via gadget.bind() (server.ts:629–642, 673–674). An existing blueprint with an assigned EARLIER_MESSAGES binding will now fail to instantiate after the new workspace has already been created. The analogous spawner validation rejects that key in a blueprint’s saved spawner env. Reserve the name in the chat namespace, where the file tools consume it, while preserving the exact names that published code expects in its own env.
| if (name in seed) { | ||
| let target = seed[name]; | ||
| delete seed[name]; | ||
| seed[fallbackBindingName(name, isSeedNameTaken)] = target; |
There was a problem hiding this comment.
Avoid assigning a seed alias that a chat has already claimed. Before first seeding, createGadget() checks chatScopeNames(), which sees the default binding EARLIER_MESSAGES but not the future alias EARLIER_MESSAGES_2 (overseer.ts:9886–9904, 14062–14088). If a user already created a gadget as EARLIER_MESSAGES_2 in that chat, this rename gives the same name to the old target. Replay then keeps the seed entry (agent.ts:3072–3078) but tells the model that name refers to the new gadget (agent.ts:3139–3141). Include names already stamped in the chat log when choosing the alias, and use the same normalization when checking a prospective seed.
| } | ||
| toolOutput = {content: readFileResult( | ||
| {kind: "blob", reader: await hooks.openBlob(toolCall.observedOid)}, | ||
| toolCall.input, toolCall.input.filename, MAX_TOOL_RESULT_CHARS).content}; |
There was a problem hiding this comment.
Replay the validated line window, not the raw model arguments. Pi validates a copy and coerces numeric strings, but the step stores block.arguments (agent.ts:4719–4724). I checked with the installed validator: startLine: "2", lineCount: "1" runs live as 2, 1. Replay passes the strings to readFileWindow(), where first - 1 + lineCount becomes "11", so a four-line file replays lines 2–4 instead of just line 2. Persist the effective window or reuse the same normalization in replay, and cover a coerced call in the replay test.
| const event = COMPACTION_FAILURE_EVENTS.find(name => message.includes(`'${name}'`)); | ||
| if (event === undefined || !message.includes(`'${session.workspaceId}'`)) return []; | ||
| const status = /\bstatusCode: (\d{3})\b/.exec(message)?.[1]; | ||
| const reason = WORKSHOP_REASON.exec(message)?.[0]; |
There was a problem hiding this comment.
Take compaction diagnostics from typed fields. This regex searches the entire rendered warning, including the provider error and stack. I verified that a 400 warning whose provider message contains Compaction produced no summary (stop reason SAMPLE_VALUE). is reported as that reason instead of HTTP 400, and the provider-controlled word reaches the trial artifact. Likewise, statusCode can match text inside the error when the actual field is absent. Emit a fixed Workshop reason code and a numeric status field at the catch site, then read only those fields. packages/observability/AGENTS.md:27–28 says, “Never log secrets, prompts, headers, tokens, or request/response bodies.”
| }; | ||
| return parent === undefined | ||
| ? await this.gitCache.writeFilesAsCommit(files, {...options, parents: []}) | ||
| : await this.gitCache.writeChangedFilesAsCommit( |
There was a problem hiding this comment.
Avoid retaining the files of an archive write that failed. The Git writer commits each fresh blob in its own storage transaction before storing the root tree (git-cache.ts:447–453, 657–663). Once the flat tree reaches the documented row limit, it rejects every new root, but every later compaction still writes that span’s blobs permanently. The checkpoint stays on the old archive, so the new bytes consume workspace storage without ever being searchable. Bound or partition the tree before writing, or ensure a failed archive update does not leave its newly written objects behind.
|
Review: 6 findings. Posted all six findings in the inline review. |
Eval resultsVerdict: 🟡 Inconclusive. No task can be compared: eval definition changed.
Failed checks
|
🔬 Eval runs reviewPerformanceChess fell from 60% to 50%, Worker Logs rose from 70% to 90%, and Chat Views rose from 80% to 100%; prompt-cache hit rates shifted by less than one percentage point on every row. Compaction passed 1/1 per model on both sides in 43 steps, with nearly identical costs (GPT $0.0698 → $0.0699; Claude $1.4700 → $1.4691) despite shorter elapsed times (122 → 68 s and 134 → 111 s, respectively). Chess lost the most candidate runs: three stopped before the PGN turn, helping explain the drop from 40.1 to 31.6 mean steps, while exact-text edit misses were the most frequent tool error on both sides. 🟡 VERDICT: INCONCLUSIVEAll eight rows are marked TriageFailure modes
Tool errors
What to do
|
A compaction leaves the agent a summary and nothing to check it against. When the summary drops a detail, the agent cannot get it back. With this change each compaction also keeps the messages it summarizes as files, and the agent reads them with tools it already has:
grepandreadFile, withEARLIER_MESSAGESas the workpiece.This was part of #1332 (Memory). It does not depend on Memory, and it adds a durable copy of chat text with retention questions of its own, so the review there asked for a separate PR. #1332 no longer contains it.
How it works
messageandagentCallbackrow before its boundary to one file, named by sequence and speaker, and writes the files as a git commit on top of the previous checkpoint's commit. The checkpoint names the commit (CompactionCheckpoint.earlierMessagesCommit).readFileandgrepresolveEARLIER_MESSAGESto that commit. No other tool accepts the name, so nothing writes the files. The name is reserved whereverGITis, from one list (RESERVED_BINDING_NAMES).Limits
mainsends, and a test holds it to that. When this was in Add Memory: a private list of facts about a person, loaded into their own chats #1332, CI's compaction eval stopped compacting onclaude-sonnet-5-5(1 run of 1;maincompacted) and kept no log of why. That build also changed the instructions of Anthropic's compaction request, which is the likely cause and is gone here. On this branch CI's compaction eval scored 100% onclaude-sonnet-5-5, asmaindid (at623dfd2a0). Every other model is told, and a person can nameEARLIER_MESSAGESto a Claude model.readFilecall in the chat's history, andreadBlobserves any blob by id. That collaborator could read the same message in the chat until it was deleted. A committed file an agent read and an attachment outlive their chat onmainin the same way. Tying the files to the chat's lifetime is a storage change this PR does not make.executeCoderan, so a result from before a revert stays readable. They hold no text thatwriteFileoreditFilewrote, and they do not show reverts, merges or a person's own edits. Of a search of the files themselves they keep only that it was made.EARLIER_MESSAGES.env.GIT, worktrees and replicas,useandviewsessions, share links, blueprint export, spawned agents, the admin view). None gives the content to someone who may not read the chat.env.GITdoes confirm that a blob exists to a caller who guesses its exact bytes, as it does for attachments onmain.What I checked
On macOS with Node 26.11.1, at
c726d00e0.workshop-backend: 3,364 unit tests, 3 integration, 5 native.workshop-evalsunit tests: 146.pnpm lintpasses; my run replayed the cached result of the lane's run on the same tree.grep(workshop-chat-recovery.test.ts).b10315b67toc726d00e0). All are fixed or written down in the package guide.Not done
623dfd2a0scored 100% onclaude-sonnet-5-5and ongpt-6-luna, on this branch and onmain. The report calls the comparison inconclusive, because the eval's definition changed on this branch, and says neither build looked anything up inEARLIER_MESSAGES. So the run shows that compaction still works on both paths, and nothing about the files. I ran no real model locally: the local gateway has no credits for provider models. An eval's result now lists the event and HTTP status the Workshop logged if a compaction fails.packages/workshop-backend/AGENTS.mdat the same place. Whichever merges second has that one conflict to resolve by keeping both sections. The code merges cleanly.An agent lane wrote the code. I read the diff and reran its tests and lint before raising this.