Building a Self-Evolving Agent Loop: A Practical Guide to Memory and Skill Consolidation

    Most agent frameworks lose everything when a session ends—lessons learned, user preferences, and project conventions all reset to zero. This article presents a closed-loop architecture that turns agent experience into durable assets through three subsystems: a capacity-constrained memory store that forces information compression, a skill library automatically distilled from task friction, and a nudge mechanism that makes reflection actually happen. It covers the design trade-offs, code sketches, engineering considerations (eviction, auditability, rollback, isolation), and a productization path for non-developers.

    1. The Problem: Amnesia at Session End, Capabilities Starting from Zero

    In most agent frameworks, “memory” lives only inside the context window. Once a session ends and the context is reclaimed, everything resets: the pitfalls discovered last round, the preferences the user confirmed, the unwritten conventions of the project. Users have to re-explain the same background in every new session, and the agent repeats the same mistakes on the same class of problems.

    Two common remedies exist, but neither is a real fix. One is append-only memory: conversation takeaways are continuously written to the end of a single file. After a few months the file balloons to tens of thousands of lines, retrieval requires reading the whole thing, and the noise overwhelms the signal. The other is a hand-written rule library: humans pre-author instructions, and the agent only knows what was written. Its capability ceiling is locked to the speed of human authoring.

    Two real problems need solving: how to keep information accurate long-term without unbounded growth, and how to grow capabilities automatically without hand-feeding. The solution below converges both into a single closed loop.

    2. Overall Architecture: Three Subsystems, One Loop

    The loop consists of three subsystems with clear boundaries:

    • Memory subsystem: stores “facts”—environment facts, project conventions, tool quirks, user preferences.
    • Skill subsystem: stores “methods”—reusable procedures and pitfall-avoidance notes, automatically distilled from task execution results.
    • Nudge subsystem: triggers reflection on a schedule or on events, checking whether the session produced facts or methods worth consolidating.

    A useful analogy: memory is a pocket notebook, skills are an operations manual, and the nudge is a recurring alarm. When the alarm rings, the agent reviews the notebook and updates the manual; both in turn shape performance on the next task—and that closes the loop.

    3. Memory Subsystem: Capacity Constraints That Force Compression

    The key design trade-off is to deliberately keep capacity tight rather than scale it infinitely. A representative storage layout:

    1. <agent_home>/memory/
    2. ├── MEMORY.md # Environment facts, project conventions, tool behaviors
    3. └── USER.md # User preferences, communication style, work habits
    1. class MemoryStore:
    2. def __init__(self, memory_char_limit=2200, user_char_limit=1375):
    3. self.memory_entries: list[str] = [] # Writable in real time
    4. self.user_entries: list[str] = []
    5. self.memory_char_limit = memory_char_limit
    6. self.user_char_limit = user_char_limit
    7. self._snapshot: dict[str, str] = {"memory": "", "user": ""} # Frozen at session start

    Two design points deserve emphasis.

    First, the capacity limit is a feature, not a constraint. As total character count approaches the threshold, the writer must compress first: merge semantically duplicate entries, delete entries overturned by newer facts, and rewrite long descriptions into short assertions. What remains is high-density facts, and stale information gets淘汰 naturally. By contrast, unbounded appends make retrieval cost grow linearly over time until the store becomes unusable.

    Second, dual tracks: snapshot plus live state. At session start, memory is frozen into a snapshot and injected into the system prompt. Content learned during the session is written to the live list but only enters the prompt in the next session. This avoids instruction drift and cache invalidation caused by a changing prompt within a session, and makes “when does what I learned take effect” predictable.

    Entries are separated by a uniform delimiter for deduplication, scoring, and eviction:

    1. def add(self, text: str, limit: int, entries: list[str]) -> None:
    2. text = text.strip()
    3. if not text or text in entries:
    4. return
    5. entries.append(text)
    6. while self._chars(entries) > limit and len(entries) > 1:
    7. entries.pop(0) # Simplified: real implementations evict by importance score

    4. Skill Subsystem: Automatic Distillation of Reusable Methods After Tasks

    The difference between skills and memory is granularity: memory holds “facts,” while skills hold “executable methods”—typically applicability conditions, step sequences, failure signals, and fallback plans.

    Automatic distillation is triggered at task wrap-up, in four steps:

    1. Value judgment: did this session involve a non-trivial error, retry, workaround, or user correction? Tasks without friction produce no skills, keeping the manual free of trivia.
    2. Structure extraction: abstract the process into “when condition C holds, execute S1..Sn in order; if failure signal F is observed, fall back to R.” One-off details like specific file names and timestamps are abstracted away.
    3. Dedup and merge: compare against existing skills by similarity. On a hit, add the new applicability condition or failure signal; only create a new entry on a miss.
    4. Persist and reference: write to the skill library, then inject a small number of relevant candidates into prompts for subsequent tasks, letting the model decide whether to invoke them.

    This step is the dividing line between “hand-fed” and “self-grown.” A hand-written rule library’s coverage depends on the authors’ experience; automatic distillation’s coverage depends on the diversity of actual tasks and grows monotonically with usage.

    5. Nudge Subsystem: Making Reflection Actually Happen

    Reflection does not happen spontaneously—it must be externally driven. Two common approaches can be combined:

    • Timer-based triggering: wake a lightweight reflection flow at fixed intervals, reading only the session summary and memory snapshot, keeping costs controlled.
    • Event-based triggering: fire immediately on signals such as task failure, user correction, or repeated retries, for better timeliness.

    The reflection prompt should strictly constrain the output format—for example, allowing only four action types (“add fact,” “update fact,” “add skill,” “no change”) plus the target file and entry text. The narrower the constraint, the more stable the written content, and the easier automated validation becomes.

    6. Engineering Considerations

    • Capacity and eviction policy: set separate thresholds for memory and skills; evict by importance rather than recency alone. Importance can combine “reference count, last-hit time, whether overturned by newer facts.”
    • Auditable writes: every automatic write retains the source task ID and timestamp for traceability and manual correction.
    • Rollback on failure: skill and memory updates should be idempotent; validate format and length before writing, compressing first when over the limit.
    • Isolation and permissions: in multi-user scenarios, memory must be isolated per user; the skill library can be split into personal and project levels to avoid cross-tenant contamination.
    • Privacy and compliance: do not persist raw conversations by default—only abstracted conclusions. Mask sensitive fields and provide one-click clearing and export.
    • Effectiveness evaluation: build a fixed task set and compare success rate, average retries, and prompt length between “self-evolution on” and “self-evolution off.” Judge the loop with data, not intuition.

    7. Making It Usable Without Writing Code

    Exposing self-evolution only as a code API sets the barrier too high. A viable productization path packages the three subsystems as configuration and conversation: users describe preferences and project conventions in natural language, and the system handles compression and writes; the skill library is presented as a searchable list of entries with manual editing and deletion; reflection frequency, memory capacity, and similar settings are exposed as a few switches. Baidu AI Cloud follows this general approach in its agent-related products, packaging memory management, knowledge consolidation, and runtime monitoring as general capabilities (categories such as object storage, logging services, monitoring and alerting, and container platforms), so users don’t need to care about the underlying implementation.

    8. Summary

    The essence of the self-evolution loop is elevating “experience” from ephemeral session state to a durable, searchable, evictable asset: capacity constraints drive compression, task friction drives skill distillation, and timer- and event-based nudges drive reflection. Remove any one of the three, and the loop degrades into ordinary log accumulation. When implementing, start with a small, auditable, measurable loop and gradually open up automation—that is the lowest-risk path forward.