Building a Self-Evolving Agent Loop: Architecture Breakdown
This article breaks down a self-evolving agent loop that lets AI agents retain knowledge and improve over time instead of forgetting everything after each session. It explains a three-subsystem architecture—a memory layer for stable facts, a skill layer for reusable procedures, and a reminder layer that triggers reflection—along with capacity limits, snapshot handling, write and eviction strategies, and common implementation pitfalls. Readers will find concrete design choices and sample code for building an agent that turns execution traces into accumulating assets.
Introduction: From Passive Execution to Continuous Growth
A long-standing pain point in agent engineering is that most agents enter an “amnesiac” state as soon as a single session ends. Users have to re-explain the environment, project conventions, and personal preferences every time. Two common approaches in the industry each have limitations: one relies on manually written rule files, so what the agent “knows how to do” depends entirely on how much a human has written; the other uses an append-only history, which works at first but quickly balloons over time, driving retrieval costs sharply upward.
This article uses the general technical problem of a “self-evolving loop” as its thread, and abstracts and reconstructs a practical architecture. The architecture is built from three cooperating subsystems: a storage layer responsible for factual memory, a skill layer responsible for consolidating experience, and a reminder layer responsible for triggering reflection. Together they form a positive feedback loop of “execute—distill—reuse,” so that the agent’s capabilities grow monotonically with usage time.
Overall Architecture: Three Subsystems, One Loop
The core of a self-evolving loop is to decouple “task execution” from “experience production,” and then periodically couple the two again.
- Memory subsystem: stores stable facts about the environment and the user, answering “Where am I, and who am I working for?”
- Skill subsystem: stores reusable procedures and lessons learned from mistakes, answering “How should this kind of problem be handled?”
- Reminder subsystem: triggers a review at the right moment, answering “What is worth consolidating right now?”
The loop runs as follows: the agent executes a task → the reminder layer triggers reflection at task boundaries → the reflection output is split into facts (written to memory) or procedures (written to skills) → the next session loads memory and matches skills → execution efficiency and success rate improve. If any link is missing, the loop degrades into a “one-off script.”
Memory Subsystem: Trading Capacity for Information Density
Two-File Structure with Separation of Responsibilities
A restrained implementation uses only two plain-text files, with entries separated by explicit delimiters:
~/.agent/├── MEMORY.md # Environment facts: directory conventions, dependency versions, tool quirks└── USER.md # User profile: preferences, communication style, collaboration habits
The value of separating responsibilities is that the read and write strategies can differ: environment facts change slowly and are reused frequently; the user profile changes even more slowly, but affects the tone and granularity of every interaction.
Hard Caps: Making “Forgetting” a First-Class Citizen
Setting fairly tight character limits on the two files (for example, on the order of a few thousand characters) is a key design tradeoff. Limited capacity forces the agent to compress information before writing: merging synonymous entries, deleting outdated conclusions, and keeping high-value facts. In contrast, an append-only mode often turns into an unmaintainable, extremely long text after a few months; retrieval requires a full scan, and the proportion of noise keeps rising.
In engineering terms, you can maintain two parallel states: a list of entries that is writable in real time, and a snapshot frozen at the start of a session. Sample code:
class MemoryStore:def __init__(self, memory_char_limit=2200, user_char_limit=1375):self.memory_entries = [] # writable in real timeself.user_entries = []self.memory_char_limit = memory_char_limitself.user_char_limit = user_char_limitself._snapshot = {"memory": "", "user": ""} # frozen within a sessiondef freeze(self):self._snapshot = {"memory": "\n".join(self.memory_entries),"user": "\n".join(self.user_entries),}
The frozen snapshot keeps the context stable within a single session and avoids mid-session rewrites that cause instruction drift; everything is written to disk together after the session ends, naturally forming a “batch commit.”
Write and Eviction Strategy
A three-stage process is recommended: candidate generation (extract facts from the task) → conflict resolution (compare against existing entries, then overwrite or merge) → budget trimming (when the limit is exceeded, evict by importance and freshness). Importance can be judged by “whether it affects the success or failure of subsequent tasks,” and freshness can be represented by the timestamp of the most recent verification.
Skill Subsystem: Turning Lessons Learned into Callable Assets
The goal of the skill layer is to upgrade experience from “narrative text” to a “searchable, parameterizable operations manual.” A qualified skill typically includes: applicable conditions, pre-checks, a sequence of steps, failure fallbacks, and verification methods.
Compared with manually written rules, the difference in automatically distilled skills lies in their source: skills are generated from real execution traces, so they naturally carry boundary conditions and exception branches. To prevent the skill library from expanding chaotically, you can introduce a two-level structure—the index layer stores only titles and trigger keywords, while the body is loaded on demand; a similarity merge threshold can also be set to prevent multiple near-duplicate skills from being consolidated for the same problem.
Reminder Subsystem: Triggering Reflection at the Right Moment
If reflection runs at every step, the cost is high and the noise is large; if it runs only at the end of a session, key details are easily missed. A workable strategy is to set lightweight triggers: a task status changes from “in progress” to “completed/failed,” a retry occurs, or an explicit user correction is detected. After a trigger fires, only a small-scale review is performed, producing structured candidates that the memory and skill layers each adjudicate.
Implementation Notes and Common Pitfalls
- Privacy and permissions: memory files may contain sensitive information, so support should be provided for per-directory isolation, redaction, and one-click clearing.
- Observability: record the source task of each write and the matched skill, making it easier to evaluate whether the loop actually delivers benefits.
- Preventing self-pollution: set a trial period and rollback mechanism for automatically generated skills, so incorrect experience cannot persist for long.
- For non-technical users: packaging visual editing of memory and skills, plus template-based consolidation, into a graphical interface is a key step in lowering the barrier to entry; deployment and operations can also be completed using general capabilities such as container platforms, log services, and monitoring and alerting offered by Baidu AI Cloud.
Conclusion
The essence of self-evolution is not “a longer context,” but “higher-quality consolidation.” Driving compression with capacity limits, driving skill generation with task traces, and driving reflection with event triggers—only when the three are combined can an agent evolve from a tool into an accumulating asset.
