# When the context is nearly full, what do I compress and what do I externalize?

Date: 2026-02-06
Category: Technology
Tags: Context Management, Agent, Engineering Practices
Summary: When long conversations reach 170k–180k tokens, the model starts forgetting things. I split content into compressible and non-compressible categories, moved large blocks of material outside the context, and also noted where this approach fails.

One afternoon, a session modifying the order export logic was in its later stages. The token counter in the bottom right corner had climbed past a hundred thousand, approaching the limit. The change wasn't sudden: it first re-read a file it had just read, then completely forgot my earlier instruction "don't touch the migration," and casually wrote a new migration script.

My first reaction was crude: I told it to summarize the preceding conversation. An eight-hundred-word summary came back, fluent and reasonably information-dense. But what it missed was exactly the most expensive stuff: two approaches I had rejected, the exact path of one interface, and that line "don't touch the migration."

After that, I split the problem in two: what can be compressed, and what must be moved outside the context.

## Three kinds of "remembering," wildly different costs

I categorized what's in the context and found that their losses under compression are on completely different orders of magnitude.

Conversation history—"what we talked about"—is the most diluted. Detours, repeated confirmations, typos I made while typing: compressing away ninety percent of it doesn't hurt.

Working state is different: what the goal is, which step we're on, what's next, where we're stuck. Very few words, but once lost, the model starts spinning in place. I've seen it re-modify a function I had already finished changing.

The hardest to handle is facts and constraints: interface signatures, file paths, verbatim error messages, approaches I explicitly rejected. These are short, hard, and non-derivable. The model can't guess from elsewhere that the primary key of the `orders` table is a composite key, nor can it guess why I rejected that approach.

Compressing the first kind is called tidying; compressing the second is called amnesia; compressing the third is called an accident. My earlier "summarize it" was indiscriminately mashing all three together and handing them to the model, then praying it understood the priorities. It doesn't.

What I do now is put a `state.md` in the project directory, thirty or forty lines, appending a few lines each time a long task advances a step:

```markdown
## 目标
订单导出改成分页拉取，兼容旧接口

## 不可动的约束
- 不要新增 migration，schema 由 DBA 那边统一走
- /api/v2/orders/export 的响应结构不能变，前端已经上线

## 已完成
- 分页拉取写完，单测过

## 待办 / 已知坑
- 大数据量下的超时没测，本地只有 3 万行数据
```

This file sits at the start of the context, and any compression routes around it. Its job is to turn the part of the state that lives in my head into a piece of original text that doesn't participate in summarization.

This approach has an obvious weakness: what goes into `state.md` depends entirely on my judgment at that moment about what will be needed later. If I judge wrong, compression is protecting something unimportant while the truly critical constraints still get lost. So when I write it now, I deliberately keep one extra category: rejected approaches and the reasons. Goals change, to-dos change, but "why not to do it this way" tends to stay valid throughout the same project.

## Compression is encoding, not retelling

After realizing one thing, I adjusted the parameters: the summary model's goal is "coverage," not "fidelity." It prioritizes information-dense, narratively complete passages, and naturally tends to omit negative sentences and short, hard facts. "Don't touch X" evaporates especially easily in summaries because semantically it carries no new information.

I tried two versions of the prompt. The first was "please summarize the above conversation," and what came out read like meeting minutes. The second changed to giving an incompressible list, explicitly listing four categories that must be preserved verbatim: verbatim error messages, interface signatures and paths, rejected approaches and reasons, and the negative requirements in my own words. For the same 60k-token history, the second version produced a longer, more list-like summary, but with noticeably fewer omissions.

The cost is that the summary itself gets longer. The compression ratio dropped from about 20:1 to 8:1, but I don't need such a high ratio—I need it to still be able to keep working after compressing.

The more fundamental problem is that the summary model doesn't know what I'm going to do next. It can only rank by "how much information this passage carries in itself," whereas what I need is "whether this passage is useful for the next half hour." These two rankings often disagree. A fifty-line error stack looks highly redundant to the summary model, but it's exactly the keyword I need to search with next. This is why the incompressible list must be written by a human—letting the model judge what's important is equivalent to outsourcing the step that should least be outsourced.

The layered approach is similar, just allocating budget by distance:

```python
def plan_budget(total=200_000, reserve=25_000):
    usable  = total - reserve           # 留给输出和工具返回
    recent  = int(usable * 0.25)        # 最近几轮，保留原文
    middle  = int(usable * 0.45)        # 中段，压成要点
    early   = int(usable * 0.20)        # 早期，只留结论
    index   = usable - recent - middle - early
    return recent, middle, early, index
```

The most recent six to ten turns keep the original text; this part is the anchor for the model to understand "what I'm doing right now," and compressing it is actually more expensive. The middle section is compressed into bullet points, and the early part keeps only conclusions and constraints. The last block has a fixed budget for the index and state file.

There's one category I simply don't allow to be rewritten: paths, commands, error messages. I learned this the hard way once—`/api/v2/orders` was compressed into "the order interface" in a summary, and later the model filled in a `/api/orders` on its own; it took half an hour of debugging to discover it had made it up. Numbers and identifiers are now all required to be carried over verbatim.

## Externalization: context is a cache, not a warehouse

No matter how careful the compression, it's still lossy. The easier approach is to keep large chunks from entering in the first place.

The most direct one: don't paste entire files into the conversation—tell it the path and let it read them itself. I used to paste two or three hundred lines of config in for peace of mind; now I just paste the path plus a sentence about "what this file defines." When needed, it reads it itself, and if it reads wrong, it can re-read.

The second is to put exploration into sub-contexts. Have it find "where the export logic is called"—this kind of search flips through a dozen files, and fragments of each pile into the main context, tens of k tokens gone, with maybe only five lines of conclusion useful in the end. Now I have this kind of work done in subtasks that bring back only the conclusion. The payoff from this change is bigger than any compression trick, especially for exploratory tasks.

The third is landing intermediate artifacts. Long generated documents, big SQL blocks, experimental scripts—all written to files, with only the path and a one-line note left in the conversation. Drafts scrolling through the conversation are the most expensive garbage: they occupy tokens and can be mistaken by the summary model for conclusions at any moment.

Externalization has another cost that's rarely mentioned: latency. Every "let it read it itself" is a round trip, and reading three files versus one is perceptibly different in interaction feel. So my trade-off is to externalize only files big enough to be worth it; a few dozen lines of config are faster to just paste.

It also introduces two new failure modes: the model can't find something, or it finds it but reads the wrong version. I've hit the former—I moved a document under `docs/design/` and forgot to leave an index in the context, and it went around four rounds before giving up. So anything externalized must satisfy two conditions: a stable path, and a sentence in the context saying what it is. Miss one, and the model resorts to guessing.

## When to just start a new session

I initially thought every scenario should be compressed, then found that half the cases should start a new session.

The criterion is simple to the point of being crude: if the goal changes, start a new one; if the goal doesn't change, compress. Pushing the same goal forward, compression is reasonable because the earlier conclusions still hold. Once the goal switches—from "modify the export logic" to "troubleshoot the online timeout"—staying in the old context only cross-contaminates; the model treats the old task's constraints as the new task's constraints. I've run into this more than once.

I underestimated the startup cost of a new session for a long time. Reading through `state.md`, reading two or three related files, confirming the constraints—about two or three rounds of work. That cost is far lower than wrangling a model with a failing memory in a 170k-token context.

Conversely, there's one case where I'd rather stay in the old session: the task itself hasn't changed, but the model needs to maintain a sense of continuity with the code style. Switching sessions then makes what it writes feel like a different person wrote it—functionally correct, but awkward to read. This loss is hard to quantify, but it's quite noticeable when editing copy or writing frontend components.

The compromise is to split a single session into stages, settling up at the end of each stage: write that stage's conclusions into `state.md`, then let the context restart from the next stage. This amounts to manually controlling when compaction happens, rather than waiting for it to hit the limit and be triggered passively. Passively triggered compaction is the worst—it usually happens halfway through a task, when the context is at its most chaotic.

My current habit is to put a `state.md` in every long-task directory, with the last line always reading "next step." When I reopened the session this morning, it read that line and picked right back up, saving ten minutes of re-explaining. The problem is I often forget to update that line. The current workaround is to have it append on its own after every code change, and once it accumulates to around twenty lines, I manually merge them once. I'm still testing this threshold—whether twenty lines is too frequent, I haven't decided.

Further reading: [The hard part of an Agent isn't getting it to run, it's converging after it goes wrong](/2025/09/03/ai-agent-engineering-interview-tool-callingmemoryragplanning--executio/)
