Safe Runtime Evolution for Long-Running AI Agents: Auditable Self-Modification
Long-running AI agents can install tools, swap memory implementations, spawn subtasks, and alter their own runtime, making restart-first recovery unsafe: a restart can erase task context, accumulated decisions, and committed effects. This article explains why plugin systems and durable sessions alone are insufficient, and describes a practical model for safe runtime evolution built on action logs, explicit dependencies, lifecycle and compensation semantics, three-phase replacement, side-effect classification, and human takeover controls. It also highlights common implementation gaps and design constraints for teams building auditable, resumable agent runtimes.
Long-running agents differ fundamentally from conventional online services. They do not merely execute a fixed program. At runtime, they may install tools, change memory back ends, spawn subtasks, switch isolation environments, and even rewrite their own scheduling loop.
In software engineering, restarting is often the cheapest repair. Restart a process when it becomes dirty. Restart when dependencies conflict. Restart after a version upgrade. When a container behaves abnormally, delete the instance and start another one. For systems with stateless requests, discardable sessions, and human operators available to take over at any time, this is almost always the right model.
For an agent that works continuously for hours or even days, a restart often discards the task, its context, and decisions that have not yet been persisted. More dangerously, the entity that damaged the runtime may be the agent itself. In that case, “stop it first, then let a human fix it” does not always have a stable takeover point: the broken layer may be the one responsible for loading configuration, reading logs, or executing rollback.
The question, therefore, is not “How should we build plugins?” It is: while the system rewrites itself, how can it still know what it did, what it depends on, and which state must survive?
Why Restarting Is Not Enough for Agents
Traditional services place correctness outside the process boundary. Configuration lives in external storage, requests can be replayed by a gateway, sessions may expire, and an orchestrator can replace failed instances.
Agents put correctness into continuous working memory. The current plan, results from tools already called, unfinished subgoals, and the scope of user authorization often exist only in the runtime of the current session.
If all of this is treated as discardable cache, three classes of failure emerge.
First, tasks cannot be resumed. After switching a retrieval tool or changing a sandbox image, the executor must plan from scratch unless there is an explicit record of completed steps. Repeated calls to external systems are not only wasteful; they may also create side effects such as duplicate orders or duplicate writes.
Second, memory cannot be explained. If long-term memory is merely a collection of hot-swappable modules, then after a replacement the system cannot answer: which write did the new memory read, which handles does the old module still hold, and which facts have already been revoked?
Third, failures cannot be localized. If the runtime has changed its scheduling policy, permissions, or tool allowlist, and the crash log contains only the last exception, it is impossible to tell whether the fault lies in model output, a tool implementation, or the composition itself.
Runtime evolution must therefore be a first-class concern, not a remediation step after an operational incident.
Two Questions That Must Be Separated
Describing dynamic composition as “all plugins can attach to the same context” conflates two different problems.
How components move. A tool, a memory implementation, a subagent, or a sandbox must be loadable, unloadable, or replaceable without stopping the entire session. This is composition in space: which components coexist at a given moment, whether their interfaces are compatible, and whether permissions still fall within the authorized boundary.
How the work continues to live. What gets replaced is not a stateless function. It is a participant in an ongoing task. The session, event log, and in-progress plan must remain alive. This is composition in time: past actions must remain interpretable, and future replacements must not erase effects that have already been promised.
Solve only the first question and you get a typical plugin system: components can be installed and removed, but when state becomes inconsistent, the system restarts. Solve only the second question and you get a durable session: execution can resume, but when components change, the system does not know who still points to the old implementation.
Only solving both together produces spatiotemporal composability: components can be recombined in space, while their effects remain traceable and compensable over time.
The Runtime Must Know What It Did and What It Depends On
A runtime capable of self-evolution should maintain at least three explicit structures rather than hiding this information in closures and global variables.
Action log. Every installation, uninstallation, replacement, authorization change, and external side effect should be recorded as an event that is not casually rewritten, rather than existing only in the model’s natural-language trace. Each event must answer: who initiated it, which component was affected, what were the summaries of inputs and outputs, and whether an irreversible effect has already occurred outside the system.
An illustrative structure is shown below:
Event {id, session_id, ts,actor, // user, planner, or subtaskkind, // load | replace | revoke | tool_call | compensatetarget, // component identifierdepends_on[], // prior eventseffect // replayable summary or "non-replayable" marker}
Dependencies. Each component should declare what it provides and what it requires, rather than having those relationships inferred later from the call stack. When replacing a memory module, the runtime must be able to see whether the planner, summarizer, and current tools still bind to the old interface. If dependencies are not satisfied, the switch should be rejected, or the system should first enter a read-only degraded mode.
Lifecycle and compensation. Reversible actions should produce undo or compensation events. Irreversible actions, such as external writes that have already been sent, must be marked as committed; a later replacement cannot pretend they never happened. Hot updates replace only computation that has not yet been committed. They do not rewrite history.
Together, these three structures make the runtime an observer of itself. The model may still propose changes such as replacing a tool, creating a subtask, or tightening a sandbox. But such proposals must pass dependency checks and permission checks and then be committed as events. They cannot directly modify an in-memory function table.
A Practical Evolution Path
The following approach uses generic components and does not depend on the API of any specific product.
Separate sessions from the event log. A session stores the current goal, permissions, and active component graph. The event log stores facts that have already occurred. Sessions can be compacted, and logs can be archived according to a retention policy, but committed events must not be rewritten merely because the model or summarization algorithm has changed. Recovery should replay logical state from the log instead of assuming that process memory is still available.
Replace in three phases rather than swapping a pointer.
- Prepare: validate the new component’s interface and run a minimal self-test while the old component continues serving.
- Switch: point the read path to the new component. Before the barrier is crossed, the write path still uses the old component to complete calls that have already started.
- Drain: wait for in-flight calls to finish, unload the old component, and write a
replaceevent.
If phase 2 fails, roll back to the old component and record a failure event. The session ID should remain unchanged, and the in-progress plan should mark only that step as needing a retry rather than invalidating the entire plan.
Classify side effects. Pure computation, such as retrieval, summarization, or local drafting, can be replayed. External reads can be cached, but the cache must preserve provenance and time. External writes should be treated as non-replayable by default and must have idempotency keys or compensating actions. When an agent proposes to “execute again,” the runtime should determine whether the action already succeeded by consulting events, not model memory.
Treat subtasks and sandboxes as dependency nodes, not temporary scripts. Creating a subtask should register its parent session, a subset of authorization, and the set of tools it may invoke. If a subtask crashes, its permissions should be reclaimed rather than allowing it to inherit all capabilities of the parent session. When switching sandboxes, unexported local files should be considered volatile, while results confirmed through object storage or message acknowledgment should be considered committed.
Place human takeover points in the runtime, not in “the next restart.” Keep at least one control plane that does not depend on the current model loop. It should allow operators to pause planning, freeze new tool installation, export the event log, and mark the session as read-only. Even if the generation policy fails, an external controller can still read the dependency graph and logs.
Where Many Implementations Stand
Many agent orchestration systems already provide tool registration, multi-turn sessions, and basic subtasks. These features address the surface of spatial composition. The parts that support safe evolution are often missing:
- Components are replaced without an in-flight call barrier, so a hot update becomes a race condition.
- Memory modules can be swapped, but there is no reference explaining which write a fact came from.
- Logs are debugging text, not replayable records, and they do not distinguish committed from uncommitted effects.
- Permissions are attached to a process rather than a session and its events, allowing subtasks to expand their own capabilities.
- The failure strategy is still to kill the process, and session recovery degenerates into pasting the previous prompt again.
Closing these gaps does not require a complete formal proof at the outset. From an engineering perspective, four priorities come first: immutable events, explicit dependencies, replacement barriers, and idempotent side effects. With these in place, switching models, tools, or sandboxes can share the same rejection and rollback semantics.
Design Constraints to Apply
- Model output is a proposal, not a commit. A commit occurs only after runtime validation passes and an event is written.
- Implementations can be hot-swapped. Effects already promised to the outside world cannot be.
- Sessions can be compacted and events can be archived, but the identifiers of the two must remain aligned.
- Degradation should come before restart: first make the system read-only, then prohibit new side effects, and only then consider reconstructing a new process from the log.
- Permissions should converge by session and subtask. They should not expand based on the secrets that the current process happens to be able to access.
The following illustrative replacement pseudocode expresses only the required ordering. It is not an API for a particular framework:
propose(replace, old, new):require compatible(interface(old), interface(new))require deps_satisfied(graph, new)stage(new)barrier(in_flight(old))swap(read_path, new)drain(old)commit_event(replace, old, new)on failure: abort_stage(new); keep(old); commit_event(failed)
Conclusion
A plugin system answers whether a component can be attached. A long-running agent must also answer whether, after attachment or removal, the work is still the same work.
Spatiotemporal composability ties spatial replacement to temporal continuity. The runtime records actions, declares dependencies, distinguishes replayable effects from committed ones, and drains in-flight calls during replacement. In this way, self-installing tools, changing memory, creating subtasks, and switching isolated environments become auditable evolution rather than an unmanageable act of self-rewriting. Restarting can remain a last resort, but it should no longer be the only resort.
