Last reviewed: 2026-06-03

Direct answer

When two or more coding agents work on the same repository at the same time, they need separate working directories, separate branches, and a handoff protocol that prevents them from silently overwriting each other’s output.

Git worktrees solve the directory isolation problem. Each git worktree add call checks out a branch into a new directory on disk without cloning the repository again. The agents share the same object store, so they see each other’s committed objects, but they each write to a different working tree and HEAD. The handoff problem — making sure an agent’s output reaches a human reviewer or another agent in a reviewable, traceable state — is solved by treating every agent output as a pull request, not a direct push to a shared branch.

The workflow in one sentence: each agent gets a worktree on its own branch, it commits there, opens a PR when the scope is done, and the next agent or human reviewer picks up from that PR rather than from a shared working directory.

If your agents call a model gateway, verify the base URL, authentication header name, and endpoint path in your gateway’s current documentation before committing any environment file. The exact fields vary by provider. Start with CometAPI if you want a single gateway that your whole agent team can share without each agent carrying its own provider credentials.


For broader release checks, see AI Coding Agent Setup, Security, and Model Routing .

Who this is for

This guide is for engineers who:

  • Run two or more AI coding agents (Codex, Claude Code, Cursor Agent, or similar tools) against the same repository simultaneously.
  • Want each agent to produce a clean, reviewable diff rather than a tangled shared-branch commit history.
  • Are setting up a handoff protocol so a human or a second agent can pick up where the first one left off without re-reading the full change set.
  • Already understand basic git branching and want the worktree-specific additions.

If you are still setting up a single agent for the first time, start with Use Git Worktrees to Keep Parallel Coding Agents Isolated before returning here for the team handoff layer.


Key takeaways

  • git worktree add gives each agent a private working directory on its own branch without a full clone.
  • Never assign two agents to the same worktree path or the same branch at the same time — collisions are not caught at the git level until a push or merge.
  • A handoff is complete only when the agent has committed its changes, pushed the branch, and opened a PR that a reviewer or the next agent can act on independently.
  • Instruction files (AGENTS.md, CLAUDE.md, or equivalent) must be scoped to the worktree’s branch context so agents do not inherit stale rules from a different task.
  • Worktrees are temporary by design: remove them with git worktree remove after the PR is merged to avoid stale checkout directories accumulating on disk.
  • A model gateway shared across agents should be configured once at the team level, not per-agent, to prevent each agent from carrying different endpoint assumptions.

Setting up worktrees for a parallel agent team

1. Create a worktree per agent task

From the main repository root:

sh

Agent A works on feature-auth

git worktree add ../repo-agent-a feature/agent-a-auth

Agent B works on feature-logging in parallel

git worktree add ../repo-agent-b feature/agent-b-logging

Each path (../repo-agent-a, ../repo-agent-b) is a full working tree. The agent process is pointed at that directory. It sees only its own branch HEAD.

Verify the worktree list at any time:

sh git worktree list

Sample output:

/home/user/repo abc1234 [main] /home/user/repo-agent-a def5678 [feature/agent-a-auth] /home/user/repo-agent-b ghi9012 [feature/agent-b-logging]

2. Place instruction files in the branch, not only main

If your agent runtime reads an AGENTS.md or CLAUDE.md file, that file must be present on the agent’s branch with rules relevant to that task. A common mistake is to keep the instruction file only on main and expect agents on feature branches to inherit it. Claude Code reads memory files from the working directory, so the file must exist in the worktree path the agent uses. Verify current memory-file discovery behavior in the Claude Code memory documentation before assuming a global file is always read.

3. Commit scope discipline

Each agent should commit only files within the scope of its task brief. Cross-scope commits (Agent A modifying logging files it was not assigned) create merge conflicts and reviewer confusion. A short AGENTS.md task-scope stanza at the top of the branch’s instruction file helps enforce this:

markdown

Scope

This agent may only modify files under src/auth/. Do not touch src/logging/.

OpenAI Codex reads AGENTS.md for repository-level instructions. Verify which instruction file your specific agent runtime reads before writing scope rules — tool behavior varies and documentation for each tool should be consulted directly.


The handoff protocol

A handoff is the moment one agent (or human) passes responsibility for a change set to another agent or reviewer. The handoff must be atomic and traceable.

Handoff checklist before opening a PR

  1. All staged changes committed to the agent’s branch.
  2. Branch pushed to remote (git push origin feature/agent-a-auth).
  3. PR opened with:
    • A description of what was changed and why.
    • Any open questions or follow-up tasks flagged explicitly (not left as TODO comments in code).
    • CI status visible (green or known-failing with explanation).
  4. The next agent or reviewer is linked or assigned in the PR.

The GitHub pull requests documentation covers the PR lifecycle and review-request mechanics. Verify the current review-request field names in that documentation — the UI and API fields have changed across GitHub releases.

What a handoff PR description should include

What this agent did

[Short summary of the change, 2-4 sentences]

Scope boundaries respected

[List the directories or files touched]

Tests run

[Command, exit code, and summary]

Open questions for the next reviewer

[Numbered list — empty means none]

Files not touched (intentionally out of scope)

[List any files the reviewer might expect to see changed but weren’t]

This format gives a downstream agent or human reviewer enough context to pick up without re-reading the full diff.

Passing context between agents

When Agent B needs to build on Agent A’s work before the PR is merged:

  1. Agent B creates its worktree from Agent A’s branch, not from main: sh git worktree add ../repo-agent-b feature/agent-a-auth

    Then create a new branch from there:

    cd ../repo-agent-b git checkout -b feature/agent-b-logging

  2. Agent B’s instruction file references Agent A’s PR number as the upstream dependency.

  3. When Agent A’s PR merges, Agent B rebases onto main before opening its own PR.

This avoids long-lived stacked branches accumulating divergence.


Smoke-test workflow

Setup assumption: You have a repository with two worktrees checked out, each on its own branch, and a shared model gateway configured via environment variable.

Happy-path request plan:

  1. In worktree A, run the agent on its assigned task.
  2. Agent commits output to feature/agent-a-auth.
  3. Push branch and open a draft PR.
  4. In worktree B, run the second agent on a non-overlapping file set.
  5. Agent B commits and pushes to feature/agent-b-logging.
  6. Open both PRs; verify no shared files appear in both diffs.

Error-path check:

  • Attempt to add a second worktree using the same branch name as an existing worktree. Git should refuse with an error indicating the branch is already checked out. If it does not refuse, the git version or worktree configuration should be investigated.
  • Attempt to commit a file outside the declared scope from Agent A’s worktree. The commit will succeed locally (git does not enforce scope), so verify that your CI lint or review step catches the violation.

Minimum assertions:

  • git worktree list shows at least two entries beyond main.
  • Each PR diff contains only files from its declared scope directory.
  • CI passes or the failure is explicitly explained in the PR description.
  • No merge conflicts exist between the two feature branches when diffed against main.

What this smoke test must not assert:

  • That a specific model responded correctly (model behavior is not a worktree concern).
  • That the gateway’s rate limit or cost budget was not exceeded (those are gateway concerns, not worktree concerns).
  • That the PR was automatically merged (human or policy gate decides that).

Log record template (fill in placeholders after each run):

date: YYYY-MM-DD worktree_a_branch: feature/ worktree_b_branch: feature/ worktrees_isolated: true|false scope_violations_detected: true|false ci_status_a: pass|fail|skipped ci_status_b: pass|fail|skipped pr_a_url: https://github.com/ //pull/ pr_b_url: https://github.com/ //pull/ open_questions_flagged: true|false notes:

Do not log real credentials, generated responses, cost figures, or user data in this record.


Cleaning up after a merge

After a PR merges, remove the worktree and delete the remote branch:

sh git worktree remove ../repo-agent-a git push origin –delete feature/agent-a-auth

If git worktree remove refuses because the worktree has uncommitted changes, use –force only after confirming the PR captured everything:

sh git worktree remove –force ../repo-agent-a

Leaving stale worktrees on disk does not corrupt the repository, but it creates confusion about which directories are active agent workspaces. A short convention — for example, all agent worktrees live under ~/agent-worktrees/ and are removed within 24 hours of PR merge — prevents accumulation.

For teams managing many agents, a nightly git worktree prune in CI removes references to worktrees that were deleted outside of git’s tracking. Verify the current prune behavior in the git-worktree reference documentation before adding it to an automated job.


Failure modes

  • Evidence gap: the agent cannot inspect the failing log, source page, pull request, or local command output. The safe action is to stop and record the missing evidence instead of guessing.
  • Scope drift: the agent edits files that are not connected to the observed failure. Keep the repair tied to the failing signal and leave unrelated cleanup for a separate task.
  • Environment mismatch: the local check uses different versions, credentials, feature flags, or runtime settings than the hosted path. Record the mismatch before treating the result as proof.
  • Unreviewed fallback: the agent changes models, endpoints, permissions, or retry behavior to make a run pass without preserving the review boundary. Treat access and provider failures as operational blockers, not topic failures.
  • Weak handoff: the final note says the issue is fixed but omits the command, result, changed files, and remaining uncertainty. That makes the next operator repeat the investigation.

Sources checked

Contract details to verify

AreaWhat to verifySource URLAccessedSafe candidate wording
git worktree add optionsConfirm –lock flag behavior and supported options in your installed git versionhttps://git-scm.com/docs/git-worktree2026-06-03“Refer to git worktree –help for options available in your git version”
git worktree pruneConfirm prune removes stale admin files only, not committed historyhttps://git-scm.com/docs/git-worktree2026-06-03“Run git worktree prune to clean up stale references; verify behavior in your git version”
AGENTS.md discovery pathConfirm Codex reads AGENTS.md from worktree root vs. repo root in current releasehttps://github.com/openai/codex/blob/main/docs/agents_md.md2026-06-03“Verify AGENTS.md placement with the current Codex docs before relying on branch-scoped rules”
CLAUDE.md / memory file pathConfirm Claude Code reads memory files from the active worktree directory in current releasehttps://code.claude.com/docs/en/memory2026-06-03“Verify memory file discovery path in Claude Code docs before assuming a global file covers all worktrees”
GitHub draft PR API fieldsConfirm draft PR creation field names in current GitHub API versionhttps://docs.github.com/en/pull-requests2026-06-03“Check current GitHub docs for the draft field name before scripting PR creation”
Shared gateway base URLConfirm current base URL and auth header format for your gateway before committing environment fileshttps://apidoc.cometapi.com/2026-06-03“Verify gateway endpoint and auth header in current docs before committing any environment file”

FAQ

Can two agents check out the same branch in different worktrees? No. Git prevents two worktrees from checking out the same branch simultaneously. The second git worktree add call for an already-checked-out branch will fail with an error. Each agent must use its own branch.

Does each worktree need its own .env or credentials file? It depends on how your agent reads configuration. If the agent reads a .env from its working directory, each worktree will need its own file — or you should use environment variables set at the process level rather than file-based config. Do not commit credentials to either file. Verify your agent runtime’s configuration-discovery behavior in its documentation.

What happens to a worktree if the host machine restarts? The worktree directory and its files persist across restarts because they are ordinary directories on disk. The worktree reference in .git/worktrees/ also persists. The agent process that was using the worktree does not restart automatically; you would need to restart it manually or via a process supervisor.

How do I prevent Agent A from accidentally committing files from Agent B’s scope? Git does not enforce scope at commit time. Your options are: (1) write a pre-commit hook that checks touched files against a scope manifest; (2) rely on CI lint or a review gate to catch scope violations before merge; (3) use a task brief that names the exact file paths the agent may touch. Option 3, combined with a review gate, is the lowest-friction approach for most teams.

Should each agent have its own model gateway key? Using a single shared gateway key across agents lets you see aggregate usage in one place and apply budget controls at the team level rather than per-agent. The tradeoff is that one runaway agent can exhaust the shared budget. Verify the key-scoping and budget-control options available in your specific gateway’s current documentation before deciding.

What is the right time to remove a worktree? After the PR is merged and you have confirmed no uncommitted work remains in the worktree directory. Removing it before the PR merges risks losing work if the agent has not committed everything. Run git status inside the worktree before removing it.

Reader next step

Turn the next coding-agent request into a one-page task brief, then compare it with How to Write Repository Instructions for Coding Agents . For the surrounding setup and permission baseline, review AI Coding Agent Setup, Security, and Model Routing before assigning broader repository work.