Keeping Critical Constraints Intact in Long AI Agent Sessions
Long AI agent sessions lose important rules because automatic compression removes the oldest messages first. Those early messages often hold short, high-value constraints, while the context window fills with repeated tool output and outdated logs. This article explains where context tokens go, which content can be collapsed safely, which constraints must stay anchored, and how to check the context before compression runs.
A long session is not just history piled into a window. An agent reads files, edits code, and runs tests, and it writes the full output of each tool call back into the context. The window has a limit. When it gets close, automatic compression starts: it summarizes or drops earlier turns to make room for new reasoning. The problem is that rules are usually stated at the start of a session, while the content that fills the context is often intermediate output that is no longer valid. Compression algorithms choose what to remove by time or length. They do not know that one sentence says “do not change the table schema” or that one block is an outdated error. As a result, the critical constraints disappear first, and the noise remains.
Why Early Instructions Are the Easiest to Lose
When developers work with agents, high-value information is usually short: compatibility requirements, modules that must not be changed, interface contracts that must hold, and data boundaries that cannot be rolled back. These sentences take up few tokens, but they constrain every later step. Low-value information is the opposite. It is long and repetitive. The same file gets read several times before and after edits, hundreds of lines of a failed test log are pasted in, and after the problem is fixed the log still occupies space. Occasional unrelated questions also stay on the main timeline.
If automatic compression removes content from the oldest messages inward, it sacrifices the rule layer first and keeps the noise layer. When a session runs into the afternoon, the model can still see recent tool output but may no longer remember a prohibition stated that morning. It may then propose a change that looks simpler but breaks the contract. This is not the model suddenly getting worse. The evidence its decisions depend on has been rewritten by the summarization process.
Where the Tokens Go in a Context Window
To manage context, you first need to see it. A single request’s context breaks down into four parts, rather than being a general “conversation that has become long.”
System and role instructions cover task identity, output format, and safety boundaries. This part is relatively stable, but if large specification blocks are pasted repeatedly, they take a fixed share of the budget.
Tool and capability descriptions list the names, parameters, and descriptions of available tools. The more tools there are, the larger this fixed overhead, and it takes up window space even when unrelated to the task.
Conversation and decisions include user instructions, assistant plans, and key confirmations. Most constraints that should persist are here, and they are concentrated early in the session.
Tool results include file contents, command output, and retrieval snippets. They take the most space and have the shortest useful life, so they should be collapsed first during compression.
In practice, rough estimates are enough. Record the approximate length of each content type and note how much room remains before the window limit. The goal is not to track exact token counts. It is to judge whether the context is nearly full and which category is filling it. Without visibility into this distribution, you can only guess when to start a new session or wait for automatic compression to run.
What Can Be Collapsed and What Must Stay Anchored
Manual cleanup before compression, with reasons you can explain, is more reliable than hoping a general summary gets it right. Typical content that can be collapsed includes:
- Files changed afterward. An early full read no longer reflects the current disk state. Replace it with one line: the path has changed since then, reread it when a conclusion is needed, and do not reuse the old excerpt.
- Repeated identical calls. If the same path and range are read or searched several times, keep only a summary of the latest result and mark older results as stale.
- Failures followed by success. Error logs may still matter for debugging, but the full text is rarely needed. Keep the error type, the key lines, and a note that the step later passed.
- Side branches unrelated to the current goal. Temporary explanations of an error message or casual confirmations that do not affect the contract can move out of the main context or be reduced to one sentence, such as “Discussed the literal meaning of an error message earlier, unrelated to this change.”
Content that must stay anchored, and that summarization must not rewrite, is the opposite. It includes constraints that cannot be violated, confirmed interface contracts, approaches the user explicitly rejected, and completion criteria for the current task. Collect these into a short list placed where it stays fully visible after compression, rather than leaving them inside long logs and hoping they survive.
As an illustration, think of the “sacred timeline” as a record that keeps only the main-line facts. It is not the name of a TV series or a plugin. The main line contains three kinds of sentences: prohibitions that remain in force, the actual state of the current code and interfaces, and the next unfinished steps. Old readings, old failures, and old plans on side branches are cut from the main line once new facts replace them.
Constraint anchors (kept in full after compression)- Do not modify existing table schemas or migration history- Keep external interface fields and error codes compatible- Do not merge behavior changes until regression coverage is in placeCollapsible- Earlier full read of path P → "Outdated, reread required"- Long failure log for test T → "Failure cause: assertion A; later runs passed"
Compression Should Follow Facts, Not Time
Common automatic compression drops content from oldest to newest. It is simple to implement, but it runs against the order of facts in software work. Older messages may hold policies that still apply, while newer messages may hold observations that are already invalid. A better approach decides what to keep based on whether later facts still override each item.
First, mark the coverage relationships. A file write overrides earlier reads of that file. A successful verification overrides earlier details of the same kind of failure. An explicit user instruction such as “do not do this” overrides the opposite suggestion the model itself proposed. Early constraints that no later fact has overridden should not be pushed out first, no matter how old they are.
Second, limit how much summarization may rewrite. A summary can shorten logs, but it must not turn “do not change the table” into “the data model may be adjusted as needed.” For constraint sentences, keep the original wording rather than letting the model paraphrase them. Paraphrasing is the main source of constraint drift.
Finally, set a compression trigger threshold rather than waiting until the window is full. When there is still ample room, collapse content. The model then has enough context to understand why things were removed and what was removed. Compressing right at the limit often forces crude truncation, and there is no time left to write the anchor list.
How This Differs from Starting a New Session
A new session clears the noise, but it also clears the constraints, unless the developer pastes the specifications again each time. For a refactor that spans half a day, repeatedly restarting is costly, and it is easy to miss decisions confirmed midway through. The goal of context management is not to avoid compression forever. It is to keep the main line complete after compression: prohibitions remain, outdated evidence is marked, and the current task can continue.
You can split a long session into three memory layers. The instant layer holds raw tool output and can be collapsed by default. The working layer holds the current plan and the latest valid observations, and its key points are kept during compression. The policy layer holds boundaries the user has confirmed and is excluded from time-based dropping by default. When these layers are stored separately, or at least marked as separate blocks, automatic compression can safely touch only the instant layer.
A Practical Checklist
Before automatic compression triggers, check the following in order. This is cheaper than discovering afterward that the model forgot the rules and then repairing the damage.
- Confirm that the policy layer is still the original text. It should not be a paraphrase from an earlier summary. If a prohibition has been softened into a suggestion, restore the original wording immediately.
- Confirm that each retained file excerpt is newer than the last modification. If it predates a change, mark it “outdated, reread required.” Do not keep part of an old file that could be mistaken for the current state.
- Confirm whether each failure log has a matching success result. If one exists, collapse the error details so the model does not keep fixing a problem that is already solved, based on an outdated stack trace.
- Check whether tool descriptions and system prompts are pasted repeatedly. Keep one copy of the stable prefix, and do not paste the full specifications into every user message.
After compression, restate the current constraints in one or two sentences and ask the model to confirm its understanding. Do not assume it still remembers them. The restatement should follow the anchor list, not leave room for the model to improvise.
Summary
Long sessions degrade mostly because the evidence structure breaks down, not because the model’s capabilities suddenly disappear. Automatic compression removes the oldest conversation first, which hits the segment that is densest in constraints yet smallest in size. What actually fills the window is repeated reads, outdated logs, and drifting side branches. First, see clearly where the tokens go. Then collapse branches based on coverage relationships, and turn prohibitions into a short set of anchors that compression cannot rewrite. This keeps the main line intact. The approach does not depend on any particular coding assistant or plugin’s proprietary features. It depends on one principle: delete invalid evidence, and keep the rules that still apply.
