Worktree Isolation
Using separate git worktrees to give each parallel agent its own filesystem checkout. Agents literally cannot touch each other’s files. The ToS-compliant, host-native alternative to container-based sandboxing.What a Git Worktree Is
A git worktree is a second (or third, Nth) checkout of the same repository in a different directory. All worktrees share the same.git object store — commits, history, refs — but each has its own working tree and HEAD.
Why Agents Need It
Without worktree isolation, parallel agents editing the same repo share a working directory. Agent A editssrc/auth.ts. Agent B, working on a different task, reads src/auth.ts and gets A’s half-finished state. Both commit. Conflict.
With worktree isolation:
- Each agent has its own filesystem state
- Agents can’t observe each other’s in-progress edits
- Each agent starts from a known clean commit
- Merge happens after each agent completes — not mid-task
Scope Overlap Detection
The precondition for safe worktree isolation is non-overlapping file scope between agents. Before assigning tasks to parallel agents, check that their target directories don’t overlap:Merge Protocol
Merge-before-cleanup rule: always merge the worktree branch before removing the worktree. Removing first loses any uncommitted or unmerged work.head— merge directly to current HEAD (low risk, non-overlapping files)merge-to-head— standard merge (default for parallel work)branch— open a PR for human review before merging (security changes, shared interfaces)
Relation to ToS and Sandboxing
Agentic Sandbox Controls recommends OS-level sandboxing (containers, Bubblewrap) per the NVIDIA AI Red Team guidance. But Anthropic’s ToS restricts Claude Code subscription keys inside Docker containers. Worktree isolation is the ToS-compliant host-native alternative:
Dangeresque (host-native) uses worktrees + tool filtering. SandCastle runs Claude on the host (worktree isolation) and only containers for tool execution — Claude itself never runs inside Docker. Note: CC’s native settings.json schema uses
permissions.allow/permissions.deny, not the older allowedTools/disallowedTools names. See Claude Code Permissions Settings.
Implementations
Per-Task vs Per-Agent
The fundamental architectural decision when assigning worktrees:
Default: worktree-per-task. Worktree-per-agent only when the agent persists across multiple tasks and benefits from warm dependency caches or accumulated environment state (e.g., a long-running specialist agent keeping a pre-compiled build warm).
Runtime Isolation Gap
Worktrees solve filesystem conflicts only. They do not provide network or process isolation. Two agents in separate worktrees still collide on:- Port numbers when both start a dev server on
:3000 - Shared databases and test state
- Build caches and configuration registries
- Deterministic port assignment from branch name hash:
PORT=$(( 3100 + $(echo "${BRANCH_NAME}" | cksum | cut -d' ' -f1) % 6899 )) - Galactic (github.com/idolaman/galactic) — assigns a unique local IP per worktree (127.0.0.2, 127.0.0.3, etc.) so multiple backends run without port juggling
- Block’s agent-task-queue — FIFO coordination for expensive shared operations like test runners; prevents multiple agents from concurrently triggering
./gradlew test - Composite pattern: worktrees for git isolation + containers (Dagger Container-Use) for runtime isolation; full isolation at both layers
Operational Details
Lock while agent runs
Conflict resolution recording
Sparse checkout (monorepos)
Constrain worktree to files the agent actually needs:Non-Git Isolation: jj Workspaces and the WorktreeCreate Hook
Jujutsu has its own equivalent, workspaces (jj workspace add ../name): one repo, one operation log, shared
change ids, several working copies. One practitioner ran parallel Cursor CLI agents this way and had an agent
merge the workspaces with revsets (Jj For Coding Agents). Reported costs: editing an ancestor of
another workspace’s change makes that workspace stale (jj workspace update-stale), and jj log does not
snapshot other workspaces.
Claude Code lets you replace its git worktree add with a WorktreeCreate hook (fires for --worktree,
EnterWorktree, subagent isolation: "worktree", workflow agents and background sessions; the command hook
prints the absolute path as its last stdout line). A paired WorktreeRemove hook must do its own dirty check,
because Claude Code checks for uncommitted work with git and finds none in a non-git directory. Worktrees made
by the hook for subagents and workflow agents are never removed automatically.
The rest of the tool is still Git-shaped: EnterWorktree validates the hook’s path against
git worktree list and refuses a jj workspace (claude-code issue #66503, open as of 2026-09-03), which hard-blocks
background sessions. Making the jj workspace also a hand-registered Git worktree was tried and abandoned: jj
never moves that worktree’s Git HEAD, so Git commands there use the wrong index.
What works in this harness: keep Claude Code’s Git worktree and colocate a jj repo inside it with
jj git init --colocate (run by a PreToolUse hook on the first Bash call). Git-based guards and review gates
see an ordinary worktree; agents get jj’s undo and history editing. See Jujutsu (jj) for the commit
funnel and gotchas.
Update 2026-11-09 (jj 0.46, Claude Code 2.1.319, tested). jj workspace add --colocate creates a real Git
worktree, listed by git worktree list, and EnterWorktree accepts it, so the #66503 refusal does not apply to
that form. The dotfiles harness now starts new sessions through scripts/jw, which makes such a workspace on a
real branch: one shared jj store, and Git-based gates keep working because the commit funnel keeps HEAD attached.
See Claude Code Worktree-Isolation Guard for why this launch path avoids the guard.
Fresh Context Window Per Task
Each worktree task gets a fresh agent session — no accumulated context from prior tasks. This is the mechanical basis for Context Compression Strategies clear-over-compact in AFK workflows:.agents/decisions.md, issue files — not in agent memory. This is what Pocock means by “make clearing safe, then prefer clearing.”
Reference Orchestrators Using Worktrees
Related Pages
- Shared Task Queue (Cross-Worktree) — filesystem inbox with atomic claim semantics; how agents discover tasks at startup across worktrees
- Branch Strategy for Agents — merge strategy after worktree work completes
- Agentic Sandbox Controls — ToS constraint driving host-native isolation
- Context Compression Strategies — clear-over-compact; worktrees make clearing safe
- Agent Subagents —
isolation: "worktree"parameter - Claude Code Worktree-Isolation Guard — Claude Code’s Bash guard for isolated sessions; refusal classes and bandaids
- Jj For Coding Agents — jj workspaces vs Git worktrees for agents; Claude Code worktree hooks
Linked pages
- Agent Subagents
- Agent Teams
- Agentic CI/CD
- Agentic Sandbox Controls
- Branch Strategy for Agents
- Claude Code Worktree-Isolation Guard
- Context Compression Strategies
- Jujutsu (jj)
- Lean Agentic Coding Workflow
- Self-Healing Loop
- Shared Task Queue (Cross-Worktree)
- Worker Coordination: Partial Result Passing Between Parallel Agents