Context Pruning and Constraint Retention in Long Agent Conversations

    Long coding-agent sessions can lose the rules set at the start once automatic compression drops the oldest messages. This article explains how to separate context into constraints, states, stale observations, and noise, then apply targeted pruning, pinning, and post-compression checks to keep key constraints in place.

    1. Why Constraints Get Lost in Long Sessions

    When an AI coding assistant or general-purpose agent handles a large refactoring task, a single session often runs for several hours and can reach dozens or even hundreds of turns. The model’s context window is limited. When token usage approaches the limit, the runtime usually triggers automatic compression, which replaces earlier conversation with a summary or drops it entirely.

    Most default strategies process messages in chronological order, starting from the oldest. This is simple to implement, but it conflicts with how task information is structured. Rules that a developer sets at the start of a session, such as “Do not modify the database table schema” or “Keep external APIs backward compatible,” sit at the earliest positions and are the first to be pushed out of the window. After these rules are lost, the model may suggest changes that violate them in later turns, and it cannot detect that it is breaking a constraint.

    The root cause is that compression algorithms decide based on position or length. They cannot judge semantic importance. Deciding which content stays valid over the long term and which has expired requires input from the people doing the task.

    2. Four Types of Context Information

    Fine-grained context management starts by distinguishing information types. Context commonly falls into four categories:

    1. Constraints: Boundaries, conventions, prohibitions, and acceptance criteria set by the user. These stay valid for the whole session and should be kept permanently.
    2. State: The current task goal, completed steps, and open issues. This information changes as the task progresses, so the latest version should be kept.
    3. Stale observations: Early reads of a file that has since been read again, or command output that became invalid after code changed. Once new information overwrites them, they no longer serve as a reliable reference.
    4. Noise: Temporary off-topic questions and answers, large unfiltered logs and stack traces, and duplicate tool output unrelated to the current task.

    In real sessions, stale observations and noise take up much of the window. For example, if the model modifies a file but the context still holds the version read before the change, later reasoning may mix in outdated code. A few hundred lines of error output pasted during a failing test keep occupying the window even after the problem is fixed.

    3. First, See Where Tokens Go

    Observability is necessary before any cleanup. A useful context panel should show at least the following metrics:

    • Current token usage and the total size of the model’s window;
    • The remaining margin before the automatic compression threshold is reached;
    • A breakdown of usage by source: system prompt, tool definitions, conversation messages, and tool output.

    Once usage is broken down, the optimization direction becomes clear. If tool definitions take up a large share, consider loading tools on demand. If tool output takes the most space, cleanup should focus on truncating and deduplicating that output. Without this data, developers can only guess, and they may delete content that is still useful.

    4. Design Principle: Pin Constraints First, Then Prune Dead Branches

    Think of the context as a main line that needs protecting. Constraints on the main line must be pinned so compression does not remove them. Branches that drift away from the main line should be pruned promptly once they are confirmed to be irrelevant. This comes down to three principles.

    First, make constraints explicit and pin them. Extract the rules stated at the start of a session into a separate constraint list, kept in a fixed region that is included in every request. This region does not take part in chronological compression, and only the user can explicitly modify it.

    Second, replace stale information with fresh information. For repeated reads of the same file, keep only the most recent content. If a write happened in between, mark the older version as superseded.

    Third, handle large outputs in tiers. For test logs, build output, and similar content, keep the head and tail, error type lines, and names of failed test cases, and replace the rest with a summary. Also record where the original output is stored so it can be fetched again when needed.

    The following is a schematic data structure sketch that illustrates the design. It does not correspond to any specific framework’s interface:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class ContextItem:
    4. kind: str # "constraint" | "state" | "file_read" | "tool_output" | "chat"
    5. content: str
    6. tokens: int
    7. pinned: bool = False # Set to True for constraints; not removed during compression
    8. superseded: bool = False # Set to True once replaced by newer information
    9. ref: str | None = None # Storage location of the original content, for on-demand retrieval
    10. @dataclass
    11. class ContextManager:
    12. window: int
    13. threshold: float = 0.85
    14. items: list[ContextItem] = field(default_factory=list)
    15. def used(self) -> int:
    16. return sum(i.tokens for i in self.items if not i.superseded)
    17. def should_prune(self) -> bool:
    18. return self.used() >= self.window * self.threshold
    19. def prune(self) -> None:
    20. # 1. Remove superseded items
    21. self.items = [i for i in self.items if not i.superseded]
    22. # 2. Replace oversized non-constraint tool outputs with summaries (summary generation omitted here)
    23. for item in self.items:
    24. if item.kind == "tool_output" and item.tokens > 2000 and not item.pinned:
    25. ...
    26. # 3. Always keep pinned constraint items

    Implementation requires two points of care. First, deletion should be auditable and reversible. Second, pruned content is best kept as a reference, so later reasoning does not fail because information is missing.

    5. Methods for Marking Expired Content and Deduplication

    The method for identifying expired content can be simple. For file reads, record the path together with the modification time or content hash at the time of reading. When a later write occurs or the hash changes, mark the earlier read entry as superseded. For tool output, generate a key from the command and its arguments, so a new result for the same key replaces the old one.

    For off-topic questions, tag them as a separate branch when the user clearly switches topics. After the task returns to the main line, ask the user whether to archive the branch. The key point is not to delete automatically. Users sometimes refer back to earlier Q&A later in the conversation, and automatic deletion would break that thread of information.

    6. Verification After Compression

    Even with thorough cleanup beforehand, compression can still occur. After compression, verify that the constraint list is complete and that every constraint remains in the fixed region. At each important stage, restate key constraints to the model explicitly, and ask it to check its proposed changes against those constraints before proposing them.

    This step costs little, and it prevents the model from proposing plans late in a long session that conflict with the rules set at the beginning.

    7. Practical Recommendations and Limits

    1. Make constraints specific and checkable. “Stay compatible” is harder to enforce and verify than “Do not change the paths, parameter names, or response fields of published interfaces.”
    2. Keep the fixed region at a manageable size. When there are too many constraints, merge similar items and periodically confirm with the user which ones are still valid.
    3. Make automatic cleanup reversible. In high-risk scenarios, get user confirmation before deleting anything.
    4. Adjust cleanup strategy to the task type. Debugging tasks need to keep log details, while design tasks depend more on keeping records of decisions.

    8. Summary

    Context compression in long sessions should not rely only on chronological order. Separate constraints, state, stale observations, and noise, then apply a different strategy to each category. This keeps key rules stable across long conversations and lowers the chance that the model gives non-compliant suggestions late in a session. This approach does not depend on a specific tool and can apply to any agent system that supports context management.