AI Coding Agent Memory System Architecture: Design and Practice
This article explains why memory engineering, not model capability, sets the ceiling for autonomous coding agents. It presents a five-layer memory model split by change frequency (system, project, module, session, and retrieval layers), then covers the core mechanisms around them: tiered loading, explicit and reviewable writes, invalidation and eviction, and deterministic conflict resolution. You will find concrete conventions for repository-level agreement files, decision records, security boundaries, anti-patterns to avoid, and three metrics for measuring whether a memory system is actually working.
1. Why memory engineering is the real ceiling on autonomous coding agents
A large language model is fundamentally a stateless function: it takes input, produces output, and resets the moment the process ends. Close the terminal or restart the process, and the model has no idea which file it edited last time, nor does it recall the three constraints the user explicitly stated. What we call “memory” is not storage that grows inside the model. It is an engineering system that reassembles the information that should be visible into the context window before every single call.
This defines the first-order constraint of any memory system: the window is finite, while information is effectively infinite. So the core question is not “how do we store more,” but “how do we store the right things at every call.” In practice, that question produces three recurring failure modes:
- Cross-session consistency breaks. Close the terminal and everything is forgotten. The user has to restate the project background, the technology choices, and the forbidden patterns over and over; collaboration cost grows linearly, and the agent never graduates beyond “temporary contractor.”
- Constraint drift. The project architecture has moved on, but memory still holds a three-month-old plan. The agent will confidently produce code against an outdated convention, and may even “fix” an implementation that was already correct. This class of error is harder to spot than a plain failure.
- Memory corruption (information pollution). Valid and stale entries coexist and contradict each other, so the model oscillates between conflicting instructions and behaves unpredictably. Long contexts also dilute attention: the more full history you pile in, the lower the compliance rate for the critical instructions becomes.
A workable memory system therefore has to answer four questions: where information is stored, when it is loaded, when it is updated, and when it is discarded. A system missing the last link is just technical debt that keeps expanding.
2. A general reference architecture: five memory layers split by change frequency
A fairly mature approach in the industry uses change frequency as the only splitting dimension and divides memory into five layers, forming a pyramid. The lower the layer, the more stable, the smaller, and the stronger the constraint. The higher the layer, the more volatile, the larger, and the more dependent on retrieval. Loading and eviction policies must be designed differently for each layer; one uniform logic cannot manage them all.
L1 System layer: hard-coded behavioral baseline
- Carrier: built into the runtime, not overridable by the user or by repository content.
- Content: tool capability descriptions, input/output constraints, execution permission policy, confirmation flow for irreversible operations.
- Loading: fully resident for the entire session.
- Key design point: safety constraints must be hard-coded, not written into an editable configuration file. When the agent can touch file deletion, force pushes to a repository, or changes to production, the safety boundary must never become a “soft setting” that project files can override. This is the foundation of the whole layered design.
L2 Project layer: repository-level team consensus
- Carrier: a convention file at the project root (a common industry practice is to name it with Markdown, e.g.
PROJECT.md), versioned together with the code. - Content: tech stack and versions, directory responsibilities, coding and naming conventions, testing and commit requirements, and an explicit “do not do this” list.
- Loading: fully injected at session start, with size strictly controlled, usually on the order of a few thousand tokens.
- Key design point: Markdown is chosen over structured configuration formats, and the reason is not expressiveness. It is that instruction-following rates for natural language are typically higher than for key-value structures. Markdown also supports comments, examples, and reviewable diffs, which keeps it maintainable by humans.
L3 Module layer: directory-level local conventions
- Carrier: convention files placed in subdirectories, co-located with the code they govern.
- Content: the module’s interface contracts, state management conventions, framework-specific idioms, locally forbidden dependencies.
- Loading: activated on demand by path. When the file touched this turn falls inside a given subtree, only the rules from that subtree and its ancestor chain are injected.
- Key design point: this is the main mechanism for solving “global rules fighting each other.” Local override takes precedence over upward inheritance, and the most specific layer wins on conflict — the same semantics as cascading rules in front-end styling.
repo/├── PROJECT.md # L2 global: tech stack, conventions, prohibitions├── services/│ ├── PROJECT.md # L3 service layer: interface contracts, error code conventions│ └── billing/PROJECT.md # L3 module layer: monetary amounts in integer cents, no floats└── .memory/├── decisions/ # L5 architecture decision records└── index.md # L5 retrieval entry point and summaries
L4 Session layer: rolling summary of the current task
- Carrier: structured session state held in memory.
- Content: the current goal, list of modified files, confirmed decisions, open questions, and the red lines the user stressed in this session.
- Loading: updated dynamically every turn using rolling compression — early conversation is summarized, recent conversation is kept verbatim.
- Key design point: summaries must be structured, not free-form prose. Representing “files changed” as a list rather than a narrative is what reliably prevents repeated edits and missed regression verification in long tasks.
L5 Retrieval layer: addressable long-term memory
- Carrier: vector indexes, full-text indexes, code structure indexes (symbol tables, call relationships, dependency graphs), and decision record files.
- Content: past decisions and their context, root causes of defects and their fixes, experience entries accumulated across sessions.
- Loading: retrieved on demand, with only the Top-K relevant fragments placed into context.
- Key design point: code retrieval cannot rely on semantic similarity alone. Hybrid retrieval (keyword matching + vector recall + structural relationship expansion) significantly outperforms pure vector recall, because precise strings like symbol names, error codes, and configuration keys are exactly what semantic vectors handle worst.
3. Core mechanisms: loading, writing, invalidation, and conflict resolution
Tiered loading, not full-volume infusion. An effective scheduling order is: L1 resident → L2 injected at startup → L3 activated by the operation path → L4 updated in real time → L5 retrieved on trigger. The goal is to make the share of “high-constraint, small-volume” information in every turn’s context as large as possible.
Memory writes must be explicit and reviewable. The recommended approach is to persist memory as human-readable files, so that each write becomes a reviewable change instead of an implicit model behavior. Whether to persist should split into two cases: only stable team consensus is promoted to long-term memory, while one-off debugging context should not be made permanent.
## Decision: store billing amounts as integer cents- Date: 2026-07-10- Context: floating-point accumulation introduced a 1-cent discrepancy in multi-currency settlement- Conclusion: internally use int64 cents everywhere, format only in the presentation layer- Scope: services/billing/**## Deprecated: global axios response interceptor unwrapping- Status: outdated (removed in 2026-05)- Handling: retained for retrieval only, not part of rule injection
Invalidation and eviction are the second life of a memory system. Attach a source, a timestamp, and an applicability scope to every memory entry, and set a review cycle. The eviction policy should cover: automatically invalidated when overridden by a higher-priority layer; not injected when the applicability scope no longer matches; downgraded to “retrieval only” when it passes the review cycle without confirmation; flagged for cleanup when it contradicts the facts in the code.
Conflict resolution follows a deterministic priority order: system-layer safety constraints > the user’s instruction in the current session > nearest module rules > project-global rules > retrieved historical experience. The priority must be explainable and reproducible; otherwise the same input produces two different outcomes and troubleshooting becomes extremely expensive.
4. Implementation and safety boundaries
- Draft by tool, review by human. A tool can scan the repository and generate a draft convention file (dependency list, directory structure, test commands), but a person must confirm it before it goes into the repository, so that the tool’s guesses never harden into team rules.
- Make memory audits routine. Include memory files in code review, and periodically run a “memory health check”: delete entries that contradict current reality, merge duplicates, and fill in missing metadata such as timestamps for incomplete entries.
- Put safety first. Credentials, tokens, and internal network addresses must never enter the memory store. Injected memory content should be treated as untrusted input, since file content can be used to indirectly manipulate agent behavior through injection. High-risk operations keep a separate confirmation step, and that step cannot be overridden by any memory layer.
- What cannot be measured cannot be optimized. Maintain a small regression task set plus a set of “constraint-following cases,” and track three metrics: constraint-following rate, first-pass success rate for cross-session tasks, and memory entry effectiveness (the share of entries actually referenced and not yet expired). Without metrics, a memory system will keep degrading without anyone noticing.
5. A platform perspective and common anti-patterns
Once memory outgrows a single repository, the engineering implementation usually lands on a combination of general-purpose cloud capabilities: object storage holds memory files and decision archives, a retrieval service holds the indexes, a message queue and container platform carry asynchronous index rebuild jobs, and logging plus monitoring/alerting services record the full trace of “this memory entry was injected, referenced, judged outdated.” General-purpose capabilities offered by providers such as Baidu AI Cloud can serve as an infrastructure reference for this kind of architecture, but the architectural principles are independent of any specific vendor.
The anti-patterns to avoid are: turning memory files into giant unmaintained lists; writing without deleting, which leads to corruption; making one-off debugging context permanent; injecting full history into every turn and diluting attention; describing facts that should be structured (such as “files changed”) in natural language; and allowing memory to override safety constraints.
Conclusion: memory engineering is essentially information management engineering, not an extension of model capability. Whoever defines “what to store, when to load it, when to invalidate it” more clearly is the one who can evolve a coding agent from a one-off code completion tool into an engineering partner you can trust over the long term.
