AI Agent Architecture with Self-Evolution: Closed-Loop Learning, Layered Memory, and Decoupling

    This article explains why most conversational AI agents forget everything once a session ends, and breaks down an architecture designed for long-term collaboration. It covers closed-loop learning that turns successful task execution into reusable, parameterized skill files; a three-layer memory system for persistent preferences, session retrieval, and external plugin storage; and architectural decoupling across the reasoning core, capability layer, memory layer, and tool execution layer. It also outlines a four-step adoption path and the human-in-the-loop safeguards required for automated prompt optimization.

    Why Most AI Assistants Forget Everything After a Session

    Developers working with AI coding tools or conversational assistants often run into a disjointed experience: a deployment workflow that took repeated debugging to get working in one session is gone when the window is reopened. The assistant is back to its initial state, and you have to re-explain the context, restate the constraints, and correct the same mistakes again. The problem is not that the model is “dumb” — it is that the system has no memory.

    This is not an isolated defect in one product. It is a shared architectural trait of mainstream conversational agents: the session lifecycle is tightly bound to the capability lifecycle. Once a session ends, the runtime holding the context is reclaimed, and the model itself retains no task experience. In one sentence, these systems are essentially stateless computation: input goes in, output comes out, and nothing is left behind.

    That design was reasonable early on. Statelessness makes horizontal scaling easy, makes gradual rollouts easy, and makes results easy to reproduce. But once agents start taking on long-chain tasks — multi-file refactoring, environment troubleshooting, data pipeline setup — the cost of statelessness is amplified quickly:

    • High context rebuilding cost: background information has to be fed in again every time, and token consumption and latency rise together;
    • No experience reuse: the same class of problem is reasoned through repeatedly, and output quality fluctuates from session to session;
    • Unpredictable behavior: without a stable record of preferences and constraints, style and conventions are hard to keep consistent;
    • No accumulated assets: practices the team has distilled through collaboration cannot be inherited by the agent.

    So the industry is shifting from “plugging a model into a chat box” to “building infrastructure that lets an agent keep evolving.” This article breaks that architectural approach down along three dimensions: closed-loop learning, layered persistent memory, and architectural decoupling.

    Dimension 1: Closed-Loop Learning That Turns Task Execution into Reusable Capability

    From a Linear Pipeline to an Execution Loop with Feedback

    The traditional agent runs in a straight line: receive instruction → plan steps → call tools → return result. When the task succeeds, the flow terminates, and the key decisions made along the way are lost.

    A self-evolving architecture adds a loop at the end of that line: once a task is judged successful, an experience extraction step is triggered, fixing “how this was done” into a structured artifact. It can be abstracted as the following pseudocode:

    1. def run(task):
    2. result = execute(task) # linear execution
    3. if verify(result): # success check
    4. skill = distill(task, trace) # experience distillation
    5. registry.save(skill) # write to capability registry
    6. return result

    Three design points matter here. First, success determination must be explicit; otherwise wrong paths get solidified too, producing “negative learning.” The common approach is to replace subjective judgment with executable checks (tests passing, compilation succeeding, API response codes matching expectations). Second, what distillation produces is a capability, not a log. A log is a time series; a capability is an invocable unit, and the two must not be conflated. Third, writes must pass admission control so the capability registry is not polluted by low-quality entries.

    Structuring the Capability File

    The experience artifact is usually a readable structured text format (Markdown is the common industry choice), with core fields that generally include:

    • Trigger conditions: which scenarios should load this capability, used for retrieval and routing;
    • Prerequisites: required runtime, permissions, and external resources;
    • Execution steps: an actionable breakdown of the process rather than a vague description;
    • Parameter placeholders: variable parts left as template variables;
    • Caveats and failure fallbacks: known pitfalls and degradation paths.

    Parameterization is the dividing line for reuse. An experience record without parameterization can only be reproduced once, while a template with placeholders can adapt to variants of the same class of task:

    1. ---
    2. name: container-deploy
    3. trigger: need to package a service as an image and release it to a cluster
    4. params: [image_name, tag, replicas]
    5. ---
    6. 1. Build the image: build --tag {{image_name}}:{{tag}}
    7. 2. Push to the image registry
    8. 3. Scale the workload replicas to {{replicas}}
    9. 4. Verify readiness probes and health checks

    In addition, if capability files follow an open skill description convention, they can be migrated between different agent runtimes, so experience is not locked into a single framework. This matters especially for enterprises: the portability of capability assets directly determines migration cost when the tech stack changes.

    Automatic Optimization of Prompts and Policies — With Human in the Loop

    Experience accumulation alone is not enough. The agent’s own “behavior policy” — system prompts, tool descriptions, and how capability files are phrased — also needs to iterate. The industry already has a class of prompt evolution algorithms that borrow the idea of parameter optimization: treat the prompt as an optimizable object, use performance on a task set as the feedback signal, and iterate across multiple candidate prompts with something like “mutate — evaluate — keep the better solutions,” searching for a better tradeoff between quality and cost. These methods typically require no model retraining and can be done entirely on the inference side, with a significantly lower engineering bar than reinforcement learning approaches.

    But automatic optimization must have boundaries. If an agent is allowed to rewrite its own policy with no supervision, goal drift is very likely: metrics go up while behavior departs from the original intent. The more robust engineering practice is:

    1. Optimization output is submitted as a change request (patch) rather than taking effect directly;
    2. A rollback-capable version history is kept, supporting regression validation against the task set;
    3. Human review is a precondition for merging, focusing on whether permission boundaries and safety constraints have been weakened.

    Dimension 2: A Three-Layer Memory System for State Persistence

    A capability registry alone cannot support long-term collaboration. It also takes a layered memory architecture, differentiated by “access frequency — lifecycle — sensitivity.”

    Layer 1: Built-in persistent memory. Holds stable user preferences and project constraints, such as code style, naming conventions, forbidden dependencies, and common environment parameters. The traits are few entries, slow change, and a need to load on every session. It is best maintained as key-value pairs or a structured document, and should support direct human editing — memory must be auditable and correctable.

    Layer 2: Session retrieval. Historical conversations and execution traces are large in volume and highly time-sensitive, so injecting all of them into context is not appropriate. The reasonable approach is to persist them to disk and build an index, then recall a small number of relevant fragments by semantic similarity, replacing “full concatenation” with “retrieval on demand.” This both controls context length and reduces interference from irrelevant information.

    Layer 3: External plugin memory. Move structured data into general-purpose cloud service categories: object storage for large artifacts, a relational database for structured records, a message queue for asynchronous writes, and logging and monitoring/alerting services to track the agent’s own behavior. The value of this layer is decoupling and governance: memory no longer lives and dies with the runtime, and it naturally plugs into the enterprise’s existing permission, backup, and compliance systems.

    The write strategy across the three layers needs a clear division of labor to avoid overlapping responsibilities:

    Layer Typical content Lifecycle Write method
    Persistent memory Preferences, constraints, conventions Long-term Human confirmation + incremental updates
    Session retrieval Conversations and execution traces Mid-term Automatic persistence + indexing
    External plugins Artifacts, records, metrics Long-term Asynchronous writes to external storage

    The privacy and security red line needs emphasis: the more complete the memory system, the closer it gets to a “digital twin,” and the more it needs least privilege, masking of sensitive information, per-project isolation, and one-click erasure. Any persistence design that lacks a forgetting mechanism should not go into production.

    Dimension 3: Architectural Decoupling for Pluggable Capability

    Once self-evolution and memory are layered on top of each other, a monolithic architecture quickly becomes hard to maintain. The goal of decoupling is to let four concerns evolve independently: the reasoning core, the capability layer, the memory layer, and the tool and execution layer.

    • The reasoning core only handles planning and decisions, and does not care where capabilities live;
    • The capability layer exposes services through a unified registration and retrieval interface, so adding capabilities requires no change to the core;
    • The memory layer plugs in through a standard read/write protocol, and local files and external storage are interchangeable;
    • The tool execution layer runs in a sandbox, with permissions granted on demand and failures isolated.

    The direct benefits of decoupling are replaceability and observability: swapping the underlying model does not affect accumulated capabilities; changing the storage backend does not affect business logic; and every tool call and memory write leaves a trace, making it easier to diagnose “why did performance get worse this time.”

    In terms of deployment, this kind of system typically runs as a long-lived service on self-managed servers or a container platform, with scheduled jobs and event triggers performing experience distillation rather than relying on a single interactive session. If a team wants to validate a similar approach in its own environment, it can build a minimal loop on general-purpose capabilities from Baidu AI Cloud — container platform, object storage, and logging/monitoring — first getting the “execute — verify — distill — reuse” chain working, then gradually introducing policy optimization.

    Implementation Advice: Four Steps, Don’t Adopt Everything at Once

    1. Do success determination first. Without reliable checks, do not enable automatic distillation, or you will keep amplifying wrong experience.
    2. Then do a single memory layer. Start with project constraints in persistent memory — the most direct benefit and the lowest risk.
    3. Next, add retrieval. Index historical traces and watch how context length and task success rate change.
    4. Finally, introduce automatic optimization, and keep the three-piece set of “patch + human review + rollback.”

    Conclusion

    The dividing line for an AI assistant moving from “passive tool” to “a technical partner that can grow” is not model parameters, but whether it has an experience accumulation mechanism, a state persistence design, and a pluggable architecture. Closed-loop learning answers “does it accumulate,” layered memory answers “does it remember,” and architectural decoupling answers “can it keep evolving.” With all three in place, an agent can form stable working habits over long-term collaboration; missing any one of them, so-called “growth” is only a brief illusion within a session.