Managing Context in Long AI Coding Assistant Sessions: From Forgetting to Control
Long AI coding sessions often lose early constraints once auto-compaction summarizes the conversation. This article explains why compaction tends to drop the most important information and describes three practical methods for managing context: visualizing token usage, pruning redundant content, and persisting key constraints. It also outlines a workflow for keeping AI coding agents reliable over long tasks.
1. Background: Memory Loss in Long Conversations
As AI coding assistants become common, more developers use agents for long, multi-turn tasks. A typical example: a developer opens a session in the morning and asks the AI to refactor an old project. The work covers code reading, solution design, and module-by-module changes, and the conversation can run all day.
This pattern creates a problem that is hard to avoid: the context window is limited. When the conversation’s token count approaches the model’s window limit, the system triggers auto-compaction, which summarizes earlier history to free up space. This sounds reasonable, but the actual experience is often unsatisfactory.
Here is a common scenario. At the start of a session, you state clearly: “Do not modify the database schema, and external interfaces must remain compatible.” For the first few dozen turns, the AI follows these rules strictly. Later in the afternoon, the conversation grows long enough to trigger auto-compaction, and the model suddenly suggests, “Why not add a field to this table? That would make the change easier.” It has forgotten the original hard rules entirely.
Why does this happen? The root cause is that the order in which auto-compaction discards information does not match the order of that information’s value.
2. Why Auto-Compaction Keeps Pushing Out the Most Important Content
2.1 The Default Compaction Strategy
Most auto-compaction methods in common use either remove content starting from the oldest messages or summarize the conversation in chronological order. The implicit assumption is that older content is more outdated and less important.
In programming work, that assumption often fails. The earliest messages in a session usually contain three kinds of high-value information:
- Task boundaries and constraints: what must not be touched, what must stay compatible, and where the performance limits are;
- Architecture decisions: why option A was chosen over option B, and the trade-offs behind that choice;
- Key background: legacy system burdens, team conventions, and release time windows.
Almost all of this content appears at the start of a session, yet compaction removes it first.
2.2 The Clutter That Fills the Context
Review the logs of a long session and you will find that much of the token budget goes to content with no lasting use:
- Outdated file contents: The AI reads the same file three times. The first two reads became invalid when the file changed in between, but hundreds of lines of the original code remain in the context.
- Past failure logs: Hundreds of lines from a failing test run fill the context. After the problem is fixed, those error messages still take up space.
- Off-topic side questions: A passing question such as “What does this error mean?” has nothing to do with the current task, yet it permanently occupies context.
- Repeated tool calls and results: The same command and the same output appear two or more times.
In short, the rules that matter most get removed, while most of what remains is clutter. Only the developer writing the code knows what can be deleted and what must stay. A compaction algorithm cannot make that call reliably.
3. A Solution: Give Developers Back Control of Context
The idea is to protect the “sacred timeline.” Treat the initial constraints as the main line that must be defended, and treat detours that appear mid-session as branches to prune promptly. The core principle is to clean up context proactively before auto-compaction triggers, instead of letting an algorithm make the wrong trade-offs passively.
A workable context management approach usually has three capabilities.
3.1 Context Visualization: Know How Much Space Is Left
The first step is to fix the lack of visibility. Developers need to know, at any time:
- How many tokens are in use, the total size of the model window, and how far the session is from the auto-compaction threshold;
- How the tokens are distributed across the system prompt, tool definitions, conversation content, and tool output.
This information can be shown as a progress bar, for example:
[██████████████░░░░░░] 70% (42k / 60k tokens)├─ System prompt 3k├─ Tool definitions 8k├─ Conversation 15k└─ Tool output 16k ← main source of growth
With this dashboard, developers can predict when compaction will happen and step in at a good moment, rather than being caught off guard by compaction in the middle of a critical task.
3.2 Redundancy Detection: Find Outdated Branches
Based on the sequence of context events, a system can automatically detect several typical redundancy patterns:
- Stale file reads: A file was modified after it was read, so the earlier read result is no longer valid;
- Repeated calls: The same tool call and the same result appear more than once;
- Failure before success: A tool failed, then a retry succeeded. The failure record no longer has value.
After identifying this content, replace it with a short note, for example:
(This file was modified after turn 37. The original read is outdated. Read it again if needed.)
This keeps a necessary pointer while freeing a large amount of token space. In practice, this step alone can typically reclaim a considerable share of the context.
3.3 Persisting Constraints: Keep the Hard Rules From Being Lost
Initial constraints and decisions should be made explicit and persistent. Common approaches include:
- Write key constraints into a persistent area that lasts for the whole session, such as a project-level configuration file or the agent’s memory rules, so they are re-injected after every compaction;
- When compaction is about to trigger, automatically attach high-priority constraints to the summary in a prominent position;
- Maintain constraint status with a structured checklist, for example:
{"constraints": [{ "id": "db-schema", "rule": "Do not modify the database schema", "priority": "high" },{ "id": "api-compat", "rule": "Keep external APIs backward compatible", "priority": "high" }]}
4. A Recommended Long-Session Workflow
Combining these capabilities leads to a practical workflow for long sessions:
- At the start: Define all boundary conditions, do-not-touch items, and acceptance criteria up front, and save them to persistent rules.
- During development: Check the token progress bar regularly. When usage reaches 60% to 70%, clean up the context or write a phase summary.
- At phase transitions: Ask the AI for a phase summary covering what is done, what is pending, and which constraints apply. Use it as the anchor for the next phase’s context.
- Split large tasks: Instead of one session for the whole day, divide the work by module into several sub-sessions. Each session carries only the background it needs, which reduces compaction pressure at the source.
- Use external storage: Put long documents and large logs in files or external storage. Keep only paths and summaries in the context, and read the full content when needed.
5. Conclusion
Compacting context in long agent conversations is, at its core, a problem of ranking information by value. General-purpose compaction algorithms lack the business context needed to make that ranking well. Rather than blaming the model for “forgetting,” take back control: use visualization to see the full picture, use cleanup to prune stale branches, and use persistence to protect the key constraints. When context is under control, AI coding assistants can stay stable and reliable through long tasks.
