Long Context Management for Agents: Stop Auto-Compaction from Erasing Your Constraints

    This article explains why long-running AI coding sessions forget early instructions once auto-compaction kicks in, and how a developer-controlled context governance workflow fixes it. You will see what actually bloats the context window, why position-based compression cannot judge semantic value, and how to add observability, declarative retain/drop rules, and a pre-compaction hook so critical constraints survive long tasks. It closes with practical habits for keeping boundaries stable across extended development sessions.

    1. The Problem: Why Agents “Forget the Brief” in Long Conversations

    Almost every developer working with an AI coding tool has hit the same awkward moment: a premise you stated repeatedly at the start of a session is completely gone dozens of turns later. A typical case looks like this — in the morning you clearly said “do not change the persistence layer’s table schema, and the external API must stay backward compatible,” and the tool honored that for the first few dozen turns. By the afternoon, turns have piled up, the context has swollen, auto-compaction fires, and the tool suddenly suggests “adding a field to the session table would be simpler.”

    This is not the model getting dumber. It is a structural weakness in context management under specific conditions. Mainstream auto-compaction strategies mostly use an approximately FIFO sliding eviction: they squeeze out the oldest messages first to free up token space. But the way humans express themselves when collaborating with a tool is the exact opposite — the statements that set rules, define boundaries, and draw red lines are almost all concentrated at the beginning of the session. So the constraints that most deserve protection disappear first, while the least valuable redundancy keeps occupying space.

    1.1 What Really Blows Up the Context Is Usually “Dead Branches”

    Reviewing the token composition of a long session shows that the bloat is highly concentrated:

    • The same file read repeatedly across multiple turns, while intermediate versions have already been rewritten by the tool, making the earlier reads stale;
    • Hundreds of lines of failing test logs pasted in at once, long since fixed, with the error text still taking up significant space;
    • Temporary side chatter inserted midway, such as asking what a particular English error message means, with no relation to the current change;
    • Rejected approaches during exploration, rolled-back patches, and repeated command output.

    These make up the “dead branches” in the context: they were useful at some point, but at the current moment they carry no decision value. What genuinely needs to stay resident long-term is constraints, goals, acceptance criteria, and key conclusions already reached — the so-called non-negotiable rules that keep you safe.

    1.2 Why You Shouldn’t Leave It All to the Compression Algorithm

    Auto-compaction decides based on position and size, not semantic value. It cannot distinguish “don’t touch the table schema” at the top from an unrelated piece of chatter at the top, nor can it tell whether a given log is already stale. Only someone who understands the business intent knows what can be dropped and what must be kept. So the right direction is not to make compression smarter, but to hand the retention decision back to the developer and perform an explicit context cleanup before auto-compaction triggers.

    2. The Approach: Let Developers Guard the “Sacred Timeline”

    One proven approach is to insert a human-led “branch pruning” step before auto-compaction: hold the main-line constraints firmly, and clear dead branches promptly. In engineering terms, a usable context governance plugin usually does only three things.

    2.1 See the Context First: Start with Observability

    Governance starts with visibility. The plugin first provides a live progress bar showing tokens consumed, the model’s total context window capacity, and how much headroom remains before the auto-compaction threshold, with usage broken down by source:

    1. Context Usage [=========-----------------] 47%
    2. window: 200K used: 94K headroom until compact: 106K
    3. breakdown:
    4. system prompt ...... 6K
    5. tool definitions ... 11K
    6. messages ........... 33K
    7. tool outputs ....... 44K <- main source of bloat

    Breaking usage down by source is the key to this step. In practice, tool outputs (file contents, logs, command echoes) are usually the largest consumer, followed by the tool definitions themselves. Once you can see the structure, optimization has a clear target instead of blindly deleting messages.

    2.2 Prune Dead Branches: Explicitly Mark What to Keep and What to Drop

    The second step is a declarative retention policy that lets developers describe in readable rules “what must stay and what can be pruned.” An example configuration:

    1. retain:
    2. - type: message
    3. match: "constraint|forbidden|must|acceptance criteria"
    4. pin: true # never evicted
    5. - type: file_snapshot
    6. keep: latest_only # keep only the newest version of a file
    7. drop:
    8. - type: tool_output
    9. match: "FAILED|Traceback"
    10. when: "a later PASSED result exists for the same case"
    11. - type: message
    12. tag: chitchat # manually tagged temporary chatter
    13. compact_hook: pre # run cleanup before auto-compaction

    Three of these rules offer the best return: keep only the newest snapshot of the same file; drop failing logs entirely once a later successful result supersedes them; and exclude messages tagged as chatter from the main line. These rules do not rely on semantic guessing — the decisions are explicit, reproducible, and won’t damage critical constraints by mistake.

    2.3 The Pre-Compaction Hook: Cleanup at the Right Moment

    The third step is binding the cleanup to the moment before auto-compaction triggers, rather than trying to repair things after compression finishes. Once compaction runs, the original messages have already been merged and the information loss is irreversible. A pre-hook guarantees pruning happens while there is still headroom and information is intact. A single cleanup pass usually frees a considerable amount of window space, letting long tasks finish within one session instead of repeatedly restating premises.

    3. Practical Recommendations and Benefits

    • Lock in constraints at session start. Consolidate immutable premises into a short statement and pin it to the top, instead of scattering them across many turns.
    • Break long tasks into stages. Split the session at verifiable milestones, and output a brief conclusion at the end of each stage as fixed input for the next.
    • Recycle tool outputs regularly. Prune large logs and full file contents right after use, keeping only conclusions and key excerpts.
    • Carry long-term memory in external artifacts. Put stable specs and interface contracts in repository docs or configuration for the tool to read on demand, rather than occupying the conversation window indefinitely.
    • Bring governance metrics into observability. Wire context usage, compaction trigger counts, and constraint violation counts into regular monitoring and alerting so improvements can be measured.

    Overall, long-conversation amnesia is not a model capability problem but a context budget allocation problem. Switching retention from algorithmic guessing to human declaration, and pruning branches before auto-compaction, keeps boundary constraints reliably in effect during long-cycle development tasks and noticeably reduces rework and risky changes. This approach aligns with the direction of Baidu AI Cloud’s work on AI-assisted programming and R&D efficiency: observability, interventability, and verifiability are the foundation of sustainable context governance.