Self-Evolving Agent Architecture: Dual-Driven Evolution and Harness Engineering

    This article examines how server-side autonomous agents move beyond session assistants into persistent autonomous systems. It outlines a dual-driven architecture: external-driven evolution for dynamic memory and skill accumulation, internal-driven evolution for reinforcement-learning-based policy improvement, and a Harness layer for prompt, context, tool execution, state control, and governance. The article covers five architecture layers, event-triggered background review, memory and skill candidate generation, skill lifecycle governance, RL data loops, GRPO, reward design, trace compression, context assembly, tool gateways, sandboxing, approval flows, observability, replay evaluation, canary release, rollback, cost control, common pitfalls, and a practical checklist. Readers will learn how to design a controlled closed loop from execution traces to candidate assets, offline evaluation, canary release, and retraining so that self-evolution remains observable, testable, and reversible.

    Self-Evolving Agent Architecture: Dual-Driven Evolution and Harness Engineering

    1. From Session Assistants to Persistent Autonomous Agents

    Traditional conversational systems and coding assistants embedded in editors usually focus on completing a single session: answering a question, completing code, or invoking a tool. They can be capable, but their intelligence boundary is often defined by three static factors: the base model, a predefined toolset, and hand-written prompts and skills. When the task ends, the execution trace is discarded. Trial-and-error experience is not retained, and the next similar problem starts from scratch.

    Server-side autonomous agents are different. They need to stay online for long periods, receive asynchronous tasks, maintain state, call external tools, recover after multiple failures, and gradually build an understanding of the business environment during continuous operation. At this point, the competitive question is no longer only “Can the model answer?” but “Can one execution become a systematic advantage for the next execution?”

    The core goals of such systems can be summarized in three points:

    1. Persistent operation: Tasks can be paused, resumed, retried, and audited, and critical state is not lost when a process restarts.
    2. Experience loop: Task traces are reviewed and retained as memory, skills, and strategies rather than being consumed once.
    3. Capability evolution: Retrieval, decision-making, and model weights are continuously improved through a data loop without compromising safety and stability.

    The architecture must therefore resolve the tension between “real-time online response” and “continuous offline evolution.” Front-end requests must be low-latency, terminable, and rollback-capable. Back-end evolution can be asynchronous, batched, and slow. This leads to a dual-driven mechanism: external-driven evolution handles dynamic memory and skill accumulation, while internal-driven evolution internalizes domain experience into model policy through reinforcement learning and similar methods. Above both, Prompt, Context, and Harness form an engineering carrier layer that keeps capability growth controllable, testable, and governable.


    2. Overall Architecture: Dual Loops and Layered Carriers

    A sustainable server-side agent can usually be divided into five layers.

    2.1 Runtime Control Layer

    This layer receives tasks, creates execution instances, schedules steps, maintains state machines, and controls budgets and termination conditions. It does not “think” directly. Instead, it decides when to call the model, when to execute a tool, when to request human approval, and when to enter recovery.

    2.2 Memory and Skill Layer

    This layer includes short-term working memory, long-term factual memory, user preferences, task constraints, a reusable skill library, and a strategy suggestion library. Memory emphasizes “facts and constraints,” while skills emphasize “reusable procedures and validation conditions.” The two should not be conflated.

    2.3 Harness Execution Layer

    In this article, Harness refers to the engineering carrier between model decisions and real tool execution. It includes context assembly, tool gateway, sandbox execution, exception recovery, permission checks, observability, and evaluation replay. The model is responsible only for local decisions; Harness turns those decisions into a safe, auditable, and reproducible execution process.

    2.4 Data and Training Layer

    This layer converts execution traces into trainable and evaluable data assets. It includes trace collection, desensitization, quality assessment, compression, reward calculation, reinforcement learning training, model evaluation, and release. This layer usually runs as asynchronous microservices or batch jobs so that online requests are not blocked.

    2.5 Governance and Release Layer

    This layer manages skill versions, prompt versions, model versions, canary releases, regression tests, audits, and rollbacks. The most dangerous design in a self-evolving system is to let background review results enter the production path without evaluation. Any automatically accumulated asset should pass through four stages: candidate, validation, canary, and stable.

    From a data-flow perspective, the overall loop can be represented as:

    1. Task request
    2. -> Orchestrator creates an execution instance
    3. -> Context assembly: task state, memory, skills, tool descriptions
    4. -> Model decision
    5. -> Tool gateway validates permissions and parameters
    6. -> Sandbox or external system executes
    7. -> Observations are written to the trace
    8. -> Front end continues execution or returns the result
    9. -> Asynchronous background review
    10. -> Memory candidates, skill candidates, strategy suggestions
    11. -> Evaluation and canary release
    12. -> Memory store, skill library, prompt configuration updates
    13. -> Periodic data processing
    14. -> High-quality trace filtering, compression, reward labeling
    15. -> Reinforcement learning training
    16. -> Model evaluation and canary release

    The outer loop updates quickly but has a limited scope. The inner loop updates slowly but may change the model’s underlying decision distribution. The two work together rather than replacing each other.


    3. External-Driven Evolution: Dynamic Skill Generation and Experience Retention

    External-driven evolution addresses the problem of “avoid making the same mistake again on the same type of task.” The key is not to store every conversation in a vector database, but to extract reusable, verifiable, and governable experience assets from execution traces.

    3.1 Trigger Mechanism: Do Not Review Every Round

    Frequent review introduces cost and noise. A more reasonable approach combines event-based and threshold-based triggers:

    • Round threshold: Trigger a review when a task has gone through multiple rounds without updating skills or memory. For example, maintain a counter for “rounds since the last skill update” and enqueue a background review when it reaches a threshold.
    • Failure events: Prioritize review when tool calls fail repeatedly, a task times out, the user explicitly corrects the agent, or a high-risk operation occurs.
    • New environment events: When unseen tools, data formats, or constraints appear, extract skills or add explanatory notes.
    • Successful but high-cost events: A task may succeed but use too many steps or tool calls. Such traces are worth reviewing for a better path.

    Pseudo-code can be represented as:

    1. on_task_finished(trace):
    2. if trace.failed
    3. or trace.user_corrected
    4. or rounds_since_last_skill_update >= threshold
    5. or trace.cost > high_cost_threshold:
    6. enqueue_review(trace.id, priority)

    Review tasks should run asynchronously and be idempotent. If the same trace is enqueued repeatedly, only one candidate result should be generated. A failed background review should not affect completion of the front-end task.

    3.2 Three Perspectives of the Background Review Agent

    The background review agent should not have direct production write access. It is more like an “analyst”: the input is a structured trace, and the output is candidate assets with confidence scores.

    First, memory review.
    Extract stable facts, user preferences, business constraints, failure causes, and success conditions from traces. For example: “This type of report must retain two decimal places” or “This task requires permission validation before submission.” Each memory item should include its source trace, confidence, effective scope, expiration time, and access permissions. Preferences that may change should have a validity period. High-risk facts should require human confirmation.

    Second, skill review.
    Abstract the solution path into a structured reusable skill. A qualified skill should describe at least:

    • Applicable scenarios and preconditions;
    • Inputs, outputs, and parameter constraints;
    • Key steps and tool-call order;
    • Intermediate validation points and failure handling;
    • Counterexamples, prohibited operations, and risk notes;
    • At least one replayable validation case.

    A skill is not a simple excerpt of a prompt, nor a verbatim copy of one successful trace. It should remove one-off parameters, temporary paths, and accidental environment states while retaining a generalizable procedure.

    Third, synthesis review.
    Reflect on error patterns from a higher level: Was the planning granularity too coarse? Was the tool choice wrong? Was context missing? Were validation conditions insufficient? Synthesis review can produce strategy suggestions such as “For write operations, always read the current state first” or “When a tool returns a structured error code, do not retry immediately; first determine whether it is a permission issue.” These suggestions enter a candidate pool and affect production prompts or runtime strategies only after evaluation.

    An abstract review output can look like this:

    1. {
    2. "memory_candidates": [
    3. {
    4. "content": "The version number must be validated before submitting this business object",
    5. "scope": "order_workflow",
    6. "confidence": 0.86,
    7. "source_trace": "trace_xxx"
    8. }
    9. ],
    10. "skill_candidates": [
    11. {
    12. "name": "cross_check_before_submit",
    13. "preconditions": ["A draft object exists"],
    14. "steps": ["Read the current version", "Compare with the target version", "If inconsistent, stop and explain"],
    15. "validations": ["Versions match", "Permissions are satisfied"],
    16. "anti_patterns": ["Submit directly without validation"]
    17. }
    18. ],
    19. "strategy_findings": [
    20. {
    21. "type": "tool_error_handling",
    22. "suggestion": "Distinguish permission errors from transient errors and avoid uniform retries"
    23. }
    24. ]
    25. }

    3.3 Skill Lifecycle and Governance

    Governance is the most underestimated part of external-driven evolution. If a skill library only grows and never shrinks, it quickly becomes a noisy repository. A complete lifecycle is recommended:

    1. Candidate: Generated by background review and not yet in production.
    2. Offline evaluation: Replay on historical tasks, synthetic cases, and safety cases; compare success rate, step count, tool error rate, and high-risk operation count.
    3. Shadow mode: In production traffic, compute but do not execute, and observe whether the skill is retrieved and whether it changes decisions.
    4. Canary release: Enable only for some tasks or low-risk scenarios.
    5. Stable: Enter the stable skill library after passing evaluation and canary release.
    6. Downgrade or deprecate: Automatically downgrade when the environment changes, success rate drops, or conflicts appear.

    At the same time, memory and skills need deduplication, conflict resolution, and source tracking. Multiple memory items on the same topic should be merged by time, confidence, and permission. Conflicting skills should not be injected into context at the same time. Instead, the retriever should select based on task conditions, or the context should explicitly mark the conflict and request clarification.


    4. Internal-Driven Evolution: A Reinforcement Learning Weight Loop

    External skills can improve explicitly describable procedures, but they cannot fully overcome the base model’s reasoning habits. Some domain problems require the model to form more stable policies in long-chain decisions, such as complex information retrieval, multi-step tool planning, error recovery, and structured output. In such cases, a reinforcement learning loop can be introduced to internalize high-quality traces into policy capability.

    It is important to note that internal-driven evolution is costly and risky and is not suitable as a default option for every team. It fits domains with stable environments, verifiable rewards, and high-quality evaluation sets.

    4.1 Basic Data Loop

    A controllable reinforcement learning loop should include at least:

    1. Trace collection
    2. -> Desensitization and permission filtering
    3. -> Quality assessment and deduplication
    4. -> Trace compression
    5. -> Reward calculation and data grouping
    6. -> Policy training
    7. -> Offline evaluation
    8. -> Canary release
    9. -> Online monitoring and feedback

    Trace collection should preserve decision points, not only the final answer. Record the context summary, model action, tool parameters, tool return, state change, exceptions, and final result for each step. Long tasks should also have checkpoints.

    Quality assessment and deduplication determine the training ceiling. Low-quality successful samples may contain lucky success, bypassed validation, or non-reproducible environment states. Failure samples are also valuable, but it is necessary to distinguish “learnable failures” from “failures caused by environment noise.” Sensitive data, causally unrelated traces, and duplicate samples should be filtered out.

    Data synthesis can supplement scarce scenarios, but it must be based on verifiable environments or strict rules. For example, use tool simulators to construct multi-branch tasks, use verifiers to generate success/failure judgments, and use counterfactual perturbations to test whether the model relies on incorrect clues. Synthetic data must not fabricate business rules or replace real safety evaluation.

    4.2 Trace Compression: Preserve the Causal Chain, Not Every Log

    Reinforcement learning training is sensitive to context length. Raw traces often contain repeated tool outputs, verbose logs, and irrelevant page content. The goal of trace compression is not simple truncation, but preservation of the causal information on which decisions depend:

    • Keep task goals, key constraints, and user preferences;
    • Keep each action and its direct observation result;
    • Summarize long tool outputs structurally and retain traceable references;
    • Merge repeated steps and mark state changes;
    • Keep failure causes and recovery actions;
    • Keep validation evidence for the final result.

    The compressed trace should support review of “why this step was taken,” not merely train a result predictor.

    4.3 Intuitive Understanding of GRPO

    GRPO stands for Group Relative Policy Optimization, a reinforcement learning method that does not rely on a separate value model and estimates advantages through group comparison. The basic idea is to sample multiple trajectories for the same question, compute the reward for each trajectory, normalize within the group to obtain relative advantages, and update the policy accordingly.

    It can be abstracted as:

    1. for each prompt q:
    2. sample trajectories y1, y2, ..., yk from old policy
    3. compute rewards r1, r2, ..., rk
    4. normalize advantages:
    5. A_i = (r_i - mean(r)) / (std(r) + epsilon)
    6. update policy with clipped objective and KL regularization

    The engineering advantage of this method is that it reduces the memory footprint and training complexity introduced by a value model and is suitable for comparing multiple candidates for the same task. But it also has clear constraints: increasing the number of samples raises cost; if the reward function is unstable, group comparison may amplify bias; for long tasks, trajectory-level rewards are too sparse and require process rewards, verifiers, or hierarchical rewards.

    4.4 Reward Design Must Prevent Reward Hacking

    The reward function should cover at least four categories of objectives:

    • Task success: Whether the final result satisfies verifiable conditions;
    • Process correctness: Whether tool calls, parameters, and intermediate validation comply with specifications;
    • Efficiency and cost: Step count, tool-call volume, latency, and budget;
    • Safety and compliance: Whether permissions are exceeded, sensitive information is leaked, or high-risk operations are executed.

    However, if only final success is rewarded, the model may learn to bypass validation, fabricate evidence, or choose high-risk shortcuts. Rule verifiers, tool state checks, and manual spot checks should be introduced, and significant penalties should be set for safety violations. Evaluation sets should include adversarial samples and out-of-distribution tasks so that the model does not merely memorize training-set paths.

    After training, the model still needs offline regression, safety evaluation, shadow traffic, and canary release. Model versions, training data versions, and reward function versions must be traceable, and degradation must be rollback-capable with one action.


    5. Harness Engineering: Turning “Thinking” into “Delivery”

    The dual-loop evolution determines how far the system can go, while Harness determines whether the system can be launched stably. Many agent demos look good but fail frequently in production. The problem is often not that the model is weak, but that the execution carrier layer is missing.

    5.1 Prompt Engineering: Define Contracts, Not Pile Up Instructions

    Production prompts should be modular:

    • System contract: Role boundaries, overall goals, prohibited behaviors, output format;
    • Task description: Current goal, acceptance conditions, available tools;
    • Context injection: Memory, skills, historical steps, environment state;
    • Safety policy: Sensitive operation restrictions, human approval conditions;
    • Failure handling: How to act when tools fail, information is insufficient, or constraints conflict.

    Prompts should not carry all knowledge. Large amounts of factual content should be placed in retrieval context, procedural content should be placed in the skill library, and hard constraints should be placed in Harness permission and validation logic. Prompt versions need to be managed together with model versions and skill versions. Any automatically generated prompt change should be evaluated.

    5.2 Context Engineering: Context Is a Budget, Not a Warehouse

    Context assembly should be managed in layers:

    1. Task layer: Goals, constraints, acceptance criteria;
    2. State layer: Current step, completed steps, pending items;
    3. Evidence layer: Tool returns, retrieval results, references;
    4. Experience layer: Relevant memories, skills, historical failure patterns;
    5. Tool layer: Tool descriptions, parameter schemas, error code explanations.

    Under a limited budget, items should be dynamically ranked by relevance, trustworthiness, timeliness, and permissions. Overly long context dilutes key information and increases prompt injection risk. Untrusted external content should be labeled by source and isolated from instructions so that it cannot override system policy.

    A context package can be abstracted as:

    1. {
    2. "task": {"goal": "...", "constraints": ["..."], "acceptance": ["..."]},
    3. "state": {"step": 3, "completed": ["..."], "pending": ["..."]},
    4. "evidence": [{"source": "tool_result", "summary": "...", "trust": "medium"}],
    5. "memories": [{"content": "...", "confidence": 0.8, "expires_at": "..."}],
    6. "skills": [{"name": "...", "preconditions": ["..."], "steps": ["..."]}],
    7. "tools": [{"name": "...", "schema": "...", "risk_level": "high"}]
    8. }

    5.3 Harness Execution: State Machines, Tool Gateways, and Sandboxes

    Harness should provide at least the following capabilities:

    • Orchestration and state machine: Control the “think-act-observe” loop and limit maximum steps, time, and budget;
    • Tool gateway: Parameter validation, permission checks, rate limiting, idempotency keys, and audit logs;
    • Sandbox execution: Run code or high-risk commands in an isolated environment with least privilege by default and restricted network egress;
    • Exception recovery: Distinguish transient errors, permission errors, and business errors; support backoff retries, compensating actions, and checkpoint recovery;
    • Human approval: Route write operations, financial operations, data deletion, and other high-risk actions into approval flows;
    • Observability: Record traces, spans, prompt versions, tool calls, model outputs, latency, and cost;
    • Replay evaluation: Re-execute based on historical traces to locate failure causes.

    A simplified execution loop is as follows:

    1. while not done and budget_remaining:
    2. context = assemble_context(state, memory, skills)
    3. action = model.decide(context)
    4. validate(action)
    5. if action.requires_approval:
    6. wait_for_human()
    7. result = tool_gateway.execute(action)
    8. state = update_state(state, action, result)
    9. trace.record(action, result)
    10. if action.is_terminal:
    11. done = True

    The key here is not to let the model be autonomous without limits, but to keep every step within Harness’s controllable boundary.


    6. Evaluation, Release, and Cost Control

    A self-evolving system must manage “change” as a release event.

    Offline evaluation should cover historical regression tasks, domain-specific tasks, safety adversarial tasks, and long-chain recovery tasks. Skill updates, prompt updates, and model updates should all run against the same regression set.

    Online canary release should support traffic splitting by task type, user group, or risk level. During canary release, focus on task success rate, average step count, tool error rate, human intervention rate, cost, and safety alerts.

    Rollback mechanisms must cover four version dimensions: skills, memory, prompts, and models. In particular, automatically generated skills should be quickly disabled and traced back to their source traces if errors spread.

    For cost control, asynchronous review should be batched and priority-queued; context assembly should use caching and summarization; simple tasks can be routed to smaller models, while complex tasks can be escalated; reinforcement learning training should use offline batch processing so that it does not compete with online inference resources. Object storage can be used for large logs, trace files, and model artifacts; message queues can be used for task scheduling and asynchronous review; logging services and monitoring alerts can be used for runtime metrics and audit logs. These general infrastructure components do not change the architecture’s essence, but they significantly improve operability.


    7. Common Pitfalls and a Practical Checklist

    Pitfall 1: Self-evolution means automatic release.
    Any automatically accumulated asset should pass through candidate, evaluation, canary, and stable stages. Self-evolution without an evaluation gate is essentially uncontrolled configuration drift.

    Pitfall 2: More memory is always better.
    Memory needs confidence, source, expiration, and permissions. Once incorrect memory enters the long-term store, it repeatedly contaminates future tasks.

    Pitfall 3: A skill is just a long prompt.
    A skill should include applicable conditions, steps, validation, and counterexamples. A skill without validation cases cannot be evaluated and is difficult to maintain.

    Pitfall 4: Heavy reliance on model self-evaluation.
    Model self-evaluation can be an auxiliary signal, but critical tasks should use verifiable rewards, rule checks, or manual spot checks where possible.

    Pitfall 5: Optimizing only final success rate.
    Process safety, cost, latency, interpretability, and failure recovery also matter. Otherwise, the system may “succeed” in unacceptable ways.

    A practical checklist includes:

    • Has persistent state and checkpoint recovery been established for tasks?
    • Are working memory, long-term memory, and the skill library distinguished?
    • Is background review isolated from front-end execution?
    • Do skills have versions, evaluation, canary release, and rollback?
    • Is context assembled under a budget and labeled with trust levels?
    • Are tool calls subject to permission checks and auditing?
    • Do high-risk operations support human approval?
    • Are trace replay and failure attribution available?
    • Does the reward function cover safety and process quality?
    • Are expired memories and inefficient skills cleaned up regularly?

    8. Conclusion

    The core competitiveness of server-side autonomous agents is shifting from “single-answer quality” to “system evolution capability during continuous operation.” External-driven evolution uses dynamic skills and experience retention to help the system quickly absorb reusable knowledge from tasks. Internal-driven evolution uses data loops and reinforcement learning to internalize domain policies into model decisions. Prompt, Context, and Harness form the engineering foundation that constrains this evolution within observable, evaluable, and rollback-capable boundaries.

    A truly production-ready self-evolving architecture does not let the model grow freely without supervision. It designs a controlled loop from execution traces to candidate assets, from offline evaluation to canary release, and from online feedback to retraining. Only when “evolution” is brought into engineering governance can an agent become more stable and more accurate over long-term operation, rather than more complex and less controllable.