Each works in its own directory, no interference
What You’ll Learn
- Why filesystem isolation matters for parallel agents
- How to use git worktrees for per-agent workspaces
- How task coordination ties into worktree lifecycle
The Problem
Two autonomous agents working on different tasks in the same directory will conflict. One writes main.py, the other also writes main.py. Chaos.
The Solution
Git worktrees provide isolated workspaces. Each agent gets its own checkout — same repo, different directory, zero interference.
repo/
main/ <-- canonical branch
worktrees/
task-001/ <-- agent A workspace
task-002/ <-- agent B workspace
task-003/ <-- agent C workspace
How It Works
-
Create a worktree per task. The task ID binds to the worktree path.
-
Agents run in their worktree. When done, merge or discard.
class WorktreeManager:
def create(self, task_id: str, base_branch="main"):
path = WORKTREES_DIR / f"task-{task_id}"
subprocess.run(["git", "worktree", "add", str(path),
base_branch])
return path
def cleanup(self, task_id: str):
path = WORKTREES_DIR / f"task-{task_id}"
subprocess.run(["git", "worktree", "remove", str(path)])
- The agent’s working directory is set to the worktree path. All file operations are naturally sandboxed.
What Changed From s17
| Component | Before (s17) | After (s18) |
|---|---|---|
| Workspace | Shared | Per-agent worktrees |
| Isolation | None | Filesystem-level |
| Cleanup | Manual | Worktree lifecycle |
Try It
cd learn-claude-code
python agents/s18_worktree_isolation.py
Create a worktree for task "add-login" and start an agentCreate another worktree for task "add-dashboard" and run in parallelCheck that the two agents don't see each other's files
Key Takeaway
Tasks answer what; worktrees answer where. Keep them separate. Each autonomous agent works in its own directory, bound by task ID, cleanly removable when done.