Self-Improving AI Agents: Dual-Loop Architecture and Runtime Engineering
A practical self-improving AI agent needs more than a larger context window or frequent model updates. This article explains a dual-loop architecture that combines reusable memory and skills with controlled model training. It covers the separation of execution, learning, and governance; asynchronous review; reinforcement learning; runtime safeguards; layered evaluation; and a phased implementation roadmap for verifiable, reversible improvements.
1. Rethinking Self-Improvement: A Verifiable Feedback Loop, Not Automatic Capability Growth
AI agents typically complete tasks through a cycle of understanding the goal, planning, calling tools, observing results, and adjusting their actions. This cycle can solve an immediate problem, but it does not necessarily produce sustained capability improvements.
If a completed task leaves behind only a conversation log, without extracting useful lessons, the system may repeat the same mistakes on similar tasks. Expanding the context window merely brings more historical information into inference. It does not guarantee that the information will be retrieved accurately, interpreted correctly, or reused consistently.
A discussion of agent self-improvement should therefore distinguish three types of change:
- Context changes: Adjusting the information available for the current task without changing model parameters.
- External asset changes: Updating long-term memory, skill documents, and task strategies so that future tasks can reuse experience.
- Model parameter changes: Updating the model through offline training or controlled reinforcement learning to produce deeper changes in its behavior policy.
These mechanisms have different costs, risks, and validation requirements. They should not be treated as interchangeable.
A comprehensive architecture supports two improvement paths. The external path captures experience and enables rapid corrections. The internal path incorporates validated improvements into the model’s policy. A shared runtime provides the execution, observability, and governance foundations for both.
2. Architecture: Separate Execution, Learning, and Governance
A maintainable dual-loop architecture can be organized into three planes.
2.1 Execution Plane: Prioritize Reliable Task Completion
The execution plane handles user requests directly. It assembles context, retrieves skills, advances plans, calls tools, and delivers results. Its primary goals are response quality and operational stability. Expensive review or training jobs should not block it.
During execution, the system should record auditable events, including task goals, tool inputs and outputs, errors, retries, user feedback, and final validation results. The emphasis is on observable action traces, not on preserving unverifiable internal model reasoning.
2.2 Learning Plane: Turn Traces into Candidate Assets
The learning plane consumes execution events to extract facts, analyze failures, organize skills, and select training examples. Its outputs should first enter a candidate area rather than directly replacing production memories, skills, or models.
This separation prevents an isolated success or an incorrect diagnosis from immediately influencing all subsequent tasks.
2.3 Governance Plane: Decide Which Changes Can Reach Production
The governance plane handles permission checks, sensitive-data processing, asset review, offline evaluation, staged rollout, and version rollback.
The overall data flow is:
Task execution → Event recording → Asynchronous review → Candidate memories and skills → Validation and publication
Qualified traces → Data selection → Training and evaluation → Candidate model → Staged rollout and rollback
This is not an unattended pipeline. It is a set of engineering workflows with explicit quality gates.
3. External Improvement: Convert Execution Experience into Reusable Skills
3.1 Trigger Reviews Based on Value, Not Just Conversation Length
Triggering experience extraction after a fixed number of interactions is straightforward, but conversation length is not a reliable measure of learning value. Ten simple exchanges may offer little reusable knowledge, while one complex troubleshooting task may reveal an important lesson.
A better approach combines several signals:
- A task encounters repeated failures and retries.
- The user explicitly corrects the system’s behavior.
- A solution path is verified in practice.
- Similar problems recur.
- A new finding changes the conditions under which an existing skill applies.
Trigger rules should be configurable engineering policies, not treated as fixed algorithmic constants. Cooldown periods and resource budgets are also needed to prevent review jobs from accumulating indefinitely.
3.2 Asynchronous Review: Reduce Foreground Latency Without Sacrificing Reliability
Once the primary task finishes, review events can be handed to background workers. These workers may use a dedicated review agent or combine deterministic rules with model-based analysis.
The key requirement is not merely starting a background job. It is ensuring reliable event delivery, retryable processing, and duplicate-free writes. Each event should have a unique identifier, and its task trace should be stored as an immutable snapshot.
Failed background jobs should be retried or routed to a human review queue. When an event is consumed more than once, asset writes should remain idempotent. Otherwise, the system may accumulate duplicate skills or conflicting long-term memories.
3.3 Separate Factual Memory, Procedural Skills, and Failure Analysis
These asset types have different lifecycles and should not be stored or managed as one undifferentiated collection.
Factual memory captures relatively stable information, such as user-confirmed preferences or task-environment constraints. It should retain its source, validity period, and scope. A temporary choice must not automatically become a permanent preference.
Procedural skills describe reusable operating methods. They should specify applicability conditions, execution steps, validation criteria, and failure-handling procedures.
Failure analysis explains why an attempt failed and how to prevent recurrence. Useful analysis must point to observable evidence, such as insufficient permissions, unexpected API responses, stale state, or missing validation. A vague explanation such as “insufficient reasoning” is not enough.
All three asset types may reference the same trace, but they should be reviewed and managed separately.
3.4 Define Skills as Bounded Operating Procedures
A high-quality skill is not a verbatim summary of a successful run. It abstracts the problem structure and the conditions that made the solution valid.
A skill should include the following fields:
| Field | Purpose |
|---|---|
| Goal and scope | Define the problem the skill addresses |
| Preconditions | Specify environment, permission, and input requirements |
| Execution steps | Provide actionable procedures and branches |
| Validation method | Define evidence of success |
| Risks and prohibited conditions | Prevent inappropriate reuse |
| Failure handling | Describe retries, fallback behavior, or human handoff |
| Source and version | Support auditing, updates, and rollback |
For example, a task that succeeds after a retry does not justify a skill that says “retry whenever an error occurs.” The abstraction must distinguish transient failures, permission errors, and unrecoverable data errors. It must also identify which operations are idempotent.
3.5 Validate Before Publication and Retire Assets Continuously
Before a skill reaches production, check whether it contains sensitive information, duplicates an existing skill, depends on an outdated environment, and passes procedural tests.
After publication, monitor its effectiveness. Skills that are rarely relevant, fail frequently, or have been replaced by newer workflows should be revised or disabled.
The size of a skill library is not a measure of agent capability. Unmanaged asset growth can increase retrieval noise and context overhead.
4. Internal Improvement: Optimize Model Policies Through Reinforcement Learning
External skills provide explicit procedures and environmental knowledge, but they do not directly change model parameters. If a model exhibits persistent weaknesses in planning, tool use, or result assessment, internal training can provide a further optimization path.
However, not every task trace is suitable for training, and training does not guarantee that existing capability limits will be overcome. Its benefits depend on data quality, reward design, model capacity, and evaluation coverage.
4.1 Production Traces Require a Separate Training Data Pipeline
Production traces may contain incorrect answers, user-private information, malicious instructions embedded in tool outputs, and paths that succeeded by chance. Training directly on these records can reinforce undesirable behavior.
At minimum, data preparation should include:
- Sensitive-data redaction and authorization checks.
- Data isolation across user, tenant, or task boundaries.
- Removal of corrupted, incomplete, or unverifiable traces.
- Independent verification of task outcomes.
- Deduplication to prevent frequent task types from dominating training.
- Separation of training and evaluation datasets to prevent data leakage.
A successful tool call does not necessarily mean that the user’s goal was achieved. Training labels should rely on actual task outcomes wherever possible, not just API status.
4.2 The Basic Idea Behind Group Relative Policy Optimization
Group Relative Policy Optimization (GRPO) is a reinforcement learning method. Its central idea is to sample multiple candidate outputs or action trajectories for the same input, compare their rewards within the group, and update the policy using relative advantage signals.
A common simplified expression is:
Relative advantage = The sample’s reward minus the group’s mean reward, normalized by the variation in group rewards
Actual training must also control the size of policy updates and apply appropriate constraints to reduce the risk of excessive deviation from a reference policy. When rewards within a group are nearly identical, normalization stability and weak learning signals require attention.
This approach does not create knowledge from nothing. It uses the model’s existing sampling capabilities and evaluation signals to favor higher-reward behavior. For agent tasks, tool environments, credit assignment across long trajectories, and executable validation add substantial complexity.
4.3 Reward Design: Prioritize Real Outcomes
Agent rewards may consider task completion, correctness, permission compliance, and resource consumption. These metrics should not simply be combined into a single score without examining their incentives.
Rewarding fewer tool calls, for example, may encourage the model to skip necessary validation. Rewarding complete-looking answers may encourage it to conceal failures. Safety and permission requirements are therefore better treated as hard constraints than as ordinary scoring components that other rewards can offset.
For executable tasks, use independent tests, state verification, or checks in controlled environments wherever possible. For tasks that are difficult to verify automatically, expert sampling and evaluation models can help. Their errors must still be acknowledged, and disputed samples should be retained for review.
4.4 Model Updates Need a Full Release Process
A candidate model should not enter production merely because its training reward increased. Evaluation should at least determine whether:
- Existing general capabilities have regressed.
- Target tasks have genuinely improved.
- Tool-call formats and exception handling remain stable.
- Permission boundaries are still respected.
- Errors accumulate during long-running tasks.
- Latency and cost meet operational requirements.
Training can run in periodic windows while production uses validated model versions. Decoupling everyday task execution from weight updates makes failures easier to diagnose and risks easier to control.
5. Runtime Engineering: Make Agent Behavior Controllable, Observable, and Replayable
An agent runtime is more than a collection of prompts. It is the execution system surrounding the model. It determines how the model receives information, takes action, and recovers from errors.
5.1 Context Management: Preserve Critical State Instead of Accumulating History
Context should prioritize the current goal, task constraints, latest environment state, and relevant skills. Earlier interactions can be compressed, but summaries must preserve key decisions, failure causes, and unfinished work.
Exact values, permission states, and the results of irreversible operations should not depend solely on free-text summaries. Store them in structured state and, when necessary, reread external systems to confirm them.
5.2 Tool Execution: Check Boundaries Before Every Call
Tool integrations need explicit input and output constraints, parameter validation, timeout handling, and error classification. High-risk operations should also require approval or user confirmation.
Retry policies must distinguish read-only operations from writes. A failed write response may indicate that the response was lost even though the change succeeded. Blindly retrying can then create duplicate submissions.
The runtime should use idempotency mechanisms or query the current state before deciding what to do next.
5.3 Prompt Injection Defense: External Content Is Not a System Instruction
Web pages, documents, and tool outputs may contain untrusted instructions. They should be treated as data to analyze, not as control information authorized to change permission boundaries.
The same rule applies to background reviews. External content claiming that something “must be remembered permanently” must not automatically become a memory or skill. External asset updates require source identification, rule checks, and validation.
5.4 Observability: Cover Both Execution and Learning
Beyond response times and success rates, record skill versions, model versions, tool calls, review status, candidate-asset review outcomes, and deployment times.
These records help answer an essential question: did a task improve because of a model upgrade, a skill update, or an environmental change?
Without linking versions to outcomes, claims of continuous improvement lack auditable evidence.
6. Demonstrating Improvement with Layered Evaluation
A dual-loop architecture needs at least three evaluation layers.
Task-level evaluation checks whether the user’s goal was achieved. Relevant measures include result correctness, human intervention rates, and repeated failures.
Asset-level evaluation checks whether skills are useful. It covers retrieval relevance, execution pass rates, conflicts, and sensitive-information leakage risks.
System-level evaluation checks overall operational quality. It includes review latency, queue backlog, inference cost, permission violations, and rollback capability.
Where possible, change only one major factor at a time. Keep the model version fixed when testing new skills, and keep the skill-library version fixed when testing a new model. Otherwise, an observed change in performance may be difficult to attribute.
Tasks with potentially destructive consequences should not be tested directly in production. First replay historical tasks in an isolated environment, or allow the candidate system to generate plans without performing real writes. Expand deployment gradually after validation.
7. Implementation Roadmap: Reliable Execution First, Reusable Experience Next, Training Last
A practical implementation sequence is:
- Improve execution and observability. Make task state, tool results, and failure causes recordable and replayable.
- Introduce asynchronous review. Generate candidate memories and skills without automatically publishing them to production.
- Establish skill governance. Add validation, version management, permission isolation, and retirement mechanisms.
- Build the data pipeline. Select authorized, verifiable training examples.
- Run controlled training. Target stable, recurring capability gaps with focused training tasks.
- Use staged rollouts. Monitor benefits, costs, and risks while preserving a fast rollback path.
The purpose of dual-loop self-improvement is not to generate more content or update models more frequently. It is to ensure that every change has a traceable source, validation, defined boundaries, and a rollback mechanism.
External experience assets provide fast, explainable improvements. Internal training enables deeper policy optimization. A reliable runtime connects both into an engineering system that can be maintained and improved over time.
