# Cursor Parallel Agents: 12 Steps, 70 Min

> Source: <https://shattered.io/cursor-parallel-agents-git-worktrees-12-steps-2026/>
> Published: 2026-11-21 23:56:27+00:00

**Recommendation:** Run each parallel coding agent in its own git worktree and branch, pre-check overlapping paths, and merge-test every branch pair before integrating to avoid clobbered files and polluted staging areas.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

Cursor 3 introduced an Agents Window that runs agents in parallel across local worktrees, cloud environments and remote SSH, according to a [2026 Cursor vs Copilot comparison](https://www.getmaxim.ai/articles/cursor-vs-copilot/) that tracks the release. The window makes it easy to start four agents at once. It does nothing to stop those four agents from editing the same file, and that is where most parallel Cursor agents runs go wrong.

Cursor agents are fast enough now that the bottleneck moved from typing to merging. You can brief one agent on a feature, another on tests and a third on docs, then walk away for twenty minutes. If all three work in the same checkout, they overwrite each other, stage each other’s half-finished files and leave you a diff nobody can review. A git worktree gives each agent its own folder and its own branch while sharing one object store, which is why Cursor builds its parallel mode on top of them.

You will build a small Python tool called `agentfleet` that sets up one worktree per task, warns you about overlapping paths before any agent starts, reports progress, tests every pair of branches for merge conflicts and assembles the clean ones onto an integration branch. It sits next to Cursor rather than replacing anything, so it works the same whether you launch agents from the Agents Window, the editor chat or [custom subagents](https://shattered.io/cursor-subagents-custom-agents-verifier-12-steps-2026/) inside a single session. The whole build takes about 70 minutes and every command below was run against a real repository.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)

## Why Parallel Cursor Agents Collide Without Isolation

Three failure patterns show up again and again when people run several agents against one working directory. The first is file clobbering. Agent A rewrites `src/cart/cart.py`, agent B opens the same file a minute later with a stale mental model and saves its own version on top. Neither agent reports a problem because, from each one’s point of view, the write succeeded.

The second pattern is index pollution. Git has a single staging area per checkout. If one agent runs `git add -A` while another is mid-edit, the first agent’s commit sweeps in the second agent’s half-written changes. You end up with a commit message about discounts and a diff that also contains a broken tax function. Reverting one task means untangling the other.

The third pattern is slower to notice: shared state outside git. Two agents that both start a dev server fight over port 3000. Two agents that both run a test suite against the same SQLite file corrupt each other’s fixtures. A branch-per-agent habit does not fix any of this, because branches do not change the files on disk. Only separate directories do.

Demand for this workflow is real. The 2025 Stack Overflow Developer Survey found that 31% of developers already use AI agents at work, and 69% of those who have used them agree the tools raised their productivity, per the survey’s [press release](https://stackoverflow.co/company/press/archive/stack-overflow-2025-developer-survey/). As those numbers climb, the pain moves from whether an agent can write the code to whether you can safely run more than one. Pricing pressure adds to it, since each extra agent burns usage. If you are weighing how many agents your plan can feed, the [Claude Code vs Cursor vs Copilot pricing and limits breakdown](https://shattered.io/claude-code-vs-cursor-vs-github-copilot-pricing-limits-2026/) covers the usage side.

Isolation alone is not enough, though. Even with perfect worktrees, two agents can both be correct in their own folders and still produce changes that collide at merge time. That is why the tool you build here has a planning step before launch and a conflict check after. The first catches overlap you can see coming. The second catches the overlap you could not.

## Prerequisites: Tools, Versions and Accounts

The project uses only the Python standard library and plain git, so setup is short. The one version that matters is Git. The conflict check relies on `git merge-tree --write-tree`, a mode of the command that performs a real three-way merge in memory without touching any working directory. Older Git releases only had a legacy form of `merge-tree` with a different interface. The table lists what the walkthrough was tested on.

| Requirement | Version used | Why it matters | 
|---|---|---|
| Git | 2.43.0 tested, 2.38 or newer needed | 2.38 added `merge-tree --write-tree` , which the conflict check calls | 
| Python | 3.12.3 tested, 3.8 or newer works | Script uses f-strings, `pathlib` and`subprocess.run` only | 
| Cursor | 3.24 or newer | Release notes tie the cloud-to-local worktree handoff to 3.24 | 
| Operating system | Linux tested | macOS and Windows run the same script, paths use `pathlib` | 
| Disk space | Your repo size per worktree | Each worktree has a full working tree, history is shared | 
| Cursor account | Any plan for local agents | Cloud agents need a paid plan with cloud agents enabled | 

Check your Cursor version from the About dialog before you start, because the Agents Window changes quickly. Cursor’s release notes put the ability to move a cloud agent into an existing or new local worktree, without touching your main checkout, in version 3.24. If your build is older, everything here still works for local worktrees. You only lose the handoff feature covered in the advanced section.

You also need a repository you can safely experiment on. The tutorial creates a throwaway one called `shop` so you never risk real work. When you move to a real project, start with a clean working tree and a base branch that builds. An agent that starts from a broken base produces a fleet of branches that all fail for the same unrelated reason.

## Cursor Agents Window, Worktrees and Cloud Agents Compared

Cursor offers several places to run an agent, and picking the wrong one for a task is a common source of confusion. The Agents Window, introduced with Cursor 3, can host parallel agents on local worktrees, in cloud environments and over remote SSH. It also added a `/worktree` command, per the same 2026 comparison. Each mode trades isolation, speed and reach differently.

| Mode | Where it runs | Isolation | Best for | Main limit | 
|---|---|---|---|---|
| Local, in place | Your checkout | None | One quick task | Collides with your own edits | 
| Local worktree | Separate folder on your machine | Own branch and files | Parallel tasks in one repo | One Git repository per local session | 
| Cloud agent | Remote sandbox | Full VM | Long jobs, several repos | Needs a paid plan with cloud agents enabled | 
| Remote SSH | Another machine | Depends on setup | Heavy builds, GPU boxes | You manage the host | 

Two details from Cursor’s documentation shape how you plan work. First, local Agents Window worktrees cover a single Git repository. A multi-root workspace does not run its projects in parallel, so cross-repository coordination belongs to [Cursor cloud agents](https://shattered.io/build-cursor-cloud-agents-2026/), whose environments support up to 300 repositories. Second, language servers are off by default inside Agents Window worktree workspaces for performance, though you can switch them back on. Expect fewer inline diagnostics in those windows until you do.

Where do the worktrees live on disk? Community reports say Cursor creates its own under `~/.cursor/worktrees`, but that comes from forum users rather than an official release note, so treat it as likely rather than guaranteed. The tool in this tutorial sidesteps the question by creating worktrees in a folder you choose, next to the repository, then letting you open them in Cursor like any other folder.

That choice has a practical upside. Because `agentfleet` owns the worktree lifecycle, it can check conflicts across branches and clean up deterministically, which the editor’s built-in flow does not promise to do for you. Use Cursor’s own worktree button when you want convenience and use this tool when you want a repeatable fleet with a merge gate. Nothing stops you from mixing the two.

## Phase 1: Prepare the Repository (Steps 1-3)

### Step 1: Check Git and Python versions

Confirm both tools before writing code. A Git older than 2.38 is the single most likely cause of a confusing failure later, so catch it now.

```
git --version
python3 --version
git worktree list
```

Expected output on the test machine was `git version 2.43.0` and `Python 3.12.3`. The third command prints your current repository’s worktrees, and outside a repository it simply errors, which is fine for now. If Git reports a version below 2.38, upgrade it through your package manager or from the project’s site before continuing. The official [git-worktree documentation](https://git-scm.com/docs/git-worktree) lists every subcommand this tool relies on, including `add`, `remove` and `prune`.

### Step 2: Create the demo repository

The demo repo is a tiny shop with four areas that map to four tasks: a cart module, an auth module with tests, a docs folder and a future tax module. Keeping the layout small makes the conflict output easy to read.

```
mkdir -p /tmp/fleet-demo/shop && cd /tmp/fleet-demo/shop
git init -q -b main .
git config user.email [email protected]
git config user.name "You"
mkdir -p src/cart src/auth tests/auth docs

printf 'def total(items):\n    return sum(i["price"] for i in items)\n' > src/cart/cart.py
printf 'def login(user):\n    return True\n' > src/auth/login.py
printf 'def test_login():\n    assert True\n' > tests/auth/test_login.py
printf '# Shop\n\nVersion 1\n' > docs/README.md

git add -A && git commit -qm "init"
```

The `-b main` flag pins the initial branch name so the rest of the commands match your terminal regardless of your global Git defaults. If your default branch is `master` or `trunk`, either keep `-b main` here or change the `base` value in the next step.

### Step 3: Describe the fleet in fleet.json

The config file is the contract between you and your agents. Each task gets an id, the paths it is allowed to touch and the prompt you will paste into Cursor. Declaring paths up front is the cheap half of conflict control. It forces you to decide ownership before any agent starts, and the same boundaries can later feed [Cursor rules and AGENTS.md files](https://shattered.io/cursor-rules-linter-agents-md-cursorignore-12-steps-2026/) that tell each agent where it may work.

```
{
  "base": "main",
  "worktree_dir": "../fleet-worktrees",
  "tasks": [
    {"id": "cart-discount", "paths": ["src/cart/"],
     "prompt": "Add a percentage discount to total() in src/cart/cart.py."},
    {"id": "auth-tests", "paths": ["tests/auth/", "src/auth/"],
     "prompt": "Add failing-login tests."},
    {"id": "docs-refresh", "paths": ["docs/"],
     "prompt": "Rewrite docs/README.md."},
    {"id": "cart-tax", "paths": ["src/tax/"],
     "prompt": "Add tax to total() and put helpers in src/tax/."}
  ]
}
```

Save that as `fleet.json` in the repository root and commit it. The `worktree_dir` value is relative to the repo, so `../fleet-worktrees` puts all agent folders beside your project and keeps them out of its tree. Task ids become folder names and branch names, so the loader you write next restricts them to lowercase letters, digits and hyphens. A prompt like the one for `cart-tax` deliberately names its own folder, which gives the agent a reason to stay out of the cart module.

## Phase 2: Build the Fleet Manager in Python (Steps 4-7)

### Step 4: Write the git wrapper, config loader and path check

Create `agentfleet.py` in the repository root. The first block holds imports, one thin wrapper around the git command line and the config loader. Every git call in the tool goes through `git()`, which captures output and exits with a readable message when a command fails. That keeps the rest of the script free of try/except clutter and means a failure always shows the exact git error.

``` bash
#!/usr/bin/env python3
"""agentfleet: one git worktree per Cursor agent, with conflict checks."""
import argparse
import json
import re
import subprocess
import sys
from itertools import combinations
from pathlib import Path

ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,40}$")

def git(*args, cwd=None, check=True):
    proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
    if check and proc.returncode != 0:
        sys.exit(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
    return proc

def repo_root():
    return Path(git("rev-parse", "--show-toplevel").stdout.strip())

def load_config(path):
    cfg = json.loads(Path(path).read_text())
    seen = set()
    for task in cfg["tasks"]:
        if not ID_RE.match(task["id"]):
            sys.exit(f"bad task id: {task['id']!r} (use a-z, 0-9, hyphens)")
        if task["id"] in seen:
            sys.exit(f"duplicate task id: {task['id']}")
        seen.add(task["id"])
    cfg.setdefault("base", "main")
    cfg.setdefault("worktree_dir", "../fleet-worktrees")
    return cfg

def wt_path(root, cfg, task):
    return (root / cfg["worktree_dir"] / task["id"]).resolve()

def branch_of(task):
    return f"agent/{task['id']}"

def norm(p):
    return p.strip("/") + "/"

def paths_overlap(a, b):
    return any(norm(x).startswith(norm(y)) or norm(y).startswith(norm(x)) for x in a for y in b)
```

Two small decisions deserve a closer look. The id pattern rejects uppercase letters, spaces and slashes because the id doubles as a folder name and as the tail of a branch name like `agent/cart-tax`. A slash in the id would silently create a nested folder and a nested ref. The `norm()` helper appends a trailing slash before comparing paths, so `src/cart/` and `src/cart/cart.py` count as overlapping while `src/cart/` and `src/cartography/` do not. Without that slash, a plain `startswith` check would flag the second pair as a clash.

### Step 5: Add the plan and up commands

Next come the first two commands, plus the status helper you will need in the following step. `plan` is a dry run that never touches git. It lists each task with its paths and exits with code 1 if any two tasks declare overlapping ones. `up` creates the worktrees. For each task it runs `git worktree add -b agent/<id> <path> <base>`, which makes a new branch from the base and checks it out in a fresh folder in one step. It then writes the prompt to a file beside the worktree, not inside it, so the prompt never shows up as an untracked file in the agent’s diff.

``` python
def cmd_plan(cfg, root, args):
    clashes = [(a["id"], b["id"]) for a, b in combinations(cfg["tasks"], 2)
               if paths_overlap(a["paths"], b["paths"])]
    for task in cfg["tasks"]:
        print(f"{task['id']:<16} {', '.join(task['paths'])}")
    if clashes:
        print("\nOVERLAP in declared paths:")
        for a, b in clashes:
            print(f"  {a} <-> {b}")
        return 1
    print("\nno declared path overlaps")
    return 0

def cmd_up(cfg, root, args):
    out_dir = (root / cfg["worktree_dir"]).resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
    for task in cfg["tasks"]:
        path = wt_path(root, cfg, task)
        if path.exists():
            print(f"skip   {task['id']}: {path} already exists")
            continue
        git("worktree", "add", "-b", branch_of(task), str(path), cfg["base"], cwd=root)
        (out_dir / f"{task['id']}.prompt.md").write_text(task["prompt"] + "\n")
        print(f"ready  {task['id']:<16} {path}")
    return 0

def changed_files(root, base, branch):
    out = git("diff", "--name-only", f"{base}...{branch}", cwd=root).stdout
    return set(out.split())

def cmd_status(cfg, root, args):
    print(f"{'task':<16} {'ahead':>5} {'files':>5} {'dirty':>5}")
    for task in cfg["tasks"]:
        path = wt_path(root, cfg, task)
        if not path.exists():
            print(f"{task['id']:<16} {'-':>5} {'-':>5} {'-':>5}  (no worktree)")
            continue
        ahead = git("rev-list", "--count", f"{cfg['base']}..{branch_of(task)}", cwd=root).stdout.strip()
        files = len(changed_files(root, cfg["base"], branch_of(task)))
        dirty = len(git("status", "--porcelain", cwd=path).stdout.splitlines())
        print(f"{task['id']:<16} {ahead:>5} {files:>5} {dirty:>5}")
    return 0
```

The `changed_files()` function uses three dots in `base...branch`. That form compares the branch against the point where it forked from the base, not against the base’s current tip, so work that landed on `main` after the fork does not show up as the agent’s change. The status table reports three numbers per task: commits ahead of the base, files changed relative to the fork point and entries in `git status --porcelain`, which counts uncommitted work. The dirty column matters because an agent that edits files but never commits has produced nothing a merge can pick up.

### Step 6: Add the conflict check

This is the part that earns the tool its keep. For every pair of live branches, `pair_conflicts()` runs `git merge-tree --write-tree --name-only`. The command performs a real three-way merge entirely in the object database. It never checks anything out, so it cannot disturb a worktree an agent is using. Exit code 0 means a clean merge. Exit code 1 means conflicts, and with `--name-only` the output is a tree id on the first line followed by the conflicted paths, ended by a blank line. Any other code means git itself failed.

``` python
def pair_conflicts(root, a, b):
    proc = git("merge-tree", "--write-tree", "--name-only", a, b, cwd=root, check=False)
    if proc.returncode == 0:
        return []
    if proc.returncode != 1:
        sys.exit(f"merge-tree failed: {proc.stderr.strip()}")
    lines = proc.stdout.splitlines()[1:]
    files = []
    for line in lines:
        if not line.strip():
            break
        files.append(line)
    return files

def cmd_conflicts(cfg, root, args):
    found = 0
    live = [t for t in cfg["tasks"] if wt_path(root, cfg, t).exists()]
    for a, b in combinations(live, 2):
        shared = changed_files(root, cfg["base"], branch_of(a)) & changed_files(root, cfg["base"], branch_of(b))
        clash = pair_conflicts(root, branch_of(a), branch_of(b))
        if clash:
            found += 1
            print(f"CONFLICT {a['id']} <-> {b['id']}: {', '.join(clash)}")
        elif shared:
            print(f"warn     {a['id']} <-> {b['id']}: same files, merges clean: {', '.join(sorted(shared))}")
        else:
            print(f"ok       {a['id']} <-> {b['id']}")
    return 1 if found else 0
```

The report has three levels on purpose. A pair prints `CONFLICT` when git cannot merge it cleanly. It prints `warn` when both branches touched the same file but git merged the edits without trouble, which usually means two agents changed different functions in one module. That is legal, but a human should read the result because clean textual merges can still be wrong logically. Everything else prints `ok`.

### Step 7: Add merge, down and the entry point

The last block assembles clean work and tears everything down. `merge` creates an integration branch in its own temporary worktree, so your main checkout never moves. It merges each task branch with `--no-ff` to keep one merge commit per agent, which makes later reverts easy. When a merge fails, it runs `git merge --abort` and records the task as skipped. Tasks with zero commits get their own label so an empty branch never masquerades as merged work.

``` python
def cmd_merge(cfg, root, args):
    integ = (root / cfg["worktree_dir"] / "_integration").resolve()
    git("worktree", "add", "-b", args.branch, str(integ), cfg["base"], cwd=root)
    merged, skipped, empty = [], [], []
    for task in cfg["tasks"]:
        if not wt_path(root, cfg, task).exists():
            continue
        ahead = git("rev-list", "--count", f"{cfg['base']}..{branch_of(task)}", cwd=root).stdout.strip()
        if ahead == "0":
            empty.append(task["id"])
            continue
        proc = git("merge", "--no-ff", "-m", f"merge {branch_of(task)}", branch_of(task), cwd=integ, check=False)
        if proc.returncode == 0:
            merged.append(task["id"])
        else:
            git("merge", "--abort", cwd=integ, check=False)
            skipped.append(task["id"])
    print(f"integration branch: {args.branch}")
    print(f"merged:  {', '.join(merged) or '-'}")
    print(f"skipped: {', '.join(skipped) or '-'}")
    print(f"no commits: {', '.join(empty) or '-'}")
    return 1 if skipped else 0

def cmd_down(cfg, root, args):
    for task in cfg["tasks"] + [{"id": "_integration"}]:
        path = wt_path(root, cfg, task)
        if not path.exists():
            continue
        dirty = git("status", "--porcelain", cwd=path).stdout.strip()
        if dirty and not args.force:
            print(f"keep   {task['id']}: uncommitted changes (use --force)")
            continue
        git("worktree", "remove", "--force", str(path), cwd=root)
        branch = args.branch if task["id"] == "_integration" else branch_of(task)
        flag = "-D" if args.force else "-d"
        res = git("branch", flag, branch, cwd=root, check=False)
        state = "removed" if res.returncode == 0 else "worktree removed, branch kept"
        print(f"{state:<30} {task['id']}")
    git("worktree", "prune", cwd=root)
    return 0

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", default="fleet.json")
    sub = parser.add_subparsers(dest="cmd", required=True)
    for name in ("plan", "up", "status", "conflicts"):
        sub.add_parser(name)
    merge = sub.add_parser("merge")
    merge.add_argument("--branch", default="fleet/integration")
    down = sub.add_parser("down")
    down.add_argument("--force", action="store_true")
    down.add_argument("--branch", default="fleet/integration")
    args = parser.parse_args()
    root = repo_root()
    cfg = load_config(root / args.config)
    handler = {"plan": cmd_plan, "up": cmd_up, "status": cmd_status,
               "conflicts": cmd_conflicts, "merge": cmd_merge, "down": cmd_down}[args.cmd]
    sys.exit(handler(cfg, root, args))

if __name__ == "__main__":
    main()
```

The `down` command is deliberately cautious. It refuses to remove a worktree that has uncommitted changes unless you pass `--force`. It deletes a branch with `git branch -d`, which Git itself refuses for unmerged work, so finished-but-unmerged branches survive cleanup. Only `--force` switches to `-D`. Save the file and run `python3 agentfleet.py --help` to confirm all six subcommands appear.

## Phase 3: Launch Cursor Agents in Worktrees (Steps 8-9)

### Step 8: Run plan, then up

Commit the script and config so the base branch contains them, then run the dry run first. Making the plan step a habit pays off the first time you reuse a path by mistake. To see it fail, change the `cart-tax` paths to `["src/cart/cart.py"]` and run it. The tool flags the pair before any agent starts, and the exit code of 1 lets you wire it into a script or a CI job.

``` bash
$ python3 agentfleet.py plan
cart-discount    src/cart/
auth-tests       tests/auth/, src/auth/
docs-refresh     docs/
cart-tax         src/cart/cart.py

OVERLAP in declared paths:
  cart-discount <-> cart-tax
```

Restore the original `src/tax/` path, commit, and run the plan again. This time it ends with `no declared path overlaps`. Now create the worktrees.

``` bash
$ python3 agentfleet.py up
ready  cart-discount    /tmp/fleet-demo/fleet-worktrees/cart-discount
ready  auth-tests       /tmp/fleet-demo/fleet-worktrees/auth-tests
ready  docs-refresh     /tmp/fleet-demo/fleet-worktrees/docs-refresh
ready  cart-tax         /tmp/fleet-demo/fleet-worktrees/cart-tax
```

You now have four sibling folders, each on its own `agent/<id>` branch, plus four `.prompt.md` files next to them. Run `git worktree list` to see all of them registered against the one repository. If a path already exists, `up` prints `skip` and leaves it alone, so rerunning the command after adding a fifth task is safe.

### Step 9: Open each worktree in Cursor and brief the agent

Open the Agents Window from the command palette and start one agent per worktree folder. Paste the matching prompt from its `.prompt.md` file and add two standing instructions that save you pain later: commit when the task is done, and do not edit files outside the declared paths. If you prefer Cursor’s native flow, create the worktree from the Agents Window or with the `/worktree` command and point `agentfleet` at the same branches by naming tasks to match. A [custom MCP server](https://shattered.io/build-cursor-mcp-server-python-12-steps-2026/) configured at user level is visible in every worktree, so tools you rely on follow the agent into each folder.

Model choice is a cheap lever here. Cursor’s release notes list Claude Sonnet 5.5 as available and Claude Haiku 5.5 as an opt-in model you turn on under Cursor Settings and Models. A docs task rarely needs your strongest model, so match the model to the job and save the expensive one for the cart logic. Cloud agents bill at the selected model’s API rate with no separate VM or memory fee, per Cursor’s own pricing material, so the same rule applies there.

No Cursor install handy, or want a deterministic run for testing? Simulate the four agents with plain shell commands. Each block below does what a finished agent does: edits files and commits. The docs agent edits but never commits, on purpose, to exercise the dirty-tree handling later.

``` python
W=/tmp/fleet-demo/fleet-worktrees

(cd $W/cart-discount && \
 printf 'def total(items, discount=0):\n    return sum(i["price"] for i in items) * (1 - discount)\n' > src/cart/cart.py && \
 git add -A && git commit -qm discount)

(cd $W/cart-tax && \
 printf 'def total(items, tax=0.08):\n    return sum(i["price"] for i in items) * (1 + tax)\n' > src/cart/cart.py && \
 git add -A && git commit -qm tax)

(cd $W/auth-tests && \
 printf 'def test_bad_login():\n    assert True\n' >> tests/auth/test_login.py && \
 git add -A && git commit -qm tests)

(cd $W/docs-refresh && printf '# Shop\n\nVersion 2\n' > docs/README.md)
```

Notice what the simulated `cart-tax` agent did. Its declared path was `src/tax/`, yet it edited `src/cart/cart.py` anyway. Real agents do exactly this when a task is easier to finish by touching a neighbor’s file. Declared paths are a plan, not a fence, which is why the next phase checks actual diffs.

## Phase 4: Check Conflicts, Merge and Clean Up (Steps 10-12)

### Step 10: Read status and run the conflict check

Status gives the quick view. Three of the four agents committed one change each. The docs agent shows zero commits ahead and one dirty entry, which tells you it wrote a file and never saved it to git.

``` bash
$ python3 agentfleet.py status
task             ahead files dirty
cart-discount        1     1     0
auth-tests           1     1     0
docs-refresh         0     0     1
cart-tax             1     1     0
```

Now ask git whether every pair can merge. The trailing `exit=1` line in the output comes from the shell, added by running `echo exit=$?` right after the command, and it shows the non-zero exit code a script or CI job would see. The tool tests six pairs from four branches and finds the one collision you expected, since two agents rewrote the same line of the same function.

``` php
$ python3 agentfleet.py conflicts
ok       cart-discount <-> auth-tests
ok       cart-discount <-> docs-refresh
CONFLICT cart-discount <-> cart-tax: src/cart/cart.py
ok       auth-tests <-> docs-refresh
ok       auth-tests <-> cart-tax
ok       docs-refresh <-> cart-tax
exit=1
```

At this point you have options. Ask one of the two cart agents to rebase onto the other’s branch and resolve the clash itself, merge them by hand, or drop one. Sequencing is usually best: land the discount first, then have the tax agent rebase and re-apply its change on top. Either way you decided with full information instead of discovering the clash in the middle of a merge.

### Step 11: Merge the clean branches

Run the merge command. It builds `fleet/integration` in its own worktree and walks the tasks in file order.

``` bash
$ python3 agentfleet.py merge
integration branch: fleet/integration
merged:  cart-discount, auth-tests
skipped: cart-tax
no commits: docs-refresh
exit=1
```

The exit code is 1 because one task was skipped, which is what you want from a gate. Two branches merged cleanly, `cart-tax` was skipped for the conflict you already saw and `docs-refresh` was reported as having no commits instead of counted as merged. Inspect the result with `git log --oneline --graph fleet/integration`. You get one merge commit per agent, each pointing back to its own task branch. The same exit-code contract works in automation, and the [Cursor CLI in GitHub Actions walkthrough](https://shattered.io/cursor-cli-github-actions-headless-agent-2026/) shows how to run a headless agent step before a gate like this one.

### Step 12: Tear the fleet down safely

Cleanup runs in two passes. The first respects your uncommitted work, and the second forces the issue once you have decided that work is disposable.

``` bash
$ python3 agentfleet.py down
worktree removed, branch kept  cart-discount
worktree removed, branch kept  auth-tests
keep   docs-refresh: uncommitted changes (use --force)
worktree removed, branch kept  cart-tax
worktree removed, branch kept  _integration

$ python3 agentfleet.py down --force
removed                        docs-refresh
```

Every unmerged branch is still there, so no agent output disappeared. Merge `fleet/integration` into `main` when you are satisfied, then delete the leftovers with `git branch -D`. The folders are gone, the registry is pruned and your repository is back to a single checkout.

## Complete Working Project and Smoke Test

The finished project is three files in the repository root: `agentfleet.py` (the four code blocks from Steps 4 to 7 joined in order), `fleet.json` and a test file. There is no `requirements.txt` because nothing outside the standard library is imported. A small unit test file covers the pure functions, the ones that need no git repository, so it runs in milliseconds.

``` python
import tempfile
import unittest
from pathlib import Path

from agentfleet import ID_RE, load_config, paths_overlap

class OverlapTests(unittest.TestCase):
    def test_nested_paths_overlap(self):
        self.assertTrue(paths_overlap(["src/cart/"], ["src/cart/cart.py"]))

    def test_sibling_paths_do_not_overlap(self):
        self.assertFalse(paths_overlap(["src/cart/"], ["src/cartography/"]))

    def test_slash_style_is_ignored(self):
        self.assertTrue(paths_overlap(["docs"], ["docs/"]))

class ConfigTests(unittest.TestCase):
    def test_bad_ids_are_rejected(self):
        for bad in ["Auth", "a", "x y", "-lead", "a/b"]:
            self.assertIsNone(ID_RE.match(bad), bad)

    def test_duplicate_ids_exit(self):
        with tempfile.TemporaryDirectory() as tmp:
            cfg = Path(tmp) / "fleet.json"
            cfg.write_text('{"tasks":[{"id":"aa","paths":["x"],"prompt":"p"},'
                           '{"id":"aa","paths":["y"],"prompt":"p"}]}')
            with self.assertRaises(SystemExit):
                load_config(cfg)

if __name__ == "__main__":
    unittest.main()
```

Run it with `python3 -m unittest -v`. The expected result is five passing tests in about a millisecond, ending with `OK`. The tests pin the three behaviors most likely to regress: the trailing-slash rule, the id pattern and duplicate-id rejection.

```
test_bad_ids_are_rejected (test_agentfleet.ConfigTests.test_bad_ids_are_rejected) ... ok
test_duplicate_ids_exit (test_agentfleet.ConfigTests.test_duplicate_ids_exit) ... ok
test_nested_paths_overlap (test_agentfleet.OverlapTests.test_nested_paths_overlap) ... ok
test_sibling_paths_do_not_overlap (test_agentfleet.OverlapTests.test_sibling_paths_do_not_overlap) ... ok
test_slash_style_is_ignored (test_agentfleet.OverlapTests.test_slash_style_is_ignored) ... ok

Ran 5 tests in 0.001s

OK
```

For an end-to-end check, save the demo setup and the simulated agents as one shell script and run it after any change to the tool. The full run takes a couple of seconds and ends with the exact output shown in the steps above. If a later edit changes a line of that output, you have caught a behavior change before it reached a real repository. Keep the script outside the repository you are testing, since it recreates the demo folder from scratch every time.

``` bash
#!/bin/sh
set -e
cd /tmp/fleet-demo && rm -rf shop fleet-worktrees && mkdir shop && cd shop
git init -q -b main . && git config user.email [email protected] && git config user.name t
mkdir -p src/cart src/auth tests/auth docs
printf 'def total(items):\n    return sum(i["price"] for i in items)\n' > src/cart/cart.py
printf 'def login(user):\n    return True\n' > src/auth/login.py
printf 'def test_login():\n    assert True\n' > tests/auth/test_login.py
printf '# Shop\n\nVersion 1\n' > docs/README.md
cp ../agentfleet.py ../fleet.json .
git add -A && git commit -qm init

python3 agentfleet.py plan
python3 agentfleet.py up
# ... simulated agent commits from Step 9 go here ...
python3 agentfleet.py status
python3 agentfleet.py conflicts || echo "exit=$?"
python3 agentfleet.py merge || echo "exit=$?"
python3 agentfleet.py down
python3 agentfleet.py down --force
```

## How to Read the Output

The tool prints short labels on purpose, because you will scan them while an agent is still typing in another window. Each label maps to a decision, and the table below spells out which one. Treat the labels as a triage list rather than a verdict. A clean result from `conflicts` means git can combine two branches without human help. It does not mean the combined code works.

| Label | Command | Meaning | What you do next | 
|---|---|---|---|
| `ok` | conflicts | Branches share no changed files | Safe to merge in any order | 
| `warn` | conflicts | Same file touched, git merged it cleanly | Read the combined file before merging | 
| `CONFLICT` | conflicts | Git cannot merge the pair, file names listed | Sequence the branches or ask one agent to rebase | 
| `skipped` | merge | Merge aborted for that task | Resolve by hand, rerun on a fresh integration branch | 
| `no commits` | merge | Branch has nothing ahead of base | Ask the agent to commit, or check its dirty count | 
| `keep` | down | Worktree has uncommitted changes | Commit, or rerun with `--force` | 
| `OVERLAP` | plan | Two tasks declare nested paths | Split the tasks differently before launching | 

The `ahead`, `files` and `dirty` columns in status work as a progress gauge. A task with zero ahead and a growing dirty count is mid-work. A task with one or two commits ahead and a clean tree is probably done. A task with many files changed on a prompt that should touch two is drifting, and the right move is to read its diff now instead of after it finishes.

## Common Pitfalls With Parallel Cursor Agents

Parallel work goes wrong in predictable ways. These six pitfalls account for most of the cleanup sessions people describe after their first week with several agents running.

1. **Splitting tasks by feature instead of by file.** Adding discounts and adding tax sound independent, yet both land in the same total function. Split by the files each task must touch, then name the feature. If two tasks need one file, they are one task or they run in sequence.
2. **Trusting the pairwise check as proof.** Branches A and B can merge cleanly, B and C can merge cleanly, and A plus B plus C can still conflict because the first merge changes the context of the third. The`merge` command catches this because it merges in order, so always run it before declaring victory.
3. **Forgetting that agents must commit.** Uncommitted work lives only in the worktree. The merge step cannot see it, and`down` without`--force` keeps the folder for exactly this reason. Put the commit instruction into every prompt.
4. **Letting worktrees age.** A branch forked at Monday’s base is a stranger by Thursday if the base moved. Conflicts grow with the distance between fork and merge, so keep fleet runs short and merge often.
5. **Skipping setup inside the new folder.** A worktree starts with tracked files only. Untracked material such as`node_modules` , virtual environments and`.env` files does not come along, and agents burn time failing tests that pass in your main checkout.
6. **Merging agent branches straight into main.** The integration branch exists as a buffer. Run your test suite on it, read the combined diff and only then fast-forward or merge into the base.
7. **Running `agentfleet` from inside a worktree.** The tool locates the repository with`git rev-parse --show-toplevel` , which resolves to the current worktree’s folder. Run it from the main checkout so paths and config resolve to the right place.

Lockfiles deserve their own warning. Files like `package-lock.json` or `poetry.lock` change whenever any agent adds a dependency, and they conflict in ways no one can resolve by reading. Assign dependency changes to a single task, or regenerate the lockfile after merging instead of trying to merge it.

## Troubleshooting: 12 Problems and Fixes

Each item lists the symptom you will see, the cause and the fix. Most failures trace back to leftover state from an earlier run, so the first habit to build is running `down` before you start a new fleet.

1. **Symptom: `a branch named 'agent/cart-tax' already exists`.** Cause: a previous run kept the branch because it was unmerged. Fix: delete it with`git branch -D agent/cart-tax` if the work is disposable, or rename the task id to start a fresh line of work.
2. **Symptom: `fatal: '...' already exists` on `up`.** Cause: the target folder is still on disk. The tool prints`skip` for folders it finds, but a folder that is not a registered worktree can still block git. Fix: inspect it, remove it and run`git worktree prune` .
3. **Symptom: the conflict check reports an unknown option error for `write-tree`.** Cause: Git is older than 2.38. Fix: upgrade Git and rerun, since the in-memory merge mode does not exist in older releases.
4. **Symptom: `git worktree list` shows a path marked prunable or missing.** Cause: you moved or deleted the folder by hand. Fix: run`git worktree prune` to forget it, or`git worktree repair` from the main checkout if you moved the folder and want to keep it.
5. **Symptom: `fatal: 'agent/docs-refresh' is already checked out`.** Cause: Git allows a branch to be checked out in only one worktree at a time. Fix: pick a different branch name, or remove the other worktree first.
6. **Symptom: no red squiggles or go-to-definition in an agent’s window.** Cause: Cursor disables language servers by default in Agents Window worktree workspaces for performance. Fix: re-enable them in the window’s settings if you need diagnostics there.
7. **Symptom: tests fail in the new worktree but pass in the main checkout.** Cause: untracked files like`.env` , local databases or installed dependencies did not carry over. Fix: copy or recreate them in each worktree as part of the task prompt or a setup script.
8. **Symptom: an agent’s edits show up in the wrong folder.** Cause: the agent was opened on the main checkout, or a prompt used absolute paths. Fix: open the worktree folder itself as the workspace root and use relative paths in prompts. Forum users have also reported agents mixing up chats when several worktrees are created in quick succession, so start them one at a time.
9. **Symptom: two dev servers crash with an address already in use error.** Cause: every worktree uses the same default port. Fix: give each task its own port through an environment variable in its prompt, such as 3001 for the first agent and 3002 for the second.
10. **Symptom: `merge` fails with a branch or path error on the second run.** Cause:`fleet/integration` and the`_integration` folder survived the last run. Fix: run`down` , then`git branch -D fleet/integration` , or pass a different`--branch` name.
11. **Symptom: `conflicts` says `ok` yet `merge` skips a task.** Cause: three-way interactions that pairwise checks cannot see, covered in the pitfalls above. Fix: treat`merge` as the authority and sequence the offending branches.
12. **Symptom: a submodule folder is empty in the new worktree.** Cause: worktrees do not initialize submodules automatically. Fix: run`git submodule update --init` inside the worktree before the agent starts.

## Advanced Tips for Bigger Fleets

Once the basic loop works, five upgrades turn it into a dependable workflow. None needs new infrastructure, and each one removes a manual check you would otherwise repeat on every run.

### Guard the declared paths with hooks

Declared paths only help if something enforces them. A pre-edit check that rejects writes outside a task’s folder turns the plan into a fence, and [Cursor hooks](https://shattered.io/cursor-hooks-tutorial-guard-agent-12-steps-2026/) are the natural place to build it. Pair that with a post-run comparison of `changed_files()` against the declared paths, and flag any file that falls outside them. In the demo, that check would have flagged `cart-tax` touching `src/cart/cart.py` long before the conflict run.

### Script the launch with the SDK

Pasting prompts by hand works for four agents and gets tedious at ten. Cursor has released an Agent SDK, and the [Cursor SDK tutorial](https://shattered.io/cursor-sdk-tutorial-typescript-review-agent-12-steps-2026/) shows how to start runs from code, which lets a loop over `fleet.json` launch one agent per worktree without touching the UI.

### Move long jobs to the cloud, then pull them back

Local worktrees suit tasks you want to watch. For long jobs, start the agent in the cloud so it keeps working while your laptop sleeps, then use the handoff described in the version 3.24 release notes to continue the branch in an existing or new local worktree without disturbing your main checkout. Cloud agents carry no separate VM or memory fee and bill at the chosen model’s API rate, and the official Teams page says Teams plans include at least $20 per seat per month in agent usage, with usage beyond that billed on demand.

Add a conflict gate to review automation. The `conflicts` and `merge` commands already return non-zero on trouble, so a CI job can call them on a runner after agents push their branches. Because the check works from branch names alone, the job needs only a clone with all `agent/*` branches fetched. Keep the integration branch as an artifact for reviewers rather than merging anything automatically.

Finally, keep tasks small. A fleet of six agents that each change one or two files merges cleanly almost every time. A fleet of three agents that each reshape a module does not. If a task prompt needs more than a paragraph to describe, split it, and use the plan step to prove the pieces do not overlap.

## Worktrees vs Clones vs Cloud Agents: Which Isolation Fits

Worktrees are not the only way to keep agents apart, and for some jobs they are the wrong choice. The comparison below uses qualitative terms because the real cost depends on your repository size and your network. The deciding question is how much of the machine the task needs to itself.

| Approach | Setup effort | Disk use | Shared history | Best fit | 
|---|---|---|---|---|
| One checkout, branch switching | None | Lowest | Yes | One agent at a time | 
| Git worktree per agent | One command each | One working tree per agent | Yes, one object store | Parallel tasks in one repository | 
| Full clone per agent | Clone and fetch | Full history per agent | No, separate stores | Fully independent experiments | 
| Cloud agent | Launch from web or editor | None locally | Remote clone | Long jobs and multi-repo work | 

Worktrees win for the common case. They start in seconds, share history so branches compare cheaply and let `merge-tree` test combinations without any checkout. Their weakness is that they share the repository’s hooks and config, so a misbehaving hook affects every agent at once. Full clones isolate even that, at the price of duplicated history and slower setup.

Cloud agents solve a different problem. They free your machine and your attention, and they reach multiple repositories at once. A 2026 [overview of Cursor’s history and feature set](https://nhimg.org/cursor-ai-editor-guide) describes Cursor 3 as a single workspace that shows local and cloud agents side by side, which is the model this tutorial assumes. If you are weighing Cursor against another editor for agent-heavy work, the [Windsurf vs Cursor comparison](https://shattered.io/windsurf-vs-cursor-devin-desktop-rename-40-seat-2026/) covers seats and positioning, and the wider [coding and developer tools hub](https://shattered.io/category/software/) collects the rest of the series.

## Review Checklist Before Merging Agent Branches

Passing the conflict gate is the start of review, not the end. Agents write plausible code that compiles and still does the wrong thing, so a short routine on the integration branch catches the rest. Run it every time, including when only one agent contributed.

- Run the full test suite on `fleet/integration` , not on each branch alone, because combined behavior is what ships.
- Read every `warn` pair’s merged file in full. Two correct edits to one module can disagree about a shared assumption.
- Compare each branch’s changed files to its declared paths and question every file outside them.
- Check lockfiles, generated files and configuration for accidental changes, since these hide in large diffs.
- Confirm each merge commit maps to exactly one task so a bad change reverts with a single command.
- Delete leftover branches only after the integration branch lands, never before.

Over time, the plan step and tighter task splits should prevent problems upstream, so the merge gate catches less. That is the goal. A quiet `conflicts` run means your task design is working.

## FAQ

### Can Cursor agents run in parallel without worktrees?

Yes, but they share one set of files, so edits collide and one agent’s staging can sweep in another’s half-finished work. Worktrees, cloud sandboxes or remote machines give each agent its own folder, which is why Cursor’s Agents Window offers those modes.

### How many cursor agents can I run at once?

Cursor does not publish a fixed local limit that this article could confirm, so treat any number you see online with caution. The practical ceiling is your machine, your plan’s usage allowance and how many tasks you can review. Start with three or four and raise it only when merges stay clean.

### Do worktrees copy my whole repository?

Each worktree checks out a full working tree of tracked files, but the commit history lives once in the main repository’s object store. Disk cost therefore scales with the size of your files, not with the length of your history.

### What happens if two agents edit the same file?

Inside separate worktrees nothing breaks while they work. The collision appears at merge time. If they changed different regions, git combines the edits and the tool prints a warning. If they changed the same lines, the tool reports a conflict and the merge step skips that branch.

### Does this work with cloud agents?

The conflict and merge steps work on any branch you can fetch, including branches that cloud agents push. Cloud agents run in remote sandboxes, so they do not need a local worktree, though the version 3.24 handoff lets you continue one inside a local worktree.

### Where does Cursor store its own worktrees?

Community reports point to `~/.cursor/worktrees`, but Cursor has not documented the location in a release note we could verify. Run `git worktree list` from your repository to see the real paths on your machine.

### Is the conflict check safe to run while agents are working?

Yes. `git merge-tree --write-tree` merges in memory and never touches a working directory, so it cannot disturb an agent’s files. It only sees committed work, though, so results lag behind uncommitted edits.

### Can I use the same setup with another AI editor?

Yes. The tool talks only to git, so any agent that edits files inside a folder and commits can use it. You lose the Agents Window conveniences but keep the plan, conflict and merge gates.
