Hot-Swapping Self-Evolving Agent Hosts: Runtime Invariants and Engineering Practices
This article explains how an agent host framework can replace parts of itself safely while long-running tasks continue. It separates the model, orchestration, and kernel; defines task continuity, semantic compatibility, effect isolation, atomic switching, and replayability as runtime invariants; passes capabilities through immutable views rather than global state; and covers component lifecycles, dependency graphs, versioning, propose-verify-publish release gates for self-evolution, observability, and a risk-ordered rollout path.
Once an agent moves from single-turn Q&A into long-running tasks, the host framework is no longer just a startup script. It becomes the runtime environment for the task itself. Tools, memory, permissions, scheduling policies, and observability probes all hang off this environment. If every adjustment requires a shutdown and reload, in-flight plans, held external resources, and intermediate conclusions that have not yet been persisted are cut off. Self-evolution that only takes effect after offline retraining or a restart cannot support continuous work. The more valuable question is whether the host can safely replace part of itself while a task is still executing, and whether behavior before and after the replacement can be explained, rolled back, and audited.
Separate three layers instead of stuffing everything into prompts
It is more stable to split the system into model, orchestration, and kernel than to write all logic into prompts. The model proposes the next step. Orchestration decomposes goals into checkable steps. The kernel determines how those steps are actually composed, scheduled, and isolated. Models will iterate, and orchestration interfaces will change. What really determines whether the system can evolve continuously is whether the kernel treats replaceability as a first-class constraint.
The kernel must answer at least four questions. First, what boundary does a capability enter through: a pure function, a command with side effects, or a long-lived service? Second, whom does it depend on, who depends on it, and are dependency cycles allowed? Third, when a replacement occurs, does an in-flight call see the old implementation, the new implementation, or an explicit failure? Fourth, after a failure, which state must be restored, and which external actions are already irreversible? Writing these four questions as invariants matters more than listing plugins.
Invariants for dynamic composition
Dynamic composition is not arbitrary code changes at runtime. An operational definition is: when a set of invariants is satisfied, replace the old component graph with a new one without losing the observable progress of the current task. These invariants should be written down explicitly.
Task continuity. Every long-running task has a stable identity and checkpoints. Replacement only affects steps that have not started or are explicitly declared reentrant. Results of committed steps remain referenceable.
Semantic compatibility. A new component must declare the capability identifier it implements, its input and output schemas, and its side-effect class. If the identifier is the same but the schema is incompatible, the hot replacement must be rejected rather than silently coerced.
Effect isolation. File reads, external writes, message sends, and quota consumption must all be classified as trackable effects instead of being scattered across callbacks. Computations without effects can be replaced freely. Computations with effects must pass through a gateway.
Atomic switching. For a given call, either the old implementation is used throughout or the new implementation is used throughout. A path that combines old logic in the first half and new logic in the second half, producing an unreproducible execution path, is forbidden.
Replayability. Scheduling decisions, component versions, input digests, and effect receipts must be linkable into a trajectory. Without a trajectory, a hot update is just an accident scene.
These invariants can be written as plain acceptance conditions: when an incompatible component is injected, the system must reject it; when a compatible component is injected, in-flight call results must be consistent with the pre-replacement behavior; when injection fails, both the component graph and the task queue must return to the pre-replacement snapshot.
Pass capabilities through context, not global variables
A mature approach is to place capabilities in an explicit context instead of importing global singletons. The call chain passes down an immutable capability view: currently available tools, configuration, quotas, trace IDs, and cancellation tokens. Components obtain dependencies only through the view. During replacement, a new view is generated. Calls that have already captured the old view continue using it until they finish.
This avoids two common failures. One is that after replacement, an old callback suddenly calls a new implementation with mismatched parameter assumptions. The other is that tests cannot construct dependencies because real logic is hidden in process-level singletons. Context also makes permission trimming easier: within the same component graph, planning steps can see retrieval, execution steps can see writes, and observability steps can see only metrics.
An illustrative structure does not need to bind to a specific language:
CapabilityViewid, versionservices: name -> handleeffects: allowed setcancel, deadline, traceresolve(task):snapshot = kernel.current_view()bind task to snapshotrun steps until task yields or finisheson reload:build next_viewif schema_ok(snapshot, next_view):kernel.publish(next_view) # affects only steps started afterwardelse:reject and keep snapshot
Publishing a new view should be a pointer swap, not an in-place mutation of the old object. In-place mutation causes already-bound calls to observe a torn state.
Lifecycles should be short, cancellable, and idempotent
Components that can be hot-swapped must have a lifecycle finer-grained than “process start to process exit.” It is recommended to keep only four states: install, ready, serving, and retired. During install, schema validation and dependency resolution are performed without external effects. Calls are accepted only after ready. During retirement, new calls are rejected first, then in-flight calls are allowed to finish or are cancelled after a timeout, and local resources are released last.
External effects should be designed to be idempotent. Writes use business idempotency keys; message delivery carries deduplication identifiers; long-running external operations expose query interfaces so that actual state can be confirmed after cancellation. If an effect is irreversible, such as a notification that has already been sent, the kernel should not pretend that rollback succeeded. Instead, the effect should be recorded in a compensation list, and the orchestration layer should decide whether to apologize, reconcile, or hand the case to a human.
Cancellation is not a synonym for an exception. Timeout, user abort, and version switching are normal control flow. Components should check cancellation tokens at wait points and, on return, state whether the outcome is completed, retryable failure, or partially applied.
Dependency graphs, versions, and compatibility strategy
Components should be connected by capability names, not by concrete file paths or implementation class names. A capability can have multiple implementations selected by policy: stable-first, experimental-first, or routing by task label. The dependency graph is expanded at install time. Implicit runtime directory scanning with immediate effect is forbidden; otherwise, it is impossible to predict which side effects a replacement will bring in.
A three-level versioning strategy is recommended. Patch versions fix defects only, keep schemas unchanged, and can be replaced automatically. Minor versions add optional fields, and old callers ignore unknown fields. Major versions change required fields or effect classes and must use a new capability name or an explicit migrator. The migrator itself is also a component: it takes an old checkpoint as input, outputs a new checkpoint, and declares whether human confirmation is required.
Cyclic dependencies usually indicate that boundaries are drawn incorrectly. If a planning component calls an execution component, and the execution component calls back into planning, the shared part should be extracted into a pure decision function with no effects, or changed to an event queue so that both sides depend only on message schemas, not on each other’s implementations.
Self-evolution should be reduced to propose-verify-publish
The danger of letting an agent modify the host is not that “it writes code,” but that release gates are missing. A reasonable loop is: the agent can only submit change proposals, including target capability, diff description, tests, and rollback point; a verifier runs contract tests, effect allowlist checks, and golden trajectory replay in an isolated environment; after passing, the kernel publishes according to atomic switching. The agent has no permission to directly modify the production view.
Verification should cover at least three trajectories. Normal path: acceptable differences for the same input between old and new versions are within the declared range. Failure path: dependency timeout, cancellation, and partial writes. Concurrency path: new and old calls arriving at the instant of replacement do not tear each other. A hot update without concurrency tests will almost certainly encounter in-flight requests after launch.
There should also be resource budgets. Self-evolution easily creates the urge to “add one more tool.” Each component declares memory, concurrency, and external call quotas, and the kernel rejects a graph that exceeds the budget after aggregation. Otherwise, the system will accumulate an incomprehensible dependency mesh during unattended operation.
Observability is part of hot updating
Each release records: old view identifier, new view identifier, diff summary, operator (a human or an agent task ID), and verification report ID. Each task trajectory records the view it was bound to. During troubleshooting, first answer “which version was in use at the time,” then look at model output. Metrics should distinguish replacement rejection, replacement success, in-flight call drain timeout, and compensation count. These metrics say more about kernel health than average response time.
Logs should not print secrets or full user content. Effect receipts only need to retain the type, stable identifier of the target resource, result code, and idempotency key. Auditability and privacy can coexist.
Rollout order
It is not necessary to build a universal kernel all at once. A risk-ordered approach is recommended: first version configuration and prompt templates as views to ensure replayability; then hot-swap side-effect-free tools to practice compatibility checks; then bring idempotent external actions into the effect gateway; only then allow agents to submit code-level changes with mandatory isolated verification. Each step is accepted against the same set of invariants, avoiding a situation where “the demo can change things, but production dares not touch them.”
Whether the interface is graphical or textual, and which language the implementation uses, are just shells. As long as constraints such as capability views, atomic switching, effect classification, and release gates hold, different teams can grow different implementations and iterate the host without interrupting tasks. Models will continue to change generations, and orchestration will continue to change. What remains is this runtime discipline that makes replacement provable and rollbackable.
