# Native provider session restoration

Agent Plane's native context protocol v1 preserves the provider's exact saved conversation identity for both Codex and Claude. It works in direct and isolated launchers. A machine change transfers bounded provider conversation files into a private provider home; a provider change creates a new lineage with an explicitly labelled structured handoff. It does not convert Claude history into a Codex native session, or vice versa.

The Claude implementation retains the native transcript store through Boujot's existing CLI query wrapper. It includes allowlisted subagent transcripts and tool-result files under the saved project/session directories. Adopting the Agent SDK `SessionStore` would require replacing or adapting that query integration; it is not an interface used by the current wrapper. Keeping the native files extends the working `--resume` path and permits the same bounded, ownership-fenced migration protocol as Codex without inventing a shared transcript format. The version-specific native fixtures below establish compatibility for this choice.

## Rollout and provider versions

The machine-readable verification matrix is [native-session-compatibility.json](native-session-compatibility.json). Official Codex 0.154.0 and 0.169.0 and Claude Code 2.1.307 and 2.1.325 passed the installed-provider fixture. These are measured versions, not a claim that every intervening or future version is compatible. The previous production provider versions do not require an upgrade for the restoration mechanism. Unverified older versions should not be enabled for this rollout.

Install the updated Boujot daemon and matching isolator before enabling the Agent Plane changes. Boujot 0.17.24 does not implement protocol v1. Agent Plane checks `agentPlaneSessionPrep.nativeContextVersion=1`; it also checks the explicit prep-file allowlist for structured provider handoffs. New instruction bundles have their own compatibility gates.

On the first resume of imported state, source and destination provider version strings must match exactly. Unknown or different versions fail before any new prompt. Once the provider confirms the exact imported native session ID, that import guard is consumed; ordinary later provider upgrades on the same host rely on the provider's native compatibility. Failed restoration preserves the saved identity. Starting a new lineage from conversation history requires an explicit owner action.

Codex paginated sessions additionally need their native SQLite store. Copying its bytes preserves history but also retains absolute `threads.rollout_path` values from the source home; even `thread/resume` with an explicit destination path refuses that mismatch. Before an imported provider starts, Boujot relocates these pointers in one SQLite transaction under the existing context writer lease. Each pointer must match a unique destination JSONL with the same native ID and relative path. The wrapper changes only `threads.rollout_path`; it preserves paginated sections, compaction, tool results, thread IDs and historical workspace records. Current workspace guidance and sandbox settings still come from the destination launch.

Indexed relocation currently accepts `state_5.sqlite` and needs Node 24.10 or later for SQLite authorization. The managed runtime uses Node 24.17.0. Missing, ambiguous, linked or unsupported state blocks restoration. SQLite authorization refuses trigger-driven actions and writes to any other column. The root importer continues to copy and verify the original archive without parsing SQLite as root. A failed launch keeps the import marker, so retrying the transaction is idempotent. JSONL-only legacy sessions continue to use Codex's native discovery.

An interrupted native turn still resumes its saved native history, including recorded tool results. A missing completed-turn marker does not trigger an additional Markdown transcript. Missing/incompatible state blocks restoration; a provider resume refusal known to occur before prompt delivery carries structured `native_context_restore_failed` evidence. Failures after input delivery are not labelled safe to replay.

## Explicit recovery and provider handoff

The owner can choose **Recover from conversation history** for a saved-context failure. Agent Plane binds that request to the expected blocked attempt, refuses it while a runtime/start or live startup lease remains, and keeps retries idempotent. The new lineage receives a fresh nonce/context ID; the old native ID is not silently replaced or reused. Current runtime permissions and approval requirements apply again.

Changing provider uses the existing provider-switch flow. The database atomically clears native bindings and records source/target provider, source context/native-session IDs, creation time and a new lineage nonce. Active spawning/running/detached/recovering conversations cannot switch through that boundary. The bounded `.agent-plane/provider-handoff.json` contains typed prior conversation messages with provenance, omission/truncation labels and `authority: conversation_data_only`; its startup guidance explicitly identifies a new native session. It carries no credential store or live-grant authority, and instructs the agent to reconcile interrupted external operations before retrying them. The old provider's native files remain separate.

## Ownership and transfer boundaries

Agent Plane pins a single source/destination transfer under the current startup owner, actor, attempt, machine and live lease. Boujot proves the source provider is stopped, takes the existing context writer fence, and durably freezes it before exporting an immutable archive. Isolated transfers additionally require every runtime in that conversation's root-owned registry to have exited. A frozen source cannot accept a new writer. A later returning migration may replace only that exact frozen context and instance; the freeze is removed only after the returned state is committed.

The transfer uses retained, idempotent 128 KiB chunks with per-chunk identities and a whole-transfer SHA-256. Agent Plane acknowledges retained chunks only after recording the imported result durably. A lost response does not unfreeze the source. Subsequent migrations rotate the completed journal only after the saved native binding belongs to its preceding destination.

File contents and their containing directories are synced before chunk/import/export acknowledgements. Newly created ancestor directories are synced as well. A cached export retry reconfirms the source freeze's directory durability. Returning imports keep the pending-import launch barrier until the new manifest and removed source freeze are durable. Fault-injection tests cover failures after rename/unlink and safe retry; they do not simulate physical power loss.

Only allowlisted provider conversation files transfer: native transcripts, compaction and tool-result history, and Codex session indexes/state databases. Credentials, configuration, MCP servers, executable hooks, environment variables and live grants are excluded as transferable authority. Conversation text can itself contain user-provided sensitive data; this mechanism is not a transcript secret scrubber.

Current credentials are supplied at outer-runtime startup; live private token renewals remain intact between provider subprocesses. Before every native subprocess, the wrapper proves the previous provider stopped, removes stale private executable settings and user guidance, and reapplies permitted current configuration. Isolated Codex policy comes from the root service's initial trusted configuration retained in wrapper memory; direct Codex policy is refreshed from its current source home. Claude's private agents/commands/rules and CLAUDE guidance and Codex's private AGENTS guidance do not survive as authority into a later subprocess. Selected skills are staged after that reset. User-global source homes are untouched, and current tool permissions still apply to the resumed turn.

Archives are limited to 8 MiB of decoded files and 4,096 files; serialized chunk transport is capped at 32 MiB. Exact nonempty native transcript presence and all paths, content encodings and digests are validated. Symlinks and path traversal are refused. Oversized histories fail explicitly; they are not silently truncated or replaced by a fresh native ID.

Workspace files, uncommitted changes, running processes and external effects do not migrate with conversation history. The destination workspace must be prepared separately. Native history may refer to old paths, so the agent must reconcile workspace and external-operation state before acting on historical assumptions.

## Validation

`src/daemon/nativeProviderRestore.integration.test.ts` runs the actual provider executable with temporary private homes and a dummy loopback model API. It imports provider-native tool/compaction history into a different workspace, resumes the exact ID, completes a turn, and checks fresh policy in the provider request. Codex also confirms read-only/no-network restrictions. No real model request or real provider credential is used.

Set `BOUJOT_NATIVE_CODEX_BINARY` or `BOUJOT_NATIVE_CLAUDE_BINARY` to the exact binary under test. The tests skip a provider without its explicit path. The daemon tests additionally exercise writer identity, missing state, symlink/FIFO refusal, version mismatch, immutable export, A→B→A migration and file/directory sync failures. Isolator tests exercise stopped-runtime enforcement and service-owned private homes through a fake backend; they do not attest a deployed systemd/cgroup sandbox. Agent Plane's PostgreSQL fixture checks real ownership, transfer-journal, recovery and provider-handoff constraints.

CI also runs the paginated-store regression with `BOUJOT_NATIVE_INDEX_CODEX_BINARY`. Its setup fetches the exact public Linux x64 Codex 0.154.0 package and verifies a pinned SHA-512 before execution. This fixture creates a real session and SQLite database through the provider, transfers it A→B→A with each source home unavailable, resumes by the same ID after restart, and checks both earlier markers and destination guidance. This is additional coverage beyond the hand-authored legacy JSONL fixtures. It uses only temporary homes and a dummy loopback Responses API.

The final integrated isolator suite passed on Linux arm64 using the exact `.drone.yml` image, `rust@sha256:3914072ca0c3b8aad871db9169a651ccfce30cf58303e5d6f2db16d1d8a7e58f` (Rust 1.90.0, Bookworm): 68 passed and two unchanged 65-second relay-silence tests ignored. The locked offline release build also passed and reported `boujot-isolator 0.5.0`. The disposable container had read-only source/cache mounts, no external network, a 2 GiB memory limit and one compile job. This executes Linux-specific transfer paths, including the directory-sync failure and fresh root-guidance observation tests; it does not add production process-isolation evidence.
