A journal of architectural patterns, failure modes, and design principles for engineers building AI agents that run continuously at scale.

Migrating a Self-Hosted Agent to Managed Infrastructure Without Losing State

Preserve conversation transcripts and tool history to survive agent restarts intact.

· 9 min read
Cover illustration for “Migrating a Self-Hosted Agent to Managed Infrastructure Without Losing State”
Resilience & Recovery · October 21, 2026 · 9 min read · 2,037 words

Moving a self-hosted agent to managed infrastructure means moving its state along with its code. The safe path is to identify, serialize, and restore all seven surfaces of state before cutting over. An agent that starts successfully but loses what it learned is a different agent.

Why migrating a self-hosted agent is a state problem, not a deployment problem

The agent comes back online, answers a prompt, and looks healthy. Then it repeats a mistake the user already corrected, re-reads files it had absorbed, or treats completed work as pending. The deployment succeeded, but the migration failed. Copying a container and restarting it elsewhere can work for a stateless web app. It does not preserve an agent’s working context.

One agent request can involve multiple LLM calls, tool invocations, memory retrieval, and parallel subtasks that accumulate over time. The session is the atomic unit of operation. If that session has no durable store, a restart can wipe out its context. Managed infrastructure must keep that state as well as keep the process running.

The seven surfaces of agent state that must survive a migration

Diagram: The Seven Surfaces of Agent State. Visualizes: Visualize the seven discrete surfaces of agent state that must survive a migration, as identified by Zylos's 2026 research on session portability.

Zylos’s 2026 research on session portability identifies seven surfaces. The first is the conversation transcript, which records user and assistant turns. Anthropic Messages API and OpenAI Chat Completions API both use role-keyed message objects, but their tool-use blocks require translation. The second is tool-call history, which records the tools called, their arguments, and their results. It tells a resumed agent which file edits and API calls have already happened, including side effects that cannot safely happen again.

The third surface is persistent memory, whose contents can survive a restart while becoming unreadable under a changed schema. The fourth is scheduled-task ownership, including cron and interval jobs whose task-ID mappings bind them to an agent. The fifth is background process handles, which point to subagents, child processes, and tool calls that run for a long time. These are usually OS-level references that do not survive process replacement. The sixth is credential and permission bindings, including API keys, OAuth tokens, and allowlists.

The seventh is behavioral conditioning. This is the context carried through a session, including user corrections, patterns the agent learned not to repeat, and its understanding of a codebase. It can exist only in the transcript. Summarizing that transcript can therefore preserve the topic while losing the correction that changed the agent’s behavior. A persistent database protects only one of the seven surfaces.

Why behavioral conditioning is the surface that causes the most post-migration regressions

Behavioral conditioning has no single export file. It is distributed through the conversation, and compaction can strip away the details that made later decisions better. A GitHub issue filed against Claude Code in early 2026 says that after compaction, an agent lost track of files and made mistakes it had already been told to correct. The requested session-preserving /upgrade command had not shipped as of April 2026. The existing command with that name upgrades a subscription plan instead.

Anthropic’s API Memory Tool, memory_20250818, provides a /memories directory that survives process restarts. Claude Code has a separate built-in memory system indexed by MEMORY.md. Anthropic’s prompting guidance for the API tool tells the agent to write down its progress because its context window might reset. That write discipline makes preservation of implicit context depend on explicit recording. The migration mitigation is therefore to minimize compaction and carry the full transcript as a first-class artifact.

The four migration strategies and the risk profile of each

Diagram: Four Migration Strategies: Risk vs. State Preservation. Visualizes: Show the four migration strategies plotted against their risk profiles.

Pause-Serialize-Replay has the lowest data-loss risk, provided checkpointing already exists. LangGraph’s checkpointer records a StateSnapshot at each graph super-step, keyed by thread_id and checkpoint_id. Versioned schemas make replay across versions possible. This takes more planning because adding checkpointing in the middle of a session is itself a migration.

Checkpoint-Plus-Version-Migration adds explicit schema versions and moves fields forward programmatically on load. Its risk is manageable when changes are small and documented. As schemas diverge, however, missing fields can fail silently. A checkpoint is only useful if the receiving runtime interprets it correctly.

Dual-Runtime Shadow Deployment reduces user-visible disruption by keeping the old agent serving while the new runtime is validated. A single atomic swap then hands over the session, at the cost of greater infrastructure complexity. Live Hot-Reload makes version bumps easier to run but has the highest risk of a regression in behavioral state. Claude Code’s upgrade-claude skill waits for idle, exits, installs, and relies on a daemon to restart the binary. It does not serialize live state and is unsuitable for cross-runtime migration.

All four strategies can leave half-migrated state. A new process may start while memory and tools still expect incompatible fields. The shared defense is transactional migration, with staged state, an atomic pointer swap, and rollback if health checks fail within a defined timeout.

How the agents you are most likely migrating — Claude Code, Codex, Hermes, OpenClaw — handle state differently

For Claude Code, keep its built-in memory separate from Anthropic’s client-side API Memory Tool when planning the move. They are not interchangeable artifacts. The transcript carries behavioral state that memory files may omit. Do not summarize or compact it before the target runtime has loaded it successfully.

OpenAI Codex Goal Mode uses a persistent thread-level state machine. Its directive persists on OpenAI’s infrastructure, which makes it unsuitable where policy requires that no data leave the private cloud network. Budget exhaustion is a soft stop, with autonomous continuation across budget resets unguaranteed. Codex also spans desktop, CLI, IDE, and cloud execution, giving migration teams more tool-call history to reconcile than a single-surface agent.

Hermes and OpenClaw depend heavily on external integrations, so credential bindings and tool-schema compatibility strongly shape their migration plans. MCP provides a tool-schema compatibility layer, while AGNTCY SLIM addresses secure transport between runtimes. Neither amounts to complete session portability. Teams that use Claude Code for local work and Codex to delegate work in the background must plan for both runtimes at once.

What managed platforms actually provide for state continuity — and what they leave to you

AWS Bedrock AgentCore handles container lifecycle, scaling, identity, and observability. Its runtime decorator lets teams wrap existing agent logic intact. Those capabilities remove infrastructure work, but not behavioral-state preservation, tool-call idempotency, schema versioning, or credential remapping. Even with managed memory, teams must still do that work in the application.

LangGraph Platform offers managed, hybrid, and self-hosted options with graph-native checkpointing. For an existing LangGraph application, moving the checkpoint backend can avoid a state-format translation. Cloudflare’s edge-native approach instead calls for mapping persistent memory to Durable Objects, which has no direct match in most self-hosted setups. The target’s state model matters as much as its hosting features.

Specialist hosting makes a different trade-off. osModa provides a dedicated Hetzner server per agent, with NixOS, Rust, watchdog auto-restart, and tamper-proof audit logging. When memory and credentials live inside the VM image, the migration must move the VM as a whole. No managed platform currently automates extracting behavioral conditioning, remapping scheduled-task ownership, or reconciling OS-level background handles. Those gaps remain the operator’s responsibility.

The pre-migration state audit: what to enumerate before touching infrastructure

Before changing infrastructure, find the artifact for every surface or note that there is none. Record where it lives, its format, and whether the target can read it. Locate the transcript and flag incompatible tool-use blocks. Then enumerate tool calls since the last checkpoint and mark non-replayable side effects as idempotency boundaries. The resume point must respect those boundaries.

In staging, run the target parser on the memory store that is already in use. Record every scheduled job and task-ID, with a remapping table where the target cannot retain the IDs. Classify background processes by whether they can terminate cleanly or leave orphaned side effects. Inventory credentials, permissions, and token expiry timestamps, then test the bindings in staging. Each check should produce an artifact or a go/no-go answer.

Finally, export the full, uncompacted transcript. Record the last user correction and the last pattern the agent was told not to repeat. These become behavioral regression tests after cutover. The audit is complete only when the team knows both what can move and what must be resolved before moving.

Sequencing the cutover: the transactional migration window

Open the migration window only after all seven surfaces have been audited and their artifacts staged. Credentials and tool bindings must already work in the environment they are moving to. The old runtime must not be executing a tool call with non-replayable side effects. A last known-good rollback point must also exist, with a defined timeout for returning to it.

First, write the new state to staging without overwriting the old store. Next, pause the old agent after its last non-replayable tool call has completed and been recorded. Serialize the full transcript without compaction and write it to the target memory store. Start the new process. Check that it can read the state required across all seven surfaces. Only then atomically swap traffic or session routing.

If health checks fail within the timeout window, restore the pointer to the old runtime and restart from the pre-migration state. After cutover, replay the last correction from the user and check that the agent no longer makes that mistake. Re-issue the last completed tool call and confirm that the agent recognizes it as done and leaves its effect unchanged. Confirm that scheduled tasks now fire against the new process.

Tool integrations as a hidden migration surface: credentials, OAuth tokens, and context windows at scale

Tool integration is a second migration inside the first. Keys and OAuth tokens must be bound before they are used, including tokens that come up for refresh during the migration window. Presence alone is not enough if a token expires before the first call. For teams using Composio, authentication continuity involves remapping connection IDs while retaining existing integration authentications. Composio handles OAuth flows, API keys, refresh, and credential lifecycles per user, with scopes defined at the auth config level.

Reloading every available tool into the new runtime can consume the context budget before useful work begins. Composio’s catalogue spans thousands of toolkits, and its meta-tools and just-in-time action discovery load only what the current task needs. If the old setup loaded tools statically, the migration is a chance to switch to that pattern. In a white-labeled deployment, both discovery and credential mapping must account for the platform and each customer’s agent.

Why the migration is harder when you hand-provisioned an agent for every customer

Hand-provisioning creates as many migration problems as there are customer instances. Each can have different configuration, tool bindings, and credential state because it was assembled at a different time. That drift makes the state audit a per-customer job. Scheduled tasks are especially hard to move when instances do not share a task-ID namespace. Each instance then needs its own check to see whether ownership has transferred.

Give each customer one isolated, persistent agent that is provisioned automatically at onboarding. A consistent template makes the audit repeatable and lets the migration sequence run programmatically across the fleet. Without it, VPS setup, Docker configuration, SSH management, monitoring, recovery, and updates all return as migration work. Stripe lets businesses that make software take payments without becoming payments companies. Managed agent infrastructure should provide the same separation, without turning each platform upgrade into a bespoke customer project.

What a state-safe managed deployment looks like end-to-end

A state-safe deployment checkpoints each session to a durable store at shutdown and other meaningful boundaries. It retains an uncompacted, versioned transcript, using compaction only as a retrieval optimization. Its authentication layer manages credentials, refresh, and permissions outside the agent process. Its scheduler persists task ownership independently of that process. A shared provisioning template makes those properties repeatable for every isolated customer agent.

The security baseline is encryption in transit and at rest, with SOC 2 Type I certification as a minimum. Conversations, files, and sessions should never be used to train AI models. The operational benchmark is one-click deployment or a single API call. Managed hosting can make that architecture accessible without a dedicated DevOps team. The founder who gets migration right is not the one who performs a heroic cutover, but the one who chooses infrastructure that preserves state by design.

Sources

  1. Migrating multi-model AI agents to Amazon Bedrock AgentCore runtime

More in Resilience & Recovery