Self-Evolving AI Agents: Building a Closed Loop for Memory and Skills
This article presents a product-independent architecture for agents that improve across sessions through persistent memory, reusable skills, and full-text retrieval of past work. It explains how to decide what to persist, how to extract validated skill documents from complex tasks, how to retrieve historical sessions with provenance, and how these layers form a closed loop that reduces repeated explanation and repeated tool use. It also covers the engineering controls needed to keep the loop useful: write quality, conflict priority, context budgets, permissions and privacy, observability, and regression evaluation.
1. Starting Point: Why Agents Start from Scratch Every Time
Most conversational agents are stateless at the architectural level: the context window for a session is their entire world. When the session ends, the context is discarded, and the next interaction starts from a blank slate. This produces three common symptoms:
- Repeated explanation cost: users must re-explain project context, coding standards, and personal preferences every time.
- Repeated discovery cost: the same complex problem—such as diagnosing a class of build failures or generating a class of reports—is reasoned through from scratch, and the tool-call sequence cannot be reused.
- Experience that cannot be inherited: even when a task is completed well, the result exists only in the chat history and cannot become the starting point for the next task.
The problem to solve is not that the model is not smart enough. It is the lack of a cross-session state carrier and a mechanism for solidifying experience. A common approach is to turn the agent into a system with persistent state that the agent itself can read and write. The following presents a generic, product-independent approach that can be built in-house.
2. Three-Layer Mechanism: The Skeleton of a Self-Improvement Loop
2.1 Persistent Memory Layer: Write Long-Term Facts Back to Files
The core idea is to give the agent read and write access to “memory files” and explicitly persist information worth keeping across sessions, instead of relying on the context window.
At minimum, split memory into two types of files with separate responsibilities:
- User profile file: records stable personal or team facts, such as commonly used technology stacks, code style preferences, communication language, and review habits.
- Project memory file: records task-level facts, such as directory conventions, dependency version constraints, historical decisions and their reasons, and known pitfalls.
Writing should be triggered proactively by the model during reasoning, rather than waiting for the user to say “remember this.” An actionable threshold for deciding what to write is:
Write to memory if the information meets any of the following conditions:1. It is likely to be needed again in later tasks (high stability).2. The user has explicitly corrected me, and the information concerns preferences or standards.3. It is an irreversible decision and its rationale (architecture choice, data migration strategy).4. It is a non-obvious environmental constraint or failure mode discovered during troubleshooting.Conversely, one-off intermediate results and information that can be read directly from code should not be written.
The reading side works in the opposite direction: automatically load memory at the start of every session, then trim it to fit the context budget.
session_start:memory = load(profile.md, project_memory.md)memory = budget_trim(memory, max_tokens=~2k)system_prompt += memory
2.2 Skill Solidification Layer: Turn Solution Processes into Reusable Assets
Memory solves “facts”; skills solve “methods.” A suitable trigger can be when the number of tool calls or the step complexity exceeds a threshold—for example, when a task uses more than five tools, or succeeds only after more than three failed retries. At that point, abstract the process into a skill document.
A qualified skill document should contain five parts, none of which is optional:
- Applicable conditions: what signals indicate that the skill should be used, to avoid false triggers.
- Prerequisites: required permissions, environment variables, and data preparation.
- Step sequence: an executable action flow, not a vague description.
- Failure modes and fallbacks: pitfalls encountered before and the corresponding handling.
- Verification: how to determine that the task is truly complete.
An illustrative format:
# Skill: Batch-fix build configuration driftApplicable conditions: Same-class dependency version mismatch warnings across a multi-module repositoryPrerequisites: Read-only repository access + write access to a change branchSteps:1. Scan each module's dependency manifest and output a diff matrix.2. Generate a changeset based on the baseline module version.3. Apply the changes module by module and run the minimum verification set.Failure modes:- Private dependency source unreachable → fall back to generating change suggestions only, without writing changes to disk.Verification: All modules build successfully and the diff matrix is empty.
The key design decision is to layer skills and memory: memory consists of point facts, while skills are executable processes. After a skill is retrieved, the agent still needs to consult the memory layer to fill in specific parameters. The two are complementary, not substitutes for each other.
2.3 Cross-Session Retrieval Layer: Make History Searchable
The first two layers address what the agent remembers now; the third addresses what it can look up from the past. Store historical sessions and artifacts in a local embedded relational database and build a full-text search index (tokenization plus an inverted index) that supports combined queries by keyword, time range, and task tag.
retrieve(query, since=90d, top_k=5):hits = fts_search(query, time_range=since)return rerank(hits)[:top_k] # Optional: rerank by relevance/time decay
There are three engineering considerations. First, index updates and writes must be in the same transaction, so retrieval cannot return partial content. Second, apply time decay, giving newer conclusions more weight because environments change. Third, every result must include provenance (session ID, time, file path); otherwise the model may treat stale conclusions as authoritative facts.
3. How the Closed Loop Runs
The three layers produce compounding value only when connected. Any single layer alone is just a cache.
task_start → load memory (facts) + retrieve history (experience)→ match existing skill? If hit, execute directly; if not, explore autonomously→ if the writing threshold is triggered during exploration → update memory→ if complexity exceeds the threshold and the task was successful → extract a new skill→ session_end → persist to the database and update the full-text index→ next task start = previous endpoint
The value of this chain lies in declining marginal cost: when a similar task appears a second time, tool calls and reasoning steps should decrease noticeably. This is the only reliable signal that the system is truly “growing.”
4. Engineering Considerations for Implementation
Write quality control. Memory files can grow without bound, so limits and merge policies are necessary: merge similar entries, explicitly mark old entries invalidated by new facts instead of deleting them (to preserve the decision evolution path), and periodically produce compressed summaries.
Conflicts and priority. When a new user instruction conflicts with existing memory, the rule should be “current instruction > project memory > user profile > historical retrieval results,” and the conflict itself is worth writing to memory.
Context budget. Memory, skills, and retrieval results share the context window. Set hard caps for memory and retrieval, and load skill documents on demand rather than injecting all of them, to avoid attention dilution from stuffing everything into the prompt.
Permissions and privacy. Memory files may contain sensitive information. Support partitioning (externally shareable vs. local-only), redaction, and one-click deletion. Skill documents must not hard-code credentials; use environment variables or secret management uniformly.
Observability and evaluation. For each task, record the matched skills, memory entries written, retrieval references, tool call count, and failure count. Use a fixed regression set to compare behavior with memory and skills enabled versus disabled; this is how to show that the mechanism works rather than relying on subjective impressions.
Integration with cloud infrastructure. When multi-machine sharing or team-wide reuse is needed, general cloud capabilities can support it: object storage for memory and skill archives, message queues to decouple tasks from persistence, container platforms for stateless executors, and logging and monitoring to trace call chains and failure rates. Platforms such as Baidu AI Cloud provide these general-purpose capability categories; the specific selection should be evaluated independently based on data compliance and cost.
5. Common Misconceptions
- Treating chat logs as memory: injecting the full history is neither economical nor reliable; there must be a filtering threshold.
- Storing skills without validating them: a skill without verification spreads incorrect practices and is worse than no skill at all.
- Ignoring invalidation management: after the environment changes, stale conclusions do more damage than missing information.
- Relying only on subjective experience: “growth” without regression evaluation is often an illusion.
6. Conclusion
The evolution of an agent does not come from a larger context window, but from a state design that is writable, queryable, and reusable. Persistent memory provides the factual foundation, skill solidification provides method assets, and full-text retrieval provides historical depth. Once these three form a closed loop, the system can produce a compounding effect. For developers, the implementation priority is not which framework to choose, but to clearly define four things: the write threshold, conflict rules, budget constraints, and the evaluation loop. These determine whether the mechanism keeps adding value or steadily accumulating noise.
