AI Agent Self-Evolution Loop: Architecture Design Explained
This article breaks down the architecture of a self-improving AI agent as a closed loop built from three subsystems: a bounded memory layer for stable environment and user facts, a structured skill layer that turns execution experience into reusable playbooks, and a reflection scheduler that decides when to write memories or distill skills. It covers minimal text-file storage with hard character limits, the dual-state design of writable entries versus a frozen session snapshot, the trigger conditions and retirement rules for skills, rate-limited reflection with optional human review, and engineering pitfalls around externalized state, observability, prompt budget, privacy, and regression evaluation. Readers will learn why longer context is not the answer, and how bounded memory, structured skills, and controlled reflection make an agent more capable the longer it is used.
1. The Problem: Agents Forget Everything When the Session Ends
Most mainstream agent frameworks today rely on a stateless session model. Once a conversation turn ends, the context is discarded, and the next run starts from scratch when interpreting the environment and the user. This design has two immediate consequences.
First, the repeated cost is high. Users have to restate project conventions, directory layout, build commands, and code style over and over, while the agent keeps making the same mistakes.
Second, the capability boundary is fixed at initialization time. What an agent can do depends on how much documentation and how many rule files the developer supplied in advance. For scenarios the documentation never covered, the agent can barely cope on its own.
The emerging consensus in the industry is that keeping an agent useful over time requires persistent state across sessions, and that “execution experience” must be turned into a reusable asset. Three capability lines — factual memory, skill accumulation, and proactive reflection — form a single loop. This article abstracts them into three subsystems.
2. Overall Architecture: Three Subsystems, One Loop
The runtime of a self-improving agent typically has three layers:
- Fact layer (memory): records stable facts about the environment and the user.
- Capability layer (skills): records executable experience on how to get something done.
- Scheduling layer (reflection trigger): wakes the agent at the right moment to review recent execution and decide whether to write memory or distill a skill.
The data flow across the three is a one-way loop: the scheduling layer triggers reflection → the reflection result is written to the fact layer or the capability layer → the next task loads the updated state → efficiency and success rate improve → new execution traces are produced for the next round of reflection. The key to understanding this loop is that memory and skills are not two static configuration files, but dynamic state that is continuously rewritten.
3. Memory Subsystem: Using a Capacity Cap to Force Compression
3.1 A Minimal Storage Design
One approach that has proven effective is to maintain only two plain-text files: one for environment facts (project conventions, tool quirks, path rules) and one for the user profile (preferences, communication style, collaboration habits). Entries are separated by a consistent delimiter, so reading and writing are simple to implement. Humans can inspect and hand-edit the files directly, which makes this easier to operate and audit than a complex vector store.
A schematic layout:
memory_root/├── MEMORY.md # collection of environment fact entries└── USER.md # collection of user profile entries
3.2 Why a Hard Cap Is a Feature, Not a Flaw
Setting a fairly tight character limit on each file (for example, a few thousand characters) forces the agent to make trade-offs before writing: Is this fact stable? Will it be reused in future tasks? Can it be merged with an existing entry? Outdated entries are naturally pushed out when new ones are written, so file length stays within a bounded range over the long term.
Compare this with the common append-only memory implementation: the file grows monotonically over time and becomes a huge document of tens of thousands of lines after a few months, where retrieval can only scan the full text and noise far outweighs signal. Bounded capacity turns memory governance from an operations headache into default behavior at write time.
3.3 Dual-State Design: Writable Entries and a Frozen Snapshot
In implementation, two states need to be distinguished: a list of entries that is writable in real time, and a snapshot frozen at session start. The former is read and written by tool calls; the latter is used to build the system prompt for the current turn, which keeps the prompt stable and reproducible within a single session and avoids context drift caused by mid-session writes.
Sample code:
class MemoryStore:def __init__(self, memory_char_limit=2200, user_char_limit=1375):self.memory_entries: list[str] = [] # writable in real timeself.user_entries: list[str] = []self.memory_char_limit = memory_char_limitself.user_char_limit = user_char_limit# frozen at session start to keep the prompt stable within a turnself._snapshot: dict[str, str] = {"memory": "", "user": ""}def freeze(self):self._snapshot = {"memory": "\n".join(self.memory_entries),"user": "\n".join(self.user_entries),}
The write path should follow three steps: generate candidates → semantically deduplicate and merge against existing entries → if the limit is exceeded, score entries by “stability × reuse frequency” and evict the low-value ones.
4. Skill Subsystem: Turning Lessons Learned into Executable Playbooks
4.1 Where Skills Differ from Memory
Memory answers “what the facts are”; a skill answers “how to get something done.” A qualified skill should include: applicable conditions, prerequisites, step-by-step operations, a fallback plan for failures, and a verification method. It is longer and more structured than memory, so it does not belong in a memory file with a strict cap. It should be stored separately and loaded by semantic retrieval against the task at hand.
4.2 Trigger Conditions for Automatic Distillation
Skills should not be written every turn, or the store fills up with low-quality entries. Reasonable trigger conditions are: a task completed successfully after at least one failed retry during execution; the same class of task repeated enough times to cross a threshold; or the user explicitly confirming “follow this process from now on.” During distillation, the agent is required to emit a structured template, and the program then validates length and fields, sending anything that fails back for a rewrite.
4.3 Reuse and Retirement
The skill library also needs to be bounded. Entries can be ranked by a weighted score of “last used time + number of successful calls,” and entries with zero calls over a long period move to an archive area rather than being deleted outright, which avoids mistaken retirement. If two skills overlap semantically, they should be merged into one entry that keeps the branching conditions.
5. Reflection Scheduling: Making the Loop Actually Turn
The reflection trigger wakes the agent at the right moment. Common strategies include firing on a task-completion event, firing after a cumulative number of interaction turns, and firing on a timer during idle periods. Once triggered, a fixed flow runs: review the trace → extract candidate facts or skills → deduplicate and validate → write → record an audit log.
Scheduling must be rate-limited. It is advisable to set a cap on the number of reflections per session and a minimum interval between them, to prevent frequent writes from polluting memory. A manual review switch should also be kept, so that in enterprise scenarios key writes take effect only after confirmation.
6. Engineering Implementation and Common Pitfalls
- Externalized state: memory and skills should live on persistent, backup-friendly storage so data survives container rebuilds; multi-instance deployments need to serialize concurrent writes.
- Observability: collect metrics and retain logs for writes, evictions, and hits, so you can assess whether “better with use” is actually happening.
- Prompt budget: injected memory and skills both count against the context budget, so inject only the fragments relevant to the current turn rather than everything.
- Privacy and permissions: the user profile is sensitive data and should support tiered authorization, masked storage, and one-click deletion.
- Evaluation loop: maintain a fixed task set for regression testing and monitor success rate and average step count, so self-improvement does not degrade into self-reinforcing bias.
7. An Open Path for Non-Technical Users
These capabilities can be delivered to users who do not write code through a layer of abstraction on top: hide memory and skill management behind a configuration interface, and offer templated entry points such as “common preferences” and “standard operating procedures,” with the platform performing structured validation and deduplication in the background. In related practice at Baidu AI Cloud, capabilities of this kind are typically combined with general cloud product categories such as object storage, log services, and monitoring and alerting, in order to close the loop on state persistence, auditing, and runtime metrics.
8. Conclusion
The core of a self-improving agent is not a longer context, but three things: bounded memory, structured skills, and controlled reflection scheduling. Chain the three into a loop, add observability and manual review, and an agent can genuinely become more capable the longer it is used.
