How to Add a Persistent Memory System to Your AI Coding Assistant
A practical guide to building an external, versionable memory layer for AI coding assistants. It covers a four-tier memory design (facts, decisions, progress, interaction), structured entry schemas, low-friction write and retrieval pipelines, conflict resolution and expiry rules, and a phased rollout plan to reduce repeated context setup across sessions.
1. The Problem: Sessions Are Stateless, Projects Are Not
When you work with an AI coding assistant over a long period, one pattern keeps repeating: every new session starts from zero. Before any real work happens, the developer has to spend several turns filling in the background — what the current iteration is aiming at, which modules were just changed, which tests still haven’t been run, why a particular approach was rejected last time. By the time the assistant is actually “up to speed,” a sizable share of the context window is already gone.
The root cause isn’t model capability. It’s the interaction model: sessions are short-lived and stateless, while projects are long-lived and stateful. The two operate on different time scales, so every piece of information that needs to cross session boundaries ends up carried in the developer’s head. Human memory is unreliable: forgetting details, drifting priorities, and getting pulled toward new ideas are all normal.
So the right abstraction is not “make the model remember.” It is to lift memory out of the session and turn it into an external system that is versionable, searchable, and auditable. The session is just an executor; memory is the asset.
2. Layered Memory Design: Four Types, Four Lifecycles
Stuffing everything into the context at once is a common mistake. It is expensive, and it drowns critical constraints in noise. A more robust approach is to layer memory, where each layer has different write permissions, update frequency, and eviction policy.
- Facts layer (long-term, stable): tech stack and version constraints, directory responsibilities, coding conventions, environment variable conventions. Changes are extremely rare, and entries are written only after human confirmation.
- Decisions layer (traceable): why A was chosen over B, guiding principles for a given judgment, rejected options and the reasons behind them. This is the most valuable layer, because it determines whether later trade-offs stay consistent.
- Progress layer (high-frequency, rolling): current tasks, unfinished items, known defects and technical debt, blockers. Rolled forward daily or per task.
- Interaction layer (disposable): drafts and temporary assumptions from the current discussion. Not persisted by default, to avoid polluting long-term memory.
The direct payoff of layering is retrieval precision. Answering “what should I do today” only needs the progress layer, while evaluating “should we take on this new requirement” must hit the decisions layer.
3. Entry Structure: Make Memory Machine-Readable, Not a Block of Prose
For a program to consume memory reliably, it has to be structured. Each entry should contain at least: a unique identifier, type, statement, source, confidence, timestamp, expiry condition, and linked entries.
{"id": "dec-2024-0117-scope-rule","type": "decision","statement": "Whether a new task is executed is judged by whether it strengthens the current impact path","rationale": "Avoid being pulled by short-term opportunities, which leads to too many threads left unfinished","source": "session-2024-0116","confidence": 0.9,"created_at": "2024-01-17T10:00:00Z","expires": null,"links": ["task-0115-doc-revision"]}
Two design points are worth stressing. First, rationale must live alongside statement; otherwise the assistant can only cite conclusions mechanically and cannot reason about edge cases. Second, expires and confidence are the key fields for memory governance: memory without an expiry condition piles up indefinitely, and eventually stale information dominates retrieval results.
4. Writing and Retrieval: Two Minimal Viable Pipelines
The write pipeline emphasizes low friction. A summary is triggered when a session ends or a phase completes; the assistant produces structured entry drafts, and the developer only confirms or corrects them. If every entry had to be written by hand, this system would be abandoned within two weeks.
def on_session_end(transcript):items = summarize_to_entries(transcript) # emit structured draftsfor it in items:if it.type in ("decision", "progress"):memory.upsert(it) # overwrite by same id, avoid duplicatesmemory.archive_expired(now())
The retrieval pipeline emphasizes constraints first, details second. When assembling context, inject in a fixed order: hard constraints (conventions, versions) → decision principles → current progress → the current question. The order itself is a form of prompt engineering, and it noticeably reduces the chance that constraints get ignored.
def build_context(query):return "\n".join([memory.query(type="fact", limit=20),memory.query(type="decision", limit=10),memory.query(type="progress", limit=15),query])
Storage selection doesn’t need to be complicated. When entries number in the thousands, local files plus an inverted index are enough. When multiple people need to share memory or sync across devices, consider a database or object storage to hold snapshots, a message queue for change notifications, and logging plus monitoring with alerting to watch write failure rates and retrieval hit rates. General-purpose offerings from cloud providers such as Baidu AI Cloud (databases, object storage, logging, monitoring and alerting) can serve as the underlying platform; the specific choice depends on team size and compliance requirements.
5. Conflict Resolution and Expiry: The Real Hard Part
Once memory accumulates, contradictions are almost inevitable: yesterday the interfaces come first, today tests come first. Without governance, the assistant picks randomly between two conflicting entries and its behavior becomes unpredictable. Three rules that work in practice:
- For the same topic, a new entry overrides the old one; the old entry is archived rather than deleted, preserving traceability.
- Type priority is fixed: the facts and decisions layers outrank the progress layer, and hard constraints cannot be overridden by a temporary preference.
- Run eviction periodically: entries past their
expiresvalue or not matched by retrieval for a long time are down-weighted, so noise doesn’t crowd out the context budget.
6. Two Typical Payoff Scenarios
Scenario one, progress handoff. At the start of a session, with no manual recap, the assistant immediately lists unfinished items, where things stopped last time, and outstanding defects — and can even flag overdue tasks on its own. It reduces the “recall cost” from a fixed daily expense to zero.
Scenario two, course correction. When a new requirement appears, the assistant searches the decisions layer first, and if the request conflicts with an existing principle it declines clearly and states the basis. People are easily led astray by an opportunity that looks good, and one persisted principle plus a collaborator with a stable memory can pull you back to the original path before the drift happens.
One boundary is worth adding: a memory system provides consistency, not judgment. The principles themselves must be set by people; the assistant’s job is only to retrieve them at the right moment and apply them.
7. A Suggested Rollout Schedule
Week one: build only the progress layer, and verify whether low-friction writing is genuinely sustainable. Week two: add the decisions layer and the conflict rules. Week three: complete eviction and archiving, and watch how context length and answer consistency change. The metrics don’t need to be complex: the number of turns spent manually filling in context each day, how often the same background has to be restated, and how much rework is caused by forgetting. If all three go down, the memory layer is starting to deliver real value.
The end state: sessions can be discarded at any time, while memory keeps accumulating. The developer shifts from “figure out what to work on today” to “just confirm and correct,” leaving energy for the parts that genuinely require judgment.
