Designing Persistent and Self-Evolving Agents: Prompt, Context, and Harness Engineering
This article breaks down the engineering methodology behind persistent, self-evolving AI agents that run long-term on the server side rather than as IDE-embedded coding assistants. It defines what "persistent operation" and "self-evolution" actually mean in practice, then explains a three-layer decoupled architecture and three core engineering dimensions: writing prompts as versioned contracts, treating context as a limited budget with partitioning and eviction policies, and building a harness with scheduling, sandboxing, checkpoints, reflection, and observability. It also covers evaluation-driven evolution loops, common anti-patterns, and a four-stage adoption roadmap, so readers can make "the longer it runs, the stronger it gets" a metric-verifiable engineering result.
Designing Persistent and Self-Evolving Agents: Prompt, Context, and Harness Engineering
Over the past two years, the AI agent space has split into two clear tracks. One is the coding assistant embedded in an integrated development environment, focused on completion and localized Q&A. The other is the resident agent deployed on the server side, focused on staying online for long periods, maintaining cross-session memory, and accumulating capabilities. This article focuses on the latter and abstracts a product-agnostic engineering methodology. Across three dimensions—prompt engineering, context engineering, and harness engineering—it discusses how to build an agent that stays alive for the long term and gets stronger with use.
1. Problem Definition: What “Persistent Operation” and “Self-Evolution” Mean
Persistent operation does not simply mean the process never exits. It covers at least four layers. First, session state survives across turns and across processes. Second, task scheduling: the agent can execute on time-based or event-based triggers even without user input. Third, failure recovery: after an exception, it resumes from a checkpoint instead of starting over. Fourth, observability: execution traces, tool calls, and resource consumption can all be replayed and audited.
Self-evolution does not mean “the model rewrites its own weights.” In an engineering context, it is closer to experience accumulation at the system level: successful and failed execution traces are distilled into searchable knowledge, reusable skill fragments, and adjustable policy parameters, so that success rate and efficiency on similar tasks improve as runtime increases. A boundary must be emphasized here: updating model parameters belongs to training-side capability, while most resident agents can only evolve at the level of prompts, context, tool orchestration, and evaluation feedback.
2. Overall Architecture: Three-Layer Decoupling as the Foundation for Stable Evolution
Split the system into three layers that communicate through explicit contracts:
┌─────────────────────────────────────┐│ Access: messaging platforms / timers / callbacks │├─────────────────────────────────────┤│ Orchestration: plan-execute-verify-reflect loop ││ Memory: working / episodic / semantic memory ││ Tools: retrieval, computation, files, external calls │├─────────────────────────────────────┤│ Runtime: sandbox, checkpoints, queues, observability │└─────────────────────────────────────┘
The value of decoupling is that swapping the model does not touch business logic, adding a tool does not change the main body of the prompt, and adjusting the memory strategy does not affect the access layer. Many projects mix all three together early on, and later any capability upgrade triggers large-scale regression.
3. Prompt Engineering: Writing the “Persona” as a Contract
The prompt of a resident agent is not a self-introduction but an executable contract. It should be organized into five sections:
- Identity and goals: state that it is a long-term assistant rather than a one-off Q&A bot, and define success criteria.
- Capability boundaries: list available tools and unavailable capabilities to avoid hallucinated promises.
- Behavioral rules: priority order (safety > compliance > explicit user instructions > default preferences).
- Output specification: structured format, length constraints, citation and confidence expression.
- Upgrade clauses: specify the trigger conditions for memory writes and policy adjustments.
Illustrative snippet:
role: long-running-assistantgoals: [complete delegated tasks, proactively report anomalies]tool_policy: {allow: [search, calc, file_io], deny: [raw_shell]}escalation: {on_low_confidence: ask_user, on_repeated_failure: propose_plan_change}memory_write_when: [user confirms preference, task succeeds and is reusable]
The key practice is versioning the prompt. Every change should record the reason and the evaluation result; otherwise self-evolution degrades into unexplainable drift.
4. Context Engineering: Context Is the Scarcest Resource
The context window is a limited budget and needs to be governed like memory management. Four context partitions and their eviction strategies are recommended:
- Working memory: the current task’s plan, completed steps, pending items, and constraints; archived when the task ends.
- Episodic memory: summaries and results of historical tasks, retrieved by time and similarity; retaining failure cases is especially important.
- Semantic memory: user preferences, domain terminology, and environment parameters; requires deduplication and conflict resolution.
- Tool results: large objects are stored only as references (such as object storage paths), with the body fetched on demand.
A practical budget allocation example:
Total budget 100%├─ System contract 10% (fixed)├─ Current plan and state 20%├─ Retrieved relevant memory 30% (truncated by relevance)├─ Tool result summaries 25% (overflow is offloaded with references)└─ Reserved for reflection and output 15%
Write policies matter just as much. Introduce a “reusability score” so that only experiences confirmed by the user, or repeatedly observed across multiple tasks, enter long-term memory; this prevents noise from drowning out useful information. For conflicting information, apply weighting by timestamp and source credibility rather than simple overwriting.
5. Harness Engineering: Making the Loop Run Reliably and Lastingly
The harness turns “able to think” into “able to deliver.” Its core components include:
- Scheduler: supports both timed and event triggers; tasks must be idempotent so repeated triggers produce no side effects.
- Sandboxed execution: tool calls run in a restricted environment with limits on network, files, and resource quotas.
- Checkpoints and replay: each step records inputs, outputs, and tool versions so execution can resume after failure.
- Reflection stage: after a failure, generate a “gap analysis” that produces policy adjustment suggestions instead of a direct retry.
- Observability: structured logs plus metrics plus tracing, covering latency, success rate, and context usage.
Pseudocode example:
while not done:plan = planner(state)result = sandbox.run(plan.tool, plan.args)state = memory.update(state, result)if result.failed:lesson = reflector(state, result.error)memory.write(lesson, score=lesson.reusability)state = checkpoint.rollback_or_continue(state)metrics.emit(state)
6. The Self-Evolution Loop: Driven by Evaluation, Not by Gut Feeling
Self-evolution must be built on evaluation; otherwise there is no way to distinguish “getting stronger” from “getting sloppy.” Three levels of evaluation are recommended:
- Unit level: tool call accuracy and parameter validity rate.
- Task level: end-to-end success rate, average number of steps, and human intervention rate.
- Cycle level: success rate trends for similar tasks over time, and context usage trends.
Evolution actions are limited to four types: adding prompt clauses, governing memory entries, adjusting tool orchestration policies, and tuning retrieval and ranking parameters. Every change must go through a “canary—compare—rollback” process, with version snapshots retained.
7. Common Anti-Patterns
- Stuffing all historical conversation into the context, causing cost and latency to grow linearly.
- Retrying failures verbatim without attribution, forming an infinite loop.
- Memory that is only written and never deleted; once noise accumulates, retrieval quality collapses.
- Frequently hand-editing prompts with no evaluation, making behavior irreproducible.
- Overly broad tool permissions with no sandbox or quotas, creating high security risk.
8. Adoption Roadmap
Stage one: build a “survivable resident agent” with scheduling, checkpoints, basic memory, and logging. Stage two: build “governable memory” with partitioning, scoring, conflict resolution, and reference-based storage. Stage three: build “measurable evolution” with an evaluation set, canary releases, and rollback. Stage four: build a “scalable ecosystem” with multiple messaging integrations, multi-model adaptation, and a unified permission model. If elasticity and persistence are needed, a container platform can host the runtime, object storage can hold large objects, a message queue can decouple tasks, and logging plus monitoring and alerting services can provide observability—all general-purpose category options.
Conclusion
The competitiveness of a resident agent ultimately does not depend on how many tools it integrates, but on three things: whether the prompt has become a versionable contract, whether context is governed as a limited budget, and whether the harness has checkpoints and an evaluation loop. Get these three solid, and “the longer it runs, the stronger it gets” stops being a marketing line and becomes an engineering result verifiable by metrics.
