Agent Architecture Design for Self-Evolving AI Agents: Closed-Loop Learning, Layered Memory, and Decoupling
This article examines the architectural flaws behind conversational AI that "forgets" users between sessions and presents a practical design for self-evolving agents. It covers a three-step closed-loop learning pipeline (extraction, consolidation, and reuse), parameterized skill files, evolutionary prompt optimization with review gates, a three-layer memory system with governance, and a decoupled layered architecture. It closes with implementation recommendations and a risk checklist for teams building or evaluating agents that retain experience over time.
1. The Root Cause: Why Conversational AI Keeps “Meeting You for the First Time”
In the previous session, the agent had just helped you write a structurally complex deployment script. Its reasoning, variable naming, and the pitfalls it hit were all recorded in the context. You close the window and reopen it, and the agent behaves as if it has never seen you before, probing from scratch. Most users blame this on the model “not being smart enough.” From an engineering perspective, however, this is not a model capability problem but an architectural flaw in mainstream conversational AI: these systems are essentially stateless functions. They take context as input, produce output, and once the session lifecycle ends, the state is reclaimed.
Stateless design is a well-validated best practice in web services: it scales horizontally, works well with load balancing, and keeps failure recovery cheap. Applying the same paradigm directly to a “long-term collaboration assistant”, however, creates a clear experience gap. What users actually expect is cumulative: preferences, terminology habits, project structure, and past decisions should all be preserved and reused across multiple interactions. This is precisely what a purely stateless architecture cannot provide.
The industry has therefore begun exploring a new direction: turning the agent from a “one-off calculator” into a “digital counterpart that accumulates and iterates.” This article focuses on the general design of a self-evolving agent across three dimensions: closed-loop learning mechanisms, layered persistent memory, and architectural decoupling and governance. These three dimensions are not an independent feature checklist; they form an engineering system in which each supports the others.
2. Closed-Loop Learning: Turning Task Experience into Reusable Capability
2.1 Where the Traditional Execution Chain Breaks
The traditional agent execution chain is linear:
Receive instruction → Plan steps → Call tools → Return result → End
The end of this chain lacks a “write-back” action. The task succeeds, but the key decisions made along the way—why a particular parameter was chosen, why a step was skipped, which error maps to which fix—all disappear along with the context. The next time a similar task comes up, the agent has to reason through it all over again, which consumes tokens and increases the probability of errors.
Some open-source agent frameworks have a fairly rich skill ecosystem, but skill creation and maintenance are still developer-led: people write, review, and publish skills. The agent itself is only the “executor” of skills, not the “producer.” This is the root cause of a stagnant capability growth curve.
2.2 The Three-Step Loop: Extract, Consolidate, Reuse
A self-evolving agent adds a loop at the end of the chain to structure and persist successful experience. It can be broken into three steps:
- Experience extraction: After a task succeeds, extract the key steps, branch conditions, and decision rationale from the execution trace, filtering out noise actions unrelated to the outcome.
- Structure consolidation: Write the experience into a standardized skill file (usually plain text such as Markdown) containing at least three parts—trigger conditions (when to use it), execution steps (how to do it), and caveats (which pitfalls to avoid).
- On-demand reuse: When a similar task appears again, first search for a matching existing skill; on a hit, load and execute it directly, skipping lengthy exploratory reasoning.
The key design point here is that a skill file is not a log. A log is a time-series record; a skill is an invocable “program.” Mixing the two degrades both retrieval hit rate and execution stability at the same time.
2.3 Parameterization: From “One-Off Script” to “Reusable Template”
For skills to be genuinely reusable, hardcoding must be eliminated. A practical approach is to introduce variable placeholders and externalize the variable parts as inputs:
---name: container-deploytrigger: The user needs to package a service and deploy it to a container platformparams: [image_name, tag, replicas, env_file]---# Steps1. Build the image: build ${image_name}:${tag}2. Validate configuration: read ${env_file} and check that all required fields are present3. Deploy ${replicas} replicas and wait for readiness probes to pass4. Rollback strategy: on failure, revert to the last available ${tag}# Caveats- If ${tag} is latest, confirm with the user first to avoid an untraceable deployment- Skipping configuration validation is forbidden in production
Parameterization brings three direct benefits: one skill can cover multiple project scenarios; skills can be statically checked and unit tested; and skills can be composed and orchestrated together to form higher-level capabilities.
In addition, the skill format should follow open, general standards as much as possible so that skills remain portable and shareable across different agent implementations, avoiding capability being locked into a single runtime.
2.4 The Self-Evolution Pipeline: Automated Optimization of Prompts and Skills
Relying on manual skill curation alone becomes unsustainable at scale. A more advanced approach is to introduce automated optimization mechanisms that iteratively improve skill files, tool descriptions, and system prompts. One representative class of methods in the industry is evolutionary prompt optimization: borrowing ideas from population search and multi-objective trade-offs, it evaluates candidate prompts on a small number of samples, retains the better individuals, and keeps mutating and iterating. Compared with some reinforcement-learning-based fine-tuning approaches, this class of methods has a clear advantage in training efficiency, and requires no GPU training—everything is done through model API calls, which lowers the adoption barrier considerably.
Automated optimization, however, must be paired with safety boundaries; otherwise the agent may gradually drift from its original intent without supervision. In engineering practice, a three-stage “propose—review—merge“ flow is typically used:
Optimizer produces candidate changes → Submitted as a patch/pull request → Human review → Merge and take effect → Regression evaluation
Supporting measures should also include: change tracking and rollback, a fixed evaluation set to prevent “optimization as regression,” and a deny list that forbids automatic modification of skills involving permissions or destructive operations.
3. A Three-Layer Memory System: Solving “Can’t Remember” and “Remembers Too Much Noise”
Skill accumulation alone is not enough. Skills solve “knows how to do it”; memory solves “remembers you.” A practical layered structure typically has three layers:
- Layer 1: Built-in persistent memory. Stores stable user profiles and preferences, such as commonly used tech stacks, code style conventions, output language and level of detail, and project directory structure. This data is small in volume and read frequently, so it should guarantee low latency and strong consistency.
- Layer 2: Session retrieval. Historical conversations are no longer stuffed into the context in full. Instead, they are first chunked, vectorized, and indexed, then recalled by similarity against the current question, with only the most relevant fragments injected into the prompt. This controls context length while preserving traceability.
- Layer 3: External memory plugins. Connects to team knowledge bases, ticketing systems, code repositories, and documentation sites, bringing organization-level knowledge into the agent’s searchable scope and dividing labor between personal memory and team memory.
For the three memory layers to be genuinely usable, a memory governance mechanism must be in place; otherwise memory quickly degrades into a noise repository:
- Write policy: Distinguish “fact memory” (the user explicitly asked to remember it) from “inferred memory” (summarized by the model on its own); the latter must be annotated with a confidence level and be allowed to be overwritten.
- Conflict resolution: When new memory contradicts old memory, adjudicate by timestamp and source credibility, and retain the change history.
- Forgetting and expiration: Set TTLs and capacity limits; downweight or archive entries that have not been hit for a long time to keep retrieval from being polluted by stale information.
- Privacy and isolation: Desensitize sensitive information before storing it; in multi-tenant scenarios, enforce strict isolation by user and project dimensions, and support one-click deletion.
4. Architectural Decoupling: Making Capabilities Pluggable and Replaceable
If self-evolution and memory mechanisms are tightly coupled to a specific model or a specific runtime, the system becomes hard to maintain. The goal of decoupling is to split the system into layers with clear boundaries:
┌─────────────────────────────────────┐│ Interaction layer: multi-channel ││ access, session management, ││ permission checks │├─────────────────────────────────────┤│ Orchestration layer: task planning,││ skill routing, tool invocation │├─────────────────────────────────────┤│ Capability layer: skill library / ││ tool adapters / memory service │├─────────────────────────────────────┤│ Foundation layer: model serving, ││ object storage, logging, monitoring│└─────────────────────────────────────┘
Communication between layers happens through clearly defined contracts, which brings several practical benefits: swapping the underlying model does not affect upper-layer skill assets; tools are integrated as adapters, so adding an external system requires no changes to orchestration logic; the memory service can scale independently; and once logging and monitoring are pushed down to the foundation layer, full-chain observability becomes a default capability rather than an after-the-fact patch.
In terms of deployment form, this kind of system is generally better suited to running on your own servers or a container platform in the cloud, paired with object storage for skill and memory snapshots, a message queue for peak shaving, and logging and monitoring/alerting services for runtime observation. Compared with purely front-end plugin approaches, a persistent server-side presence is what allows scheduled tasks, background evolution, and long-term memory to actually run.
5. Implementation Recommendations and Risk Checklist
If you are about to build or evaluate an agent with growth potential, proceed in this order:
- Build memory first, then evolution. Without reliable persistent memory, skill accumulation lacks contextual support and tends to generate a large number of low-quality skills.
- Set the skill format standard first. Fields, version numbers, parameter declarations, and evaluation cases should be fixed from the start; migration costs later are extremely high.
- Put gates on automation. All automatically generated skill and prompt changes should enter a pending-review state by default; operations involving production environments and permissions require human confirmation.
- Establish an evaluation baseline. Use a fixed set of tasks to measure whether “new skills actually bring improvement,” preventing capability expansion from being accompanied by declining accuracy.
- Prioritize observability. Log every skill hit, memory recall, and tool invocation result so that when something goes wrong you can pinpoint whether the memory was wrong, the skill was wrong, or the model was wrong.
The risks also need to be recognized clearly: memory brings privacy and compliance pressure; automatic evolution may amplify early biases; and skill library growth increases retrieval difficulty and maintenance cost. A “growth agent” is therefore not a switch to flip but an engineering system that requires continuous governance. Its value lies not in making the model smarter, but in ensuring that your experience no longer disappears when the window closes.
