Designing Prompts, Context, and Runtime for Persistent Self-Evolving AI Agents
This article examines how to build AI agents that run persistently on the server side, maintain cross-session memory, and improve over time. It breaks down "self-evolution" into three engineering layers: prompt engineering for behavioral protocols, context engineering for state and memory management, and harness engineering for execution, evaluation, and rollback. Readers will learn a layered reference architecture, practical patterns for memory governance, and common anti-patterns to avoid.
I. Background: Why “Persistent Runtime + Self-Evolution” Is Now a Design Focus
Recently, a class of agent projects has drawn attention: agents that reside long-term on the server side, maintain cross-session memory, support scheduled tasks, and interact through multiple entry points. They differ clearly from traditional chatbot shells and IDE coding assistants: the former are centered on single sessions, while the latter, though useful for coding, remain bounded by specific toolchains. The goal of a persistent agent is to accumulate experience over longer time horizons, reuse skills, and continuously improve task completion quality.
First, let’s clarify what “self-evolution” means in engineering practice. It usually does not mean online training of LLM parameters; rather, it means improving runtime behavior policies at three levels:
- Context layer: converting historical experience into information usable for future decisions through memory, summarization, retrieval, and reflection;
- Prompt and protocol layer: constraining and optimizing model behavior through system prompts, tool-calling protocols, output contracts, and reflection templates;
- Runtime layer: making “improvement” verifiable and governable through scheduling, sandboxing, evaluation, replay, rollback, and permission control.
A persistently running agent is therefore not “a model that got smarter on its own,” but “a system that distills execution traces into reusable assets and continuously validates them in controlled loops.” This defines the framework of this article: Prompt Engineering defines behavioral protocols, Context Engineering organizes state and memory, and Harness Engineering closes the loop on execution, observation, and feedback.
II. Overall Architecture: Three Layers Working Together, Not Single-Point Optimization
A reasonably complete persistent self-evolving agent can be abstracted into the following layers:
- Ingress layer: receives requests from messaging channels, scheduled tasks, and admin consoles;
- Orchestration layer: maintains task state and decides whether to continue, wait, reflect, or terminate;
- Prompt and protocol layer: assembles goals, constraints, tool descriptions, and memory fragments into model input;
- Context and memory layer: manages working memory, task state, long-term facts, preferences, skill cards, and execution logs;
- Tool runtime layer: registers tools, executes calls, isolates permissions, and handles timeouts and retries;
- Evaluation and observability layer: records traces, computes metrics, replays failures, and triggers human approval;
- Governance layer: version management, permission policies, data retention, and migration.
The key is not the number of components but how three of them couple: prompts define “how to think and call,” context provides “what information to think with,” and the runtime guarantees “how to verify and improve after execution.” Missing any layer, self-evolution degrades into context bloat, tool misuse, or unreproducible “voodoo tuning.”
III. Prompt Engineering: Writing Self-Evolution as an Executable Protocol
1. Layer system prompts instead of stacking long instructions
Split the system prompt into a stable layer and a dynamic layer. The stable layer describes role boundaries, safety principles, general tool-usage rules, output contracts, and stopping conditions. The dynamic layer injects the current task, relevant memories, a summary of available tools, and stage-level reflection requirements. This preserves behavioral consistency while avoiding stuffing the entire history into every prompt.
An example of a maintainable prompt structure:
[Identity & Goals] You are a persistently running task agent. Prioritize verifiable completion.[Tool Protocol] State the purpose before calling a tool; clarify missing parameters first; retry at most N times after failure and log the reason.[Context Rules] Only use memory with labeled sources; on conflict, trust the latest confirmed facts; if uncertain, retrieve or ask.[Reflection Rules] After each task stage, output: results, failure points, reusable lessons, and whether to write to long-term memory.[Safety Boundaries] High-risk operations require human approval; never bypass permissions; never fabricate execution results.[Output Contract] Return structured status: done/blocked/need_input, with evidence and next steps.
2. Make tool-calling protocols explicit
Tool descriptions should cover more than names and parameters: include applicable scenarios, side-effect levels, failure semantics, and return formats. Prompts should require the model to state its intent briefly before a call and update its plan based on observations afterward. For tools with side effects, distinguish “read-only” from “mutating” operations, and gate the latter with approvals or idempotency keys.
3. Reflection templates should produce durable assets
If “reflection” just produces a free-form summary, it rarely gets reused. A more effective approach is requiring structured skill cards: trigger conditions, steps, required tools, success criteria, failure cases, and applicability. Skill cards must pass evaluation and deduplication before entering long-term memory, preventing occasional successes from being固化—hardened into wrong lessons.
4. Output contracts and stopping conditions
The biggest fear in persistent systems is infinite loops. Prompts should make stopping conditions explicit: goal achieved, sufficient evidence, budget exhausted, human input needed, or risk too high. Output contracts should include status codes, evidence references, confidence levels, and suggested next steps so the runtime can decide whether to continue.
5. Drift prevention and safety boundaries
Long-running systems suffer prompt drift: models gradually ignore constraints or treat old memories as current facts. Fix a priority order in the prompt: safety rules > current user goal > long-term preferences > historical experience. Every injected memory should carry a timestamp, source, and confidence level, with explicit handling instructions for conflicts.
IV. Context Engineering: Making Memory Retrievable, Compressible, and Governable
1. A layered memory model
Divide context into at least four categories:
- Working memory: current-turn plans, observations, and temporary variables with short lifecycles;
- Task state: cross-turn goals, progress, to-dos, and blockers;
- Long-term facts and preferences: user preferences, environment constraints, confirmed facts;
- Skill and case library: reusable steps, failure modes, evaluation conclusions.
Different layers need different write permissions, retention periods, and retrieval methods. Working memory updates at high frequency; long-term facts require confirmation before writing; skill cards require evaluation before publishing.
2. Balance retrieval and compression
Context windows are finite—simply appending history doesn’t scale. Common strategies: produce stage summaries of execution logs; use vector or keyword retrieval over long-term memory; structurally trim tool returns; retain sources when information conflicts. When compressing, prioritize keeping “decision rationale, failure causes, and unverified hypotheses” rather than full conversational transcripts.
3. Context budgets and priorities
Set budget ratios per context category: fixed allocation for system protocols, medium for task state, and dynamic relevance-based allocation for retrieved memories. When over budget, compress low-confidence history first, then trim redundant tool outputs, and only reduce safety constraints last. Never delete safety and permission instructions to fit more history.
4. Conflicts, contamination, and versioning
The biggest risk for long-term memory is contamination: wrong conclusions cited repeatedly, outdated preferences overriding current goals. Mitigations include deduplication and confidence evaluation before writing; keeping multiple versions with labeled sources on conflict; periodically purging low-value memories; and versioning and rolling back skill cards. Bigger context is not better—“traceable, small, and accurate” is better.
5. Observability
Every injected context item should be traceable to its source: which task, which tool result, which user confirmation. Only then can failure replay determine whether a problem lies in the prompt, retrieval, or execution.
V. Harness Engineering: Runtime Loops That Make “Improvement” Trustworthy
1. The execution loop
The core of a persistent agent is a controlled loop: plan, act, observe, reflect, update state. Pseudocode:
while not done:ctx = build_context(task_state, retrieve_memory(task), budget)decision = model.generate(render_prompt(ctx))if decision.type == "tool_call":result = sandbox.execute(decision.tool, decision.args)trace.record(decision, result)task_state = update_state(task_state, result)elif decision.type == "reflect":skill = evaluate_and_distill(trace)memory.propose_write(skill)elif decision.type == "need_input":pause_and_notify(decision.question)breakdone = check_stop_condition(task_state, budget, decision)
The key is that every step produces an observable trace—not just a final answer.
2. Tool registration, sandboxing, and permissions
Tools should be registered centrally, declaring parameter schemas, side-effect levels, timeouts, retries, and idempotency policies. Execution must occur in a sandbox, granting file, network, and data access under least privilege. Mutating operations need approval, auditing, and rollback points. Tool returns should be structured; avoid stuffing large blocks of unstructured text back into context.
3. Scheduling and long-running tasks
Persistent operation requires scheduled triggering and task pause/resume. The scheduler should support idempotent triggers, failure retries, timeout termination, and concurrency limits. Long tasks need checkpoints that persist task state and key evidence, so they can recover after a crash rather than restarting.
4. Evaluation, replay, and observability metrics
Self-evolution demands evaluation. Track metrics such as task success rate, human intervention rate, tool failure rate, context hit rate, average step count, and rollback count. Replay failed traces to pinpoint whether the cause is missing prompt constraints, incorrect memory retrieval, unclear tool descriptions, or insufficient permissions. “Self-improvement” without evaluation is just uncontrolled drift.
5. Failure recovery and human approval
High-risk checkpoints should support human approval; after failures, follow policies for retry, degradation, or rollback. Skill cards and memory writes should go through a “propose–evaluate–publish” pipeline, preventing the model from writing a one-off success directly into long-term assets.
6. Versioning and migration
Prompt templates, tool protocols, memory schemas, and evaluation rules should all be versioned. During upgrades, preserve old traces and rollback capability; during migration, validate memory compatibility. The competitiveness of a persistent system comes from long-term maintainability, not a one-time demo.
For the hosting layer, generic cloud capabilities—container platforms, object storage, logging, and monitoring/alerting—can run the resident loop, store memory snapshots, and observe quality; offerings in these standard categories from providers such as Baidu AI Cloud can serve as one neutral hosting option. The emphasis remains on architecture layering and governance mechanisms rather than any specific implementation.
VI. Three Layers in Concert: A Closed Loop of “Verifiable Self-Evolution”
Prompts define protocols, context provides state, and the harness executes and verifies. A healthy loop looks like:
- The runtime produces traces;
- The evaluator judges success/failure and causes;
- Reflection templates generate skill cards or memory candidates;
- The context layer deduplicates, labels sources, and versions them;
- The prompt layer injects them on demand in future tasks;
- The harness continues observing whether the skill improves success rates;
- Rollback if it is ineffective or degrading.
In this loop, every “write” must be traceable, every “reuse” must be evaluable, and every “upgrade” must be rollback-able.
VII. Practical Checklist and Anti-Patterns
Checklist:
- Define stopping conditions and safety priorities before pursuing self-evolution;
- Layer prompts, separating stable rules from dynamic context;
- Include side effects, failure semantics, and return formats in tool descriptions;
- Layer memory; require confirmation for writes and label conflicts;
- Compress context within budgets while preserving evidence chains;
- Record full traces at runtime, supporting replay and rollback;
- Publish skill cards only after evaluation; regularly purge degrading assets;
- Require human approval for high-risk operations; make mutations idempotent and rollback-able.
Common anti-patterns:
- Stuffing all history into context, raising costs and polluting decisions;
- Letting the model freely write long-term memory, causing contamination;
- No permission isolation for tools, making side effects uncontrollable;
- Evaluating only final answers without analyzing execution traces;
- Hardening a one-off success into a universal skill;
- Prompts that grow longer without priorities or conflict handling;
- No versioning, so regressions after upgrades cannot be diagnosed.
VIII. Conclusion
The hard part of persistent self-evolving agents is not “getting the model to reflect more.” It is decomposing self-evolution into governable engineering problems: prompts handle behavioral protocols, context handles state and experience assets, and the harness handles execution, evaluation, and rollback. Only when the three work together can a system move from “occasionally good” to “verifiably better over the long run.” For developers, the highest-value investment is not stacking more tools but building the infrastructure of layered prompts, traceable memory, sandboxed runtimes, and evaluation replay. For enterprise adopters, prioritizing permissions, auditing, data retention, and rollback capability usually matters more than chasing short-term demo effects.
