Building Persistent AI Agents: Self-Evolution Architecture and Harness Engineering Practices
This article breaks down the architecture of long-running, server-side AI agents that must survive across sessions and restarts. It explains a four-layer design (access, orchestration, cognition, and execution), the closed loop that turns execution traces into reusable experience, and a dual-loop self-evolution mechanism combining hourly trajectory reflection with day-level tool expansion. It also covers versioned prompt configuration, layered memory with token budgets, and the Harness execution layer required for production, including sandboxing, permissions, observability, recovery, and regression testing. The goal is to show how teams can move agents from demos to production reliably.
Building Persistent AI Agents: Self-Evolution Architecture and Harness Engineering Practices
1. Background: From Session-Based Q&A to Always-On Server Agents
Over the past two years, AI coding tools and conversational assistants have significantly improved developer productivity. However, most of them share one constraint: their capabilities are bound to a single session. When the session ends, the state disappears; the model’s capabilities stay fixed and do not improve through use; and tool calls are confined to an editor or a single wrapped interface. This form factor is suitable for “assistance,” but not for “ownership.”
Once an agent is deployed on the server side and needs to stay resident for a long time, the engineering constraints change fundamentally. It is no longer a request-response function but an always-on process with a lifecycle, state, and a queue of goals. The core questions then become two:
- Persistent operation: processes, state, tasks, and memory must survive across sessions and restarts;
- Self-evolution: the system must be able to modify itself during operation instead of waiting for a manual release.
This article abstracts these capabilities into a general architectural pattern, organized around two main threads: “dual-loop self-evolution” and “Harness engineering.” All descriptions reflect general industry engineering practices and do not point to any specific product implementation.
2. Overall Architecture: Four Layers and One Closed Loop
A long-running agent system can typically be divided into four layers:
- Access layer: task sources (scheduled triggers, event messages, manual instructions) all enter a unified task queue;
- Orchestration layer: task scheduling, prioritization, concurrency control, failure retries, and idempotent deduplication;
- Cognition layer: context assembly, planning and reflection, and tool selection;
- Execution layer (Harness): tool registration, sandboxed execution, permission checks, result write-back, and log tracing.
Beyond the four layers, there is a closed loop that runs through the whole system: execution trace → experience accumulation → policy update → re-execution. This loop is the physical carrier of “self-evolution.” Without the loop, an agent is just an expensive wrapper around model calls; with the loop, it becomes capable of accumulating capability.
A schematic state structure (pseudocode, expressing field semantics only):
class AgentState:task_id: strgoal: strplan: list[Step] # current plan treescratchpad: list[Note] # short-term reasoning draftsmemory_refs: list[str] # long-term memory indextool_policy: Policy # tool allowlist and permissionscheckpoint: str # recoverable snapshot location
The key fields are checkpoint and memory_refs: the former guarantees “persistence,” and the latter guarantees “evolvability.”
3. Dual-Loop Self-Evolution Mechanism
Self-evolution is not a slogan; it must be grounded in two verifiable feedback loops.
3.1 Inner Loop: Trajectory Reflection for Policy Correction (Hour-Level)
The inner loop focuses on “did we do it right this time.” After execution finishes, the system performs a structured review of the trace: whether the goal was achieved, which step produced an invalid tool call, and whether the error was caused by the environment or by planning. The conclusions are written as structured experience entries and fed back into optional fragments of the prompt template and the tool selection policy.
The emphasis is on attribution, not “scoring.” Recording only “failure” is useless; you must record the failure type and its trigger conditions, for example:
{"failure_type": "tool_param_mismatch","trigger": "path containing spaces was not escaped","fix": "normalize parameters before every call","scope": "file-related tools"}
Such entries are selectively injected during context assembly for subsequent tasks, producing a “more stable with use” effect.
3.2 Outer Loop: Capability Expansion and Tool Self-Growth (Day-Level)
The outer loop focuses on “can we do new things.” When the inner loop repeatedly encounters the same type of “no tool available” gap, the system should trigger a capability expansion workflow: generate new tool descriptions and implementation drafts, construct test cases in a sandbox for validation, and register the tool into the tool registry only after it passes the regression set.
The safety boundary of the outer loop must be strict: new tools default to low privilege, default to read-only, and must have a rollback version. Any automatically generated execution body should never directly obtain production write permissions. This is a non-negotiable bottom line in production environments.
3.3 Coordinating the Two Loops
The inner loop improves the “correctness rate,” while the outer loop expands the “range of what can be done.” Both share the same experience library and the same regression evaluation set, preventing the inner loop from overfitting and the outer loop from uncontrolled expansion. In engineering practice, it is recommended to set different review cadences and admission thresholds for the two loops: the inner loop can take effect automatically, while the outer loop requires human or policy-based approval.
4. Prompt Engineering: Treating Prompts as Versionable Configuration
In an always-on agent, a prompt is not a string but layered configuration:
- System layer: role, boundaries, and safety constraints, which remain stable;
- Policy layer: planning methods, reflection rules, and tool preferences, updated by the inner loop;
- Task layer: the current goal and constraints;
- Experience layer: retrieved historical entries, injected on demand.
There are three design principles. First, strictly separate instructions from data, and treat all external content as untrusted input to prevent prompt injection. Second, require structured output, asking the model to return a parseable format for program validation and retries. Third, make templates versionable, gradually rollable out, and rollback-capable, so any policy update can be traced to a specific version and evaluation result.
[SYSTEM] You are an always-on task executor and must follow the least-privilege principle.[POLICY] Plan with "verify before execute"; after two failures, you must switch paths.[EXP] Retrieved experience entries (confidence: medium)...[TASK] Goal: ... Constraints: ...[OUTPUT] Return JSON only: {"action":..., "args":..., "reason":...}
5. Context Engineering: Layered Memory and Budget Constraints
Context is a finite resource, and a long-running system must manage it like memory.
It is recommended to divide context into four layers: working context (the current step), task context (the goal and a summary of completed steps), long-term memory (vector retrieval plus structured entries), and external knowledge (pulled on demand). The core mechanism is summary compression plus retrieval backfill: early steps are compressed into conclusive summaries, and details are retrieved by index when needed, avoiding unbounded context growth.
At the same time, set budgets and eviction policies: define a token limit for each layer, and when the limit is exceeded, evict low-value raw logs first while retaining decisions and results. All injected content should carry source and freshness markers to prevent stale experience from polluting current judgment.
6. Harness Engineering: A Production-Grade Execution Framework
The Harness is the “operating system” between the agent and the real world, and it determines whether the system can go to production. It includes at least six capabilities:
- Tool registration and description normalization: name, parameter schema, side-effect level, and timeout;
- Sandboxing and isolation: containerized execution with least-privilege file system and network access;
- Permissions and approval: tiered write operations, with explicit confirmation required for high-risk actions;
- Observability: full-chain tracing, tool call logs, metrics, and alerts;
- Fault tolerance and recovery: idempotency keys, resume from checkpoints, retry limits, and circuit breaking;
- Evaluation and regression: a fixed test case set that must pass after any policy or tool change.
A simplified execution skeleton:
def run(step, ctx):tool = registry.get(step.action) # 1. resolve tooltool.assert_allowed(ctx.policy) # 2. permission checkwith sandbox(tool.side_effect): # 3. isolated executionresult = tool.call(**normalize(step.args))trace.record(step, result) # 4. full trace loggingif result.error:ctx.reflect(result) # 5. trigger inner-loop reflectionreturn result
It is important to emphasize that the quality ceiling of the Harness determines the capability ceiling of the agent. No matter how strong the model is, if tool descriptions are vague, execution is untraceable, and failures are unrecoverable, the system cannot take on real business.
7. Implementation Advice and Common Pitfalls
- Start narrow, then widen: begin with read-only, rollback-capable scenarios, and gradually open write permissions;
- Govern the experience library: deduplicate, classify, and set expiration to avoid experience bloat that pollutes prompts;
- Evaluation first: evolution without a regression set equals loss of control;
- Keep costs controllable: use tiered model calls, small models for simple steps, and large models for complex planning;
- Safety fallback: treat external content as untrusted, require generated code to run in a sandbox, and keep a human gate for sensitive operations.
If elastic capacity is needed, state and memory can be placed in object storage and managed databases, task distribution can use a message queue, execution bodies can run on a container platform, and logging services and monitoring alerts can be integrated to form a complete operations loop.
8. Conclusion
The competitiveness of a persistent agent does not come from any single call, but from the engineering maturity of the “execute-reflect-update” loop. Making prompts into versionable configuration, making context into budgeted layered memory, and making execution into a sandboxed and traceable Harness is what truly brings dual-loop self-evolution to life. On general-purpose infrastructure from cloud platforms such as Baidu AI Cloud, this pattern is easier to implement with elasticity, observability, and governance, helping teams move agents from demos to production.
