Skip to main content
MindStudio
Pricing
Blog About
My Workspace

How to Run Parallel AI Coding Agents With Git Worktrees

Run multiple Claude Code sessions simultaneously without conflicts. This guide covers git worktrees, database branching, and port isolation for parallel agents.

MindStudio Team RSS
How to Run Parallel AI Coding Agents With Git Worktrees

The Problem With Running AI Agents Sequentially

If you’ve tried running multiple Claude Code sessions on the same project, you’ve probably hit the same wall: agents step on each other. One session rewrites a file while another is mid-edit. Tests fail for reasons that have nothing to do with the feature being built. The database is in an unexpected state. Context windows fill up with noise from other agents’ work.

The fix is straightforward, but it requires setting up your environment correctly before you start. Git worktrees give each parallel AI coding agent its own isolated working directory, checked out from the same repository. Pair that with database branching and port isolation, and you can run three, four, or five Claude Code sessions simultaneously — all working on the same codebase, none of them interfering with each other.

This guide covers the full setup: creating worktrees, configuring isolated environments, running agents in parallel, and merging everything back cleanly.


What Git Worktrees Actually Are

A git repository normally has one working tree — the directory where your files live. Git worktrees let you check out multiple branches from the same repo simultaneously, each in its own directory, all sharing the same .git folder.

This is different from cloning the repo multiple times. Clones are completely separate copies. Worktrees share history, objects, and refs. You can see all branches from any worktree, commits made in one worktree are immediately visible in others, and you don’t duplicate the .git directory.

REMY IS NOT
  • a coding agent
  • no-code
  • vibe coding
  • a faster Cursor
IT IS
a general contractor for software

The one that tells the coding agents what to build.

The practical upshot for parallel AI development: each agent gets its own branch and its own directory to work in. No file conflicts. No state bleed. Clean isolation at the filesystem level.

If you want more background on how this pattern emerged in the AI coding context, the Claude Code git worktree pattern explained covers the conceptual side in depth.

Why This Matters More for AI Agents Than for Human Developers

Human developers typically work on one thing at a time. They’re the bottleneck, not their tools. AI agents aren’t bottlenecked the same way — they can execute at full speed and in parallel. But standard development setups assume a single developer, so they don’t isolate resources at the level parallel agents require.

When you run two Claude Code sessions against the same working directory:

  • Agents overwrite each other’s edits to shared files
  • The dev server only runs on one port, so the second agent can’t test its changes live
  • Database mutations from one agent corrupt the test assumptions of another
  • Both agents read from the same context, creating context rot faster than either would alone

Worktrees fix the file isolation problem. Database branching and port assignment fix the rest.


Prerequisites

Before you start, make sure you have:

  • Git 2.5 or later — worktrees were introduced in 2.5, but 2.15+ is recommended for stability
  • Claude Code installed and authenticated
  • A project with a real git repository (not just a folder with files)
  • Some understanding of how your app’s dev server and database are configured

You don’t need any special plugins or third-party tools. Everything here uses native git commands and standard environment variable patterns.


Step 1: Set Up Your First Worktree

Start in your main project directory. This is your “main” worktree — the one git created when you initialized the repo.

# Check your current worktrees
git worktree list

You should see just one entry, pointing to your current directory on your main branch.

Now create a new worktree for your first parallel task:

git worktree add ../my-project-feature-a feature/add-auth

This creates a new directory at ../my-project-feature-a and checks out the feature/add-auth branch into it. If that branch doesn’t exist yet, git creates it automatically.

For a second agent working on something else:

git worktree add ../my-project-feature-b feature/refactor-payments

Your directory structure now looks like this:

~/projects/
  my-project/           ← main worktree (main branch)
  my-project-feature-a/ ← worktree for agent 1 (feature/add-auth)
  my-project-feature-b/ ← worktree for agent 2 (feature/refactor-payments)

Each directory has its own copy of all the source files, checked out from the appropriate branch. The .git folder only exists in my-project/ — the others have a .git file (not folder) that points back to it.


Step 2: Isolate Your Development Database

File isolation is handled. Database isolation is the next problem.

Most development setups share a single local database. If agent A runs a migration or seeds test data, agent B is now working against a different schema or dataset than it expects. This causes subtle failures that are hard to trace.

Option A: Separate SQLite Files

Remy is new. The platform isn't.

Remy
Product Manager Agent
THE PLATFORM
200+ models 1,000+ integrations Managed DB Auth Payments Deploy
BUILT BY MINDSTUDIO
Shipping agent infrastructure since 2021

Remy is the latest expression of years of platform work. Not a hastily wrapped LLM.

If your app uses SQLite, the simplest solution is to give each worktree its own database file. SQLite databases are just files, so you configure the path with an environment variable.

Create a .env.local file in each worktree directory:

# my-project-feature-a/.env.local
DATABASE_URL=./data/feature-a.sqlite

# my-project-feature-b/.env.local
DATABASE_URL=./data/feature-b.sqlite

Make sure your app loads .env.local and that data/ is in .gitignore. Now each agent has a completely independent database. Migrations, seeds, and test mutations stay isolated.

Option B: Separate Postgres Databases

For Postgres, create separate databases for each worktree:

createdb my-project-feature-a
createdb my-project-feature-b

Then set DATABASE_URL in each worktree’s .env.local:

# my-project-feature-a/.env.local
DATABASE_URL=postgresql://localhost/my-project-feature-a

# my-project-feature-b/.env.local
DATABASE_URL=postgresql://localhost/my-project-feature-b

Option C: Database Branching Services

Services like Neon and PlanetScale support database branching — creating a copy of a database at the branch level, similar to git branching. This is cleaner for shared dev environments or cloud-hosted databases.

With Neon, you create a branch via their API or CLI:

neon branches create --name feature-add-auth
neon branches create --name feature-refactor-payments

Each branch gets its own connection string. Set those in the respective .env.local files and agents work against completely separate database states, forked from the same baseline.


Step 3: Assign Separate Ports

If your app runs a dev server, two agents can’t both bind to port 3000. Assign different ports to each worktree.

The exact mechanism depends on your framework. Most support a PORT environment variable:

# my-project-feature-a/.env.local
PORT=3001
DATABASE_URL=./data/feature-a.sqlite

# my-project-feature-b/.env.local
PORT=3002
DATABASE_URL=./data/feature-b.sqlite

For Next.js, pass the port directly:

next dev -p 3001

For Vite:

vite --port 3001

If your agents need to communicate with each other or with external services, make sure those port assignments are consistent. Document them somewhere each agent can reference — a WORKTREE.md file in each directory is a lightweight solution.


Step 4: Launch Claude Code in Each Worktree

Now that each worktree has its own directory, database, and port, open a terminal window (or tmux pane) for each one, cd into that directory, and start Claude Code.

# Terminal 1
cd ~/projects/my-project-feature-a
claude

# Terminal 2
cd ~/projects/my-project-feature-b
claude

Each Claude Code session sees only the files in its worktree. It runs against its own database. It talks to its own dev server port. The sessions have no awareness of each other.

This is the core of running multiple agents without conflicts — not clever coordination between agents, but hard isolation at the infrastructure level so they don’t need to coordinate at all.

For structured guidance on how to run multiple Claude Code sessions simultaneously and coordinate the outputs, this parallel agentic development playbook covers the workflow side in detail.


Step 5: Write Task Instructions for Each Agent

Agents work better with clear, self-contained task definitions. When you have multiple agents running, you want each one to have everything it needs without asking clarifying questions that interrupt the other sessions.

A good starting prompt for each agent in its worktree:

You're working in the feature/add-auth branch. Your task is to:
1. Add email/password authentication using the existing User model
2. Create login and signup endpoints at /api/auth/login and /api/auth/signup
3. Add session handling with JWT tokens stored in httpOnly cookies
4. Write tests for the happy path and the main error cases

The dev server runs on port 3001. The database is at ./data/feature-a.sqlite.
Do not modify anything outside of the auth-related files.
Do not change the User model schema.

Not a coding agent. A product manager.

Remy doesn't type the next file. Remy runs the project — manages the agents, coordinates the layers, ships the app.

BY MINDSTUDIO

The last two constraints are important. Without them, agents will sometimes make “helpful” changes to shared utilities or configs that create merge conflicts later.

You can scale this approach further using Claude Code Agent Teams, where agents share a task list in real time and coordinate at a higher level. But for most use cases, isolated task instructions per worktree are sufficient.


Step 6: Monitor and Review Progress

With multiple agents running in parallel, you need a way to see what’s happening without jumping between terminals.

Simple approach: tmux

Create a tmux session with panes for each worktree:

tmux new-session -s agents
# Split the window and cd into each worktree in each pane

This gives you a single view of all agent activity.

Git-based checkpoints

Agents should commit their work incrementally. Configure Claude Code to commit after completing each discrete task. This gives you a clear audit trail and makes merge review easier.

You can check progress from any worktree using git:

# From the main worktree, see commits on each feature branch
git log feature/add-auth --oneline
git log feature/refactor-payments --oneline

Review before merging

Before merging anything into main, review each worktree’s diff:

cd ~/projects/my-project-feature-a
git diff main...feature/add-auth

This shows exactly what the agent changed, relative to the shared baseline. Catch issues here rather than after merging.


Step 7: Merge the Work Back

Once you’ve reviewed each branch, merge in the order that minimizes conflicts. Usually this means starting with the most foundational changes.

cd ~/projects/my-project
git merge feature/add-auth

If there are conflicts, resolve them in the main worktree. Run your test suite. Then merge the next branch.

git merge feature/refactor-payments

For larger parallel workflows — especially ones using the split-and-merge pattern — you may want a dedicated integration step where an agent reviews the combined output and resolves any inconsistencies.

Clean up worktrees when done

git worktree remove ../my-project-feature-a
git worktree remove ../my-project-feature-b
git branch -d feature/add-auth
git branch -d feature/refactor-payments

The remove command deletes the directory and unregisters the worktree. The original .git directory in your main project is unchanged.


Common Mistakes and How to Avoid Them

Running agents in the same directory

The most common error. Two agents in the same directory will overwrite each other’s work. Always verify you’re in the worktree directory before starting each Claude Code session.

Shared .env files

If your project uses a single .env file that’s committed to the repo, both worktrees will read from it. Use .env.local (which should be in .gitignore) to override environment variables per worktree.

Not specifying task boundaries

Agents without clear boundaries will wander into shared utilities, modify configs, or “improve” code outside their assigned scope. Always define what files or modules are off-limits.

Merging without reviewing

Parallel agents produce a lot of output fast. The speed is the point — but it also means you need to be more disciplined about reviewing changes before they land in main. Don’t skip the diff review step.

Forgetting database migrations

Day one: idea. Day one: app.

DAY
1
DELIVERED

Not a sprint plan. Not a quarterly OKR. A finished product by end of day.

If agent A adds a table and agent B also adds a migration, you’ll have a migration conflict. Coordinate migrations explicitly: either assign one agent as the “migration owner” for shared schema changes, or structure tasks so each agent only touches its own tables.


Scaling to More Agents

The same pattern scales to as many agents as you need. Each worktree gets:

  • Its own directory
  • Its own branch
  • Its own .env.local with a unique port and database
  • A self-contained task description

For large parallel workflows, consider building a lightweight coordination layer — a TASKS.md file at the repo root that all agents can read (but not write to while working), or a simple task queue that an orchestrator agent manages.

Claude Code’s agentic workflow patterns covers several approaches to multi-agent coordination, from simple sequential handoffs to fully autonomous parallel execution. The right pattern depends on how tightly your subtasks depend on each other.

For browser-based automation tasks running alongside coding agents, the setup is similar — parallel browser agents follow the same isolation principles.


A Note on Context Management

Each Claude Code session has its own context window. Parallel agents don’t share context, which is actually an advantage — each one stays focused on its specific task without being distracted by everything else happening in the codebase.

But it also means each agent needs enough context to work effectively. Give each one a clear CONTEXT.md or include relevant background in the task prompt: architecture decisions, existing patterns to follow, constraints to respect.

Long-running sessions can develop context rot — where accumulated back-and-forth in the session window degrades output quality. Keep tasks focused. If an agent needs to work on something substantially different after completing its first task, consider starting a fresh session in the same worktree rather than extending the existing one.


How Remy Approaches This

The worktree pattern solves a real problem, but it also highlights something: when you’re running AI coding agents in parallel, most of the work is managing infrastructure, not building features. You’re assigning ports, creating databases, writing isolation configs, and monitoring multiple terminals.

Remy takes a different starting point. Instead of writing code and managing the infrastructure around it, you write a spec — a structured markdown document that describes what the application does, with typed annotations for data models, edge cases, and business rules. Remy compiles that spec into a full-stack app: backend, database, auth, tests, deployment.

When you need to add or change something, you update the spec and recompile. The code is the derived artifact, not the source of truth.

This doesn’t eliminate the need for parallel work on large projects. But it changes what that work looks like. Instead of coordinating multiple agents writing TypeScript across isolated worktrees, you’re working at the spec level — which is both easier to review and easier to keep consistent.

You can try Remy at mindstudio.ai/remy if you want to see how spec-driven development handles the kind of complexity that pushes people toward parallel agent setups in the first place.


Frequently Asked Questions

Can you use git worktrees with any AI coding tool, or just Claude Code?

Remy doesn't build the plumbing. It inherits it.

Other agents wire up auth, databases, models, and integrations from scratch every time you ask them to build something.

200+
AI MODELS
GPT · Claude · Gemini · Llama
1,000+
INTEGRATIONS
Slack · Stripe · Notion · HubSpot
MANAGED DB
AUTH
PAYMENTS
CRONS

Remy ships with all of it from MindStudio — so every cycle goes into the app you actually want.

Worktrees are a git feature with no tool-specific dependencies. You can use them with Claude Code, Cursor, Aider, or any other AI coding tool that operates on files in a directory. The setup steps in this guide apply regardless of which tool you’re running in each worktree.

How many parallel agents can you run at once?

There’s no hard limit from git — you can create as many worktrees as your disk has space for. The practical limit is usually your API rate limits and your ability to review the output. Most developers find three to five parallel agents is manageable. Beyond that, the coordination overhead and review burden start to offset the speed gains.

Do worktrees slow down git operations?

Slightly. Git has to check all registered worktrees when performing certain operations. For most projects, the overhead is negligible. If you’re running a dozen worktrees simultaneously on a very large monorepo, you may notice some slowdown in git status and similar commands.

What happens if two agents modify the same file?

If they’re in separate worktrees on separate branches, nothing happens immediately — each has its own copy of the file. The conflict surfaces when you try to merge those branches. Standard git merge conflict resolution applies. This is actually one of the key reasons to use worktrees: conflicts are deferred to merge time, where you can review them explicitly, rather than happening live while agents are still running.

How do you handle shared dependencies like npm packages?

Each worktree shares the same package.json from the repo, but has its own node_modules directory. You’ll need to run npm install (or equivalent) in each worktree separately. If you update dependencies in one worktree, make sure to update and reinstall in others before merging, or you may end up with a package-lock.json conflict.

Is there a way to automate worktree creation for new tasks?

Yes. You can write a simple shell script that creates the worktree, copies a .env.local template with the next available port, creates a branch, and opens a new terminal window. Many teams doing parallel agentic development build small automation scripts to standardize this setup and reduce the manual steps before each new agent session.


Key Takeaways

  • Git worktrees give each AI agent its own isolated working directory, checked out from the same repository without duplicating .git
  • Database isolation (separate SQLite files, separate Postgres databases, or database branching) prevents state bleed between agents
  • Port isolation lets each agent run its own dev server independently
  • Clear, bounded task instructions prevent agents from wandering into shared code
  • Review diffs from each branch before merging — speed means more output to check, not less
  • The pattern scales linearly: add a worktree, assign a port and database, write a task prompt, launch an agent

If managing this infrastructure is taking more time than the parallel development saves, try Remy — a spec-driven approach where the application is defined at a higher level and the infrastructure is handled automatically.

Presented by MindStudio

No spam. Unsubscribe anytime.