Designing Persistent and Self-Evolving AI Agents: Prompt, Context, and Harness Engineering

    This article breaks down the engineering behind AI agents that run persistently and improve over time. It explains why long-running agents require durable state, self-evolution, and strong controllability, then walks through three core disciplines: prompt engineering for layered, versioned instructions; context engineering for tiered memory and on-demand retrieval; and harness engineering for main loops, tool abstractions, scheduling, isolation, and observability. It also covers common anti-patterns and a pre-launch checklist for teams building their own long-running agents.

    1. From Session-Based Assistants to Always-On Agents

    Over the past two years, the form of AI agents has shifted noticeably: from coding assistants tied to an IDE, to chat wrappers around a single model API, to autonomous executors deployed on servers that can stay resident for long periods. The key difference along this path is not model size but a change in the assumption about lifecycle.

    A session-based assistant implicitly assumes that “one interaction ends the session.” It therefore needs no long-term memory and bears no consequences. An always-on agent assumes that “the process keeps running and tasks span days or weeks.” As a result, three engineering capabilities that were once optional become mandatory:

    1. Persistence: state, memory, and tasks must survive process restarts.
    2. Self-evolution: new experience must accumulate into reusable capabilities rather than reasoning from scratch every time.
    3. Controllability: long-running unattended operation requires scheduling, auditing, and circuit-breaking mechanisms.

    Industry evaluation of such systems usually falls along three dimensions: prompt engineering solves “how to express intent and constraints reliably,” context engineering solves “what to put in a limited window, how to compress it, and how to recall it,” and harness engineering solves “tools, loops, scheduling, isolation, and observability.” This article follows these three threads and presents a reusable set of design practices.

    2. Prompt Engineering: Writing Persona, Rules, and Skills as Evolvable Assets

    2.1 Layered Prompt Structure

    The prompt of a long-cycle agent should not be a single concatenated block of text; it should be layered, with different change frequencies across layers:

    • Invariant layer: identity, safety red lines, output contract (very low change frequency, must be versioned);
    • Stable layer: domain rules, tool usage conventions, failure-handling policies;
    • Dynamic layer: current task, recent memory summary, environment snapshot.

    The direct benefit of layering is cache friendliness and testability: the invariant layer can be reused for a long time, the dynamic layer is swapped each time, and regression testing only needs to fix the first two layers to reproduce behavior.

    2.2 Prompts as Code

    Managing prompts as code is a basic requirement for long-cycle systems: put them under version control, route them through review, keep change records, and run A/B and regression evaluations on critical prompts. An illustrative directory layout:

    1. prompts/
    2. identity.md # Identity and safety boundaries
    3. rules/tool_usage.md # Tool invocation conventions
    4. skills/pdf_extract.md# Reusable skill descriptions
    5. templates/task.md # Task templates
    6. evals/
    7. cases/*.jsonl # Fixed evaluation set

    2.3 Structured Output and Failure Fallback

    When interacting with external systems, output must be a parseable contract rather than natural language. A common practice is to agree on fixed fields and validate with retries:

    1. {"tool": "file_search", "args": {"path": "docs/", "limit": 20}, "reason": "Locate configuration notes"}

    Pairing this with a loop that “returns the error message on validation failure and asks for correction” can significantly reduce the proportion of invalid calls.

    3. Context Engineering: Tiered Memory and On-Demand Recall

    3.1 Why Subtraction Is Necessary

    The context window is a scarce resource and has two well-known problems: declining utilization of mid-section information (“lost in the middle”), and irrelevant content diluting attention. So the goal of context design is not to “fill it up” but to “present only the minimal sufficient set needed for the current decision at each step.”

    3.2 A Four-Layer Memory Model

    • Working memory: intermediate variables and tool results for the current task, reclaimed when the task ends;
    • Episodic memory: events and outcomes recorded along a timeline, supporting retrospection like “how was this done last time”;
    • Semantic memory: distilled stable facts, such as environment structure, conventions, and preferences;
    • Procedural memory: reusable operation sequences, i.e., “skills.”

    Writes must go through filtering and deduplication; reads must carry relevance ranking and time decay to avoid unbounded memory growth.

    3.3 When to Compress and Summarize

    Compression is not a scheduled task but should be triggered by budget: when usage exceeds a threshold, summarize the oldest and least relevant fragments, keeping conclusions and citation locations while discarding process noise. Summaries themselves should also be structured, for example a three-part “Conclusion / Basis / Open Questions” format, to ease later retrieval.

    3.4 Retrieve Rather Than Inject Everything

    For documents, logs, and historical trajectories, prefer retrieval to inject on demand, with source identifiers attached, so the agent can trace and verify when citing and reduce fabrication.

    4. Harness Engineering: Letting Capabilities Grow Stably Unattended

    4.1 Main Loop and Tool Layer

    A typical main loop is “perceive—plan—call—validate—record.” The tool layer needs a unified abstraction: name, parameter schema, permission level, timeout, idempotency, and return structure. High-risk tools (deletion, deployment, payment) should be graded separately and require secondary confirmation or human approval.

    1. def run(task):
    2. ctx = load_context(task) # Assemble the minimal sufficient context
    3. for step in range(MAX_STEPS):
    4. plan = model.decide(ctx) # Structured decision
    5. if plan.type == "tool":
    6. res = tools.call(plan, permission=policy.check(plan))
    7. ctx.append(compress(res)) # Compress the result before adding to context
    8. elif plan.type == "final":
    9. return plan.answer
    10. return fallback_report(task) # Safe fallback when steps run out

    4.2 Dual Triggering by Schedule and Event

    Always-on operation relies on two types of triggers: time-driven (periodic inspections, daily reports, data sync) and event-driven (message arrival, file changes, metric breaches). Both share the same executor and the same permission and audit logic, avoiding a “backdoor channel that bypasses controls.”

    4.3 Three Practical Paths to Self-Evolution

    Self-evolution does not mean automatically rewriting its own source code; a more robust engineering approach is a three-level progression:

    1. Memory evolution: write successful trajectories and failure lessons into memory to change the next decision;
    2. Skill evolution: solidify repeatedly occurring and validated operation sequences into skill documents or scripts, forming reusable assets;
    3. Prompt evolution: iterate prompts and rules based on evaluation results, published after human review.

    This requires an “evaluation set + canary + rollback”: any evolution must be able to measure its benefit and roll back quickly when it degrades.

    4.4 Isolation, Observability, and Cost

    Long-cycle operation must assume “things will go wrong”: isolate the execution environment with containers or sandboxes, grant files and network access by least privilege; record decisions, tool calls, and results across the full chain, with metrics covering success rate, average steps, tool failure rate, and resource consumption; logs and metrics can rely on cloud providers’ logging services and monitoring/alerting capabilities for centralized management, with object storage used to archive long-cycle trajectories.

    5. Common Anti-Patterns and a Checklist

    Anti-patterns include: blindly concatenating all history, frequently hand-editing prompts without versioning, tools without permission grading, memory that only grows and never shrinks, claiming “it got stronger” without evaluation, and letting the agent perform high-risk operations in an unisolated environment.

    A simplified pre-launch checklist:

    • Are prompts layered and versioned, and is there a fixed evaluation set?
    • Does the context have a budget and compression strategy, and is memory reclaimable?
    • Are tools graded, idempotent, and equipped with timeouts and retry limits?
    • Are there scheduling, auditing, circuit-breaking, and a human takeover channel?
    • Does self-evolution have measurement and rollback mechanisms?

    6. Conclusion

    “Longer runtime, stronger capability” is not an intrinsic property of the model but the result of engineering design: prompt engineering ensures predictable behavior, context engineering ensures limited resources are spent on key decisions, and harness engineering ensures long-running operation is controllable and measurable. Stacked together, these three give an agent the chance to turn the “cleverness” of a one-off interaction into “capability” that accumulates sustainably. For teams that want to build such systems, the recommendation is to start from a minimal closed loop—first get the main loop and auditing working, then gradually add memory tiering, skill accumulation, and canary evaluation, keeping evolution on an observable, rollback-capable track.