OpenAIintermediate

How to Use Git Worktrees with OpenAI Codex CLI

Complete guide to using Git worktrees with OpenAI Codex CLI for parallel development. Learn project root detection, AGENTS.md behavior, session management across worktrees, and best practices for multi-branch workflows.

15 min readUpdated January 2025

Want us to handle this for you?

Get expert help →

Git worktrees allow you to check out multiple branches of a repository simultaneously in separate directories. When combined with OpenAI Codex CLI, this enables powerful parallel development workflows where you can work on features, fixes, and experiments concurrently with AI assistance.

Prerequisites

Before setting up worktrees with Codex CLI, ensure you have:

  • Git 2.5 or higher (worktrees were introduced in Git 2.5)
  • OpenAI Codex CLI installed and authenticated
  • A Git repository with at least one commit

To verify your Git version:

git --version

To verify Codex CLI is installed:

codex --version

If you need to install Codex CLI, see our installation guide.

Understanding Git Worktrees

A Git worktree is an additional working directory linked to your repository. Unlike cloning, worktrees share the same .git history, branches, and remote configurations.

Key Concepts

ConceptDescription
Main worktreeYour original repository directory
Linked worktreeAdditional working directory for another branch
.git fileIn linked worktrees, a file pointing to the main .git directory
Project rootDirectory containing .git (file or directory)

How Codex CLI Detects Project Root

Codex CLI determines the project root by searching for a .git file or directory. This works correctly in worktrees because:

  1. The main repository has a .git directory
  2. Linked worktrees have a .git file containing a path like gitdir: /path/to/main/.git/worktrees/branch-name

Codex correctly follows this reference to understand the full repository context.

Setting Up Git Worktrees

Step 1: Create Your First Worktree

From your main repository, create a worktree for a new branch:

# Create a new branch and worktree simultaneously
git worktree add ../feature-auth feature/authentication

# Or create a worktree for an existing branch
git worktree add ../hotfix-branch hotfix/security-patch

The path (../feature-auth) can be anywhere on your filesystem, but keeping worktrees as siblings is recommended for organization.

Step 2: Verify Worktree Creation

List all worktrees:

git worktree list

Output example:

/Users/dev/myproject           abc1234 [main]
/Users/dev/feature-auth        def5678 [feature/authentication]
/Users/dev/hotfix-branch       ghi9012 [hotfix/security-patch]

Platform-Specific Setup

macOS

# Create worktree directory structure
mkdir -p ~/worktrees/myproject

# Create worktrees with descriptive paths
git worktree add ~/worktrees/myproject/feature-auth feature/authentication
git worktree add ~/worktrees/myproject/bugfix-login bugfix/login-issue

Windows (PowerShell)

# Create worktree directory structure
New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\worktrees\myproject"

# Create worktrees
git worktree add "$env:USERPROFILE\worktrees\myproject\feature-auth" feature/authentication

Windows (WSL)

# Same as macOS/Linux
mkdir -p ~/worktrees/myproject
git worktree add ~/worktrees/myproject/feature-auth feature/authentication

Linux

# Create worktree structure in home directory
mkdir -p ~/worktrees/myproject
git worktree add ~/worktrees/myproject/feature-auth feature/authentication

# Or use /tmp for temporary experimental worktrees
git worktree add /tmp/experiment-branch experiment/new-approach

AGENTS.md Behavior in Worktrees

Codex CLI uses AGENTS.md files for persistent project instructions. Understanding how these files are discovered in worktrees is essential for effective configuration.

Discovery Order

Codex CLI searches for AGENTS.md files in this order:

  1. Global scope: ~/.codex/AGENTS.md (applies to all projects)
  2. Project scope: Walking from project root to current working directory

Project Root to CWD Walk

If your worktree is at /Users/dev/feature-auth and you run Codex from /Users/dev/feature-auth/src/components, Codex checks:

  1. ~/.codex/AGENTS.md (global)
  2. /Users/dev/feature-auth/AGENTS.md (project root)
  3. /Users/dev/feature-auth/src/AGENTS.md
  4. /Users/dev/feature-auth/src/components/AGENTS.md

All found AGENTS.md files are merged, with more specific files taking precedence.

Worktree-Specific AGENTS.md

Each worktree can have its own AGENTS.md for branch-specific instructions:

Main branch (/Users/dev/myproject/AGENTS.md):

# Project Guidelines
- This is a Node.js TypeScript project
- Use Jest for testing
- Follow existing code style

Feature worktree (/Users/dev/feature-auth/AGENTS.md):

# Authentication Feature Context
- Working on OAuth2 implementation
- Reference existing auth patterns in src/auth/
- New dependencies: passport, passport-google-oauth20
- Test files go in __tests__/auth/

Per-Worktree Configuration with CODEX_HOME

For completely isolated Codex configurations per worktree, use the CODEX_HOME environment variable:

macOS/Linux:

# Set per-worktree Codex home
export CODEX_HOME=~/worktrees/myproject/feature-auth/.codex
codex

Windows (PowerShell):

$env:CODEX_HOME = "$env:USERPROFILE\worktrees\myproject\feature-auth\.codex"
codex

This gives the worktree its own:

  • Session history
  • AGENTS.md location
  • Configuration settings

Shell Alias for Worktree-Aware Codex

Add to your shell profile (~/.zshrc, ~/.bashrc):

# Worktree-aware Codex launcher
codex-wt() {
  local git_root=$(git rev-parse --show-toplevel 2>/dev/null)
  if [ -n "$git_root" ]; then
    export CODEX_HOME="$git_root/.codex"
    mkdir -p "$CODEX_HOME"
  fi
  codex "$@"
}

Now codex-wt automatically uses worktree-specific configuration.

Session Management Across Worktrees

Codex CLI's session management works seamlessly with worktrees, allowing you to maintain separate conversation contexts per branch.

Resume Sessions in Current Worktree

# Navigate to worktree
cd ~/worktrees/myproject/feature-auth

# Resume last session for this directory
codex --resume

Resume Sessions Across All Worktrees

To see sessions from all worktrees and directories:

codex --resume --all

This displays sessions from:

  • Main repository
  • All linked worktrees
  • Any other directories where you have used Codex

Session Organization by Worktree

Sessions are stored by working directory path:

~/.codex/sessions/2025/01/
├── 22/
│   ├── rollout-2025-01-22T10-30-00-main.jsonl      # Main branch session
│   ├── rollout-2025-01-22T11-45-00-feature.jsonl   # Feature worktree session
│   └── rollout-2025-01-22T14-20-00-hotfix.jsonl    # Hotfix worktree session

Best Practice: Name Sessions Clearly

When starting work in a worktree, begin with context:

cd ~/worktrees/myproject/feature-auth
codex "Working on feature/authentication branch. Goal: implement OAuth2 login."

This makes sessions easier to identify when resuming later.

Known Issues and Workarounds

Issue #5483: Edits Landing in Wrong Worktree (Fixed)

Status: Fixed in recent versions

Previously, Codex could sometimes apply file edits to the wrong worktree when multiple worktrees were open. This has been resolved. Ensure you are running the latest version:

# Update via Homebrew
brew upgrade codex

# Or via npm
npm update -g @openai/codex

Issue #3727: Branch Switching Confusion (Fixed)

Status: Fixed

Earlier versions could become confused when switching branches within a session. This is now handled correctly.

Issue #9084: /review Command Fails in Worktrees (Open)

Status: Open issue

The /review slash command may fail when run from a linked worktree directory.

Workaround options:

  1. Use the command-line review instead:

    codex review
    
  2. Run reviews from the main repository:

    cd /path/to/main/repo
    codex review
    
  3. Specify the path explicitly:

    codex review --path ~/worktrees/myproject/feature-auth
    

Issue #9313: Windows Sandbox and .git Files

Status: Open (Windows-specific)

On Windows, the sandbox may not properly handle .git files in worktrees.

Workaround:

Use WSL for worktree-based development on Windows, which handles .git files correctly:

# In WSL
cd ~/worktrees/myproject/feature-auth
codex

Best Practices for Codex CLI with Worktrees

1. Use Descriptive Worktree Names

Name worktrees to reflect their purpose:

# Good: Clear purpose
git worktree add ../auth-oauth2 feature/oauth2-implementation
git worktree add ../fix-memory-leak bugfix/memory-leak-dashboard

# Avoid: Generic names
git worktree add ../branch1 feature/xyz

2. Install Dependencies Per Worktree

Each worktree needs its own node_modules or equivalent:

cd ~/worktrees/myproject/feature-auth
npm install  # or yarn, pnpm

Codex may fail to run or test code if dependencies are missing.

3. Commit or Stash Before Removing Worktrees

Always commit or stash changes before removing a worktree:

# Check for uncommitted changes
cd ~/worktrees/myproject/feature-auth
git status

# Commit or stash
git add -A && git commit -m "WIP: OAuth implementation"

# Then remove the worktree
cd ~/main-repo
git worktree remove ~/worktrees/myproject/feature-auth

4. Create Worktrees Before Starting Codex

Set up your worktree structure before beginning a Codex session:

# Create worktree first
git worktree add ~/worktrees/myproject/new-feature feature/new-feature
cd ~/worktrees/myproject/new-feature
npm install

# Then start Codex
codex "Help me implement the new feature"

This ensures Codex has the correct context from the start.

5. Use Global AGENTS.md for Cross-Project Standards

Create ~/.codex/AGENTS.md for standards that apply across all projects:

# Global Development Standards

## Code Quality
- Write tests for new functionality
- Add JSDoc comments for public APIs
- Follow semantic versioning for changes

## Git Practices
- Use conventional commit messages
- Keep commits atomic and focused
- Always verify changes compile before committing

6. Leverage Branch-Specific Context

Take advantage of worktree isolation for focused AI assistance:

# In feature worktree
cd ~/worktrees/myproject/feature-auth
codex "Review the authentication implementation and suggest security improvements"

# In a different terminal, in bugfix worktree
cd ~/worktrees/myproject/bugfix-memory
codex "Help me identify the memory leak in the dashboard component"

Each Codex instance maintains separate context appropriate to its worktree.

Workflow Example: Parallel Feature Development

Here is a complete workflow demonstrating worktrees with Codex CLI:

Initial Setup

# Main repository
cd ~/projects/webapp

# Create worktrees for parallel work
git worktree add ~/worktrees/webapp/feature-dashboard feature/new-dashboard
git worktree add ~/worktrees/webapp/feature-api feature/api-v2
git worktree add ~/worktrees/webapp/hotfix-auth hotfix/auth-bypass

# Install dependencies in each
for dir in ~/worktrees/webapp/*/; do
  (cd "$dir" && npm install)
done

Working in Parallel

Terminal 1 - Dashboard Feature:

cd ~/worktrees/webapp/feature-dashboard
codex "Help me build a real-time dashboard using WebSockets"

Terminal 2 - API Feature:

cd ~/worktrees/webapp/feature-api
codex "Refactor the REST API to use versioned endpoints"

Terminal 3 - Hotfix:

cd ~/worktrees/webapp/hotfix-auth
codex "Find and fix the authentication bypass vulnerability"

Resuming Work Later

# See all recent sessions across worktrees
codex --resume --all

# Or resume specific worktree session
cd ~/worktrees/webapp/feature-dashboard
codex --resume

Troubleshooting

Codex Cannot Find Project Root

If Codex does not recognize your worktree as a Git repository:

  1. Verify the .git file exists:

    cat .git
    

    Should output something like: gitdir: /path/to/main/.git/worktrees/branch-name

  2. Check the path is valid:

    ls -la $(cat .git | cut -d' ' -f2)
    
  3. Ensure the main repository's .git/worktrees directory is intact

Sessions Not Appearing for Worktree

If codex --resume does not show expected sessions:

  1. Verify you are in the correct directory:

    pwd
    git rev-parse --show-toplevel
    
  2. Check session files exist:

    ls -la ~/.codex/sessions/$(date +%Y/%m)/
    
  3. Use --all flag to see all sessions:

    codex --resume --all
    

AGENTS.md Not Being Loaded

If worktree-specific AGENTS.md is not applied:

  1. Check file exists and has correct name (case-sensitive):

    ls -la AGENTS.md
    
  2. Verify Codex can read it:

    cat AGENTS.md
    
  3. Check for syntax errors in the markdown

  4. Try the global location as a test:

    cp AGENTS.md ~/.codex/AGENTS.md
    

Next Steps

Frequently Asked Questions

Find answers to common questions

Yes, Codex CLI fully supports Git worktrees. It detects the project root by looking for a .git file or directory, which works correctly in worktree directories where .git is a file pointing to the main repository.

Need Professional IT & Security Help?

Our team of experts is ready to help protect and optimize your technology infrastructure.