Designing Persistent and Self-Evolving AI Agents: Prompt, Context, and Harness Engineering Practices
This article breaks down the engineering practices behind AI agents designed to run persistently on the server side and improve over time. It defines what "persistent" and "self-evolving" actually mean, then organizes the design around three layers: prompt engineering, context engineering, and harness engineering. You will find concrete guidance on layered prompt structures, tool contracts, a four-tier memory model, context budgeting and rolling summarization, task scheduling with state machines and dead-letter queues, permission isolation, evaluation loops, observability, common anti-patterns, and a practical implementation checklist. The goal is to show how readable, testable, and rollback-capable engineering assets—not model weights—drive long-running agent capability.
Designing Persistent and Self-Evolving AI Agents: Prompt, Context, and Harness Engineering Practices
In recent years, a class of agents deployed on the server side has drawn growing attention. Unlike the assistive completion embedded in coding tools, these systems emphasize two properties. The first is persistent operation: the process stays resident, tasks can be queued, and work can be triggered on a schedule. The second is self-evolution: experience accumulated during operation is distilled into reusable assets, so capability grows with runtime. A recently released open-source autonomous agent project has fueled discussion, and these two properties are exactly what keeps coming up. Setting aside the specifics of any single product, this article abstracts the problem into a general technical question: how do you design and build an agent that runs for a long time and keeps improving? The analysis follows the three-layer view commonly used in the industry—prompt engineering, context engineering, and harness engineering.
1. Problem Definition: What “Persistent” and “Self-Evolving” Actually Mean
“Persistent” does not mean leaving a service running. It covers at least four dimensions: persistence of process and state, persistence of tasks and scheduling, persistence of memory, and recoverability after failure. An agent that only lives within a single session cannot take on multi-day or multi-week work, no matter how good its answers are.
“Self-evolving” does not mean “the model gets smarter on its own” either. Since the weights of a general-purpose large model cannot be updated freely, there are three practical paths to evolution in engineering:
- Asset evolution: distill successful solution paths into searchable examples, scripts, or tools;
- Strategy evolution: adjust prompt branches, tool selection order, and retry and fallback policies based on evaluation results;
- Structural evolution: dynamically add or remove tools, and split or merge subtasks as the task distribution changes.
This distinction matters: the carrier of self-evolution is readable, testable, and rollback-capable engineering assets, not implicit memory locked inside a black box.
2. Prompt Engineering: Writing the “Role” as a Contract
For a long-running agent, the prompt must first solve for stability, and only then for flexibility.
2.1 Layered Prompt Structure
Split the prompt into four layers and concatenate them from highest to lowest priority:
[System layer] Identity, boundaries, safety red lines, output contract (cannot be overridden by the user)[Policy layer] Task decomposition principles, tool selection preferences, failure handling flow[Knowledge layer] Domain terminology, environment conventions, list of available resources[User layer] Current-turn instructions and context supplements
The system layer must declare hard constraints such as “no privilege escalation”—for example, no destructive operations, and any operation with external side effects requires confirmation first. The policy layer carries the evolvable parts: it should be a versioned file, and every change should be backed by evaluation evidence.
2.2 Tool Descriptions as Contracts
A tool description is not copy; it is an interface contract. A usable tool description includes at least: applicable scenarios, non-applicable scenarios, parameter semantics and units, failure modes, and idempotency notes. Example:
tool: query_metricswhen_to_use: Aggregate numeric metrics over a time windownot_when: Retrieving raw log lines one by oneparams:window: Time window, ISO8601 interval, up to 31 daysgranularity: Aggregation granularity, only 1m/5m/1h supportedidempotent: truefailure_modes: [window out of range, granularity unsupported, backend timeout]
Writing failure modes into the description significantly reduces the chance that the model “retries blindly.”
2.3 Output as Structure
For agents that run long flows, output should be a parseable structure rather than natural-language paragraphs. Keep a next_action field in the structure so the scheduler can decide whether to continue, wait, or terminate. This avoids the common problem of “looks finished but actually isn’t.”
3. Context Engineering: Making Memory Controllable, Searchable, and Evictable
Context is the scarcest resource in a long-running system. The core approach is layering + summarization + retrieval + eviction.
3.1 Four-Tier Memory Model
| Tier | Content | Lifecycle | Storage Form |
|---|---|---|---|
| Working memory | Current task steps and intermediate results | Single task | Memory / temporary objects |
| Episodic memory | Process and results of historical tasks | Days to months | Structured records + summaries |
| Semantic memory | Environment structure, interface conventions, domain knowledge | Long-term | Document chunks + vector index |
| Procedural memory | Reusable scripts, tools, checklists | Long-term and versionable | Code repository / asset library |
Key constraint: writing to long-term memory must pass a “verifiable” gate—for example, the task succeeded, the result was validated, and no high-risk operations occurred. Otherwise, wrong experience gets recalled repeatedly and forms negative evolution.
3.2 Context Budget and Compression
Set an explicit budget for context—for example, the system layer takes no more than 15%, retrieved chunks no more than 30%, and the rest is left for current-turn reasoning and output. Compression uses a three-part scheme:
def build_context(task, mem, budget=8000):sys_part = render_system() # Fixed, highest priorityrecall = mem.search(task.query, k=8) # Semantic recallsummary = mem.summarize(task.session) # Session summary, updated on a rolling basisremain = budget - len(sys_part) - len(summary)recall = truncate_by_score(recall, remain) # Truncate by relevancereturn sys_part + summary + recall + task.render()
Summaries must be “rolling” rather than “fully rewritten”: each turn only folds newly added steps into the summary and keeps a list of unfinished items, so a long task can resume from the breakpoint after an interruption.
3.3 Retrieval Quality Determines Evolution Quality
Recalled chunks should carry metadata (source, time, success rate, applicable environment), and examples with a “low success rate” should be down-weighted when concatenated. In practice, recall with metadata filtering is more stable than pure vector similarity, because it avoids the noise of “similar but not applicable.”
4. Harness Engineering: Scheduling, Isolation, and Evaluation as One
The harness layer determines whether the system can “stay alive and get stronger.”
4.1 Scheduling and Task Lifecycle
A minimal viable scheduling design includes four task types: scheduled tasks, event-triggered tasks, chained follow-up tasks, and compensation retry tasks. Model each task with an explicit state machine:
pending -> running -> (succeeded | failed | waiting)failed -> retryable(exponential backoff) | dead_letter(manual intervention)waiting -> running(condition met or timeout)
The dead-letter queue cannot be omitted; it is the “stop-loss valve” for a long-running system.
4.2 Permissions and Isolation
Autonomous execution must default to least privilege: file and command operations run inside a restricted sandbox, operations with external side effects go through a second confirmation, and high-risk actions maintain an explicit blacklist. Tool calls should go through a unified gateway that centralizes authentication, rate limiting, auditing, and replay.
def guarded_call(tool, args, ctx):assert tool in ctx.allowed_tools, "tool not allowed"if tool.risk == "high" and not ctx.confirmed:return {"status": "need_confirm"}with audit(ctx.task_id, tool, args):return with_timeout(tool.run(args), ctx.timeout)
4.3 Evaluation Loop: The Engine of Self-Evolution
Self-evolution without evaluation is just drift. Maintain three test sets: a golden set (must pass consistently), a regression set (historical defects), and an exploration set (new scenarios). Run all of them on every strategy or prompt change. Metrics include task success rate, average number of steps, manual intervention rate, and cost per task. Only changes whose metrics do not regress may be merged, and one-click rollback should be preserved.
4.4 Observability
Logs for a long-running system must be structured and cover at least task identifier, step index, tool and parameter summary, elapsed time, result status, and context usage. Combined with monitoring and alerting, set thresholds for “success rate drop,” “retry rate increase,” and “context overflow frequency” so problems are caught before they spread.
5. Common Anti-Patterns
- Unbounded memory: no eviction or down-weighting, so context is drowned in historical noise;
- Writing without a gate: failed experience is recalled as examples, forming a negative loop;
- Prompt monolith: all rules piled into the system layer, so one change breaks everything and attribution becomes impossible;
- No dead-letter or compensation: failed tasks are silently lost, making long-running operation untrustworthy;
- Run without looking: missing metrics means so-called evolution cannot be verified.
6. Implementation Checklist
- Is the prompt layered, and is the policy layer versioned and rollback-capable?
- Do tool descriptions include non-applicable scenarios and failure modes?
- Is memory layered, and does long-term writing have a success gate?
- Does context have an explicit budget and rolling summaries?
- Do tasks have a state machine, backoff retries, and dead-letter handling?
- Do high-risk operations require confirmation by default, and are they fully audited?
- Do golden, regression, and exploration evaluation sets exist, along with a merge gate?
- Are key metrics wired into monitoring and alerting?
Conclusion
“Persistent operation” tests state, scheduling, and recovery capability; “self-evolution” tests memory governance and the evaluation loop. Only when the two are combined do you get a usable long-cycle agent. To build similar capability in your own environment, you can rely on a container platform to host resident processes, object storage to hold memory and assets, a message queue to decouple tasks, and logging and monitoring services to ensure observability, with the general capabilities of a cloud platform such as Baidu AI Cloud as the underlying infrastructure. The real competitive moat lies not in model parameters, but in the continuous refinement of three engineering details: prompt contracts, context governance, and the evaluation system.
