AI Agent Self-Evolution Loop: Architecture Design Breakdown

    This article breaks down the architecture of a self-evolving AI agent runtime built as a closed loop across three cooperating subsystems: memory, skills, and proactive reflection. It explains why session state that disappears after each conversation forces users to repeat context and lets the same mistakes recur, and why the two common workarounds—hand-written rule files and unbounded memory appends—both fall short. The core design uses hard character limits to force filtering and compression, a frozen snapshot plus a writable copy to keep prompts consistent within a session, four-element skill entries with deduplication and conflict resolution, and a structured reflection output that drives automated writes. It closes with production concerns such as persistence, concurrent writes, observability, privacy, and cost control. Readers will learn how to make experience retention and reuse a built-in part of an agent runtime rather than an external patch.

    1. The Problem: Why Most Agents Forget Everything After a Session

    A common structural flaw in current agent engineering is that session state does not carry over. Once a user finishes an interaction, the context is destroyed with the session, and the next run starts the agent from a “zero knowledge” state. This has two direct consequences: users have to repeatedly restate environment background, project conventions, and personal preferences; and the agent cannot accumulate lessons from past failures, so the same class of error reappears across different sessions.

    The industry typically responds in one of two ways. The first is for developers to hand-write rule files that feed domain knowledge to the agent as structured documents. The second is to append conversation history and memory entries without constraint. The first approach depends entirely on human effort for knowledge supply, and its coverage is limited by the author’s experience. The second lacks any eviction mechanism, so memory grows monotonically over time, retrieval cost rises, the noise ratio climbs in step, and the hit rate for useful information ultimately drops.

    The direction worth pursuing is to make learning a built-in stage of the agent runtime rather than a bolt-on patch. The example below uses three cooperating subsystems to show how this loop lands in engineering practice.

    2. Overall Architecture: Three Subsystems Forming a Loop

    The runtime of an agent that can improve continuously can usually be abstracted into three interlocking subsystems:

    • Memory subsystem: stores factual knowledge about the user and the runtime environment, answering “who you are and what your environment looks like”;
    • Skill subsystem: stores reusable procedures and lessons learned from failures, answering “how this kind of task should be done”;
    • Proactive reflection subsystem: triggers a review at the right moment, answering “is there anything worth distilling right now”.

    Together they form a loop: task execution produces raw experience, the reflection subsystem triggers consolidation at the right time, the consolidated results are written into memory and skills separately, and the next task reads this structured knowledge back, reducing trial and error and raising the first-attempt success rate. Missing any one link breaks the loop—memory without reflection makes consolidation depend on human discipline; reflection without skills leaves experience unstructured and unreusable.

    3. Memory Subsystem: Trading Capacity for Information Density

    3.1 A Minimal Storage Format

    One approach that has proven effective is to keep memory in just two plain text files: one recording the agent’s knowledge of the environment (environment facts, project conventions, unusual tool behavior), and one recording the agent’s knowledge of the user (preferences, communication style, collaboration habits). Entries are separated by a consistent delimiter so the program can parse and replace them one by one.

    A schematic structure:

    1. <agent_home>/memories/
    2. ├── MEMORY.md # Environment facts, project conventions, tool quirks
    3. └── USER.md # User preferences, communication style, working habits

    Choosing plain text is not a step backward but a deliberate decision: it is naturally versionable, human-reviewable, portable across tools, and easy to inject directly during prompt assembly.

    3.2 The Intent Behind a Hard Character Limit

    The key design choice is that capacity is deliberately kept tight—for example, on the order of roughly two thousand characters for environment memory and roughly one thousand characters for user knowledge. Limited capacity produces three chained effects:

    1. Forced filtering: before writing, you must judge whether a piece of information is important enough, and low-value content is naturally dropped;
    2. Forced compression: when a new entry exceeds the budget, old entries must be merged, rewritten, or evicted rather than appended to indefinitely;
    3. Stable retrieval: because total size is bounded, the token cost of injecting it into the prompt is controllable and latency is predictable.

    This contrasts sharply with append-only implementations. Those feel good early on, but after a few months the file swells to tens of thousands of lines, finding an old conclusion requires a full scan, and a large amount of stale facts conflicts with the current state and misleads decisions.

    3.3 Dual-State Design: Writable Copy and Frozen Snapshot

    The implementation needs to distinguish two states: a list of entries read and written in real time during the session, and a snapshot frozen at session start. The former supports immediate updates within the current round; the latter guarantees prompt consistency within the same session and avoids context drift caused by mid-session changes.

    1. class MemoryStore:
    2. def __init__(self, memory_char_limit=2200, user_char_limit=1375):
    3. self.memory_entries: list[str] = []
    4. self.user_entries: list[str] = []
    5. self.memory_char_limit = memory_char_limit
    6. self.user_char_limit = user_char_limit
    7. # Frozen at session start to keep the prompt stable within the session
    8. self._snapshot: dict[str, str] = {"memory": "", "user": ""}
    9. def render(self) -> dict[str, str]:
    10. """Assemble the text injected into the prompt; snapshot first for consistency"""
    11. return self._snapshot
    12. def upsert(self, entry: str, kind: str = "memory") -> bool:
    13. """Insert or replace one entry, trigger compression/eviction when over budget, return success"""
    14. ...

    Separating the snapshot from the live copy is essentially decoupling “consistency” from “writability”—a classic tradeoff every runtime that needs long-lived state runs into.

    4. Skill Subsystem: Turning Lessons Learned into Callable Assets

    Memory solves “facts”; skills solve “methods”. The granularity of a skill entry should be small enough to be reused in a single step—for example, “always push the image before deploying a stateful service” or “a certain class of API requires an idempotency key on retries”. Each skill typically contains four elements: trigger condition, steps, failure modes, and verification.

    The skill library needs three governance mechanisms:

    • Deduplication and merging: semantically similar entries are merged into one to avoid competing duplicate skills;
    • Effectiveness feedback: record invocation count and success rate, and downweight or retire entries that go unused for a long time or have a low success rate;
    • Conflict resolution: when two skills give opposite advice, the newer one with the higher success rate wins, and the change history is retained.

    Skills and memory must be strictly layered. Writing methods into memory eats into the already tight character budget; writing facts into skills pollutes the skill library with one-off information.

    5. Proactive Reflection Subsystem: Making Reviews Happen at the Right Time

    The trigger for the loop is the reflection mechanism. It does not need to be complex; the core is three strategies:

    1. Trigger timing: fire when a round of tasks ends, when errors repeat consecutively, or when the user expresses dissatisfaction;
    2. Review outline: a fixed question list—was this round’s goal met, what was the root cause of failure, which conclusion is worth reusing, which old memory has expired;
    3. Output constraint: the review must land on concrete write actions and produce parseable structured output, not a piece of free-form reflection.

    A schematic review output structure:

    1. {
    2. "outcome": "success | partial | failure",
    3. "root_cause": "image not pushed, causing pull failure",
    4. "new_skills": [{"trigger": "deploy stateful service", "steps": ["push image", "verify digest", "roll out"]}],
    5. "memory_updates": {"add": ["this project uses a private registry"], "remove": ["old registry address"]}
    6. }

    With structured output, the write stage can be automated, and only then is the loop truly closed.

    6. Engineering Implementation and Cloud Support

    To carry this mechanism in production, pay attention to the following engineering issues:

    • Persistence and consistency: memory and skill files need reliable persistence; object storage can be used for periodic snapshots and rollback;
    • Concurrent writes: with multiple sessions running in parallel, serialize writes with file locks or a single-writer queue to avoid entries overwriting each other;
    • Observability: bring reflection trigger counts, skill hit rates, and memory eviction counts into logging and monitoring/alerting, so you can quantify “whether it is actually getting stronger”;
    • Permissions and privacy: user knowledge is sensitive data, so support encrypted storage, per-session isolation, and one-click deletion;
    • Cost control: a budget constraint is also a cost constraint, and bounded memory naturally suppresses token growth.

    In related practice at Baidu AI Cloud, the capabilities above can typically be carried by combinations of general product categories such as object storage, container platforms, logging services, and monitoring/alerting, with no proprietary interface required to achieve persistence and observability for the loop.

    7. Conclusion

    The bottleneck in agent capability growth often lies not in the model itself but in whether the runtime has a mechanism where “experience is not discarded and can be reused”. Bounded-capacity memory that forces information compression, skill distillation standardized by four elements, and scheduled reflection driven by structured output—stacked together, these move an agent from “fed by humans” to “growing on its own”. This approach does not depend on a specific framework; any agent runtime with file read/write and prompt assembly capability can adopt it.