Long Context Management for Long Conversations: Keeping Critical Constraints from Being Compressed
This article explains why hard constraints tend to get lost in long AI coding sessions and how to prevent it. As the context window fills up, automatic compaction tends to discard the earliest messages—exactly where developers usually state non-negotiable rules. The article walks through a user-controlled approach that runs before automatic compaction: visualizing token usage by source, pruning stale or redundant history such as outdated file reads and resolved failure logs, and pinning critical constraints in a dedicated high-priority block that is re-injected every turn. It closes with practical rollout advice and the expected benefits, including less rework, higher useful information density, and more predictable token costs.
1. The Problem: Why Long Sessions Drift Away from the Rules
When you collaborate with an AI coding assistant over a long session, a familiar pattern shows up: hard constraints stated clearly at the beginning—never change the persisted data structures, keep external interfaces backward compatible, do not introduce new runtime dependencies—get “forgotten” dozens of turns later, and the model starts proposing convenient shortcuts that violate them.
The root cause is not mysterious. The context window is a finite resource. As the history approaches the window limit, the system triggers automatic compaction: earlier turns are folded into a summary to free up space for what comes next. Most compaction strategies default to squeezing content out starting from the oldest messages, yet the rules and boundaries in human–AI collaboration are usually stated right at the start. So the content that gets sacrificed is often the constraints you least want to lose, while what remains is noise that has long been obsolete.
That noise typically falls into three categories:
- The same file read repeatedly: the first two read results are already stale because the file was modified in between, yet they still consume a large number of tokens.
- Failure logs that linger: a crashed test once dumped hundreds of lines of errors; even after the issue is fixed and the test passes, the error text still occupies space in the context.
- Off-topic interjections: a casual question midway about the meaning of an English error message has nothing to do with the change at hand, but stays in the history permanently.
The conclusion is clear: a compaction algorithm cannot reliably decide what can be dropped and what must be kept. That decision has to be declared explicitly by the person who understands the task best—the developer. This is exactly the problem context governance addresses.
2. The Core Idea: Prune Before Automatic Compaction Kicks In
A useful analogy is the “sacred timeline”: the main line must be defended at all costs, and messy branches must be cut off in time, or the whole line collapses. In engineering terms, this means inserting a layer of user-controlled context curation before the platform’s automatic compaction triggers, doing three things: see clearly, prune, and anchor.
2.1 See Clearly: Make Token Usage Visible
First, stop guessing whether the window is nearly full. The metrics to surface include: tokens used, the model’s total window capacity, and the remaining headroom before the automatic compaction threshold, shown as a progress bar. Usage should also be broken down by source—for example, how much the system prompt, tool definitions, conversation content, and tool output each consume. Only when the breakdown is visible can you decide which category to compact instead of cutting indiscriminately.
Illustration (pseudocode):
usage = {used: 78k, window: 128k, threshold: 0.85,breakdown: { system: 3k, tools: 6k, chat: 41k, tool_output: 28k }}render_progress(usage) # outputs a progress bar plus per-category shares
2.2 Prune: Identify and Fold Redundant Branches
Compress history that can be judged obsolete, replacing it with a one-line note that preserves the fact that something happened without keeping every byte:
- File modified after being read: mark it as “this file has changed since; read it again if needed.”
- The same call repeated with identical results: keep only the latest one.
- A tool call that failed and then succeeded: fold away the failed attempts and keep the final successful result and conclusion.
Example rules:
if read(file) and file.mtime > last_read_time:replace(old_read_output, "File has changed; please read again")if identical(call) repeated:keep_latest_only()if tool_call failed then succeeded:drop_failed_attempts()
2.3 Anchor: Keep Critical Constraints Out of Compaction
Put non-negotiable constraints (data structure and interface compatibility, prohibited actions, acceptance criteria) into a separate, highest-priority persistent block that compaction skips. Re-inject it once before each task turn starts, forming a “constraint–execution–verification” loop.
PINNED_CONSTRAINTS = ["Do not change the persisted schema","Keep external interfaces backward compatible","Do not add new runtime dependencies"]
3. Implementation Advice and Benefits
- Observe before governing: hook up the visualization, run real long sessions for a week, measure the share of each category, and then decide the pruning rules.
- Whitelist the rules: only fold content that can be proven obsolete, to avoid deleting critical context by mistake.
- Make constraints explicit: write the hard rules into the persistent block instead of scattering them across the chat.
- Combine with general-purpose cloud capabilities: you can use common capabilities such as log services and monitoring alerts to track the number of compaction triggers and the pruning hit rate.
Expected benefits: critical constraints no longer get squeezed out, and the rework rate on long tasks drops; the density of useful information in the context increases, so the same window supports longer continuous development; token consumption becomes more predictable and costs more controllable. Context governance is not optional—it is a required engineering practice for long-session AI agent applications.
