Deterministic session handoff and context checkpointing for coding agents. Use when saving coding checkpoints before context window growth, executing phase-boundary fresh-window handoffs, resuming work by handoff ID, verifying workspace Git baseline and full SHA-256 artifact digests, or running guarded multi-baton continuation without repository pollution.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Is that skill safe to install?
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
Are you the author of Baton Relay?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/baton-relay-baton-relay)
---
name: baton-relay
description: Deterministic session handoff and context checkpointing for coding agents. Use when saving coding checkpoints before context window growth, executing phase-boundary fresh-window handoffs, resuming work by handoff ID, verifying workspace Git baseline and full SHA-256 artifact digests, or running guarded multi-baton continuation without repository pollution.
---
# Baton Relay
Baton Relay coordinates multi-turn coding continuity across context-window boundaries using immutable, size-bounded Markdown snapshots (`<= 4096 B`), full SHA-256 artifact digests, Git baseline drift checks, and user-local SQLite leases. All coordination artifacts stay strictly outside target repositories under a user-local state directory (`BATON_STATE_DIR` or `PLUGIN_DATA`).
## Entrypoints
Both the skill plaintext tree and the deterministic release bundle expose the exact same CLI commands and stable exit codes (`0..7`). **Global flags (`--state-dir`, `--worktree`, `--json`) must appear before the subcommand**, and `--state-dir` (or `BATON_STATE_DIR`) **must always point outside the target worktree** (`STATE_DIR_INSIDE_WORKTREE`, `exit 2` if placed inside the repo such as `.baton/`):
```bash
# Source / skill plaintext entrypoint
python3 -B scripts/baton.py --state-dir /tmp/baton-state --worktree . --json version
# Release zipapp bundle entrypoint
python3 -B scripts/baton.pyz --state-dir /tmp/baton-state --worktree . --json pack --input-json ...
```
If running from the repository root rather than the installed skill directory, invoke `python3 -B skills/baton-relay/scripts/baton.py` or `python3 -B dist/baton.pyz` (built via `python3 -B scripts/build_pyz.py`).
## Quick Verification Demo
Run the self-contained fixed-HEAD tamper guard demo in an isolated temporary Git repository (zero changes to your current repository):
```bash
python3 -B scripts/baton.py demo
```
The demo packs a canonical snapshot with a tracked file digest and `file#L1-L10` focus slice, mutates that tracked file without moving Git `HEAD`, verifies `resume` blocks with `ARTIFACT_DRIFT` (`exit 4`) while keeping the handoff `ready`, restores exact bytes, claims atomically once (`in_progress`), and rejects a duplicate claim (`ALREADY_CLAIMED`, `exit 7`).
## Core Workflow
### 1. Plan Multi-Baton Stages (Optional)
Define phase-boundary batons persisted outside the worktree at `<state_dir>/plans/<workspace_key>.plan.json` so terminal states override automatic relay requests:
```bash
python3 -B scripts/baton.py --worktree . --json plan init --input-json '{
"goal": "Implement module migration safely",
"batons": [
{"id": "B1", "title": "Core encoder", "exit_gate": "Unit tests green"},
{"id": "B2", "title": "Integration check", "exit_gate": "Contract tests green"}
]
}'
python3 -B scripts/baton.py --worktree . --json plan show
```
### 2. Pack an Immutable Checkpoint Snapshot
Pack a six-section `<= 4096 B` snapshot and `<= 16 KiB` manifest before closing or rotating a session:
```bash
python3 -B scripts/baton.py --worktree . --json pack --input-json '{
"goal": "Complete storage adapter refactoring",
"checkpoint": "Updated validator helpers and verified baseline unit tests",
"decisions": ["Keep schema backward compatible across relay steps"],
"artifacts": ["src/validator.py"],
"open_issues": ["Add edge case test for empty payload"],
"next_actions": ["Run contract suite and verify output digests"],
"focus": "src/validator.py#L1-L40"
}'
```
Use `--baton-done <id>` to advance a plan, or `--awaiting-review` / `--terminal-state <complete|awaiting_review|cancelled>` to enforce human review stops (`auto_relay_allowed: false`). When coordinating with the T2 outer loop, pass `--emit-t2-signal` (and `--t2-run-id <run_id>`, or rely on injected `BATON_T2_RUN_ID`) to atomically write `<state_dir>/signals/<workspace_key>/.handoff_ready.json` (`baton-signal/v1`) and return `t2_signal_path` and `t2_signal_id`.
### 3. Inspect or Atomically Claim on Resume
Preview without claiming (`--inspect`), or atomically claim the single `ready` snapshot (or pass `--id <handoff_id>` when multiple ready snapshots exist):
```bash
python3 -B scripts/baton.py --worktree . --json resume --inspect --id <handoff_id>
python3 -B scripts/baton.py --worktree . --json resume --id <handoff_id> --claimer-id session_2
```
By default, both `GIT_HEAD_DRIFT` and `GIT_WORKTREE_DRIFT` block claim (`exit 4`). Dirty tracked and untracked files present at `pack` time are SHA-256 digested (`dirty_file_digests`), so mutating an already-dirty unlisted file between `pack` and `resume` also raises `GIT_WORKTREE_DRIFT` even when `git status --porcelain` text is unchanged. Pass `--allow-worktree-drift` only when unstaged edits between `pack` and `resume` are intentional and tracked artifacts remain intact or updated cleanly.
### 4. Evaluate Unified Context Lookahead Gate (`Q / I / C / M`)
Baton Relay decouples the default cognitive quality budget (`Q = 120,000`) from the physical/compaction ceiling `U = min(I, C)` and mandatory pack headroom (`M = 12,000`), deriving `hard = min(Q, K(U - M - 1))`, `soft = K((5 * hard) // 6)`, and `lookahead = K((5 * hard) // 8)` where `K(x) = 1000 * (x // 1000)`. Hosts with `U >= 132,001` (`codex-272k`, `codex-400k`, `codex-1m`, provisional `antigravity-1m`, and live-verified `gemini-1m`, `claude-200k`, `claude-1m`) keep the `75K / 100K / 120K` cadence, while tighter shared windows downscale automatically (`shared-128k -> 51K / 69K / 83K`, `shared-64k -> 21K / 29K / 35K`):
```bash
python3 -B scripts/baton.py --state-dir /tmp/baton-state --json gate \
--profile codex-272k \
--log-file usage.jsonl \
--cache-semantics inclusive \
--usage-scope single_turn
```
`gate --profile ... --json` emits `{"ok": true, "gate": ..., "policy": ...}`. The example above uses the live-tested `codex-272k` profile (`--cache-semantics inclusive`); `--profile claude-200k` and `--profile claude-1m` (with `--cache-semantics excluded_from_input`) are live-verified on Claude Code `2.1.330` Plan OAuth (`1M/128K` models still lock the `75K / 100K / 120K` quality ceiling). Host cache semantics are strictly enforced: Codex uses `inclusive` (`input_tokens` already includes `cached_input_tokens` from single-turn `last_token_usage` / `thread/tokenUsage/updated` `last` / `turn.completed.usage`, never `total_token_usage`), while `dsh` uses `exclusive` (`inputTokens + cacheReadTokens + cacheWriteTokens` from committed `assistant/message` or camelCase usage payloads). Policy precedence resolves as: CLI flags > `BATON_GATE_*` env vars > `<state_dir>/gate_policy.json` > trusted session metadata > `GATE_PROFILES`. Raw `transcript_bytes` / `char_count` telemetry is demoted to advisory (`confidence: "unknown"`), `context_estimated` is capped at `soft_handoff`, and unknown token semantics never trigger numeric `hard_stop`.
### 5. T0 Structural Fallback (Prompt-Only / No-Telemetry Hosts)
When host token telemetry is unavailable (`confidence: "unknown"` or prompt-only T0 clients such as Cursor, OpenCode, or Cline), trigger `baton pack` at the earliest structural boundary:
- The planned stage `exit_gate` boundary (persisted at `<state_dir>/plans/<workspace_key>.plan.json`), **OR**
- After **`12` top-level tool rounds**, **OR**
- After **`128 KiB` of delivered tool output**.
## Automation Tiers (T0 / T1 / T2)
> [!NOTE]
> **Claude Code Live Verification (`2.1.330`, Plan OAuth, `C0-C4` + `R3` PASS):** `.claude-plugin/` validation, T1 hooks (`PreToolUse`, `Stop`), and T2 `--runner claude` (including 2-hop `stream-json` telemetry/cost and Windows `MAX_PATH` safety) are live-verified on Windows 11 Plan OAuth with three documented boundaries: (1) live `C2` `Read(limit=60)` passed through (`additionalContext` covered by offline `C0`); (2) `Stop` extension keys returned `outcome=success` on `2.1.330`; (3) `1M/128K` models still lock `75K/100K/120K`. `R3` live verification (`claude-opus-5-5`) confirmed exact T1/T2 token parity (`40,804`/`47,595`) and `$0.7131` billing; Windows Claude Desktop users can locate the bundled CLI at `%LOCALAPPDATA%\Claude-Data\...\claude.exe`.
- **T0 (Manual CLI & Structural Fallback)**: Explicit `plan`, `pack`, `resume`, and `gate` commands in any terminal or host, governed by the `exit_gate` / `12`-round / `128 KiB` fallback rule when token telemetry is absent.
- **T1 (Hook Advisory)**: Non-blocking lifecycle hooks (`adapters/universal/t1_hooks.py`) normalize telemetry across Codex (`inclusive` single-turn rollout/app-server/exec usage), `dsh` (`exclusive` camelCase `inputTokens + cacheReadTokens + cacheWriteTokens`), Gemini CLI (live-verified `0.71.1`, `G2` PASS: `AfterModel` `promptTokenCount` [`included_in_input`] persistence, `BeforeTool` / `AfterTool` / `BeforeAgent` model-visible `additionalContext` with `hook_stderr_error=false`, compatibility `AfterAgent` with `model_visible_injection: false`), and Claude Code (live-verified `2.1.330`: 3-part cache accounting, nested `message.usage` / `context_window.current_usage`, `parent_tool_use_id` subagent filtering, permission-neutral `PreToolUse`, bounded `256 KiB` `transcript_path` tail sampling).
- **T2 (Headless Loop Runner)**: Explicit external CLI coordinator (`python3 -B adapters/universal/t2_loop.py --runner <codex|dsh|claude|gemini> --allow-headless-exec ...`, where `codex`, `dsh`, `claude` [`2.1.330` `C0-C4` + `R3`], and `gemini` [`0.71.1` `G1-G4` PASS: Skill discovery, T1 `AfterModel`, 2-hop T2 `terminal_complete` relay `17,001 -> 23,737` peak, and `2.69s` watchdog kill-tree with `0` lingering; excluding 108-trial CLI benchmark] are live-verified in `v0.1.0`) injecting `BATON_T2_RUN_ID` and `BATON_STATE_DIR`, paired with `baton pack --emit-t2-signal` to write `<state_dir>/signals/<workspace_key>/.handoff_ready.json` (`baton-signal/v1`) under CAS worktree leases (`30 s` TTL renewed via `10 s` `renew_lease` heartbeats keyed by `workspace_key`, `owner_token`, and `generation`, failing closed with `LEASE_LOST` if stolen), budget, and cooldown guards.
## Security & Hygiene Boundary
- Baton Relay **verifies digests, renders fenced payloads, and claims handoffs atomically**; it never implicitly executes instructions contained inside snapshot text.
- Snapshot payloads and `--focus` slices are sanitized (ANSI escapes and Unicode bidirectional controls stripped) and wrapped in a fresh 128-bit random fence (`<<<BATON_UNTRUSTED_DATA:<nonce> ...>>>`) on every render.
- Target repositories remain completely clean: `--state-dir` is validated strictly outside the target worktree (`STATE_DIR_INSIDE_WORKTREE`, `exit 2`), keeping SQLite state, snapshots, plans, and T2 signals exclusively in the user-local state directory.
## Dual-Install Deduplication
If this repository is installed both via a plugin marketplace (`.claude-plugin`) and as a standalone skill directory (`~/.claude/skills/baton-relay` or `.gemini/skills/baton-relay`), keep only **one** active registration to avoid duplicate skill triggers:
1. Remove or disable the duplicate standalone skill folder when using the plugin marketplace install, **or** disable the plugin registration if managing skills manually.
2. Never run a `native` host automation loop and the T2 outer runner concurrently on the same Git worktree; the four-domain store rejects concurrent ownership with `WORKTREE_DRIVER_MUTEX` (`exit 5`).
## Further Reference
- Protocol contract, schemas, fencing, four-domain leases, and exit codes: [PROTOCOL.md](references/PROTOCOL.md)
- Host compatibility matrix (T0/T1/T2) and hook setup snippets: [HOST_ADAPTERS.md](references/HOST_ADAPTERS.md)