Self-Evolving Agent Design: A Closed-Loop Practice of Memory, Skills, and Reflection

    Most AI agent systems suffer from "amnesia" once a session ends, requiring developers to repeatedly feed context via prompts. This article explores the architecture of self-evolving agents that automatically accumulate and reuse experience. It breaks down a closed-loop system comprising three subsystems—Memory, Skill, and a Reflection Engine—detailing how constrained memory capacity, automated skill extraction, and event-driven reflection enable agents to improve continuously over time.

    A common shortcoming of most agent systems is “amnesia” at the end of a session. Deployment sequences learned today or user communication preferences are reset to zero in the next session. Developers are forced to repeatedly “feed” context through prompts, with efficiency dropping rapidly as task complexity increases. In contrast, self-evolving agents proactively consolidate experiences after completing tasks, reusing them for similar future problems. The longer they are used, the stronger their capabilities become. This article breaks down how this closed-loop architecture is implemented.

    1. Closed-Loop Overview: Three Subsystems at Work

    A self-evolving agent typically consists of three subsystems, which can be analogized to a personal assistant:

    • Memory: A notebook carried around to record environmental facts, project conventions, and user preferences, such as “Images must be pushed before deploying to the production environment.”
    • Skill: An accumulated operation manual recording “what steps to take when encountering a certain type of problem,” which can be retrieved and reused.
    • Reflection Engine (Nudge): An alarm clock that reminds the agent to review: Is there anything in the previous task worth writing into the notebook or refining into a manual?

    These three form a closed loop: Execute task -> Accumulate trajectory -> Reflect and extract -> Write to memory/skill library -> Influence next execution. The key is that this chain is automatically driven by the system, not dependent on manual prompt organization.

    2. Memory: Forcing Information Compression via Constrained Capacity

    The core design of the memory system is “restraint.” A typical implementation uses only two plain text files, separating entries with delimiters:

    1. ~/.agent/memories/
    2. ├── MEMORY.md # Agent's personal notes: environment facts, project conventions, tool quirks
    3. └── USER.md # Understanding of the user: preferences, communication style, work habits

    The character limits are deliberately tight (e.g., MEMORY 2200 chars, USER 1375 chars). This limit is not a flaw but a design philosophy: With limited capacity, the agent must compress information, retaining only high-density facts, while outdated content is naturally squeezed out.

    Compared to a pure append-only memory design—where appending content every conversation turns the file into a tens-of-thousands-of-lines “monster” after a few months, making retrieval require reading the whole text—the constrained capacity approach requires evaluating before each write: Is this information worth displacing existing content? This naturally achieves the survival of the fittest for memory.

    In implementation, the memory store maintains two parallel states:

    1. class MemoryStore:
    2. def __init__(self, memory_limit=2200, user_limit=1375):
    3. self.memory_entries: list[str] = []
    4. self.user_entries: list[str] = []
    5. self.memory_limit = memory_limit
    6. self.user_limit = user_limit
    7. # Snapshot frozen at session start, used to diff out increments at session end
    8. self._snapshot: dict[str, str] = {"memory": "", "user": ""}
    9. def snapshot(self) -> None:
    10. self._snapshot = {
    11. "memory": "\n".join(self.memory_entries),
    12. "user": "\n".join(self.user_entries),
    13. }
    14. def changed_entries(self) -> dict[str, list[str]]:
    15. # Compare the frozen snapshot with current content, return added/modified entries
    16. ...
    • Call snapshot() at the start of the session to freeze the state;
    • The agent can edit entries in real-time during the session;
    • At the end of the session, compare with the snapshot to see “what was learned,” which can be used for auditing or further skill extraction by the reflection engine.

    3. Skill: Automated Skill Extraction After Task Completion

    Memory answers “what do I know,” while skills answer “what should I do.” The typical pipeline for skill extraction is:

    1. Trajectory Collection: After task execution, collect the complete trajectory—goals, steps, tool calls, errors and fixes, and final results.
    2. Experience Extraction: Have the model review the trajectory to identify generalizable experiences: Which step was a key decision? What pitfalls were hit? What was the fix?
    3. Structured Generation: Write the experience into a structured skill file, for example:
    1. ---
    2. name: fix-k8s-image-pull-error
    3. trigger: "ImagePullBackOff occurs during deployment"
    4. scope: "Containerized deployment"
    5. ---
    6. ## Steps
    7. 1. First confirm the image has been pushed to the target registry
    8. 2. Check if the image tag matches the deployment manifest
    9. 3. Check if the registry credentials have expired
    10. ## Notes
    11. A successful local build does not mean it can be pulled remotely; always push before deploying.
    1. Deduplication and Merging: Compare with existing entries in the skill library; semantically duplicate items are merged, and conflicts are resolved by favoring the update.
    2. Retrieval Injection: When encountering a similar problem next time, retrieve relevant skills based on trigger conditions and inject them into the context for execution.

    Compared to hand-written skill libraries, the advantage of automated extraction is that the experience comes from real execution results, not the document author’s imagination. Furthermore, the skill library grows naturally with use without needing dedicated maintenance.

    4. Reflection Engine: Making Reviews Automatic

    Without an external trigger, skill extraction will never happen. The reflection engine’s role is to create trigger moments. Common strategies include:

    • Event Trigger: Immediately review after a task failure, as failure trajectories often contain the most valuable information.
    • Timed Trigger: Scan recent trajectories every N tasks or during hourly off-peak periods.
    • Capacity Threshold Trigger: Batch process when the pending trajectory buffer exceeds a certain amount to control costs.

    The reflection engine makes three types of decisions for each trajectory: write to MEMORY, write to USER, generate/update Skill, or discard directly. To control costs, cheap rule-based filtering can be applied first (e.g., skipping trajectories with no errors and no new tool calls), followed by model-based deep reviews for candidate trajectories.

    5. Engineering Practices

    • Skill Quality Evaluation and Elimination: More skills are not always better. It is recommended to track usage counts and success rates for each skill. Long-term invalid skills should be down-weighted or cleared to prevent context from being occupied by low-quality content.
    • Security Validation: Auto-generated skills are essentially instructions that will be executed in the future. They must undergo whitelist validation and manual spot-checks to prevent prompt injection or dangerous commands from being solidified into the skill library.
    • Concurrency and Consistency: When multiple sessions concurrently write to the same memory file, serialization is required (e.g., via file locks or database transactions), and the latest version should be re-read and merged before writing.
    • Cost Control: Reflection and extraction are extra calls. They should be tiered based on trajectory value, prioritizing reviews of failures and new scenarios.
    • Cloud Deployment: If deploying this architecture on model inference and serverless computing services, such as those on Baidu AI Cloud or similar platforms, the memory and skill libraries can reside in object storage or managed databases, combined with logging and monitoring services to observe the actual effectiveness of the closed loop.

    6. From Developers to Non-Developers

    The value of this closed loop is not limited to developers. By abstracting skills as “process manuals” and replacing task entries with natural language conversations, non-technical users can also enable agents to accumulate operational experience in their own business domains: finance personnel can consolidate report reconciliation processes, and operations personnel can consolidate ad placement checklists. The agent is no longer a black box learning from scratch every time, but an assistant that continuously aligns with user habits through use.

    Conclusion

    The essence of a self-evolving agent is liberating “experience” from human prompts and turning it into a system-managed asset. Constrained memory capacity ensures information density, automated skill extraction makes experience reusable, and the reflection engine ensures the closed loop continues to operate. For developers, these three subsystems are not complex, but when combined, they allow the agent to truly achieve “the longer it is used, the stronger its capabilities.”