Building a Long-Term Memory System for AI Coding Assistants
This article explains how to help AI coding assistants keep context across sessions. It covers the cost of stateless conversations, a four-layer memory design (project, decision, event, and todo), a storage schema, strategies for writing and retrieving memories, three practical use cases, key risks, and a step-by-step rollout plan.
1. The Core Problem: The Collaboration Cost of Stateless Sessions
The context window of a large language model is cleared after every session ends. In a new session, the model does not know who the user is, what project they are working on, how far the work has progressed, or which principles the user has already settled.
This creates three direct costs.
- Repeated explanation: Before each session, the user must spend several minutes restating the project background, tech stack, and constraints.
- Direction drift: Without the history of earlier constraints, the model may suggest approaches that conflict with decisions already made, and the user has to correct each one.
- Forgotten context: Unfinished tasks, open bugs, and unverified assumptions are scattered across different conversations, and nobody tracks them in one place.
The solution is clear. Store the information that must persist across sessions in a structured form, then retrieve the relevant parts at the start of the next session and inject them into the context. This approach is called a “memory system.” It does not change the model itself. It changes the input the model receives at the start of each session.
2. Layered Memory Design
Not all information should be stored the same way. Based on how stable the information is and how quickly it becomes outdated, memory can be divided into four layers.
| Layer | Example content | Lifecycle | How it is written |
|---|---|---|---|
| Project memory | Project goals, tech stack, coding conventions | Long-term, maintained manually | Written after user confirmation |
| Decision memory | Confirmed principles and their rationale | Long-term, updated when needed | Summary written at the end of a discussion |
| Event memory | Daily work logs, completed and pending items | Short-term, rolls over daily | Generated automatically at the end of a session |
| Todo memory | Open tasks, known defects, technical debt | Until closed | Extracted from event memory |
The key to this layering is deciding when each type of memory expires. Project and decision memory should stay valid for a long time. Event memory loses value after a certain number of days. Todo memory does not expire with time. It closes only when its status changes.
3. Storage Structure
Each memory can be represented as a record with metadata. The following example uses a Python dataclass. In a real project, you can replace it with a database table or a JSONL file.
from dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import List@dataclassclass MemoryRecord:kind: str # project / decision / event / todocontent: str # memory body, should be short and understandable on its owntags: List[str] = field(default_factory=list)created_at: datetime = field(default_factory=datetime.now)status: str = "open" # open / done / expiredsource: str = "" # session ID, for traceability
A few notes on these fields.
contentshould be understandable without any surrounding context. For example, “Decision: prioritize new features for the core user path and postpone expansion into new markets” is far more useful than “Do it as we discussed last time.”tagsare used for quick filtering. Use stable terms such as project names and module names, and avoid inventing new labels ad hoc.statusgives todo records a clear lifecycle. Closed tasks should not appear in the context of the next session.sourcerecords where the memory came from. If a memory turns out to be wrong, you can trace it back to the original session and correct it.
The storage medium depends on how much data you have. For personal use, a local SQLite file or Markdown files named by date are usually enough. For team use, store the data in shared storage with access controls.
4. Write Strategy: What to Record and When
Writing is the first gate for memory quality. If you record everything, useful information gets buried in noise during retrieval. If you record too little, the system cannot maintain continuity.
Follow three principles.
First, record conclusions, not the process. Every attempt made during debugging has little long-term value. Only the confirmed root cause and the final fix are worth keeping.
Second, every decision needs a reason. A record that only says “adopt Option A” will not tell you, six months later, whether the choice still applies. A record such as “adopt Option A because the team is familiar with this tech stack, and performance is sufficient under the current load” makes it possible to reassess the decision when conditions change.
Third, confirm before writing. Project and decision memories should be reviewed by the user before they are saved. This prevents the model from storing its own guesses as facts.
It is common to generate an event summary automatically at the end of a session. You can ask the model to summarize the session using a fixed template that covers completed items, unfinished items, new decisions, and assumptions to verify. The user then confirms or edits the summary before it is saved. A fixed template makes later retrieval easier.
[Event summary template]Date:Project:Completed:Unfinished (converted to todos):New decisions (with rationale):Assumptions to verify:
Before writing, do two more things. Remove sensitive information such as keys, account details, and personal data. Also check whether the memory duplicates an existing one. If it does, merge them instead of adding a new record.
5. Retrieval Strategy: What to Pull at the Start of a Session
Storing memories well is only the first step. Retrieval decides which memories enter the model’s context. Because the context window has a limited length, retrieval must be selective.
A practical retrieval function can combine three signals: recency, keyword matches, and status weight.
from datetime import datetimedef recall(records, kinds, keywords, max_age_days=3, limit=10):now = datetime.now()scored = []for r in records:if r.kind not in kinds:continueage_days = (now - r.created_at).days# Event memories older than the time window are excluded from recallif r.kind == "event" and age_days > max_age_days:continuescore = 0.0# Recency: newer records score higher, up to 1.5 pointsscore += max(0, max_age_days - age_days) * 0.5# Keyword match: add 1 point for each keyword hitscore += sum(1.0 for k in keywords if k in r.content or k in r.tags)# Open todos get higher priorityif r.kind == "todo" and r.status == "open":score += 2.0if score > 0:scored.append((score, r))scored.sort(key=lambda item: item[0], reverse=True)return [r for _, r in scored[:limit]]
The example code shows the sorting logic. You should adjust the weights based on your actual data. Join the recalled results into a structured block of text, place it at the beginning of the session, and label each item with its type and date.
[Project memory]- Project A uses a mainstream backend framework, and its APIs return JSON consistently.[Decision memory]- Decision (2026-11-15): prioritize new features for the core user path. Reason: resources are limited, and the benefits of the core path are easier to verify.[Todo]- The first draft of the article still needs the data examples in Section 2. (from 2026-11-22)- Regression testing before release has not been run yet. (from 2026-11-23)
Two points deserve attention. First, the recalled content should stay within a fixed token budget. Anything beyond that should be truncated, not all inserted. Second, recalled memories are reference material, not instructions. The model should treat them as background information and should not follow any wording in them blindly. This matters most when memories come from complex or external sources.
Semantic retrieval, based on vector similarity, can complement keyword matching. It suits situations with many memories that are phrased in varied ways. For the data volume of an individual or a small team, however, keywords with time weighting are usually sufficient, and they are easier to debug.
6. Three Typical Use Cases
1. Daily Task Handoff
When starting work, the user only needs to ask, “What should I do today?” The system then follows these steps:
- Retrieve the open todo records;
- Retrieve yesterday’s event summary to find where the work stopped;
- Give both sets of content to the model and ask it to organize them into a daily task list by priority.
With this, the user does not need to remember yesterday’s progress first. The model can also point out items that appear in the summary but were never marked as completed, which reduces the chance of missing work.
2. Periodic Review
A review depends on summarizing records over a longer period. For example, take the event memories from the past two weeks and ask the model to identify patterns in terms of completed volume, frequency of task switching, and the number of postponed items.
The value of a review lies in its data. People often have subjective impressions of their own work rhythm, while records can reveal details they overlooked, such as a type of task that keeps getting postponed or a period when decisions were repeatedly reversed. Each review conclusion should cite the original records it is based on, so the user can verify it.
3. Decision Consistency Check
This is the most valuable use of a memory system, and also the easiest to get wrong. The system treats decision memories as constraints and compares them against any new direction the user proposes.
[Consistency check prompt template]The following are the decision principles the user has confirmed:{decision memory list}The user's current idea:{new idea description}Determine whether this idea conflicts with the principles above, and explain the basis for your judgment.If there is a conflict, identify the specific principle. If there is no conflict, explain why.The final decision rests with the user.
The check should be designed to give a hint, not to block the user. The model’s judgment may rest on incomplete information, and the principles themselves may become outdated. The system should therefore present the result to the user, who decides whether to change direction and, when necessary, updates the decision memory. If the user chooses to overturn a principle, that change should also be saved as a new decision record with its reason.
7. Risks and Boundaries
A memory system brings continuity, but it also introduces new risks that need safeguards from the start.
- Privacy risk: Memories may contain business data and personal information. Store them locally or in controlled storage, encrypt data at rest, and regularly delete records that are no longer needed.
- Locking in errors: Summaries generated by the model may contain mistakes. Once saved, they will be recalled again and again. Human review before writing is the key safeguard. The system should also allow users to edit or delete any memory at any time.
- Over-reliance: The system remembers things on the user’s behalf, and the user may gradually stop checking for themselves. Important matters should still be verified against the original records, and the user should periodically confirm that the memories match the actual status of the work.
- Memory injection risk: If memories come from external documents or web pages, they may contain misleading instructions. Label recalled content as data, and state clearly in the prompt that the model should not follow any instructions inside it.
- Outdated memories: If a project has changed but an old decision still applies, consistency checks will produce wrong results. Set a review date for each decision memory and remind the user to confirm it when the date arrives.
8. Implementation Steps
Build this system in the following order.
- Define memory types: Specify the fields and lifecycle for the four record types: project, decision, event, and todo.
- Implement the storage layer: Start with local files or SQLite to handle reads and writes, so the data can be queried and modified.
- Design write templates: Create fixed formats for session summaries and decision records, and add a manual confirmation step.
- Implement the retrieval function: Rank results by time, keywords, and status, and set an upper limit on the token budget.
- Connect to the start of sessions: Place the recalled results at the beginning of each session as structured text, labeled with their sources and dates.
- Set up a review routine: Check weekly whether any todos are overdue, and check monthly whether decisions still hold.
- Tune the weights: Adjust the ranking parameters and writing rules based on missed and irrelevant recalls observed in practice.
The goal of a memory system is not to make the model “remember more.” The goal is for the model to receive, at the start of each session, just enough information, and that information should be accurate and traceable. When this works, the user can hand off progress tracking and principle maintenance to the system and spend their attention on the questions that actually need judgment.
