Dual-Drive Self-Evolutionary Architecture for Persistent AI Agents: Engineering Practice

    This article explains how to build server-side AI agents that improve over time through two complementary loops: an external loop that turns task experience into retrievable, testable memory and skills, and an internal loop that uses governed data for model training. It covers persistent state and recovery, asynchronous experience review, layered knowledge assets (facts, skills, and error reflections), trajectory compression, group-relative policy optimization (GRPO), the separation of responsibilities among prompts, context, and the execution harness, and production governance including evaluation, controlled release, and rollback. The core takeaway: "self-evolution" is a controlled feedback system, not a model property, and every update must be evidence-based, permission-bounded, and reversible.

    1. From Single-Turn Dialogue to Long-Running Agents

    Traditional conversational applications organize computation around a single request: receive input, assemble a prompt, call the model, and return the result. Even with tool calling, if execution processes and experience live only in the current session, the system cannot accumulate capabilities across tasks.

    Server-side autonomous agents designed to run over the long term must solve three deeper problems:

    1. Can a task persist beyond a single model call? Complex tasks may involve retrieval, file processing, external system access, and human confirmation. They cannot depend solely on in-process conversational state.
    2. Can useful experience be retained after a task ends? Saving chat history is not the same as learning. The system must distinguish facts, preferences, execution methods, and incidental errors, then convert them into retrievable, verifiable assets.
    3. Can experience further improve the model itself? External knowledge and skills improve task execution but do not change model weights. Improving behavior in a specific domain requires separate data governance, training, and evaluation processes.

    Therefore, “persistence” and “self-evolution” should be understood as systems-engineering goals, not properties a model naturally has. Persistence relies on state storage, scheduling, and recovery mechanisms; self-evolution relies on feedback quality, asset management, and training governance. Only when these form a closed loop can sustained improvement occur.

    2. Dual-Drive Self-Evolution: External Asset Updates and Internal Model Optimization

    The dual-drive architecture consists of two paths that cooperate but must not be conflated.

    • External drive: updates knowledge, memory, and skills without changing base model weights. It primarily answers “how can the next task avoid repeating past mistakes.”
    • Internal drive: updates model parameters using filtered task data for training. It primarily answers “how can the model form more stable behavior in a specific task distribution.”

    The overall flow can be summarized as:

    1. Task input
    2. → Agent execution
    3. → Trajectory recording and result verification
    4. → Experience review
    5. → Memory and skill candidate updates
    6. → Data filtering and training
    7. → Offline evaluation and controlled release
    8. → Next round of task execution

    What matters most is not whether the process is complete, but whether each stage has a trustworthy basis for judgment. Unverified success records, conversations containing sensitive information, and wrong answers self-confirmed by the model must never enter long-term assets or training data directly.

    2.1 External evolution: turning one success into a reusable method

    A skill should not be a static prompt fragment. It is better treated as an execution asset with an applicability scope, preconditions, and verification methods.

    For example, after a data-processing task succeeds, what is worth preserving is not the full conversation, but information such as:

    • What inputs the method applies to;
    • Which conditions must be checked before starting;
    • Key steps and their dependency order;
    • Which errors are likely to occur;
    • How to determine whether the result is correct;
    • How to recover or exit when exceptions occur.

    This structure reduces dependence on long histories, and makes testing and version management easier. But skills have boundaries: a workflow suited to one data structure may not suit another; an operation depending on specific permissions cannot be reused in arbitrary environments.

    Therefore, skill retrieval must consider both semantic relevance and condition matching, not just name or description similarity.

    2.2 Internal evolution: improving domain behavior through training

    External skills supplement methods, but the model may still repeatedly make mistakes in understanding, planning, or tool selection. Training the model can be considered for scenarios with stable task distributions, clear outcome feedback, and sufficient data volume.

    Be clear: training does not guarantee breaking through all capability limits. It typically improves behavior under a specific data distribution and evaluation criteria, and the outcome depends on data quality, reward design, training stability, and task coverage. The system should not equate “collected trajectories” with “model capability necessarily improved.”

    3. Engineering the External Loop: Asynchronous Review and Layered Knowledge Assets

    3.1 Decoupling foreground execution from background review

    Placing experience organization in the user-response path increases latency and can let review logic interfere with the current task. A more sensible design: the foreground completes the task and persists the trajectory; a background service receives review events through a message queue and independently generates candidate assets.

    Review triggering can be based on task complexity, failure count, tool-call density, human feedback, or periodic checks. Specific thresholds should be tuned to workload and benefit; a fixed number of turns is not a universally applicable standard.

    Review tasks must also be idempotent. For the same task and trajectory version, repeated event consumption should not repeatedly generate identical skills or write conflicting memories.

    3.2 Separating factual memory, method skills, and error reflections

    The three asset types have different lifecycles and risks.

    Factual memory stores information with lasting value, such as user-confirmed work preferences, task constraints, or business rules. Management focuses on provenance, permissions, validity periods, and conflict handling. Preferences inferred by the model must not be automatically promoted to confirmed facts.

    Method skills store reusable execution workflows. Management focuses on preconditions, applicability scope, test coverage, and version compatibility. For operations involving writes, deletions, or external submissions, confirmation points and rollback methods must be explicitly specified.

    Error reflections record failure patterns and mitigation measures. They should state the conditions under which an error occurs, not simply say “be more careful next time.” For example, if a failure came from misinterpreting a date string as local time, the reflection should require explicitly confirming the time zone, rather than generalizing that all time handling must use a single strategy.

    Layered storage prevents short-term noise from becoming long-term rules, and makes it convenient to set different review thresholds for different assets.

    3.3 Candidate generation is not formal release

    A background review model can only propose candidate content; it cannot inherently prove its correctness. Skill updates are recommended to follow this state flow:

    1. Draft → Automated checks → Quarantined environment testing → Review approval → Limited enablement → Full release

    Automated checks can cover structural integrity, sensitive information, dangerous operations, and duplicate content. Testing must validate normal inputs, boundary inputs, and known failure cases.

    For high-risk actions such as payments, permission changes, and production data modifications, human approval must be retained; skills must not enter the executable skill library based solely on model self-assessment.

    4. The Internal Loop: Data, Compression, and Reinforcement Learning

    4.1 Data construction: feedback authenticity over sample volume

    Training samples can come from real tasks, controlled synthetic tasks, and manually revised cases. Synthetic data helps cover long-tail scenarios but must still satisfy business constraints; model-generated answers must not be treated directly as true labels.

    A usable sample typically includes: task description, necessary context, observable action records, tool feedback, and verification results. The trajectory should focus on auditable actions and environmental feedback, not the model’s internal implicit reasoning process.

    Data governance should at minimum cover:

    • Removing or masking personal information, credentials, and sensitive business content;
    • Deduplicating by task and source to avoid repeated samples dominating training;
    • Distinguishing feedback levels: model self-evaluation, automated verification, and human confirmation;
    • Isolating training, validation, and test sets to reduce leakage;
    • Retaining data versions and provenance for later auditing.

    4.2 Trajectory compression: preserving causality, not merely shortening text

    Long trajectories contain repeated queries, failed retries, and irrelevant output. Using them directly for training can raise cost and amplify noise. But over-compression can remove decisive conditions.

    Reasonable compression should preserve the external evidence for “why an action was taken,” including input constraints, key tool results, action order, and result determination. For example, if a modification was performed only after confirming a file’s encoding, deleting the encoding check during compression could lead later models to learn an unsafe shortcut.

    Failed trajectories are also valuable. They can be used to build counterexamples, contrast samples, or recovery tasks, but the failure cause must be clearly labeled to avoid treating erroneous behavior as a positive demonstration.

    4.3 Reinforcement learning based on group-relative advantage

    Group relative policy optimization (GRPO) is a reinforcement learning method. Its basic idea is to sample multiple candidate outputs for the same input, compare the relative performance of candidates based on rewards, and update the policy accordingly.

    In agent tasks, rewards can come from result correctness, process-constraint satisfaction, resource consumption, and safety violations. But these indicators cannot simply be summed and assumed reliable.

    For example, rewarding only task completion rate may teach the model to bypass confirmation steps; over-penalizing tool-call counts may cause the model to omit necessary verification. A more robust design is to first define non-negotiable constraints, then evaluate quality and cost among compliant candidates.

    The training process should also monitor policy drift, reward hacking, and general-capability degradation. Improvements must be verified with independent test sets and safety regression tests, not by observing only rising training rewards.

    5. The Responsibility Boundaries of Prompts, Context, and the Execution Framework

    Production agents must not stuff all control logic into the prompt. Prompts express behavioral requirements, context supplies task information, and the execution framework enforces deterministic control.

    5.1 Prompts: define rules, but do not act as a permission system

    The prompt should clearly describe task objectives, available tools, output requirements, evidence standards, and escalation conditions. Stable rules should be separated from dynamic task data.

    Retrieved documents, web pages, user-uploaded files, and tool-returned text are all potentially untrusted input. Even if they contain instructions such as “ignore previous rules,” they must not gain elevated privileges.

    However, prompts alone cannot reliably prevent dangerous operations. Real permission restrictions must be implemented by the execution framework, e.g., tool allowlists, parameter validation, and human approval.

    5.2 Context: select effective information rather than appending endless history

    Context management aims to preserve sufficient decision basis within a limited budget. It can be organized in layers:

    • Stable system constraints;
    • Current task objectives and state;
    • Long-term memory relevant to the task;
    • Skills whose preconditions match;
    • Recent and critical tool feedback;
    • Summaries of historical process.

    When compressing context, unfinished items, key constraints, confirmed facts, and abnormal states must be preserved. Summaries should link back to the original records for re-verification. Otherwise, errors in a summary will be amplified by subsequent execution.

    5.3 Execution framework: make model actions subject to verifiable constraints

    The execution framework (also called the harness) converts model output into controlled actions. Its core responsibilities include state-machine management, tool scheduling, timeout control, retry policies, budget limits, permission validation, and audit logging.

    For long-running tasks, runtime state must not live only in memory. The system should save checkpoints at key steps and re-verify environment state during recovery.

    It is especially important to distinguish retry semantics across tools: reads can usually be retried, but operations such as transfers, notification sends, and resource creation may have duplicate side effects. Such operations need business idempotency keys or result-confirmation mechanisms, and must not simply replay the model’s previous instructions.

    6. A Practical Execution and Learning Workflow

    The following architectural pseudocode illustrates responsibility boundaries only; it does not represent any existing product interface:

    1. Receive task and establish persistent state
    2. Validate caller identity, permissions, and task budget
    3. Retrieve relevant memories and published skills
    4. Execution loop:
    5. Build current context
    6. Model proposes the next action
    7. Validate action format, permissions, and risk
    8. Request human confirmation when necessary
    9. Execute tools and record observations
    10. Update state and checkpoints
    11. Check completion conditions, budget, and timeouts
    12. Verify the final result
    13. Return response
    14. Publish an asynchronous review event
    15. Background processing:
    16. Extract candidate memories, skills, and error patterns
    17. Perform masking, deduplication, and testing
    18. After approval, update asset versions
    19. Route qualifying samples into the independent training pipeline

    One key principle: execution, review, and training must have different permissions. The execution service must not modify model weights itself; the review service must not directly gain production write access; and the training service must not bypass release approvals to swap the online model.

    7. Production Governance: Evaluation, Release, and Rollback

    7.1 Measure execution quality and learning gains separately

    Execution quality can be measured by task success rate, recovery success rate, human-intervention rate, latency, cost, and safety incidents.

    Learning gains should be observed through reuse effectiveness of new skills, reduction of failure patterns, improvement on target tasks after training, and absence of regression on non-target tasks.

    The two must not be conflated. A single successful task may result from manual correction or environmental change, which does not prove the system has learned the capability.

    7.2 Use fixed baselines and independent tests

    Before releasing a new skill or model, compare it against the old version on the same task set, with the same permissions and comparable budgets. The test suite should cover common tasks as well as abnormal inputs, permission conflicts, and tool failures.

    For behaviors that have real business impact, a shadow mode that logs decisions without executing write operations can be used first, followed by gradual expansion.

    7.3 Make all learning assets traceable and revocable

    Memories, skills, datasets, reward rules, and model versions should all retain provenance and change records. When an error is discovered, affected tasks can be located, problematic assets revoked, and versions rolled back.

    When concurrent tasks update the same memory or skill, version conflicts must be handled to prevent later low-quality content from overwriting verified assets.

    8. Conclusion: Self-Evolution Is First a Controlled Feedback System

    The long-term value of persistent agents lies not in saving more chat logs, nor in letting the model modify itself, but in establishing a trustworthy feedback chain.

    The external drive converts task experience into retrievable, testable memories and skills; the internal drive converts governed data into model training signals. Prompts define behavioral requirements, context supplies decision basis, and the execution framework constrains actual actions.

    In engineering practice, first establish recoverable task execution, trustworthy result verification, and rollback-capable asset management; then introduce the training loop gradually. Only when every update has evidence, every action has boundaries, and every regression can be detected and undone is “self-evolution” an operable capability rather than an unverified architectural slogan.