Designing Persistent and Self-Evolving AI Agents: Prompts, Context, and Runtime Harness
This article breaks down the architecture of long-running, self-evolving AI agents across three engineering layers: prompt engineering, context engineering, and the runtime harness. It explains how to structure instructions into layered, versioned blocks with a controlled write-back area, how to manage memory through tiered storage, retrieval instead of full injection, rolling summarization, and eviction, and how to turn intent into action with a main loop, tool governance, scheduling, observability, and sandboxing. It also outlines a closed loop for converting experience into capability, common anti-patterns to avoid, and how generic cloud capabilities support production deployment.
1. Background: From Session-Based Assistants to Long-Lived Autonomous Agents
Over the past two years, the shape of AI agents has shifted noticeably. Early products were mostly coding assistants embedded in development environments, or chat shells wrapping a single model API. Their capability boundary was effectively limited to a single session: when the session ended, the state was lost; if the model did not change, the capability stalled.
The core differences of a new generation of autonomous agents come down to two points:
- Persistent: runs as a long-lived server-side process, invoked through multiple entry points such as messaging platforms, scheduled jobs, and event triggers, without depending on a particular front-end interface.
- Self-Evolving: turns successful experience, lessons from failures, and environment knowledge accumulated during operation into reusable assets, so that “the longer it runs, the better it performs.”
It is worth stressing that “self-evolving” does not mean modifying model weights. In engineering practice, it is usually achieved by stacking three layers of mechanisms: strategy accumulation at the prompt layer, memory and retrieval at the context layer, and a tool-and-scheduling loop at the runtime framework layer. This article focuses on these three layers.
2. Prompt Engineering: A Stable and Evolving Instruction Layer
In a long-lived agent, the prompt plays the role of “personality and rules.” The key design points are as follows.
Layered organization. Split instructions into four layers: identity and boundaries, global rules, task templates, and local patches. The identity layer describes the role and refusal boundaries; the rules layer defines output format, language, and safety constraints; the template layer provides reusable skeletons by task type; the patch layer injects special requirements for the current task.
Define a controlled write-back area. If you want the agent to improve itself, you must carve out a controlled region in the prompt (for example, an experience section) and specify the write format and admission criteria, so the model cannot freely rewrite core constraints.
[Experience section - append-only, fixed format]- Scenario: <trigger condition>- Approach: <reusable steps>- Verification: <how to confirm success>- Confidence: high/medium/low
Constraints over expectations. Replace vague wording such as “try to” or “preferably” with decidable statements like “must / must not / if X then Y,” reducing behavioral drift across long chains.
Versioning and canary rollout. Prompts should enter version control like code, with each change accompanied by change notes and regression samples. Roll out gradually by canary percentage in production, and roll back to the previous version in seconds if a regression appears.
3. Context Engineering: Controllable, Searchable, Evictable Memory
Context is the part most likely to get out of control in long-running systems. The core tension: the window is finite, but experience is unlimited.
- Tiered memory structure. A common industry approach has three layers:
- Working memory: reasoning and intermediate results for the current task, reclaimed when the task ends;
- Episodic memory: records “what was done and what happened” over time, used for retrospectives;
- Semantic memory: abstracted stable knowledge, such as environment structure, API contracts, and preferences.
- Retrieve instead of injecting everything. Once semantic memory grows, switch to “retrieve first, then inject”: generate a retrieval key for the current request, fetch the top few most similar entries, and attach timestamps and confidence scores so the model can judge reliability.
def build_context(task, mem, k=5):hits = mem.search(task.key, top_k=k) # semantic retrievalhits = [h for h in hits if h.confidence >= 0.6]stable = mem.get_policy() # stable rulesrecent = mem.recent(limit=3) # recent episodesreturn f"{stable}\n{recent}\n{hits}\n{task.raw}"
Summarization and compression. Use rolling summaries for long histories: compress into key points every few turns, keeping decisions, conclusions, and open items while discarding pleasantries and repeated content. The compression process should be auditable so critical information is not silently dropped.
Eviction and conflict handling. Give memory a lifecycle and a decay factor. When new experience conflicts with old experience, prioritize “verifiable evidence” and keep a record of the conflict, preventing the model from oscillating on the same problem.
Privacy and compliance. Sensitive information must be classified and de-identified before entering memory, stored on a minimum-necessary basis, with the ability to delete data by subject.
4. Runtime Framework Engineering: Turning “Thinking” into “Doing”
Even the best prompt and memory need a reliable execution shell (harness) to land in practice.
- Main loop. The standard “perceive - plan - call - observe - reflect” loop needs explicit timeouts, retries, and termination conditions to avoid infinite loops and resource exhaustion.
while not done:plan = model.decide(observation, tools)if plan.type == "tool":result = run_tool(plan, timeout=30, retries=2)observation = summarize(result)if step > MAX_STEPS: escalate_to_human()
Tool layer governance. Tool descriptions should state purpose, inputs and outputs, side effects, and failure modes; introduce secondary confirmation and whitelists for high-risk operations; log all calls to form a replayable execution trace.
Scheduling and triggering. A built-in scheduler handles periodic and delayed tasks, while an event entry point handles external message triggers. Scheduling must support idempotency keys to prevent repeated execution from stacking side effects.
Observability. Collect three signal types together: logs, metrics, and traces. Logs record the basis for decisions, metrics monitor success rate and latency, and traces reconstruct the full path of a task. On anomalies, inspect the trace first rather than a single log point.
Sandboxing and resource isolation. Code execution, file reads and writes, and network access should run in restricted environments with resource quotas and egress policies configured, reducing the risk of privilege escalation and data leakage.
5. The Self-Evolution Loop: Converting Experience into Capability
The key to self-evolution is not “writing a lot” but “filtering accurately.” A working loop has five steps:
- Collect: record task input, execution trace, result, and human feedback;
- Evaluate: produce objective scores using automatically decidable checks (tests passing, format compliance, metrics meeting targets);
- Distill: abstract only high-scoring and reusable traces into experience entries; low-scoring traces go into a failure library for negative constraints;
- Inject: experience enters context via retrieval, or is written into the prompt experience section after review;
- Regress: periodically replay a fixed sample set; if metrics drop, automatically roll back the corresponding experience.
evolution:min_score: 0.8max_new_per_day: 20regression_suite: baseline_v3rollback_on_drop: 0.03
6. Common Anti-Patterns and How to Avoid Them
- Unbounded memory growth: append-only storage raises retrieval noise and costs out of control. Set capacity limits and decay.
- Experience pollution: writing an accidental success into a general rule. Require multiple reproducible validations as the admission bar.
- Prompt monolith: all rules piled in one place, so any change ripples everywhere. Layer and modularize.
- No termination in loops: missing step and budget caps. Set explicit circuit breakers and a human escalation path.
- Writing without evaluating: without objective evaluation, the evolution direction is uncontrollable. Build the evaluation system before self-evolution.
7. Deployment Advice and Cloud Support
To deploy this kind of agent in production, build it in layers on generic cloud capabilities: use a container platform to host long-lived processes and sandboxes, object storage to archive memory and traces, a message queue to decouple tasks and smooth peaks, and logging plus monitoring and alerting to close the observability loop, while a unified identity and permission system constrains the scope of tool calls. Baidu AI Cloud offers corresponding capabilities in these generic categories, and you can proceed at a pace of “validate with small traffic first, then scale up gradually.”
Overall, persistence answers “is it there,” context engineering answers “does it remember,” the runtime framework answers “does it act,” and the self-evolution loop answers “does it keep getting better.” Missing any one of the four, a long-lived agent will struggle to deliver stable value.
