Toggle Theme

Codex Worktree Guide: Run Multiple AI Coding Tasks Without Polluting Your Repo

"OpenAI Codex Worktrees documentation is used to verify Codex app Worktree behavior, Handoff, .worktreeinclude, Codex-managed worktrees, cleanup policy, and branch limitations."

Three tasks are running in the same repo: fix/auth-expired-session, test/payment-webhook, and docs/setup-node20. The main checkout’s git status is now a pile of unrelated changes: a login bug fix, test fixture files, and a README note about Node 20. All three live in one checkout, so you can no longer tell which change can be committed on its own and which one may affect the others.

That is not an abstract “parallel task” problem. It is what happens when a Git checkout gets polluted. Worktree mode in the Codex app splits tasks into separate directories and branches, so each work line has a diff you can review, merge, or roll back.

Local / Worktree / Cloud: how to choose the right mode

The Codex app supports three running modes. Local and Worktree both run on your computer. The official docs phrase it directly: “Both Local and Worktree threads will run on your computer.” Cloud runs in a remote environment.

ModeWhere it runsWhat it editsBest fitRisk and cost
LocalYour computerThe main checkoutSingle tasks, stable developmentDirectly edits the main directory; unfinished work can pollute it
WorktreeYour computerSeparate directory + branchParallel tasks, experimentsNeeds setup scripts and .worktreeinclude
CloudRemoteCloud environmentCI/CD, remote buildsCovered in a separate article

Worktree mode fits independent parallel tasks or experiments. Each thread has its own directory and branch, so the main checkout stays untouched. Local mode is simple, but once several tasks are mixed together, separating commits becomes painful. Cloud mode leaves your computer entirely and fits CI/CD or remote builds.

The decision rule is simple: use Local for one task, Worktree for parallel or experimental local work, and Cloud for remote work.

How Worktree mode works in the Codex app

Worktree creation and Handoff

The flow for creating a Worktree thread in the Codex app is:

  1. Create a new thread
  2. Choose Worktree mode (the exact UI label may change after 2026-06-18)
  3. Choose a starting branch, or work from detached HEAD by default
  4. Submit the first prompt
  5. Codex starts working in an isolated directory

By default, Codex works from detached HEAD. That lets it continue inside the worktree and create a branch when you need to keep the result. Handoff moves a thread and its code between Local and Worktree.

Handoff scenarios:

Worktree to Local: after the task is complete, create a branch inside the worktree first if it is still on detached HEAD, then use Handoff to move it back to Local, and finally merge it or create a PR.

Local to Worktree: move unfinished work into an isolated environment so it no longer pollutes the main checkout.

Handoff is not just a directory switch. It carries the current thread context, prompt history, and unfinished changes along with it.

What is special about Codex-managed worktrees

Codex-managed worktrees have several behaviors worth remembering:

Default location: $CODEX_HOME/worktrees

Default retention: 15 worktrees, according to the 2026-06-18 docs; older ones may be cleaned up automatically

Permanent worktree: manually created worktrees are not deleted automatically

Branch limitation: Git does not allow the same branch to be checked out in multiple worktrees; trying it will fail

Rule inheritance: AGENTS.override.md is copied into the worktree automatically so project rules stay consistent

The practical meaning: worktree count has a limit, old managed worktrees may be cleaned up, the same branch cannot be used in parallel, and project rules are inherited.

Use .worktreeinclude for ignored files

Worktrees inherit Git tracked files by default. Files listed in .gitignore do not automatically move during Handoff. Common missing items include .env, .env.local, dependency caches, and local config files.

The fix is to create a .worktreeinclude file at the project root and list ignored files that should be copied. Example:

.env
.env.local
node_modules/.cache

With that file in place, ignored files listed there can be copied during Handoff.

Setup scripts: make the project runnable inside a worktree

A worktree lives in a different directory, so it may lack dependencies or files that were never checked in. Setup scripts run when a new worktree or new thread is created, so the environment becomes usable.

Configuration steps:

  1. Configure setup steps in Local environments inside the Codex app
  2. Create a .codex directory for configuration files
  3. Write platform-specific scripts

Node.js project example:

# .codex/setup.sh
npm install
npm run build

Python project example:

# .codex/setup.sh
pip install -r requirements.txt
python manage.py migrate

Setup scripts run for each newly created worktree and reduce manual dependency setup. The app UI and file format may change after 2026-06-18, so check the current docs before relying on exact labels.

Plain Git worktree also works without the Codex app

If you prefer the CLI or terminal path, you can create isolated directories directly with Git worktree and then start Codex inside each directory. You do not need Codex app management, but you do need to manage everything yourself.

Common Git worktree commands:

# Create a new worktree and branch, following the official use-case style
git worktree add ../analysis-highway-eda -b analysis/highway-eda

# Create a new worktree from an existing branch
git worktree add ../task-b existing-branch

# List all worktrees
git worktree list

# Remove a worktree
git worktree remove ../task-a

# Prune stale worktree metadata
git worktree prune

Codex-managed versus plain Git:

CapabilityCodex-managedPlain Git
CreationAutomatic through the app UIgit worktree add
Location management$CODEX_HOME/worktreesManually chosen
Cleanup policyAutomatically keeps 15 worktrees by defaultManual prune
HandoffSwitch inside the appManually cd into the directory
Setup scriptsRun automaticallyConfigure manually

Plain Git worktree fits developers who like the CLI, but you must handle dependency installation, environment setup, and cleanup yourself. Codex-managed worktrees automate more of that work.

Should background automations use worktrees?

Automations in a Git repo can run in the local project or in a dedicated background worktree. The right choice depends on task type and risk.

Decision logic:

Local mode fits one-off tasks and temporary tests. It edits the main checkout directly, so unfinished work can be polluted. If you are editing a file, a background automation may modify the same file.

Worktree mode fits repeated or scheduled tasks. It isolates automation changes from unfinished local work. The automation runs in its own directory and leaves the main checkout alone.

Risk notes:

Automations use the default sandbox settings, which may change after 2026-06-18

Background automations are riskier under full access, so they should use worktrees

Do not run repeated background tasks directly in Local

Use Local for one-off temporary tasks. Use Worktree for repeated tasks and for full-access background work.

Which tasks can run in parallel, and which ones must stay serial

Official use cases suggest splitting different explorations into separate worktrees. In practice, you still need to judge file conflicts and task dependencies.

Parallel task decision table:

Task typeParallel fitWhyRecommendation
Localized bugfix in different modulesGood fitLow file-conflict riskRun several worktrees at once
New feature in an independent componentGood fitModule boundary is clearOne worktree per component
Several edits to the same fileMust be serialMerges will conflictFinish them one by one by priority
Dependent tasksMust be serialThe first task is input for the nextFinish the upstream task first
Documentation updateGood fitUsually touches separate filesCan run beside other tasks

Parallel rules:

Start with two small independent tasks, not five or six at once

Keep the number of tasks around 3-4 to reduce review cost

Give every task a clear verification target

Do not over-parallelize. More parallel tasks mean more review cost and a higher merge-conflict risk.

Task card template: define what each worktree should do

Before starting a worktree, write down the task clearly so it can be verified later.

Task card example:

Goal: "Fix the session expired bug in the auth module"
Context:
  - "The session expires after 30 minutes, but the frontend does not show a prompt"
  - "Relevant files: src/auth/session.js, src/components/AuthProvider.jsx"
Constraints:
  - "Do not change the database schema"
  - "Do not add a new dependency"
Done when:
  - "The frontend shows a prompt when the session expires"
  - "npm test passes"
  - "The login flow is manually tested"

Branch/Worktree: "fix/auth-expired-session"
Verification command: "npm test && npm run lint"

What to fill in:

Goal: describe the outcome in one sentence

Context: provide file, module, and background context

Constraints: define boundaries, including what not to change

Done when: list verifiable completion criteria

Branch/Worktree: use a clear name such as task-type/module-description

Verification command: give a concrete command that can be run

This makes every worktree’s boundary clear. During review, compare the result with Done when.

Merge queue: review, test, and merge one result at a time

After parallel tasks finish, do not pour every result into main at once. Sort them by risk, then review, test, and merge them one by one.

Merge queue steps:

  1. Sort worktrees by risk, starting with the lowest-risk one
  2. For the first worktree:
    • Run the verification command: tests, lint, or both
    • Inspect the diff and confirm the change scope
    • Create a branch if it is still on detached HEAD
    • Review the diff, following your PR review guidelines
  3. Merge into Local or create a PR:
    • Local merge: Handoff back to Local, then merge
    • PR merge: create a PR and wait for CI and review
  4. Repeat the same process for the next worktree
  5. After all tasks finish, merge into the main branch

Verification checklist:

Verification commands pass: tests and lint

Diff check: the changed scope matches the task

Review guidelines: no sensitive files and no hard-coded secrets

CI passes, if available

Manual test flow is complete

Risk notes:

Do not promise that several worktree results will be merged automatically

If several tasks edit the same file, resolve conflicts manually

Keep human review and tests in the loop

The point of a merge queue is to make every work line’s diff reviewable and recoverable, not to submit every change at once.

Troubleshooting checklist

"branch already used by worktree" error

Cause: the branch is already used by another worktree

Fix:

Use git worktree list to see which branches are occupied

Choose a different branch or remove the worktree that is using the branch

The code does not run inside the worktree

Cause: dependencies or config files are missing

Debug steps:

Check whether .env and .env.local exist; they may not have been copied

Check whether dependencies are installed, such as node_modules or venv

Check whether config files are complete

Fix:

Configure .worktreeinclude to copy ignored files

Configure setup scripts to install dependencies automatically

Worktree disk usage grows too much

Cause: frequent automations create many worktrees

Fix:

Archive automation runs you no longer need

Run git worktree prune manually to clean stale worktrees

Check the Codex app worktree retention setting, which may change after 2026-06-18

Agent-created worktrees are out of sync with the UI or thread context

Cause: an agent-created worktree may bypass the app UI

Fix:

Use git worktree list to inspect all worktrees

Check the thread-to-worktree binding manually in the app

Avoid asking the agent to create worktrees automatically; create them from the app UI instead

The core troubleshooting habit is to inspect worktree state first with git worktree list, then handle the specific error.

Cost judgment: parallel tasks can consume quota faster

Parallel tasks are more likely to consume more turns or quota. Each worktree is its own session, and Codex accounts for each session separately.

Cost rules:

Keep parallel task count around 3-4

Start with two independent small tasks to reduce review cost

Give each task a clear verification target to avoid endless iteration

For exact price, quota, and plan details, use a later cost and quota article. This page does not repeat unverified numbers.

Next steps and further reading

Upstream articles:

Codex entry choices: a short introduction to Local / Worktree / Cloud modes

AGENTS.md project rules: how each worktree inherits the same project rules

Run two Codex tasks in parallel with Worktree

Create isolated work lines for two independent Codex tasks, then execute, verify, merge, and clean them up without polluting the main checkout.

⏱️ Estimated time: 45 min

  1. 1

    Step 1: Check the main repo state

    Run `git status` in the main checkout first and make sure any existing changes are explainable, so uncommitted state does not become the shared starting point for several worktrees.
  2. 2

    Step 2: Pick two small independent tasks

    Start with a local bugfix, a test addition, or a documentation update, and write Goal, Context, Constraints, and Done when for each task.
  3. 3

    Step 3: Create a Worktree for each task

    Choose Worktree mode in the Codex app, or run `git worktree add ../project-task-a -b codex/task-a main` manually.
  4. 4

    Step 4: Bring over environment files and dependencies

    Use setup scripts to install dependencies. If ignored local config must be copied, list it explicitly in `.worktreeinclude` and never commit secrets.
  5. 5

    Step 5: Run Codex inside each worktree

    Ask Codex to report the diff, checks it ran, failures, and unverified risks. Do not let several tasks share the same Local checkout.
  6. 6

    Step 6: Review and merge in a queue

    Merge lower-risk docs or tests first, then bugfixes. After each merge, rerun the task's verification command.
  7. 7

    Step 7: Clean up unused worktrees

    Let Codex-managed worktrees follow thread/archive management. For manually created worktrees, use `git worktree remove` and `git worktree prune`.

FAQ

Can Codex run multiple tasks at the same time?
Yes. The Codex app supports parallel threads, and each thread can use Local, Worktree, or Cloud mode. If several tasks will produce unmerged diffs at the same time, Worktree is usually safer than putting all of them in Local.
What is the difference between Local, Worktree, and Cloud in the Codex app?
Local and Worktree both run on your computer. Local edits the current project directory directly. Worktree runs inside an isolated Git worktree. Cloud runs in a remote environment and fits remote repos, background tasks, and PR workflows.
How is Worktree different from opening more terminals or copying the project?
More terminals still share the same working directory and branch. Copying the project creates separate repositories. A Git worktree shares the same repository history while giving each task its own directory and Git state.
Why is .env.local or a dependency missing inside the worktree?
A worktree is created from Git tracked files by default, so files in `.gitignore` and dependency caches may not come along. Use setup scripts to reinstall dependencies, and use `.worktreeinclude` to copy required ignored local config explicitly.
Can several worktrees check out the same branch?
No. Git prevents the same branch from being checked out in multiple worktrees at once, so the same branch reference is not advanced by several working directories. Each worktree should use its own branch or detached HEAD.
Will Codex Worktree automatically merge the results from several agents?
No. Worktree isolates work lines. The final review, tests, merge order, and conflict decisions still belong to the developer.

10 min read · Published on: Jul 4, 2026 · Modified on: Jul 4, 2026

Comments

Sign in with GitHub to leave a comment

Easton BlogEaston Blog