Context Engineering for Coding Agents: A Practical Guide to Layered Management and Compression
Context management often determines whether an AI coding agent succeeds or fails—more so than model capability or tool count. This guide covers the three pillars of context design for coding agents: visibility into token usage, orderly layered compression when the context window fills up, and persistent memory across sessions. You'll learn how to audit context composition, control tool-definition overhead, configure compression rules, and maintain a layered memory system with clear content criteria.
Why Context Is the Fundamental Problem in Agent Design
When working with intelligent coding assistants (agent-based tools), most people focus on model capability, tool count, or workflow orchestration. In practice, however, context management is often what decides whether a task succeeds or fails. Whether you’re looking at the harness layer or the agent itself, the core job is selecting and arranging information within a finite context window.
The context window is a rigid resource: it must hold the system prompt, tool definitions, and conversation history, while also carrying dynamic content like file contents and command outputs. Poor design leads to two classic failure modes:
- Information overflow: total tokens approach the window limit, triggering forced compression that cuts critical information.
- Information pollution: low-value content (verbose command output, duplicated file contents) occupies the context long-term, diluting the model’s attention on what matters and degrading behavior.
A mature context design therefore rests on three pillars: visibility (knowing what’s in the context), layered compression (making room in an orderly way when space runs out), and persistent memory (retaining core knowledge across sessions and compressions). Let’s walk through each.
Context Composition and Visibility
Context typically consists of:
- The system prompt and built-in capability descriptions;
- Tool definitions (each tool’s name, parameter schema, and usage instructions);
- Project-level and user-level memory files;
- Conversation history (user instructions, model replies, tool calls and their results).
A good design must provide observability, letting users inspect the current context composition and token distribution at any time. For example, a built-in command that shows the share of each content type is the first step in diagnosing “why did the model suddenly get dumber.”
One easily overlooked hidden cost is the tool definitions themselves. Take a common external tool integration protocol as an example: connecting a service that exposes 20–30 tool definitions can consume 4k–6k tokens; connect five such services and tool definitions alone eat roughly 25k tokens—tools that won’t even be invoked in the vast majority of turns.
Practical recommendations:
- Only mount the tool services your current task actually needs, and unload them when done;
- Prefer integrations with a lean tool set, or use on-demand loading mechanisms to defer injecting tool definitions;
- Periodically audit token distribution with a context-inspection command and clear out anything that is “always resident but never used.”
Layered Context and Automatic Compression
3.1 When Compression Triggers
When total tokens approach the context window limit, the system triggers automatic compression. Compression is not simply “truncating the tail”—it’s an orderly process of relocating information.
3.2 The Three Actions of Compression
First, clear tool outputs. Historical outputs from retrieval, command execution, file reads/writes, and web searches are often bulky but extremely time-sensitive—they only have value in the turn where they were produced. During compression, these outputs are replaced with placeholders, keeping only the fact that “this operation was performed.”
Second, persist key memories. During normal operation, a background sub-agent can continuously extract key information from the conversation (user preferences, understanding of project structure, task progress) and write it to local memory files. When compression happens, the system reuses these already-distilled conclusions instead of relying on raw conversation text.
Third, generate a summary. The model summarizes the conversation history, the oldest content is cleared, and the summary is re-injected into the context—forming a rolling window that “keeps the recent, summarizes the distant.”
3.3 Flexible Triggering
The process should support multiple trigger modes:
- Automatic triggering at a threshold;
- Manual compression with a specified retention scope, e.g., “compress but keep XXX”;
- Compression rules written into the project memory file so compression follows team conventions—for example, “compression must always retain the current branch name, test commands, and the list of known issues.”
3.4 Limits of Compression and Fallback Options
Any summarization is lossy; automatic compression inevitably drops details. Two practical solutions:
Option one: explicit compression rules. Write “what must never be lost” into the project memory file so compression has clear guidance. This uses conventions to hedge against information loss.
Option two: manual takeover for long tasks. Disable automatic compression, manually summarize the prior context during the planning phase, review it, save it to a local file, then clear the session and reload that file to continue. This hands the pruning authority from the model back to the human. It costs a few extra steps, but guarantees zero loss of critical information. For complex refactoring tasks spanning days, this is far more reliable than repeated automatic compression.
The Memory System: Persistent Knowledge Across Sessions
4.1 What Memory Files Contain
A memory system typically consists of layered files at the project and user levels, with a dedicated command to view the memory currently in effect. The most important is the memory file at the project root—it is permanently in context, injected into every turn, so its content quality directly determines the starting point of every session.
4.2 Priority Design
Memory files should follow a clear override priority. A common design is:
CLAUDE.local.md > ./CLAUDE.md > ~/.claude/CLAUDE.md(local personal) (project) (user global)
Each layer has its own role:
- Local personal layer: a personal config in the project root that should be added to
.gitignore; records personal habits and local environment differences; - Project shared layer: at the project root, committed with the repository, shared by the team for project conventions;
- User global layer: global personal preferences under the home directory.
The same applies to configuration files: if hooks, plugins, permissions, and similar settings only apply to the current project, write them into the project-local config file to avoid polluting the global environment. Additionally, a special prefix (such as #) is often supported for quickly appending information to a memory file mid-conversation, lowering maintenance cost.
4.3 Content Trade-offs: What to Write and What Not to Write
Memory files are permanently in context—every line is a cost. The criteria can be summarized as a checklist.
What should be written:
- Correct build, test, and run commands—the information the model is most likely to guess wrong, where mistakes are most expensive;
- Key directory structure, module boundaries, and core constants—to help the model quickly build a mental model of the project;
- Naming conventions—to prevent style drift in every generation;
- Non-obvious environment configuration issues and known pitfalls—for example, “dependency X needs special flags in environment Y”—things that cannot be inferred from code;
- Things that must not be done, always paired with the alternative—saying “don’t use X” without “use Y instead” usually means the model keeps making the mistake;
- Information that must survive compression (anything compression would drop doesn’t need to be written);
- “Which document path to consult in which situation”—build a knowledge index, don’t move the knowledge itself.
What should not be written:
- Knowledge for infrequent tasks—move it to on-demand skill modules, injected only when needed;
- Large amounts of background material or full API documentation—replace with a single line like “see path/to/doc” so the model reads it on its own when needed;
- Vague principles like “write high-quality code”—unactionable platitudes only waste tokens;
- Information the model can obviously infer by reading the repository;
- Rules that only forbid without offering an alternative.
A typical anti-pattern is using special syntax to reference a file, which loads the entire file into context. The right approach is a plain-text path, e.g., “see src/api/client.ts,” avoiding loading the whole file.
4.4 Maintaining Memory
A memory file is not a static document written once. In practice, you can let the agent maintain its own memory files: whenever it confirms a long-lived project fact during a conversation, it appends it; when it finds an entry is outdated, it updates or deletes it. Humans only need to review periodically, so memory quality keeps improving with use.
Conclusion
Context design spans the entire lifecycle of an agent system and can be condensed into four engineering principles:
- Visibility first: provide ways to inspect context composition; hidden costs like tool definitions must be auditable;
- Orderly compression: clear tool outputs, persist memories, generate summaries—in that order; write compression rules as conventions, and use manual takeover as the fallback for complex long tasks;
- Layered memory: personal, project, and global layers with clear override priorities, each serving its own purpose;
- Restraint with resident content: for every line that lives permanently in context, ask “what mistake does this prevent the model from making?”—keep what prevents errors, and move the rest to on-demand loading or a document index.
Treat context as a resource that requires continuous operation and maintenance, and your agent will perform reliably across long tasks and multi-session scenarios.
