# Parallel worktrees and handoffs

Running multiple coding agents on the same repository usually breaks in three places: agents clobber each other's working tree and git index, their dev servers fight over the same ports, and switching models mid-task forces you to copy-paste context into a blank chat.

Sikemux solves all three in `sikemux-core`: every worker can run in an isolated, warm-cloned git worktree with its own ports and atomic linear landing queue, while the core owns the chat transcript so you can hand a live conversation from one harness to another without losing state.

## Isolated git worktrees (`checkout: "own"`)

You can isolate any chat or worker in its own git worktree on its own branch:

- **From the UI:** Before sending the first message in a chat, toggle **worktree** on the project strip above the composer (on Mac or phone). Sikemux cuts a `feat/` or `fix/` branch named for your prompt and launches the agent there.
- **From a lead agent:** Spawn a worker with `agent_spawn` and `checkout: "own"` (plus an optional `branch` name). The worker builds, edits, and tests apart from your checkout and every other worker's unfinished diff.
- **In a folder that isn't a Git repository:** `checkout: "own"` gives the worker a copy of the folder instead, up to 20,000 files or 512 MB, never your home folder. There `git_commit` keeps a checkpoint of its work, and `land: true` copies it back, keeping a backup first and stopping if the same file changed in the folder meanwhile; `push` is refused.

### Warm copy-on-write starts on macOS

Cutting a fresh worktree normally means cold Cargo and Node rebuilds. On macOS hosts, Sikemux starts each new worktree warm using APFS copy-on-write clones:

- **Build caches cloned in ~1 second:** Cargo's `target` and each `node_modules` whose lockfile matches your main checkout arrive as copy-on-write clones that use zero extra disk until one side mutates a file. Matching files inherit your checkout's modification times so Cargo treats unchanged crates as already built.
- **Project-specific includes:** `.env` files at the repository root and one folder down are copied automatically. Add a `.worktreeinclude` file at the project root (one path or pattern per line) to copy extra untracked files or copy-on-write clone git-ignored build folders such as Gradle's `build` or `.turbo`.
- **Safe exclusions:** Python virtual environments and CMake build folders are never cloned even when listed, because their internal paths still point back at your main checkout. A `target` directory is skipped while Cargo is actively compiling in it, and cloning is skipped across different disks.
- **Non-macOS hosts:** Lockfile-matched `node_modules` are linked rather than CoW-cloned.

### Lifecycle hooks and automatic cleanup

Worktree `target` caches diverge over time. Sikemux reclaims them automatically without touching your main checkout:

- **Cache pruning:** A worktree's Cargo output is removed once its agent closes, or after its work lands and its processes exit (re-checking for up to 43 seconds). If free disk drops below **15 GB** (or 10% of a smaller disk), idle worktree caches are pruned least-recently-built first until **25 GB** (or 15%) is free. Active builds, running servers, and your main checkout are never touched.
- **Worktree pruning:** Sikemux-created worktrees whose agents are idle go away after **3 untouched days**. Any unfinished commits remain safely on their local branch, and resuming the agent recreates the worktree.
- **Custom hooks:** Define `worktree.onCreate`, `worktree.onSettle`, and `worktree.onRemove` commands in `sikemux.json` to seed or drop per-checkout databases and containers.

## Per-checkout ports, heavy-command queuing, and resource locks

Parallel checkouts need parallel runtime environments. Every checkout Sikemux cuts receives a short checkout name (derived from its branch) and **10 dedicated ports** in the `21000–30999` range that persist across restarts. Your main folder keeps your normal ports so bookmarks and OAuth callbacks stay stable.

```json
{
  "version": 1,
  "ports": { "db": 5432 },
  "env": {
    "DATABASE_URL": "postgres://localhost:{port.db}/app_{checkout}",
    "VITE_API_URL": "http://localhost:{port.api}"
  },
  "tasks": [
    { "id": "web", "label": "Web", "command": "pnpm dev --port $PORT", "port": 5173 },
    { "id": "api", "label": "API", "command": "uv run uvicorn app:app --port $PORT", "port": 8000 }
  ],
  "preview": { "url": "http://localhost:{port.web}" },
  "worktree": {
    "onRemove": [{ "id": "db", "label": "Drop DB", "command": "dropdb --if-exists app_$SIKEMUX_CHECKOUT" }]
  }
}
```

- **Verified setup:** Run `setup_check` (or **Set up** in Project Home → **Checkouts & setup**) to prove your `sikemux.json` by cutting **two fresh checkouts at once**, booting every port-bound task, verifying responses, running checks, tearing both down, and confirming nothing remains listening.
- **Memory-aware build queue:** Heavy builds (`cargo`, `xcodebuild`, `gradle`, `swift`, plus measured >1 GB commands) share a host-wide memory queue and a shared compiler job pool (`cores - 1`), with `kache` / `sccache` automatically reused across worktrees. Pre-commit and landing checks run with `final` priority ahead of routine builds.
- **Exclusive resources:** Declare singleton resources (such as a Stripe webhook listener or fixed-port daemon) under `resources` in `sikemux.json`. Agents acquire them via `hold` or task `needs` with deadlock detection and automatic release when the turn ends.

See [Run, test and build](/getting-started/run/) for the full `sikemux.json` reference.

## Line-owned commits and the linear landing queue (`git_commit`)

Agents never run raw `git add .` or `git commit`. Instead, every agent commits through `git_commit`, backed by two kernel mechanisms:

### Line-level edit ownership

As chat agents edit files, `sikemux-core` records every changed file and line range per agent turn into a per-project journal under `edits/`. When an agent calls `git_commit`, the core constructs an isolated git index containing **only the lines that agent wrote** (or the paths it explicitly names), leaving other agents' and your own uncommitted edits untouched, even in a shared checkout.

### Atomic landing queue (`land: true`)

When a worker in an isolated worktree finishes, it calls `git_commit` with `land: true` (and optionally `push: true` or `sync: true` to rebase onto the latest base tip):

```text
Worker A (worktree) --+
                      |  git_commit(land: true)
Worker B (worktree) --+---> [ Linear Landing Queue ]
                                    |
                  1. Replay commits onto base branch tip
                  2. Run rustfmt + targeted cargo check (or sikemux.json landChecks) once per batch
                  3. If batch fails -> bisect & return error ONLY to the breaking worker
                  4. Merge cleanly around uncommitted user edits (or refuse with Clash before moving HEAD)
                                    |
                                    v
                       Base branch advances linearly
                       (merged remote worktree branches pruned automatically)
```

Key guarantees enforced by `git_commit`:

- **Linear history:** Commits are replayed onto the target branch tip in queue order, with no merge commits or race conditions between concurrent workers.
- **Targeted batch verification with automatic bisection:** The queue checks the stacked batch once, running `rustfmt` and targeted `cargo check` for touched Rust crates (or matching `landChecks` defined in `sikemux.json`). If a batch fails, Sikemux bisects the stack to isolate the exact breaking piece and sends only that piece back to its owner with the compiler output.
- **Protected branches:** `force: true` is rejected on `main` and `release/*` branches. A checkout on a `release/*` branch cannot land back onto `main`; it must be pushed directly with `push: true` and no `land`.
- **Uncommitted user safety:** If you have uncommitted edits in the main checkout, Sikemux merges the landed diff cleanly into them, or aborts with a clash error before moving `HEAD` if your lines conflict.

## Live cross-harness handoffs

Because `sikemux-core` folds every agent's output into one canonical transcript (`sikemux-fold`), a conversation is never locked to the CLI that started it.

At any idle point in a chat, open the model picker under the composer and switch to another harness, moving a live session across [Claude Code](/each-agent/claude-code/), [Codex](/each-agent/codex/), [Antigravity](/each-agent/antigravity/), [OpenCode](/each-agent/opencode/), [Hermes](/each-agent/hermes/), [Pi](/each-agent/pi/), [OMP](/each-agent/omp/), [Grok](/each-agent/grok/), or [Muse](/each-agent/muse/).

- [Claude Code](/each-agent/claude-code) (Anthropic): runs `claude`
- [Codex](/each-agent/codex) (OpenAI): runs `codex app-server`
- [OpenCode](/each-agent/opencode) (Open source): runs `opencode serve`
- [Hermes](/each-agent/hermes) (Nous Research): runs `hermes acp`
- [Pi](/each-agent/pi) (Open source): runs `pi --mode rpc`
- [OMP](/each-agent/omp) (Open source): runs `omp acp`
- [Grok](/each-agent/grok) (xAI): runs `grok agent`
- [Antigravity](/each-agent/antigravity) (Google): runs `agy acp`
- [Muse](/each-agent/muse) (Meta): runs `muse serve`

### Deterministic selection, not an LLM summary

When you switch harnesses, the chat stays one continuous thread in the UI while the new harness starts a fresh vendor session. On your next message, the core builds a **deterministic handoff payload** directly from the transcript, with no LLM summarization step:

| Included in handoff | Limit / rule |
| --- | --- |
| **First user request** | Always preserved (up to 12% of budget, clamped 8K–24K chars) |
| **Latest exchanges** | Word-for-word user/assistant turns until budget fills (single turn capped at 9% of budget, 6K–18K chars) |
| **Recent commands** | Up to **20** commands with exit outcomes (200 chars each; 6% of budget) |
| **Touched files** | Up to **40** files (3% of budget) |
| **Project decisions** | Up to **40** decisions from the last **14 days** (10% of budget) |
| **Active rules** | Your rules and project rules (6% of budget) |

Reasoning traces, raw tool output blobs, and binary attachments are excluded to keep the new context sharp; the incoming agent can read the full prior history through Sikemux's tools whenever needed.

### Window-relative `HandoffBudget`

The handoff payload scales automatically to the target model's effective context window:

- **Budget formula:** **8% of the target model's effective context window**, clamped between **16,000 tokens** (minimum) and **64,000 tokens** (maximum).
- **Preview & override:** Before you send your next message, a strip above the composer shows what will cross over and its estimated token count (persisted across restarts). Click **Leave out** to start clean without the handoff.
- **Switching back:** Before the new harness runs, Sikemux keeps the previous harness's `resume_id` (`RanOn`). Picking the previous agent again resumes its original vendor session without re-sending a handoff.
- **Forking (`/fork`):** Typing `/fork` creates a new parallel chat with the exact same deterministic handoff on the same agent and account, leaving the original thread intact.

### Multi-account failover and warm cache compaction

Cross-harness mobility pairs with two host-side continuity features:

- **Multi-account failover:** When you sign in multiple accounts for Claude Code, Codex, or Antigravity (see [Accounts](/agents/accounts/)), Sikemux routes around quota exhaustion or account lockouts without losing the chat transcript, offering one-click moves to the account with the most headroom.
- **Idle cache-boundary compaction:** When a chat sits idle near a provider's prompt-cache expiry window (for example, 50 minutes idle inside Claude's 60-minute cache window, or 4 minutes idle inside Antigravity's 5-minute window), Sikemux tracks warm compaction thresholds so returning to a long thread does not trigger an unnecessary full-context cold miss.

- [The Agent Kernel](/agents/agent-kernel): How sikemux-core owns state, leases, and verified receipts beneath every harness.
- [Chats](/agents/chats): Composer controls, snoozing, settling, asks, and moving chats across hosts.
