Long Context Management for Coding Agents: Keep Critical Constraints from Being Compressed
As coding sessions grow longer, hard constraints stated at the beginning often get compressed away while stale tool output stays behind. This article explains why context auto-compaction causes behavior drift, breaks down where tokens actually go, and presents a three-layer governance approach—observability, branch pruning, and constraint pinning—along with a practical workflow and common pitfalls.
1. Background: Why “Getting Dumber Over Time” Is Not the Model’s Fault
When working with an AI coding assistant over a long session, many people run into the same pattern. At the start of the task, the hard boundaries are stated clearly: “Do not change persistent data structures,” “External APIs must remain backward compatible,” “Do not introduce new runtime dependencies.” For the first few dozen turns, the assistant follows them. Then, as the conversation grows and the context approaches the window limit, automatic compaction kicks in—and the assistant suddenly starts suggesting table schema changes, adjusting API fields, or “casually” refactoring directories.
This is not the model suddenly forgetting the rules. It is an inevitable result of how context management works under specific conditions. Most automatic compaction strategies trim or summarize from the earliest messages first, prioritizing the integrity of the most recent turns. Human collaboration habits are the opposite: goals, boundaries, and acceptance criteria are usually stated at the beginning of a session, while later turns are mostly execution details, trial and error, and temporary discussion.
The result is a structural mismatch:
- High-value information (constraints, acceptance criteria, architecture decisions) sits in the early part of the conversation and is the most likely to be compressed.
- Low-value information (outdated file contents, failed logs, unrelated Q&A) sits in the middle and later parts and is the most likely to be retained.
- The compaction algorithm cannot judge semantic value, so it can only make approximate trade-offs based on position and length.
The fuller the context gets, the more behavior drifts. Understanding this is the prerequisite for designing a governance approach: do not expect the compaction algorithm to get smarter; instead, change the structure of the context before compaction happens.
2. Where Context Bloat Actually Comes From
To govern context, you first need to measure it. Token consumption in a long session usually breaks down into four categories:
- System prompt and role setup: relatively fixed, with a stable share.
- Tool/interface definitions: grows linearly with the number of available capabilities, and is often underestimated.
- Conversation content: user instructions, assistant reasoning, and suggestions.
- Tool output: file contents, command echoes, test logs, retrieval results—usually the main driver of bloat.
The fourth category is the most typical source of “junk branches.” Common forms include:
- The same file read in full multiple times, while the file has been modified in between, making the earlier content completely stale.
- Entire failed test or build logs pasted in, still occupying space long after the problem is fixed.
- Temporary questions unrelated to the current task, such as asking what an English error message means.
- Large blocks of repetitive retrieval results with heavily overlapping information.
- Full implementation details of rejected approaches, still sitting in the context and continuously interfering with judgment.
These share a common trait: they were useful once, they are useless now, but they still consume budget and keep participating in attention allocation. They not only crowd out critical constraints but also lead the model to repeat already-rejected paths in similar contexts.
3. Governance Approach: Give Control of the Timeline Back to the Developer
A workable idea is to introduce a mechanism of “main-line protection plus branch pruning”: before automatic compaction triggers, the developer explicitly decides what to keep, what to fold, and what to delete. This can be understood as three layers of capability.
3.1 Observability: See Where the Budget Goes
The first step is visualization. The minimum viable form is a budget view in the session interface:
Context usage: 68,420 / 128,000 tokens (53%)system : 4,120tool defs : 11,300messages : 26,500tool output : 46,500 <-- main consumerauto-compact threshold: 80% (about 34,000 tokens remaining)
With this view, a team can turn “are we almost full?” from a guess into a metric, and use it to decide when to tidy up, when to start a new session, and when to narrow the toolset. In engineering terms, token estimation does not need to rely on any specific platform capability; approximating by character count combined with a tokenizer is enough to support the decision.
3.2 Pruning: Identify and Fold Redundant Branches
The second capability is automatically identifying foldable content and replacing it with a one-line summary that keeps the fact that “this happened” while dropping the specific payload. The rules can be entirely based on general heuristics:
If the same path is read >= 2 times and a write occurs in between:fold into "[file X has changed; re-read for the latest content]"If the same tool call has identical arguments and identical results:fold into "[duplicate call, same result as above]"If a tool call fails first and then succeeds:fold the failed output, keeping only "[initial attempt failed, later succeeded]"If output lines > threshold and there is no overlap with current task keywords:fold into "[long log, archived, retrievable on demand]"
The key is “fold” rather than “delete”: keep a traceable clue so the model does not repeat work due to missing context, while giving the budget to what really matters.
3.3 Pinning: Make Hard Constraints Uncompressible
The third capability addresses the root cause. Since the opening statements are the most likely to be squeezed out, stop letting them survive on conversation history and promote them to part of the persistent context:
- Externalize the constraint list: write non-negotiable rules into a project-level description file or initialization prompt that is injected throughout the session.
- Use structured expression: replace long natural-language paragraphs with verifiable entries that tools can check.
- Change gates: modifications involving persistent structures or external APIs must go through explicit confirmation.
- Session segmentation: start a new session when the task goal changes, avoiding the accumulation of irrelevant history.
Example (project constraint snippet):
constraints:- id: db-schemarule: Do not modify persistent table structuresrequire_confirmation: true- id: api-compatrule: Keep external APIs backward compatible; only allow adding optional fields- id: depsrule: Do not add runtime dependencies
4. Implementation Flow: A Recommended Rhythm for a Long Task
- Pin constraints at the start: write the constraints first, then the task, with constraints given as a list.
- Measure during the process: keep watching the budget view and the growth rate of tool output.
- Tidy up at milestones: after each verifiable milestone, run branch pruning and log archiving once.
- Pre-process before compaction: tidy up proactively before automatic compaction triggers, avoiding blind positional trimming by the algorithm.
- Recheck constraints: after tidying up, read back the constraint list to confirm the key rules are still in effect.
- Close in time: start a new session when the goal changes or acceptance is complete, preventing history pollution.
5. Common Pitfalls
- Relying only on a larger window: a bigger window only delays the problem; redundancy still dilutes attention.
- Summarizing all history: summaries lose executable details and can create more misunderstanding.
- Writing longer rules: verbose rules are themselves a token burden; itemized entries work better.
- Leaving tidying fully automated to the algorithm: judging semantic value requires the task initiator’s involvement, and human-AI collaboration has the lowest cost.
6. Conclusion
The essence of quality degradation in long sessions is a mismatch between context budget allocation and human collaboration habits. The workable solution is not mysterious: make usage observable, make redundancy foldable, and make hard constraints persistent. Turn these three things into part of the process, and the stability of long tasks no longer depends on luck. On top of this, if cloud-based observability capabilities (such as log services and monitoring alerts) are used to track session length and resource consumption over the long term, teams can further optimize collaboration norms and tool configuration strategies.
