Preserving Critical Constraints in Long Agent Coding Sessions: A Practical Guide
Automatic compression in long coding sessions often removes the oldest messages first, which tends to discard the constraints that matter most, such as schema rules and compatibility requirements. This guide explains how to sort session content into hard constraints, active working memory, and disposable traces, and how to keep constraints in a separate ledger that is injected into every request. It also covers layered context assembly, cleanup before compression, verifiable summaries, and checks after compression.
Where the problem comes from
Once an AI coding assistant enters a long session, its context window will eventually fill up. A common automatic compression strategy is simple: it removes the oldest messages first until the remaining content fits within the length the model can process. In casual chat, this is often acceptable. In engineering sessions that involve changing code, interfaces, or data models, it often causes problems.
The cause is not compression itself but how information is distributed over time. Rules, boundaries, and compatibility requirements are almost always stated at the start of a session. The content that fills the window is usually process noise from the middle and later stages. The same file gets read repeatedly, and earlier versions are already outdated. Long logs from failing tests keep occupying space after the bug is fixed. Unrelated side questions are kept as they were asked. As a result, the critical constraints disappear first, while low-value traces remain. In the later part of the session, the model still appears cooperative, but its suggestions may directly violate hard boundaries set earlier that day. Examples include changing table structures without permission, breaking external interface compatibility, or presenting a temporary workaround as a formal implementation.
Therefore, the goal for long sessions is not to buy a bigger window. The goal is to separate “what must be kept” from “first in, first out” and build an auditable, verifiable mechanism for preserving context fidelity.
Separate three types of information first
Before designing anything, divide session content into three categories so that all history is not treated as equally important.
Hard constraints. These include prohibitions, compatibility commitments, environment boundaries, acceptance criteria, and security red lines. For example: existing table structures must not be changed; external field names and error codes must stay compatible; changes are allowed only in specified directories; keys and production data must not enter prompts. This category has few items, but violating them is costly. It should be treated as a main thread that time cannot eliminate.
Active working memory. This includes the current task goal, confirmed design decisions, unfinished to-do items, the latest file summaries that are still valid, and assumptions being verified. These items can be updated and merged, but they must not be lost silently.
Disposable traces. This includes repeated full file contents, old versions overwritten by later changes, stack traces from bugs that have been fixed, unrelated side conversations, and lengthy raw output from tool calls. These occasionally help with retrospectives, but they are usually noise for continued reasoning.
If automatic compression only considers which content is older, it places categories 1 and 3 in the same elimination queue. The core of a fidelity mechanism is to ensure that elimination happens only to category 3, and that category 2 is rolled forward as an updated summary.
Why “remove the oldest first” fails systematically
Engineering conversations have three consistent features.
First, constraints come first. When people describe a task, they usually say what must not be done before explaining how to do it. These sentences are short and dense, yet they sit exactly where a compressor is most likely to delete.
Second, process growth comes later. Reading files, running tests, pasting logs, and trial and error all happen after the constraints are stated. A single tool output can run to hundreds of lines, and much of it is outdated by the next turn.
Third, the model does not automatically know which sentence is a rule. If the system prompt has no explicit reserved area, the compressor can only score content by position, length, or rough relevance. Relevance scoring is not reliable either. A sentence such as “do not change the schema” may share few words with a large block of business code that follows it, so its score can come out low.
For these reasons, raising the compression trigger threshold or reminding users to “repeat important points” only reduces the problem without eliminating it. What is needed is a retention channel that is independent of the conversation timeline.
Replace reliance on memory with a constraint ledger
A more reliable approach is to maintain a short constraint ledger outside the session and inject it into the context every time a request is assembled. The ledger is not a copy of the chat history. It is a set of rules that a person has confirmed.
Keep the fields restrained so the ledger does not turn into a second document that grows without limit:
- ID: used for reference and revocation, for example C-01.
- Type: forbid, require, compatibility, scope, or acceptance.
- Statement: one sentence that is executable and testable, avoiding vague wording such as “pay attention to quality.”
- Scope: the current task, this repository, this interface, or this release.
- Status: active, deferred, or retired.
- Source: the human confirmation that established the rule, not the model’s own description of it.
The following example shows the data shape only. It is not an interface definition for any specific platform.
id: C-01type: forbidscope: datastorestatus: activetext: Do not add, delete, or rename any fields in existing data tables. Any extension must go through a compatibility layer or a new table, and requires prior human confirmation.
The ledger should have a clear entry threshold: only sentences that the user has explicitly confirmed can be recorded. The model may propose a constraint, but it must not quietly turn its own inference into a hard rule. Retirement must be recorded. Otherwise, after the user casually backs off a rule later in the conversation, the system could keep enforcing a prohibition that was already withdrawn, or delete it without a trace.
Context assembly order
Each request sent to the model should assemble context in a fixed hierarchy, rather than flattening all history and trimming it afterward.
- System-level role and safety baseline. Keep this stable and do not let it change with the task conversation.
- Full text of the constraint ledger. Keep it short enough for the model to read in full. If it becomes too long, the rules are too scattered and should be merged rather than piled up.
- Current task card. Include the goal, the definition of done, and the scope of changes allowed in this session.
- Working memory summary. This covers recent decisions, key points of valid files, and open questions. The program generates it on a rolling basis and labels it with a “summary time” so that old conclusions are not treated as the latest facts.
- Recent raw turns. Keep only the few turns not yet covered by the summary, to preserve tone and unfinished tool calls.
- On-demand retrieved snippets. When the model needs old logs or earlier versions, fetch them from external storage rather than keeping them in the window at all times.
With this structure, the compressor mainly works on candidates from layers 5 and 6. Layer 2 never enters the pool of material that can be eliminated.
Identify garbage before compression
Before shortening any text, run a structured cleanup pass. This is usually more controllable than asking the model to summarize all history by itself.
- Deduplicate file reads: for each path, keep only the latest valid summary, and mark earlier full contents as superseded. If a write happened in between, treat earlier reads as expired by default.
- Fold test logs: when a failure has been fixed, replace the stack trace with a one-line conclusion such as “failed earlier, now passing.” Keep only the key error lines of an open defect, not the whole output.
- Trim tool receipts: for successful calls, keep the key parameters and the result code. For failed calls, keep the minimum information needed to reproduce the failure.
- Isolate side topics: put questions unrelated to the current change into a separate note that does not take part in the main summary.
- Deduplicate decisions: if the same issue came up several times, keep only the last conclusion confirmed by a human, and note that the earlier conclusions it replaced are no longer valid.
Where possible, cleanup rules should be applied by a program, for example “a later read of the same path overwrites an earlier one” or “when a test changes from failing to passing, fold its log.” If the model writes summaries freely, it may rewrite a prohibition as a suggestion or drop the “do not” entirely.
Make the summary verifiable
Use a fixed set of sections for the working memory summary instead of a free-form narrative paragraph:
- Goal: what this session is meant to deliver.
- Confirmed decisions: list only items a human has explicitly approved.
- Active constraints: reference them by ledger ID without rewording them, so the meaning does not drift with each summary.
- Current code facts: which paths have changed, whether interfaces have been touched, and the state of the tests.
- Open questions: points that need a human answer.
- Explicitly out of scope: prohibited items copied from the ledger, quoted verbatim.
Each version of the summary should record its source range, for example “covers up to turn N.” Each new version may only be an incremental update built on the previous one. If the summary conflicts with the ledger, the ledger wins. The conflict should be logged as a defect, not resolved by asking the model to “reconcile” them.
Regression checks after compression
After the context has been shortened, do not start large changes right away. Run a quick, inexpensive check to confirm that the main constraints are still present. The questions should come from the ledger, not be open-ended. For example:
- Is changing the structure of existing tables allowed? The expected answer should restate the relevant prohibition.
- What are the compatibility requirements for external interfaces?
- Which directories or modules may be changed in this session?
- Which actions must stop and wait for a request for approval first?
If an answer does not match the ledger, stop all further automatic changes, inject the ledger again, and alert the user. The value of this step is that it turns “compression damage” into a detectable event. Otherwise, the problem is only discovered after an incorrect patch has already been written to the repository.
Keep the check short, because a long check creates new noise. Three to five high-risk constraints cover most engineering incidents.
Working habits when collaborating with people
The mechanism can only lower the probability of errors. It does not replace how the task is explained. A few habits significantly reduce accidental deletions:
- Open with short sentences that state prohibitions, one rule per sentence, so they are easy to record. Avoid mixing background, preferences, and hard requirements in a single paragraph.
- When you change your mind mid-session, explicitly retire the old constraint. Do not just add “on second thought, it’s fine to change it” later on.
- Store long logs in an external record first. In the session, paste only the conclusion and the few lines needed to locate the problem.
- Open a separate session for unrelated questions. Mixing error explanations, concept lookups, and repository changes in one thread keeps distorting relevance judgments.
- For key decisions, have the assistant restate them as ledger entries, and get human confirmation before continuing to write code. The confirmation itself serves as the retention marker.
For teams, the constraint ledger and high-risk checklist can be placed in the repository’s task documentation, so that every new session loads the same boundaries from the start, rather than relying on luck in how a particular chat begins.
Common failure modes
Even with a ledger, several pitfalls need to be anticipated.
Ledger bloat. If everything is treated as sacred, the injected content ends up longer than the original conversation. The remedy is to set a limit and periodically merge repeated rules into more general clauses. Only items whose violation would cause data corruption, interface breakage, a security incident, or an unrecoverable state deserve to be hard constraints.
Summary smuggling. The model may write “prohibited” as “suggested to pause” in a summary, and later turns then follow the softened wording. The remedy is to reference only the original text by identifier, and to deny the summarizer any right to reword it.
Stale facts passing as current status. When a log is folded, writing only “the test failed earlier” may lead the model to believe it still fails. Status statements must carry the current conclusion, for example “this failure was resolved by a later change.”
Cross-task interference. If one session covers two unrelated tasks, constraints from the first task may wrongly block the second. The scope field exists to solve this problem. When the task changes, switch the scope rather than clearing all memory.
Implicit relaxation. If a user says “just temporarily change it” and the matching constraint is not marked as deferred, the check will still conflict. If the system marks it as deferred on its own, that amounts to granting an exception automatically. Both deferral and retirement should require explicit confirmation.
A minimal implementation
You do not need to wait for full platform support to build a minimal working loop outside the existing assistant workflow.
- Keep the constraint ledger as a plain text file or a structured note. A person maintains it, and it should stay within a few dozen entries.
- Before continuing a long task, place the ledger and the task card at the front of the current request, and state that later compression must not rewrite these sentences.
- At the end of each stage, have a person update the “current facts” in the working memory in their own words. Do not let failure logs accumulate unchanged.
- Before submitting or before starting a large change, run a constraint restatement check.
- Keep raw long logs and complete file histories in a record system outside the session, and retrieve them when needed rather than keeping them in the conversation.
If a team uses containerized builds, log services, and code review, add “Are the constraints still being respected?” to the review checklist. The change description should name the ledger entries this change touches, and reviewers should check the diff for anything out of bounds. This way, fidelity no longer exists only inside the chat window.
How to evaluate the results
Do not judge this mechanism by vague impressions such as “it feels smarter.” Track several process metrics instead. Check whether, in the second half of a long session, the assistant can still quote key prohibitions word for word. Check whether rework caused by violating agreed-upon opening constraints has decreased. Check whether the share of repeated file content and outdated logs in each request has dropped. Check whether the number of human-confirmed constraints stays stable rather than growing without limit. A team can measure all of these itself, so none of them depends on unverified performance claims.
Summary
Automatic compression in long sessions is not inherently dangerous. The real danger is that the order of elimination runs opposite to the importance of engineering information. Put hard constraints in a separate ledger that is injected on every request. Turn working memory into a summary that can be verified incrementally. Remove outdated reads, fixed logs, and side conversations from the resident window. Then run a short regression check after compression with a few targeted questions. This turns the statements made at the start of a session from memory that depends on luck into a repeatable process control. Window size still matters, but fidelity depends first on classifying, retaining, and verifying information, not on packing all history into a single round of reasoning.
