Memory System Design for Self-Evolving AI Agents: Architecture and Engineering Practices
This article examines the engineering design of memory systems for self-evolving AI agents. It covers two structured long-term memory files—MEMORY.md for environment facts and lessons learned, and USER.md for user preferences—along with session-time prompt injection, SQLite FTS5-based conversation retrieval, skill consolidation, and practical considerations around memory conflicts, privacy, cost, and observability.
Memory System Design for Self-Evolving AI Agents: Architecture and Engineering Practices
1. Background: Why Agents Need to “Remember You”
Most current agent frameworks remain at the stage of “single-session intelligence.” Once a conversation ends, the agent knows nothing about the user, and the next interaction starts from scratch. The drawbacks are obvious: users must repeatedly explain background, preferences, and working conventions, and the agent cannot learn from past mistakes.
A truly valuable agent should have a complete learning loop: distill skills from experience, improve through use, proactively save knowledge, retrieve its own conversation history, and continuously deepen its understanding of the user across sessions. The key differentiator for this kind of self-evolving agent is not model capability alone, but the engineering design of its memory system.
2. The Core of the Memory System: Two Carefully Managed Files
A practical self-evolving agent typically maintains two structured long-term memory files and injects their contents into the system prompt at the start of each session.
2.1 MEMORY.md: Environment Facts and Lessons Learned
This file records “the agent’s understanding of the world.” Typical contents include:
- Environment facts: operating system, available tools, project path conventions, and similar details.
- Conventions and standards: for example, “tests must be run before committing code in this project” or “logs are written to a designated directory.”
- Lessons learned: root-cause analysis and avoidance strategies from failed tasks, such as “external API calls need timeout and retry handling; otherwise long-running tasks will be interrupted.”
2.2 USER.md: User Preferences and Communication Style
This file records “the agent’s understanding of the user,” for example:
- Whether the user prefers concise replies or detailed explanations.
- Code style preferences, such as functional style or naming conventions.
- Common workflows and areas of interest.
A sample MEMORY.md might look like this:
## Environment Facts- Development machine runs Linux with Python 3.11- Project code is located at ~/workspace/project## Lessons Learned- Run a dry-run before batch file operations to avoid accidental deletion- The user often runs long tasks late at night, so progress logs are required
3. Session Injection: Making Memory Effective in Every Conversation
Memory files are only static data. The key lies in the injection mechanism. A recommended approach is:
- At session start, read MEMORY.md and USER.md and concatenate them into the system prompt.
- During the session, the agent decides from the interaction whether there is new knowledge worth preserving.
- At session end or when a trigger condition is reached, update memory by adding, modifying, or merging entries.
A simplified injection flow example:
def build_system_prompt():memory = read_file("MEMORY.md")user_profile = read_file("USER.md")return f"""You are a self-evolving intelligent assistant.The following is your long-term memory:{memory}The following are the user's preferences:{user_profile}Please follow the above memory in your responses, and suggest memory updates when you discover important new facts."""
Note that injected content should be length-controlled and deduplicated to prevent the system prompt from growing without bound. Common practices include organizing by topic, periodically compressing summaries, and limiting the maximum number of entries per file.
4. Conversation History Retrieval: SQLite-Based Full-Text Search
File-based memory is suitable for storing “conclusion-level knowledge,” but users often need to look back at specific conversation details from weeks earlier. This requires a searchable conversation archive layer.
SQLite is a lightweight and sufficiently powerful choice: single-file deployment, zero operations overhead, and efficient retrieval when combined with the FTS5 full-text search extension. A basic table design is as follows:
-- Conversation message tableCREATE TABLE messages (id INTEGER PRIMARY KEY,session_id TEXT,role TEXT,content TEXT,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);-- FTS5 virtual table for full-text searchCREATE VIRTUAL TABLE messages_fts USING fts5(content, content='messages', content_rowid='id');
When writing messages, update the FTS table in sync. Retrieval can then be performed with:
SELECT m.created_at, m.contentFROM messages_fts fJOIN messages m ON m.id = f.rowidWHERE messages_fts MATCH 'deployment script'ORDER BY rankLIMIT 10;
The agent can wrap retrieval as a tool and call it as needed during a conversation. When the user asks, “How did we solve that configuration issue last time?”, the agent first retrieves the history and then answers based on the results, achieving evidence-based responses.
5. Skill Consolidation: From Experience to Reusable Capabilities
A step beyond memory is skill generation. When the agent finds that a solution for a certain type of task has reusable value, it can solidify it into a “skill”—usually an executable script plus usage instructions, stored in a skills directory. When similar tasks appear later, the agent can call the skill directly instead of exploring from scratch.
The key to the skill loop lies in triggering and validation:
- Trigger: the task repeats, or the user explicitly asks to “do it this way from now on.”
- Validation: after a skill is generated, test it on a small scale first. If it fails, roll back and record the lesson in MEMORY.md.
- Evolution: skills themselves can be modified and combined, forming an increasingly capable library.
6. Engineering Considerations
- Memory conflicts and staleness: memory entries should be reviewed regularly, and outdated information should be removed so the agent does not act on stale facts.
- Privacy and security: user profiles and conversation history are sensitive data. Access control should be enforced, and sensitive information should be desensitized before storage.
- Cost control: system prompt injection and full-text search both introduce overhead. Set limits on the number of entries and the number of retrieval results returned.
- Observability: add logging and human confirmation steps for memory updates and skill generation to prevent incorrect knowledge from being reinforced repeatedly.
7. Conclusion
The essence of a self-evolving agent is to elevate “memory” from an auxiliary feature to a core architecture: MEMORY.md captures environment and experience, USER.md describes user preferences, session injection keeps memory effective, SQLite full-text search connects conversation history, and the skill mechanism turns experience into reusable capabilities. For teams hoping to build long-term companion intelligent assistants, this design approach offers strong reference value. Models will change, but a carefully designed memory system is the foundation for an agent’s continuous evolution.
