Worktree + Task Isolation
CollaborationIsolate by Directory
Each works in its own directory; tasks manage goals, worktrees manage directories, bound by ID
s01 > s02 > s03 > s04 > s05 > s06 > s07 > s08 > s09 > s10 > s11 > [ s12 ]
"Each task gets its own world" -- Git worktree gives each agent an independent filesystem copy.
Harness layer: Isolation -- process-level filesystem isolation preventing parallel task interference.
Problem
s04's subagents have independent context windows but share the filesystem. If Agent A modifies main.py while Agent B also modifies it, conflicts arise. s20's file locks prevent simultaneous writes but not inconsistent reads.
Solution
main branch: /project/ → shared repository
worktree-1: /project/.worktrees/w1/ → Agent 1's isolated copy
worktree-2: /project/.worktrees/w2/ → Agent 2's isolated copy
Each worktree is a complete filesystem copy managed by Git, merged back upon completion.
Key Code
def create_worktree(branch_name):
worktree_path = f".worktrees/{branch_name}"
subprocess.run(["git", "worktree", "add", worktree_path, "-b", branch_name])
return worktree_path
class IsolatedAgent:
def __init__(self, task_id):
self.workdir = create_worktree(f"agent-{task_id}")
def run(self, task): ... # All file ops in self.workdir
def complete(self):
merge_worktree(self.branch) # merge back to main
What's New (s11 → s12)
| Component | s11 | s12 |
|---|---|---|
| Filesystem | Shared | Per-task isolated (worktree) |
| Conflict risk | High | Low (Git merge handles) |
| Rollback | Difficult | Simple (git branch delete) |
Deep Dive
Q1: Why Git worktree not Docker containers?
Speed (<1s vs 5-30s), disk efficiency (hardlinks), built-in merge, only needs Git.
Q2: What if merge has conflicts?
Three strategies: auto-resolve (let agent handle), re-execute on latest main, or human intervention.
Q3: How does this pair with s20 Parallel Teams?
Perfectly: each s20 Worker runs in its own worktree. s20 = process parallelism, s12 = filesystem isolation.
Q4: Worktree count limits?
Git has none. Practical limits: disk space, inode count. 10-20 worktrees is typical max.
Q5: Why is this the last foundational session?
s12 completes the agent puzzle: isolation. With it, agents can safely parallel-execute (s08+s20), avoid file conflicts (s09+s10), and roll back failures. s13-s21 add evaluation, engineering, and safety.
Try It
cd learn-claude-code
python agents/s12_worktree_task_isolation.py
References
- Git Worktree — Git Docs.
- Claude Code: Parallel Worktrees — Anthropic Docs.
- Building Effective Agents: Parallelization — Anthropic, Dec 2025.