Self-Evolving AI Agent Architecture: Design and Implementation

    This article breaks down how self-evolving AI agents turn experience into a first-class capability. It covers a two-layer memory design that separates environment facts from user profiles, full-text retrieval for looking back at past sessions, and a closed loop that grows reusable skills from execution traces. It also compares execution-loop-first architectures with centralized control planes, details a practical stack with pluggable execution backends, a unified message gateway, and model decoupling, and outlines the cost, security, and observability practices needed to run such agents reliably.

    1. The Starting Point: Why “Learning” Becomes the Key Agent Capability

    Most agent frameworks use a stateless runtime model: receive input, call the model, execute tools, return a result, and discard the context when the session ends. This works well for one-off tasks, but the weaknesses grow quickly in scenarios that require long-term companionship or continuous collaboration. Users have to repeat the same preferences over and over, the agent makes the same mistakes week after week, and the operational experience a team accumulates cannot be reused.

    The core premise of a self-evolving AI agent is to make “experience” a first-class citizen: the agent should be able to distill methods from execution traces, persist knowledge, and actively retrieve it in later sessions. This is not about stretching the context window. It is about building an external memory and skill system that is cumulative, retrievable, and versionable.

    2. Two-Layer Memory: Managing “Environment Facts” and “User Profile” Separately

    A fairly mature engineering practice is to split memory into two kinds of files and inject them into the system prompt at the start of each session:

    • Environment memory (playing a role similar to MEMORY.md): records project structure, build and test commands, directory conventions, and pitfalls and lessons learned. It answers “what is this world like?”
    • User memory (playing a role similar to USER.md): records communication style, output format preferences, tech stack habits, and things to avoid. It answers “who am I collaborating with?”

    The value of this split lies in their different lifecycles: environment facts change frequently as the project evolves, while user preferences are relatively stable. Mixing them in one file causes the prompt to bloat frequently and the two to contaminate each other. A practical recommendation is to keep each file at a manageable size (usually within a few hundred lines), push details down into on-demand topic documents, and keep only an index and high-frequency conclusions in the main memory.

    Injection alone is not enough; you also need retrospection. Full-text search backed by a local structured database lets the agent locate a specific conversation fragment from weeks ago, which is the key step in turning a vague impression back into verifiable evidence. Three engineering points matter here: write timing (at task wrap-up rather than every turn), deduplication and conflict resolution (new conclusions overwrite old ones instead of piling up side by side), and credibility labeling of retrieval results (distinguishing “the user explicitly corrected this” from “the model inferred this on its own”).

    A sample memory entry structure could look like this:

    1. ## Environment facts
    2. - Build: use the build script in the workspace root; artifacts are output to the dist directory
    3. - Lesson: editing the generated directory directly will be overwritten on the next build (the user has corrected this twice)
    4. ## User preferences
    5. - Lead with the conclusion, then the reasoning; write code comments in Chinese
    6. - Do not add dependencies without explanation

    3. Skills Are Not Written, They Are “Grown”

    Traditional skill systems rely on manual authoring: reusable tools and process instructions are fixed in advance, and the agent can only use authorized capabilities. The self-evolving approach differs in its closed loop. After a task completes, the agent performs a self-assessment: which steps actually advanced the goal, which were rolled back or corrected by the user, and which tool calls were redundant. It then extracts the verified, effective paths into reusable skills, annotated with trigger conditions and failure boundaries.

    Three constraints are needed to make this mechanism reliable:

    1. Admission threshold. Only patterns that recur and maintain a stable success rate may be promoted into skills, which prevents one-off accidental paths from polluting the skill library.
    2. Rollback capability. Both skills and memory should be under version control so you can quickly revert to the previous version when a regression appears.
    3. Explainability. A skill should retain its source trace (which task it was distilled from and what was corrected), making manual auditing easier.

    Describing skills in an open, plain-text declarative format (metadata plus instruction body) has clear benefits: it is portable across frameworks, reviewable, and diffable. Teams can govern the skill repository like a code repository, with code review and regression testing. Preloading a set of foundational skills around areas such as MLOps, code hosting platform workflows, and research is a common cold-start strategy: it covers high-frequency scenarios first, then lets runtime fill in the long tail.

    4. Execution Loop First, Not Control Plane First

    Two architectural orientations are worth comparing. One centers on a centralized control plane: a resident gateway process handles session management, message routing, tool dispatch, and state maintenance in a unified way. Its strengths are strong controllability, easy centralized governance, and tight native integration with the workspace, making it suitable for processes that need fine-grained human intervention. The other puts the agent’s own “execute, learn, improve” loop at the center, with everything else (connections, backends, models) built as replaceable peripheral components around that loop. Its strength is a clear evolution direction: the longer it is used, the thicker the accumulated experience.

    The selection decision can come down to three questions: does the task need to keep evolving across months or even quarters; is the cost of errors high enough that step-by-step human calibration is required; is experience reuse more important than process determinism. If the answers lean toward the former, a long-running self-evolving architecture is the better fit; if they lean toward the latter, a centralized control plane is safer. Most production systems eventually converge on a hybrid: the core loop handles learning and execution, while the periphery retains centralized observability and permission governance.

    5. Implementation Architecture: Terminal Backend, Message Ingestion, and Model Decoupling

    To actually run a self-evolving agent, three engineering constraints must be solved.

    Execution backend abstraction. Abstract command execution and file operations behind a unified interface with pluggable backend implementations: local processes, containerized sandboxes, remote hosts, managed development environments, and stateless compute that wakes on demand. The direct benefit is that the same agent logic can run as a personal assistant on a low-spec virtual host, handle batch tasks on a cluster with accelerators, and scale down to zero when idle to control cost. Sandboxing is the security baseline, especially when the agent can write files and execute commands autonomously.

    Unified message gateway. Connect instant messaging tools, team collaboration tools, and the command-line terminal to the same gateway process, hiding platform differences in authentication, message formats, and streaming replies, and exposing a consistent event model to the layers above. Engineering must handle idempotency (duplicate delivery does not cause duplicate execution), rate limiting and concurrency serialization (tasks in the same session are queued), and progress reporting for long-running tasks.

    Model layer decoupling. Use a unified adapter layer to hide vendor differences, and treat the model identifier as a runtime-switchable configuration item rather than a compile-time constant. Only then can you dynamically trade off capability, latency, and cost: simple intent classification goes to a lightweight model, while complex reasoning and code generation go to a stronger model. The switching capability must be paired with a regression evaluation set; otherwise “swap the model and quality drops” becomes the norm.

    1. # Sample: layered runtime configuration
    2. agent:
    3. loop: evolve # execute-learn-improve loop
    4. memory:
    5. env_file: memory/environment.md
    6. user_file: memory/user.md
    7. index: sqlite
    8. skills:
    9. source: git
    10. auto_create: true
    11. promotion_min_repeats: 3
    12. executor:
    13. backend: container # local | container | remote | serverless
    14. sandbox: true
    15. gateway:
    16. channels: [cli, chat, team_im]
    17. model:
    18. default: balanced
    19. routing: [light, balanced, strong]

    6. Cost, Security, and Observability

    Self-evolving mechanisms amplify two kinds of risk: memory pollution and skill degradation. The former is controlled by write review and conflict resolution; the latter is controlled by evaluation sets and version rollback. It is advisable to build a minimal observability dashboard for the agent: task success rate, human correction rate, skill hit rate, retrieval hit rate, and compute and token consumption per task. The human correction rate is the most underrated metric, because it directly reflects whether the learning loop is actually converging.

    For the permission model, follow least privilege: file and command allowlists, approval for outbound network access, and redaction of sensitive information before it is written to memory. If elastic compute and managed runtime environments are needed, you can compose general cloud capabilities: a container platform hosts the sandboxes, object storage holds skill and memory snapshots, a message queue smooths out task spikes, and logging, monitoring, and alerting services handle tracing and anomaly notification. This yields scalability and operability without binding to a specific implementation.

    7. Conclusion

    Whether an agent framework is worth a long-term investment does not depend on the length of its feature list, but on whether it has a verifiable learning loop: layered and retrievable memory, skills distilled from practice and rollback-capable, and full decoupling of the execution and model layers. A centralized control plane and a self-evolving execution loop are not mutually exclusive: the former provides order, the latter provides growth. Making the tradeoff based on task persistence and error cost is the pragmatic engineering decision.