Self-Evolving Mechanisms for Long-Running AI Agents: Prompts, Context, and Runtime Design

    This article breaks down how long-running AI agents achieve self-evolution through practical engineering design rather than automatic model weight updates. It defines verifiable signals of evolution, outlines a five-layer architecture, and explains how to structure prompts into stable and evolving layers, manage context with budget partitioning and compression, build a fault-tolerant runtime with persistent tasks and idempotency, organize memory into four storage types with lifecycle management, and measure progress through evaluation and observability. Security and cost governance practices are also covered, giving readers a complete blueprint for building agents that improve reliably over time.

    Self-Evolving Mechanisms for Long-Running AI Agents: Prompts, Context, and Runtime Design

    1. Background: From Session-Based Assistants to Long-Living Autonomous Executors

    Agent technology has been iterating quickly over the past two years, and product forms are converging fast. One clear trend stands out: agents are shifting away from being coding assistants tied to an IDE or chat wrappers around a single endpoint, toward execution entities deployed on the server side that stay online for extended periods, accumulate experience, and steadily improve their completion rates.

    This shift brings three fundamental changes:

    1. The time horizon is extended. A session is no longer the only unit of work; tasks now progress over hours, days, or even weeks.
    2. State must be externalized. The model itself is stateless, so any capability growth has to come from external structures that can be persisted.
    3. Evaluation criteria change. The focus moves from “does a single-turn answer look right” to “long-cycle task completion rate, rework rate, and human intervention rate.”

    In an engineering context, “self-evolution” is not mysterious, nor does it mean model weights are automatically rewritten. It means the system can convert experience accumulated from execution traces into reusable prompt fragments, context entries, tool orchestration strategies, and validation rules, so that performance on similar tasks becomes more stable. Understanding this is the prerequisite for not mistaking marketing language for technical capability.

    2. A Practical Definition and Boundaries of Self-Evolution

    Strictly speaking, whether a long-running agent “evolves” can be judged by four verifiable signals:

    • Memory growth: after a new task finishes, does the persistence layer gain structured, retrievable entries.
    • Strategy updates: when recurring failure patterns appear, are prompts and workflows adjusted accordingly.
    • Retrieval hits: in later tasks, is historical experience actually retrieved and does it influence output.
    • Metric improvement: do success rate, elapsed time, and number of human corrections trend better for similar tasks.

    Boundaries matter just as much. Three red lines should be explicit: first, never automatically rewrite the base model; second, experience writes must pass validation and deduplication to avoid pollution; third, all automatic adjustments must be auditable and rollback-capable. Without these three, “self-evolution” quickly degrades into “memory noise accumulation.”

    3. Overall Architecture: A Five-Layer Structure

    A long-running agent can usually be abstracted into five layers:

    1. Access layer: receives tasks through message channels, scheduled triggers, API calls, and other means.
    2. Orchestration layer: task decomposition, plan generation, step scheduling, failure retries, and termination decisions.
    3. Capability layer: a built-in toolset (file read/write, command execution, retrieval, network access, structured output, and so on) plus a model adaptation layer.
    4. State layer: four types of storage covering short-term sessions, working memory, long-term memory, and task archives.
    5. Governance layer: permissions, auditing, evaluation, cost, and alerting.

    Self-evolution happens in the closed loop between the state layer and the governance layer: execution produces traces, the governance layer performs evaluation and distillation, results are written back to the state layer, and the orchestration layer consumes them in subsequent tasks.

    4. Prompt Design: Layered, Stable, and Evolving

    A prompt should not be one monolithic block of text. It should be split into four layers, each with its own update cadence:

    • Constant layer: identity, safety constraints, and output specifications. Rarely changes.
    • Domain layer: business rules, glossary, and interface conventions. Updated in small steps as requirements evolve.
    • Experience layer: automatically accumulated “practices and prohibitions,” stored as entries with hit conditions.
    • Task layer: the current goal, constraints, and completed steps.

    An illustrative structure looks like this (it only expresses the organization, not a specific product interface):

    1. [Constant] You are a long-running executor; do not exceed your authority; output must be verifiable.
    2. [Domain] The project uses a unified code style; static checks must pass before commit.
    3. [Experience] Condition: goal contains "batch rename" -> Practice: generate a mapping table first and validate on a sample
    4. [Task] Goal: ... Constraints: ... Completed: ...

    The key design of the experience layer is the “condition-practice-evidence” triple. Before writing, entries must pass three checks: semantic deduplication against existing entries, confirmation by a validator that the practice is executable, and an attached source trace for traceability. Set an upper limit on the number of hits to prevent context from being crowded out by historical entries.

    5. Context Engineering: Budget, Compression, and Retrieval

    Context is a finite resource and must be managed like memory. A “budget partitioning” approach is recommended:

    • System zone, about 10%–15%, carrying constant and domain rules.
    • Task zone, about 40%, carrying the goal and current steps.
    • Evidence zone, about 25%, carrying retrieved fragments, file summaries, and execution results.
    • Reserve zone, about 20%, for unexpected expansion.

    Compression strategies come in three levels: first, summarization, turning lengthy output into conclusions plus key points; second, structuring, converting logs into key-value pairs or tables; third, externalization, writing large blocks of content to external storage while keeping only a reference identifier and summary. On the retrieval side, a hybrid strategy is recommended: keyword recall ensures precision, vector recall ensures semantic coverage, and reranking selects the top few entries to enter the evidence zone.

    One common misconception deserves emphasis: stuffing all historical conversation into the context does not mean “remembering more.” Instead, attention dilution degrades instruction following. What actually works is “few but precise,” ensuring every piece of information entering the context has a clear purpose.

    6. Runtime Framework: Scheduling, Parallelism, and Fault Tolerance

    Staying online long-term means handling concurrency, timeouts, and interruptions. Key engineering points include:

    • Task persistence: task state is written to storage so execution can resume after a process restart.
    • Idempotency design: tool calls carry idempotency keys so retries produce no duplicate side effects.
    • Tiered retries: retry recoverable errors; terminate immediately and report permission and parameter errors.
    • Dual drivers of schedules and events: periodic tasks use a scheduler, external changes use event triggers.
    • Concurrency isolation: different tasks use separate working directories and temporary resources to avoid cross-contamination.

    A simplified execution loop can be expressed as:

    1. while not done(task):
    2. plan = planner(task, memory.recall(task))
    3. for step in plan.steps:
    4. result = tools.run(step, idem_key=step.key)
    5. memory.observe(task, step, result)
    6. if validator.fail(result):
    7. memory.propose_fix(task, result) # experience candidate, pending governance review
    8. task.save() # resume from checkpoint

    7. Memory System: Four Storage Types and Lifecycle

    • Session memory: only the current interaction, reclaimed when the session ends.
    • Working memory: intermediate artifacts of the current task, compressed into a summary after the task is archived.
    • Long-term memory: entry-based experience and preferences, carrying tags, confidence, hit counts, and expiration time.
    • Task archives: goals, processes, results, and human correction records, serving as raw material for evaluation and auditing.

    Lifecycle management determines long-term health. It is recommended to set up confidence decay and periodic review: entries not hit for a long time are down-weighted, and entries proven false are archived rather than deleted outright, preserving traceability.

    8. Evaluation and Observability: Making Evolution Measurable

    Evolution without measurement is just guesswork. A minimum viable evaluation set should include three categories: typical tasks, historical failure tasks, and boundary and adversarial samples. Core metrics should include task success rate, first-pass rate, human intervention rate, average number of steps, cost per task, and average latency.

    For observability, trace linking should cover four levels: task, plan, tool call, and context snapshot. Logs and metrics should be collected uniformly, and anomalies should be reported through an alerting channel. Context snapshots are especially important, as they are the only basis for reviewing “why the model made that decision at the time.”

    9. Security and Cost Governance

    On security, tool permissions should be minimized, sensitive operations require explicit confirmation, and all external content should be treated as untrusted input to prevent prompt injection. On cost, set context limits per zone, route steps that smaller models can handle, and cache results for high-frequency repetitive tasks. If deployed on Baidu AI Cloud’s general cloud products, container platforms can host runtime instances, object storage can hold task archives, message queues can drive events, and logging and monitoring services can complete the observability loop, all integrated through standard interfaces without binding to proprietary forms.

    10. Conclusion

    The core competitiveness of a long-running agent lies not in how many tools it integrates, but in whether it establishes a closed loop of “execute-evaluate-distill-reuse.” Layered prompts ensure stability and evolvability, context budgets prevent attention dilution, the runtime framework ensures long-cycle reliability, and the evaluation system keeps the direction of evolution correct. When all four are in place, “getting stronger with use” becomes a verifiable engineering result rather than a slogan.