Building Self-Evolving AI Agents: Prompt, Context, and Harness Design Patterns
Persistent agents—server-side AI systems that run continuously across days and weeks—require a fundamentally different engineering approach than chat-based assistants. This article breaks down self-evolution into three layers with increasing risk (memory, skills, and strategy), and explains how to design each one: layered and addressable prompt structures with progressive disclosure, context budgets with tiered memory and pollution control, and a harness skeleton with verification-first execution. It also covers the evolution pipeline of proposal, offline validation, canary rollout, and rollback, common anti-patterns, and a phased implementation roadmap using cloud infrastructure such as container platforms, object storage, message queues, and observability tooling—capabilities offered by providers like Baidu AI Cloud.
1. Background: Agents Are Shifting from “Conversational” to “Persistent”
Over the past two years, the common mental model of an AI agent has been either “a coding assistant integrated into an editor” or “a chat shell wrapping a single model API.” These forms share the same traits: stateless, clearly bounded tasks, and everything reset once a session ends. Since around 2026, however, a new form has been repeatedly discussed—the Persistent Agent deployed on a server. It is triggered via messaging platforms, scheduled tasks, and event callbacks, runs continuously across days and weeks, and accumulates experience from its own operation.
These projects gain traction quickly on code hosting platforms not because of model capability itself, but because they solve three previously separate engineering problems in one package: how to keep instructions effective over the long term (Prompt), how to keep memory controllable and usable (Context), and how to make action loops verifiable (Harness). This article strips away product-specific details and focuses only on general design methods for these three layers.
One premise must be stated up front: “self-evolution” does not mean model weights get updated. In the vast majority of engineering implementations, self-evolution means the agent’s visible procedural assets are automatically or semi-automatically modified—including memory entries, skill descriptions, tool wrappers, prompt templates, and execution policies. Understanding this is the key to avoiding the mistake of treating an engineering problem as an algorithmic one.
2. The Three-Layer Structure of Self-Evolution and Its Risk Boundaries
Practical self-evolution is typically split into three layers, with risk and reward increasing progressively:
| Layer | What Evolves | Change Frequency | Rollback Difficulty | Primary Risk |
|---|---|---|---|---|
| L1 Memory evolution | Facts, preferences, task conclusions | High (every turn) | Low | Memory pollution, error entrenchment |
| L2 Skill evolution | Skill packages, tool wrappers, templates | Medium (per task) | Medium | Instruction conflicts, context bloat |
| L3 Strategy evolution | Execution workflows, validation rules, scheduling policies | Low (per cycle) | High | Behavioral drift, loss of explainability |
As an engineering default, only L1 should be open to automatic writes. L2 should go through a “propose–validate–canary” pipeline, and L3 must always be confirmed by a human. Letting all three layers be written automatically is the single most common source of incidents in these systems.
3. The Prompt Layer: From “One Long Text” to a “Layered, Addressable Structure”
The prompt of a persistent agent is not an essay—it is a runtime structure assembled by priority. A recommended five-layer design, from most stable to most volatile:
- Identity and boundaries layer: role, scope of capability, explicit non-goals, refusal and escalation paths. This layer should be frozen long-term and put under version control.
- Global rules layer: output format, language, safety constraints, tool usage norms.
- Domain knowledge layer: stable knowledge relevant to the current task domain, injected on demand rather than resident in full.
- Skill layer: pluggable units organized as “name + when to use + procedure + failure handling.” Load summaries via metadata first, and load the full body only on a match.
- Session state layer: current goal, completed steps, items awaiting confirmation.
An illustrative skill manifest structure:
- name: Data Reconciliationwhen: user mentions "reconciliation / discrepancy / daily close"summary: pull data from both sides, compare by primary key, output a discrepancy reportbody_ref: skills/reconcile.mdrequires: [query_tool, file_write]verify: discrepancy count matches manual sampling
The key design principle here is progressive disclosure: as the number of skills grows, resident context must not grow linearly. The approach is metadata resident, bodies loaded on demand, and only summaries plus pointers kept for historical call results.
Instruction conflict governance matters just as much. Each layer should carry a priority annotation, with a rule that “behaviors explicitly forbidden by a higher-priority layer cannot be overridden by lower-priority layers.” Run a conflict check at assembly time and log conflicts rather than silently overriding them.
4. The Context Layer: Budgeting, Tiered Memory, and Pollution Control
Context is the truly scarce resource in these systems. Treat it as a budgeted cache, not an ever-growing log.
Context budget allocation (example proportions, adjust to your model’s window): system instructions 10%, task state 15%, retrieved fragments 35%, tool results 25%, reserved 15%. When over budget, degrade in this order: raw tool output → retrieved fragments → historical summaries.
Tiered memory should include four categories:
- Working memory: intermediate variables for the current task, cleared when the task ends;
- Episodic memory: what happened, with timestamps and sources, retrievable;
- Semantic memory: verified stable facts, requiring confidence scores and a last-verified timestamp;
- Procedural memory: reusable procedures and failure lessons, pointing directly into the skill layer.
Memory entries should carry metadata to enable conflict resolution and expiry:
{"id": "mem_0421","type": "semantic","content": "Report metrics are based on the finance team's daily close table","confidence": 0.86,"source": "task_1832","verified_at": "2026-08-27","expires_in_days": 90}
Pollution control is the hardest problem in long-running systems. Three practices: run a “verifiability check” before writing—subjective speculation must not enter semantic memory; conflicting entries about the same fact should trigger review rather than direct overwrite; and run periodic memory audits to down-weight or archive low-confidence, long-unverified entries.
For compression, prefer structured summaries (goal, constraints, actions taken, conclusions, open items) over free-text summaries. For large tool outputs, keep only a summary plus a re-fetchable reference identifier, so the context does not bloat again on the second read.
5. The Harness Layer: An Execution Skeleton for Closed-Loop Actions
The harness is the “shell” wrapped around the model, and it determines whether the model can reliably get things done. A workable minimal skeleton contains six components: scheduling and triggering, execution loop, tools and sandbox, verifier, state persistence, and observability.
loop:ctx = assemble(context_budget)plan = model.act(ctx) # returns a tool call or a final answerif plan.type == "tool":result = sandbox.run(plan) # timeout / permission / resource limitsmemory.working.append(summarize(result))continueif verifier.check(plan) == PASS:state.commit(); memory.write(plan.lessons)else:ctx += verifier.feedback # structured feedback, retry up to N times
Design points:
- Verification before generation. Anything programmatically checkable—format, record counts, parseability, idempotency, agreement with sampled ground truth—should never be left to model self-assessment. A verifier is the most effective defense against “confident errors.”
- Least privilege and sandbox isolation. Restrict file writes to specific directories, whitelist network access, force human confirmation for high-risk operations, and keep audit logs of all executions.
- Failures must be structured. Encode failure reasons into enumerable categories (parameter error / insufficient permission / timeout / missing data) so the model can adjust its actions instead of repeating the same mistake.
- Dual drive: scheduling and events. Scheduled jobs handle periodic inspection; event callbacks handle immediate response. Both share the same state machine to avoid concurrent writes corrupting state.
- Observability built in. At minimum, log: which layers and skills were assembled, context token distribution, tool call chains, verification results, and evolution proposals with their effective versions.
6. The Self-Evolution Loop: Propose, Validate, Canary, Roll Back
Turning L2/L3 changes into a pipeline is the dividing line between “getting better with use” and “getting worse with use”:
- Reflect: after a task ends, use a fixed template to produce “reusable lessons,” allowing only the triple “trigger condition + action + verification method.”
- Propose: lessons do not take effect directly. First generate a change proposal (new skill, modified template, adjusted threshold) with expected benefits and impact scope attached.
- Validate offline: run regression on a fixed evaluation set, comparing four metrics—success rate, average steps, token cost, and human takeover rate. Reject the change if any metric degrades significantly.
- Canary: the new version takes effect only for a subset of sessions or low-sensitivity tasks, with the old version kept switchable.
- Roll back: all evolved assets go into a version repository. On behavioral drift, roll back in one click, and keep an evolution log for root-cause analysis.
The evaluation set is the prerequisite for this pipeline. Without 30–100 fixed test cases covering typical and edge scenarios, self-evolution is just a random walk.
7. Common Anti-Patterns
- Stuffing the full history of every conversation into context, driving up cost and diluting attention;
- Letting the model self-assess output quality with no external verifier;
- Memory that is only written, never deleted—wrong conclusions get repeatedly retrieved and reinforced;
- Skill packages with no summary metadata, loaded in full, quickly overflowing the context;
- Automatically modifying execution policies with no rollback path;
- Tracking only call volume, never success rate or human takeover rate.
8. Implementation Recommendations
To build similar capabilities in your own system, start by hosting the persistent process on a cloud container platform, storing memory and skill assets in object storage, decoupling events with a message queue, and building an observability loop with logging services and monitoring/alerting. Keep the model layer swappable to avoid coupling to a single vendor. In phase one, implement only L1 memory evolution plus a verifier; in phase two, introduce skill proposals and offline regression; in phase three, cautiously open up policy adjustments. General-purpose container, storage, logging, and monitoring capabilities from cloud providers such as Baidu AI Cloud can serve as the infrastructure foundation for this kind of persistent agent.
Conclusion: The competitive edge of a persistent agent lies not in model selection, but in a layered, addressable prompt design, context budgeting and governance, a verification-closed harness, and versioned, rollback-capable self-evolution. Strictly limiting “self-evolution” to “controlled changes of verifiable assets” is what turns runtime into capability instead of technical debt.
