Building a Self-Evolving AI Agent Loop: Memory and Skill Retention in Practice

    This article explains how to build a self-evolving feedback loop for AI agents that turns execution experience into reusable assets. It covers a three-subsystem architecture—memory, skills, and reflection scheduling—and details how capacity limits force information compression, how to turn debugging experience into callable skill units, how to trigger reflection at low frequency to avoid metacognition overhead, and how to control security and cost. A phased rollout path is also provided.

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

    In intelligent coding and automated office workflows, a recurring pain point is that an agent performs well within a single session, but once the session ends, the context is cleared. The next time it faces a similar task, it has to reason from scratch. The two common remedies in the industry both have clear drawbacks.

    The first is “pure append-only memory.” All historical conclusions are continuously written into one long text file. This looks effective in the short term, but after a few months the file swells to tens of thousands of lines. Retrieval requires reading the whole file, where noise far outweighs signal, and outdated information cannot be retired automatically.

    The second is a “manually written skill library.” Developers hand-write rule files that read like operation manuals in advance. The agent can do only what has been written; anything not written is beyond its reach. Its ceiling is locked by the amount of human effort invested, and it cannot grow automatically through usage.

    From an engineering perspective, both approaches share the same problem: they lack a feedback loop that converts “execution experience” into “reusable assets.” This article discusses, in a general architecture, how to build such a loop, and describes the categories of general capabilities that can be reused when implementing it on cloud platforms such as Baidu AI Cloud.

    2. Overall Architecture: Three Subsystems and One Loop

    A usable self-evolving loop typically consists of three subsystems, each addressing one of three questions: “what to remember,” “how to reuse,” and “when to reflect.”

    • Memory subsystem: stores environment facts and user preferences, determining the agent’s “understanding of you.”
    • Skill subsystem: turns a one-off problem-solving process into a callable, versionable unit of capability.
    • Reflection scheduling subsystem: triggers experience distillation at the right time, avoiding expensive metacognition overhead on every turn.

    The loop runs in this order: task execution → trigger reflection → distill candidate experience → deduplicate and validate → write to memory or generate a skill → the next task calls it directly. The key is that the “execution result” must become part of the input for the next round; otherwise the loop does not hold.

    3. Memory Subsystem: Using Capacity Limits to Force Information Compression

    The core of memory design is not “storing a lot” but “storing accurately.” One proven approach is minimal layering: maintain only two plain text files. One records environment and project facts (tech stack versions, directory conventions, build commands, known abnormal behavior of tools), and the other records a user profile (communication style, output format preferences, review habits, long-term goals). Entries are separated by a uniform delimiter to make programmatic addition and deletion easy.

    What really determines quality is the capacity limit. Capping the fact file and the profile file at a few thousand characters each forces the agent to make trade-offs before writing: keep only facts with high reuse value that remain stable across sessions, and let one-off details decay naturally in the session context. This is a sharp contrast with “infinite appending”—whose problem is not storage cost but signal-to-noise ratio monotonically worsening over time.

    For implementation, it is recommended to maintain two parallel states: one is a list of entries that can be read and written in real time, and the other is a snapshot frozen at the start of the session. The system prompt uses only the snapshot, avoiding prompt drift, cache invalidation, and inconsistent behavior caused by memory changes within the same session.

    1. class MemoryStore:
    2. def __init__(self, fact_limit=2200, user_limit=1375):
    3. self.fact_entries = [] # real-time writable entries
    4. self.user_entries = []
    5. self.fact_limit = fact_limit
    6. self.user_limit = user_limit
    7. self._snapshot = {"fact": "", "user": ""} # session-level frozen snapshot
    8. def freeze(self):
    9. self._snapshot = {
    10. "fact": "\n".join(self.fact_entries)[: self.fact_limit],
    11. "user": "\n".join(self.user_entries)[: self.user_limit],
    12. }
    13. return self._snapshot
    14. def upsert(self, entry, user=False):
    15. target = self.user_entries if user else self.fact_entries
    16. limit = self.user_limit if user else self.fact_limit
    17. if entry in target:
    18. return False
    19. target.append(entry)
    20. self._evict(target, limit)
    21. return True
    22. def _evict(self, entries, limit):
    23. # When over the limit, evict low-frequency, outdated entries first rather than simply truncating the tail
    24. while sum(len(e) for e in entries) > limit and entries:
    25. entries.pop(0)

    Three engineering details are worth emphasizing: writes must be idempotent, so duplicate entries should not consume the quota; the eviction strategy should be based on access frequency and timeliness tags rather than simple truncation; and memory changes must be auditable, making it easy to trace “why the agent judged this way.”

    4. Skill Subsystem: Turning Lessons Learned into Callable Assets

    A skill is a higher-order asset than memory: memory describes “what the facts are,” while a skill describes “how to handle this kind of problem.” A reliable skill unit should contain five fields—trigger conditions, pre-checks, step sequence, failure fallback, and verification method—and be stored as plain text or a structured file under version control.

    The recommended time to generate a skill is after a task concludes successfully. The agent self-checks which steps showed unexpected behavior during the process and which workarounds were proven effective, then abstracts them into general steps loosely coupled to the specific project. Too low a level of abstraction degrades into a one-off script, while too high a level loses executability. In practice, “transferable to a similar tech stack” is a sound criterion.

    The skill library needs governance: similarity-based deduplication, naming conventions, reference counting, failure rate statistics, and periodic retirement. A skill library without an eviction mechanism will repeat the old problem of the long memory file.

    5. Reflection Scheduling: Low-Frequency Triggering to Avoid Metacognition Overhead

    Distilling experience on every turn is unacceptable in both cost and noise. A workable approach is to introduce a lightweight scheduler: trigger by time window, task count, or explicit instruction; use low-cost rules to pre-filter candidates, and only let those meeting conditions such as “the result succeeded and the process had anomalies” enter the distillation flow. On Baidu AI Cloud, this kind of scheduling can typically use a message queue for asynchronous decoupling, a container platform to host distillation tasks, and logging services with monitoring and alerting to track success rate and duration.

    6. Security and Cost Control

    Self-evolution means the agent can modify its own capabilities, so boundaries must be set: memory and skill writes require quota and whitelist validation; skills undergo parameter validation and least-privilege constraints before execution; high-risk actions retain human confirmation; and the distillation flow is given a token and call-count budget. Observability is equally necessary, covering at least four metrics: write success rate, hit rate, eviction rate, and cost per reflection.

    In the first phase, implement only limited memory with snapshot isolation, and verify the improvement in signal-to-noise ratio. In the second phase, add post-task skill distillation and deduplication governance. In the third phase, integrate asynchronous reflection scheduling and a metrics dashboard. Proceeding in this order lets the agent shift from “being fed by humans” to “growing on its own,” without introducing a complex framework.