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

  1. Create a worktree per task. The task ID binds to the worktree path.

  2. 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)])
  1. The agent’s working directory is set to the worktree path. All file operations are naturally sandboxed.

What Changed From s17

ComponentBefore (s17)After (s18)
WorkspaceSharedPer-agent worktrees
IsolationNoneFilesystem-level
CleanupManualWorktree lifecycle

Try It

cd learn-claude-code
python agents/s18_worktree_isolation.py
  1. Create a worktree for task "add-login" and start an agent
  2. Create another worktree for task "add-dashboard" and run in parallel
  3. Check 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.