# In-Place PTY Account Rotation

> How vapor-core orchestrates a 7-phase formally verified PTY handoff without dropping queued prompts, killing live turns, or jumping your Rex pane.

- Site: VAPOR.TOWN (https://vapor.town)
- Canonical: https://vapor.town/docs/in-place-rotation
- Markdown: https://vapor.town/docs/in-place-rotation.md
- Section: Architecture

## Seven-Phase Rotation State Machine

Every account rotation is driven by a pure, zero-I/O state machine in crates/vapor-core/src/rotation.rs whose transitions mirror specs/InPlaceRotation.tla 1:1.

Before Vapor ever tears down the original child PTY, it enters `confirming_original` and re-checks three conditions:

1. Has the original transcript advanced since `limit_hit`?
2. Did the original account's quota window renew while staging?
3. Is the original account still confirmed rate-limited?

If **any** check indicates the original session recovered or kept making progress, Vapor transitions to `withdrawing` instead of stopping it — enforcing `NoStaleOriginalStop`.

```vapor-diagram Vapor Architecture — PTY Wrapper, vapord & Pool Engine
vapor
```

## Protocol Safety Invariants

These invariants are model-checked exhaustively by TLC in specs/InPlaceRotation.tla and validated against execution traces from vapor-sim.

| Invariant | Guarantee | Failure Mode Prevented |
| --- | --- | --- |
| NoStaleOriginalStop | Original child is never stopped if transcript_advanced \/ quota_renewed \/ ~still_limited | Killing an agent that resumed working after a transient error |
| KeepTypedReplacement | If the operator typed into the replacement before commit/withdraw, release it independently | Destroying user keystrokes during a rollback |
| NoLostQueuedPrompts | all_queued_ever = queued_prompts U delivered_prompts across commit and withdraw | Silently dropping prompts typed while swapping |
| MonotonicSwapEpoch | swap_epoch never decreases and increments by 1 only on swap commit | Out-of-order late events corrupting the active PTY |

## Compile-Time Contracts in vapor-core

Vapor follows parse-don't-validate with zero-I/O newtypes so invalid states are unrepresentable on stable Rust.

```rust crates/vapor-core/src/contracts.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RotationPhase {
    Running,
    LookingForAccount,
    StagingReplacement,
    AwaitingAdmission,
    ConfirmingOriginal,
    SwappingInPlace,
    Withdrawing,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SwapEpoch(pub u64);

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LeaseToken(pub u64);
```
