Layered Context Memory for Large Codebases: Design and Engineering Practices
This article explores how AI coding assistants can manage limited context windows when working in large repositories. It presents a seven-layer memory model, describes implementation mechanisms for instruction, retrieval, session, and workspace memory, and discusses token budget allocation, common pitfalls, and a practical rollout checklist for teams.
1. Problem Background: Limited Windows, Growing Tasks
In real software development scenarios, an intelligent coding assistant must handle multiple types of information at the same time: reading source files from a large project, retrieving relevant code from the repository, recording the history of multiple editing rounds, preserving requirements and acceptance criteria, and including test output and error logs. Each type of information consumes part of the model’s context window. As soon as the project becomes moderately large, or the task spans multiple conversation turns, the window is quickly filled.
Window overflow usually has three consequences. First, early key constraints are pushed out of the window, and the model begins to violate coding standards that have already been established. Second, irrelevant files take up a large amount of space, the model’s attention is diluted, and modification quality declines. Third, the token cost of a single request increases with input length, and response latency grows accordingly.
Therefore, the core problem is not “how much content can be placed in the window,” but “which content should be placed in the window at each step.”
2. Why Simply Expanding the Window Does Not Solve the Problem
Many teams first consider switching to a model with a larger window. This direction has value, but it cannot solve the problem on its own for three reasons.
First, the longer the input, the higher the computation and cost. For development tools that are called frequently, this overhead accumulates continuously.
Second, information utilization within a long context is not uniform. It is widely observed in the industry that models are more likely to overlook content in the middle of the input and are more sensitive to content at the beginning and end. Putting an entire repository into the window at once does not automatically produce better results.
Third, the codebase itself changes quickly. Content loaded once may become outdated after several editing rounds, and retaining it may instead mislead subsequent judgments.
A more reasonable approach is therefore this: window capacity is a hard constraint, while memory management is a soft strategy. The two need to work together.
3. Basic Idea of Layered Memory
The core of layered memory is to classify information by “stability” and “frequency of use,” and then define the loading timing and priority for each category. The following gives a general structure using seven layers as an example. The number of layers can be increased or decreased according to project scale; the key is that the responsibility boundary of each layer must be clear.
| Layer | Content | Lifecycle | Loading Method |
|---|---|---|---|
| 1. Instruction layer | Coding standards, prohibitions, output format | Long-term stable | Always resident |
| 2. Project layer | Architecture overview, module responsibilities, directory conventions | Updated with releases | Always resident or high priority |
| 3. Task layer | Current goal, acceptance criteria, to-do steps | Within a single task | Always resident |
| 4. Session layer | Summaries of completed decisions and changes | Within a single session | Loaded after rolling compression |
| 5. Retrieval layer | Code snippets relevant to the current problem | Per request | Retrieved on demand |
| 6. Workspace layer | Currently open files, diffs, test results | Current editing cycle | Loaded on demand |
| 7. External layer | Third-party interface documentation, protocol descriptions | Long-term stable | Loaded when explicitly referenced |
The advantage of this division is that each layer has clear “entry” and “exit” rules. Resident layers ensure that constraints are not lost, while on-demand layers ensure that the window is not wasted.
4. Key Implementation Points
4.1 Instruction Layer and Project Layer: A Manual Written for the Model
Resident information should be short and accurate. Lengthy explanations consume a large amount of space, and the model may not be able to follow all of them. A better approach is to list constraints as items and include the basis for judgment.
# Project Conventions## Coding Standards- All public functions must have type annotations.- Database access must go through the repository layer only; do not execute queries directly in views.## Directory Structure- `services/`: business logic, independent of the HTTP framework.- `api/`: routing and parameter validation, calls services.## Prohibitions- Do not modify migration files that have already been released in `migrations/`.- Do not output user phone numbers or email addresses in logs.
Project-layer documentation should be maintained in sync with the code. If the documentation describes a module that has already been refactored, the model will act according to the old structure and introduce errors. It is recommended to include documentation updates in the code review process.
4.2 Retrieval Layer: Locate First, Then Read
A large repository should not be loaded in full. A more reasonable approach is to first find candidate files based on task keywords, and then read only the relevant snippets. The following example shows a simplified keyword retrieval function. In a real project, it can be replaced with a symbol index or a full-text search service.
import refrom pathlib import Pathdef find_related_files(repo: Path, keyword: str, limit: int = 5) -> list[Path]:"""Find relevant Python files in a repository by keyword and return the first few hits."""pattern = re.compile(re.escape(keyword))hits: list[Path] = []for path in repo.rglob("*.py"):try:text = path.read_text(encoding="utf-8")except (UnicodeDecodeError, OSError):continueif pattern.search(text):hits.append(path)if len(hits) >= limit:breakreturn hits
There are two points to note in this function. First, the number of results is capped to prevent a single retrieval from returning too much content. Second, files that fail to read are skipped directly to avoid interrupting the entire process. In real scenarios, dependency directories, generated files, and binary files should also be ignored to reduce noise.
4.3 Session Layer: Rolling Summaries Instead of Full Retention
Multiple editing rounds produce a large amount of intermediate process, such as failed attempts, repeated errors, and back-and-forth code changes. Most of this content has no long-term value, but the decision conclusions within it need to be retained. The rolling summary approach is as follows: when the session length approaches the budget, compress earlier conversations into brief conclusion records, keeping only constraints that are still valid and changes that have been completed.
from dataclasses import dataclass, field@dataclassclass LayeredMemory:budget_tokens: intlayers: dict[str, list[str]] = field(default_factory=lambda: {"rules": [], # Instruction layer"project": [], # Project layer"task": [], # Task layer"session": [], # Session layer (summary)"retrieved": [], # Retrieval layer})# Load priority: resident information before on-demand informationPRIORITY = ["rules", "task", "project", "session", "retrieved"]def assemble(self, count_tokens) -> str:"""Assemble context by priority; chunks that exceed the budget are not added."""packed: list[str] = []used = 0for layer in self.PRIORITY:for chunk in self.layers[layer]:cost = count_tokens(chunk)if used + cost > self.budget_tokens:continue # Skip the current chunk and try smaller later chunkspacked.append(chunk)used += costreturn "\n\n".join(packed)def compress_session(self, summarize) -> None:"""Merge historical entries in the session layer into a single summary."""if len(self.layers["session"]) > 1:merged = summarize(self.layers["session"])self.layers["session"] = [merged]
Here, count_tokens and summarize are both externally injected functions. The former can use the tokenizer corresponding to the model being used, and the latter can call the model to generate a summary or can first be implemented with rule-based methods, for example by keeping only sentences containing markers such as “decision,” “constraint,” or “completed.”
4.4 Workspace Layer: Replace Guesswork with Test Results
After editing code, the most reliable feedback comes from tests and static checks. Saving test output as part of the workspace layer allows the model to adjust modifications based on facts rather than repeatedly guessing the cause. In practice, the following loop can be followed:
- Modify the code.
- Run tests related to the change.
- Put only the names of failed cases, assertion information, and key stack traces into the context, omitting passing cases.
- Continue modifying based on the failure information until the related tests pass.
- Write the conclusions of this round into the session-layer summary.
The third step is especially important. A complete test log often contains a large amount of output unrelated to the problem, and trimming it can significantly reduce noise.
5. Token Budget Allocation
Within a fixed window, approximate quotas need to be set for each layer. The following is a common allocation reference; the specific proportions should be adjusted according to task type.
- Output reserve: set aside enough space in advance for the model’s answer and code generation; input should usually not fill the entire window.
- Instruction layer and task layer: prioritize these; they take up less space but have the greatest impact.
- Project layer: keep it concise and include only structural information, not implementation details.
- Retrieval layer: this is the flexible part; give it more space when the task is complex, and compress it when the task is simple.
- Session layer: keep only summaries to avoid unlimited growth of historical conversation.
There is no universal answer for budget allocation. A practical method is to record the actual token usage of each request, observe which layer most often exceeds the limit, and then adjust accordingly.
6. Common Pitfalls
Pitfall 1: Putting the entire repository into the context. This approach is costly and dilutes key information. The correct approach is to locate first and read afterward.
Pitfall 2: Summaries lose constraints. When compressing a session, the information most easily lost is the limiting conditions established early on, such as “do not change the return structure of a certain interface.” The summary template should include a dedicated “constraints” section to ensure that such information is retained.
Pitfall 3: Memory files become disconnected from the code. The documentation describes an old structure, and the model modifies based on it, which introduces errors. Memory files should be treated as part of the code and reviewed and updated together with the code.
Pitfall 4: Incorrect information is stored for a long time. If a reasoning round reaches an incorrect conclusion and writes it into memory, that error will be repeated in every subsequent request. Content written into long-term memory should be manually confirmed.
Pitfall 5: Sensitive information is written into memory files. Keys, credentials, and user privacy data should not appear in any memory layer. Keys should be provided by environment variables or a secret management service; the model only needs to know the variable names.
7. Rollout Checklist
To introduce layered memory within a team, the following steps can be used as a reference.
- Review existing coding standards and architecture documentation, remove outdated content, and keep them short enough for quick reading.
- Create a brief index document for the project that lists module responsibilities and entry files rather than enumerating all implementation details.
- Prepare task templates for common task types, such as adding an API, fixing a defect, or refactoring a module, and standardize the format of goals, constraints, and acceptance items.
- Add keyword retrieval or symbol indexing to the toolchain so that on-demand loading has a reliable entry point.
- Design a fixed template for session summaries that includes at least five parts: “goal, completed, pending, constraints, key decisions.”
- Regularly collect statistics on token usage and failure cases, identify the stages most frequently affected by limit overruns or misjudgments, and then decide the direction for optimization.
Layered memory does not require building a complete system all at once. Starting with the instruction layer and retrieval layer, and gradually adding session compression and the test feedback loop, can usually significantly improve stability and cost performance for long tasks.
