Self-Recomposition and Steady-State Boundaries in Long-Running AI Agents
Long-running AI agents cannot rely on restart-based recovery because their state spans plans, tool calls, external side effects, and accumulated memory. This article explains how an agent runtime can support safe recomposition through explicit capability dependencies, lifecycle management, event logging, isolation boundaries, generational binding, state migration, rollback, and controlled self-modification. It also outlines recovery layers, observability requirements, testing priorities, and practical deployment trade-offs.
Traditional software often treats a restart as a universal recovery mechanism. If state becomes inconsistent, restart the process. If a plugin fails, reload the module. If a version changes, roll the container. This works because the correctness of most systems is concentrated in the stable window after startup. Configuration is frozen during initialization, dependencies are resolved at build time, and failures discard in-memory state before returning to a known image. The usual cost is a brief interruption.
Long-running AI agents invalidate that assumption. Their value lies not in a single request, but in task graphs that span hours or days: confirmed goals, unfinished tool calls, side effects that have already occurred in the outside world, and working memory accumulated gradually through interaction. A session cannot simply be discarded. Memory cannot be cleared after every restart. An active plan cannot be rebuilt from scratch merely because a tool implementation changed.
The situation becomes more serious when the runtime component being modified includes the agent itself. If the system fails and depends on a human to restart and repair it, the stable point for human intervention may disappear. The runtime must therefore be more than a plugin socket. It needs to function like a small execution environment that can be recomposed while remaining auditable.
Two Questions That Must Be Answered Together
Treating dynamic composition as “loading, unloading, and replacing modules” addresses only the spatial dimension. The real challenge is that space and time change together.
How do components move? This concerns composition boundaries. Can model adapters, tools, memory backends, subtask executors, and sandbox policies all attach to the same context as replaceable units? During replacement, does the caller see a stable interface, or does the old implementation’s internal type leak through? Can a new unit coexist with the old one during a transition window instead of requiring a global shutdown?
How do components continue to operate? This concerns temporal continuity. After a unit is replaced, who owns calls that are already in progress? Who is responsible for side effects that have already been written to an external system? Do dependent units still consider the old contract valid? If a hot update occurs in the middle of an inference loop, can the event sequence still be replayed to return the system to a state that is logically equivalent but implemented by the new version?
Answering only the first question produces an ordinary plugin framework: components can be swapped, but the system cannot explain what it has done. Answering only the second produces logs and checkpoints: events can be replayed, but the system does not know which modules currently define its world. Both dimensions must be grounded in the same set of runtime facts.
Make the Runtime Aware of What It Did and What It Depends On
Self-evolution does not mean allowing arbitrary code changes. Safe evolution requires the runtime to maintain a machine-readable description of itself. At minimum, that description should include four categories of facts.
1. Dependencies
Each execution unit should declare the capabilities it requires instead of hard-coding a specific implementation. Capabilities can be represented by stable names and version constraints, such as:
- Read-only retrieval
- Rollback-capable external writes
- Short-term working memory
The runtime can then construct a dependency graph showing which unit provides each capability, which units consume it, and which consumers must receive invalidation or migration notifications when a provider changes.
2. Lifecycle
A unit is not merely a function pointer. It is an object with creation, readiness, service, draining, and destruction phases.
During draining, the unit rejects new calls, waits for in-flight calls to complete or explicitly cancels them, and exposes any state handles that must be migrated. Without a draining phase, hot replacement turns race conditions from occasional incidents into a routine operating mode.
3. Effect Records
Actions that change the outside world or alter session facts should enter an append-only event log. Each record should identify when the action occurred, which unit performed it, which decision led to it, which resource it affected, and what result or failure occurred.
The purpose is not to accumulate verbose debugging text. It is to make a question answerable: from which event is the current session still valid?
4. Failure Domains
When a unit crashes, the default assumption should be that the failure remains inside its isolation boundary. Units should have independent permissions, quotas, timeouts, and observable identifiers.
The runtime’s responsibility is to contain failures rather than allowing an arbitrary module to modify the global scheduler directly.
Together, these four elements answer whether the system can still explain its own causality while being recomposed. A hot update that cannot explain causality is merely a restart postponed until a more difficult moment to investigate.
What Spatial and Temporal Composability Mean in Practice
Spatial composability means that, at a given moment, the system consists of multiple replaceable parts, and replacing one does not require rewriting every caller.
Temporal composability means that the state and events of those parts can be connected across time: the new implementation takes over old commitments, while in-flight work handled by the old implementation reaches a defined outcome.
A practical minimum model can be understood as follows:
- The context is a session-scoped container for facts, not a global singleton garbage dump. Tool results, plan steps, and memory fragments all have explicit scopes.
- A capability registry records which unit currently satisfies each capability. Changes to the registry are events as well.
- The scheduling loop depends only on capability interfaces. When an implementation changes, the loop sees a new generation of the binding rather than a closure being replaced behind its back.
- Checkpoints store only the minimum state required for replay: the event offset, identifiers for unfinished calls, and private state that cannot be derived from the log. Data that can be derived from the log should not be duplicated as a potentially stale copy.
The structure does not need to depend on a particular framework, as long as its boundaries are explicit:
Session├─ Append-only event log├─ Capability binding table (current generation)├─ Execution units│ ├─ Planning loop│ ├─ Tool adapters│ ├─ Memory read/write│ └─ Subtask runner└─ Isolation policies (permissions, quotas, timeouts, network egress)
Generations are important. Every successful binding change creates a new generation number. In-flight calls remain pinned to the old generation until they complete or are canceled. New calls use the new generation. This prevents a tool replacement from splitting one call into two different semantic interpretations.
What Can and Cannot Be Hot-Replaced
Components that are relatively safe to replace include units with no non-migratable local state, or units whose state can be exported. Examples include model routing policies, read-only tools, prompt assembly policies, and reconstructable retrieval index handles.
Before replacement, the runtime should check contract compatibility:
- Input and output schemas
- Error types
- Idempotency declarations
- Timeout limits
If the contracts are incompatible, the runtime should reject the binding rather than attaching the new unit and waiting to see whether it fails.
Units that hold a session working set require a migration protocol. Examples include short-term memory, task queues, and unconfirmed plan nodes. Migration should be explicit:
- Export a snapshot.
- Validate the snapshot.
- Import it into the new unit.
- Reconcile record counts and checksums.
- Switch the binding only after validation succeeds.
If import fails, the old binding remains active and the failure is recorded as an event.
Certain components should not be directly rewritten by the agent. These include the trust roots:
- Identity and permission decisions
- The audit-log write path
- Isolation policies
- The rules governing who may modify the binding table
These components can expose controlled management interfaces, but those interfaces must remain outside the policy boundary that the model can alter through generated code. Otherwise, self-repair and self-destruction become indistinguishable.
External side effects require their own classification. Queries can generally be retried. Creating an order, sending a message, or changing a production configuration requires an idempotency key or a compensating action. Replacing an implementation must never turn one external write into two. At minimum, the event log must answer whether the side effect was sent and whether it was confirmed.
Session Continuity: Restart Is No Longer the Default Recovery Method
Recovery should have three layers rather than relying solely on process restart.
1. In-Place Draining
If a unit fails while its isolation boundary remains healthy, the runtime cancels or completes in-flight calls, retries steps that are explicitly retryable, and leaves confirmed side effects untouched.
2. Generation Rollback
If a new binding causes contract failures or pushes the error rate beyond a threshold, the capability table returns to the previous known-good generation. This requires keeping the old implementation available for a short period after the switch instead of destroying it immediately.
3. Checkpoint Reconstruction
If a process or node is genuinely lost, the runtime reconstructs the session from the event log and checkpoint rather than clearing memory and starting a new conversation.
The first action after reconstruction is reconciliation: which external calls succeeded, and which remain unknown? An unknown side effect must not be replayed blindly.
All three recovery layers share one constraint: the recovery action itself must be recorded in the event log. Otherwise, the next recomposition cannot determine why the system currently has its particular binding.
Brakes for Self-Modification
If an agent can install tools, replace a memory implementation, create sub-executors, switch sandboxes, or even propose changes to runtime policies, the system must separate proposal from activation.
A proposal should enter a change record containing:
- The motivation
- The affected capabilities
- Compatibility claims
- A rollback plan
- Expected observation metrics
Before activation, the system should perform static checks, including whether the change expands permissions, touches a trust root, or requires a new outbound destination. It should also perform shadow validation using a small amount of read-only or simulated traffic to verify that outputs still satisfy the required schemas.
Only after these checks should the runtime begin draining and switching generations.
During the observation window, guardrails can monitor error rates, timeouts, duplicate side effects, and the number of human interventions. If the guardrails fail, the system should roll back automatically instead of waiting for the entire session to become unusable.
An agent may recommend a change, but it should not have permission to bypass the guardrails. This is not merely a statement of distrust toward models. It keeps irreversible operations inside the policy engine.
The same principle applies to sub-executors. A parent session may create a child task with limited permissions. The child’s tool set must be a subset of the parent’s, with narrower network and file access and a shorter lifetime than the parent session. If the child crashes, only the child scope is deleted. The parent session’s event log remains intact.
Observability and Testing: Recomposition Requires Facts
Dynamic systems are particularly vulnerable to the illusion that everything worked because it appeared to work at the time. A minimum observability set should include:
- The current generation
- The provider for each capability
- The number of in-flight calls
- The most recent binding change
- Drain duration
- Rollback count
- The number of unknown side effects
These metrics should be correlated with a session identifier rather than reduced to a generic process error.
Testing should go beyond static unit tests. At minimum, regression scenarios should cover:
- Concurrent calls during replacement
- Retaining the old binding after an import failure
- Reconstruction after a truncated log
- Duplicate submission with an idempotency key
- Rejection of unauthorized child tasks
- Preventing ordinary tools from calling trust-root interfaces
These scenarios provide more evidence that the runtime understands its dependencies than simply adding more plugin points.
Working with General Cloud Infrastructure
This type of runtime usually needs general-purpose infrastructure around it rather than placing every capability in one process.
- Object storage can hold checkpoints and larger memory snapshots.
- Message queues can deliver retryable asynchronous steps.
- Container platforms can separate sandbox boundaries.
- Logging, monitoring, and alerting systems can support event-log search and generation guardrails.
These services provide persistence, delivery, and isolation. They do not replace the runtime’s internal dependency graph and lifecycle model. Putting checkpoints in storage without implementing generations and reconciliation merely moves the restart problem to a more distant disk.
When deployed in an environment such as Baidu AI Cloud, the same principle applies: treat platform services as replaceable infrastructure. Storage, queues, containers, and observability should remain behind interfaces that are separate from the session’s semantic model.
The platform is responsible for resources and infrastructure reliability. The runtime is responsible for answering which generation of a binding is responsible for which part of a session. If the two are merged into an implicit and unauditable configuration, self-recomposition once again becomes a matter of luck.
Practical Trade-Offs
Not every agent needs full self-evolution. For short conversations with no external side effects and workflows that can be restarted at any time, restarting remains the cheapest option.
The added complexity becomes worthwhile when tasks span multiple steps, side effects cannot be safely repeated, or users and business processes cannot tolerate losing the session. In those cases, explicit dependency declarations, event logs, and draining protocols become justified.
A practical implementation sequence is:
- Classify side effects and implement idempotency.
- Convert tools and memory into explicit capability bindings.
- Add generations and draining.
- Only then allow the model to propose changes.
Reversing this order means enabling self-modification on top of a system with no reliable record of causality.
A long-running agent resembles an operating system not because it has many modules, but because it can answer three questions while replacing its own components:
- Who does it currently depend on?
- What has it already done externally?
- Which generation can it return to after failure?
When these questions have stable answers, recomposition becomes evolution. Without them, it is simply another crash that is harder to reconstruct.
