Proactive Context Governance for Long Conversations with AI Coding Agents

    This article explains why constraints set at the start of a long AI coding agent session tend to be forgotten after automatic context compression. It proposes a proactive approach: measure context usage, identify redundant and outdated content that can be pruned, and protect key constraints in a dedicated segment. Developers keep control over what gets removed while the session stays within its context limits.

    1. The Problem: Why the Earliest Rules Disappear First

    In practical use of AI coding agents, a common problem is rarely discussed: the longer a session runs, the more likely the key constraints set at the beginning are to be forgotten. Developers often state a few non-negotiable boundaries at the start of a conversation, such as “Do not modify database table schemas,” “Public interfaces must remain backward compatible,” and “Do not introduce new third-party dependencies.” For the first few dozen turns, the agent usually follows these rules strictly. However, once a session has run for several hours, the context window approaches its limit, and automatic compression is triggered, the agent may start suggesting things like “Adding a field to that table would be simpler,” which directly violates the original constraints.

    The root cause is a structural flaw in context compression, not a shortage of model capability. Mainstream automatic compression strategies generally follow the principle of evicting content from the oldest history first. When token usage nears the window limit, the system discards content from the head of the conversation to make room for new interactions. This strategy implicitly assumes that older content is less important. In real development work, that assumption is backwards. Rules, boundaries, and business background are almost always established at the very beginning of a conversation.

    Even more concerning, what gets evicted is often the constraint information that keeps the project safe. Meanwhile, much of what fills the context is outdated, redundant content. A review of typical long session logs reveals several frequent types of “context junk”:

    • Repeated file reads: The same file is read several times in a conversation. In between, the agent has modified the file, so earlier read results are already stale.
    • Outdated error logs: A failed test produces hundreds of lines of error output. After the problem is fixed, those logs still occupy significant space.
    • Unrelated side questions: A developer briefly asks what an English error message means. The question has nothing to do with the current task but still counts toward the context.
    • Resolved tool call chains: A tool fails, then succeeds after a retry. The full record of the failed attempt remains in the context.

    If this content is not cleaned up, the opening instruction “Do not touch the table schema” will eventually be pushed out. The difficulty is that a general compression algorithm cannot reliably decide which content is safe to delete and which must stay. The algorithm sees a token sequence. It cannot tell whether a message is a business constraint or an expired log. Only the person writing the code knows which information is critical.

    2. A Change in Approach: From Passive Compression to Proactive Pruning

    This conflict points to a clear direction. Context management should not be left entirely to the compression algorithm. Developers should govern the context proactively before compression is triggered. This approach can be summarized as “prune before compressing.” Before the timeline is forced to shrink, remove the branches that are clearly no longer needed, and lock in the constraints that must be kept.

    The idea comes from an analogy with timeline management. If a long session is viewed as a timeline, the constraints the developer sets at the start form the main line, and they must be protected. Repeated reads, outdated logs, and unrelated Q&A that appear along the way are branches. They should be cut before the main line is squeezed. Otherwise, when the system has to compress, it will cut the main line.

    Based on this approach, a practical context governance plan needs three core capabilities: visibility, identification, and control. Each is described below.

    3. Capability 1: Visualizing Context Usage

    Governance starts with measurement. Developers first need answers to a few basic questions. How many tokens are in use? How large is the model’s context window? How much room is left before automatic compression? Where are the tokens going? How much is taken up by the system prompt, the tool definitions, the chat content, and the tool outputs?

    Without measurement, developers judge whether the context is getting full mostly by guesswork. They often realize something is wrong only after the agent’s behavior has already become abnormal. Once usage is broken down by category, many problems become visible immediately. For example, tool output may occupy more than half of the context, and most of it may be outdated logs and repeated file contents. At that point, the priority is clear: clean up the tool output first instead of waiting for automatic compression.

    A simplified breakdown of context usage can be organized as follows:

    1. Context usage overview
    2. ├── System prompt and tool definitions Fixed overhead, usually cannot be trimmed
    3. ├── Conversation messages Developer instructions + agent replies
    4. │ ├── Early constraint segments ★ Must be kept
    5. │ └── Mid-session side questions Evaluate, then trim if unrelated
    6. └── Tool outputs
    7. ├── File read results Mark by whether they are outdated
    8. ├── Command execution logs Mark by whether the issue is fixed
    9. └── Error stack traces Mark by whether the error is resolved

    The value of this breakdown is that it turns a vague sense that “the context is almost full” into a specific, actionable judgment, such as “outdated logs account for a large share of the tool output.”

    4. Capability 2: Identifying and Marking Redundant Branches

    With visibility in place, the next step is to identify which content can be pruned. Based on common patterns in development work, the following types of redundancy are easy to recognize:

    (1) Stale file reads. When the same file is read several times and was modified in between, the reads from before the change are outdated. Such content should not be kept as is. Instead, replace it with a one-line note, for example: “This file was modified after this point. Read it again if needed.” This frees up space while preserving the signal that a read happened here, so the agent does not assume it never read the file.

    (2) Repeated tool calls and results. When identical call parameters produce identical results, keep only the most recent one and collapse the others into a one-line reference.

    (3) Resolved error paths. When a tool fails and then succeeds after adjustments, the full failure output can be collapsed. Keep only a marker saying the problem was resolved later. This works especially well when hundreds of lines of error logs were pasted and the problem was later fixed.

    (4) Unrelated detours. Side questions, small talk, and consultations unrelated to the current code changes can be collapsed or removed after review.

    This identification should not be fully automatic. A practical approach is for the system to propose candidate markers, then have the developer confirm before pruning runs. Judging whether a piece of content is truly unrelated requires business context. Algorithms can provide clues, but the final decision belongs to the developer.

    5. Capability 3: Locking In Key Constraints

    Pruning solves the problem of making room. A more fundamental problem remains: even with enough space, how can you ensure that the key constraints from the beginning of a long conversation keep getting the model’s attention?

    One effective approach is to lift key constraints out of ordinary conversation messages and store them in a separate, stable segment. The context structure can include a constraint zone dedicated to explicit rules the developer has declared as non-negotiable. During every compression, this zone is protected first and is never trimmed. This way, no matter how the conversation grows, those constraints stay in the context with high priority.

    From an engineering perspective, the context is no longer a flat list of messages in chronological order. It becomes a structured object with segment metadata:

    1. ContextSegment {
    2. type: "constraint" | "dialogue" | "tool_output"
    3. priority: "locked" | "normal" | "evictable"
    4. content: ...
    5. expires_at: <event marker, e.g. "invalid after the file is modified">
    6. }

    With this structure, when space is needed, the compression algorithm can clear evictable segments first, following their priority, instead of discarding content from the head of the list. locked constraint content always stays. This returns the decision about what to cut from the algorithm to the developer.

    6. Recommendations and Practical Points

    To put this approach into practice, follow these steps:

    1. Measure before changing anything: