CLAUDE-CODEX-INTEGRATION.md
# Claude + Codex Integration Guide
Complete guide for AI-to-AI collaboration between Claude Code and OpenAI Codex CLI.
## Table of Contents
1. [The Think-Act-Observe Loop](#the-think-act-observe-loop)
2. [Integration Patterns](#integration-patterns)
3. [Model Selection Strategy](#model-selection-strategy)
4. [Complete Feature Development](#complete-feature-development)
5. [Safety Patterns](#safety-patterns)
6. [Structured Communication](#structured-communication)
7. [Error Handling](#error-handling)
8. [Best Practices](#best-practices)
## The Think-Act-Observe Loop
**Core Principle**: Claude orchestrates, Codex executes. Claude makes strategic decisions, Codex handles tactical implementation with full automation.
### Basic Pattern
```bash
#!/bin/bash
# Claude THINKS: What needs to be done?
# Goal: Add user caching system
# Claude directs Codex to ACT (with full automation):
codex exec --dangerously-bypass-approvals-and-sandbox \
"List all functions in ./src/auth.js" \
> auth-functions.txt
# Claude OBSERVES results:
cat auth-functions.txt
# Claude THINKS: Need to add caching to login function
# Claude directs atomic action:
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add Redis caching to login function in ./src/auth.js"
# Claude directs verification:
codex exec --dangerously-bypass-approvals-and-sandbox \
"Run auth tests and report results"
# Loop continues...
```
### Advanced Loop with JSON
```bash
#!/bin/bash
# Claude THINKS: Need structured analysis for decision-making
# ACT: Get JSON output for reliable parsing
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Analyze ./src/auth.js and return JSON:
{
'functions': [...],
'complexity': {...},
'issues': [...],
'recommendations': [...]
}" \
> analysis.json
# OBSERVE: Parse JSON reliably
echo "Functions found: $(jq '.functions | length' analysis.json)"
echo "Critical issues: $(jq '.issues[] | select(.severity == "critical")' analysis.json)"
# THINK: Based on analysis, decide next action
# ACT: Execute decision with full automation
for issue in $(jq -r '.issues[].id' analysis.json); do
codex exec --dangerously-bypass-approvals-and-sandbox \
"Fix issue $issue from analysis and run tests"
done
```
## Integration Patterns
### Pattern 1: Research-Driven Development
Claude orchestrates research, Codex executes with web search:
```bash
#!/bin/bash
# Phase 1: RESEARCH (Claude directs, Codex searches)
codex exec --search --dangerously-bypass-approvals-and-sandbox \
--json \
"Research GraphQL best practices 2025 and return structured findings" \
> research.json
# Phase 2: ANALYZE (Claude processes research)
echo "Claude reviews research findings..."
jq '.findings' research.json
# Phase 3: PLAN (Claude creates plan, Codex validates)
codex exec --search --full-auto \
"Based on @research.json, create implementation plan for GraphQL API" \
> plan.md
# Phase 4: IMPLEMENT (Codex executes with full automation)
codex exec --dangerously-bypass-approvals-and-sandbox \
"Implement GraphQL API according to @plan.md with tests"
# Phase 5: VERIFY (Claude checks results)
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Run all tests and return results as JSON" \
> test-results.json
```
### Pattern 2: Sequential Task Decomposition
Claude breaks complex goals into safe atomic steps:
```bash
#!/bin/bash
# Complex Goal: Implement complete OAuth2 authentication
# STEP 1: Research (safe, read-only)
echo "=== Step 1: Research ==="
codex exec --search --full-auto \
"Research OAuth2 best practices and security considerations 2025" \
> oauth-research.md
# STEP 2: Plan (Claude reviews)
echo "=== Step 2: Planning ==="
codex exec --json \
"Create detailed OAuth2 implementation plan based on @oauth-research.md" \
> oauth-plan.json
read -p "Review plan. Continue? [y/N] " -r
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
# STEP 3: Dependencies
echo "=== Step 3: Install Dependencies ==="
codex exec --dangerously-bypass-approvals-and-sandbox \
"Install OAuth2 packages per plan: passport, passport-oauth2, express-session"
# STEP 4: Implementation (full automation)
echo "=== Step 4: Core Implementation ==="
codex exec --dangerously-bypass-approvals-and-sandbox \
"Implement OAuth2 strategy according to @oauth-plan.json:
1. Create OAuth2 config
2. Implement auth routes
3. Add session management
4. Create middleware"
# STEP 5: Security (critical step)
echo "=== Step 5: Security Hardening ==="
codex exec --search --dangerously-bypass-approvals-and-sandbox \
"Research OAuth2 security vulnerabilities and harden implementation:
1. CSRF protection
2. State parameter validation
3. Secure token storage
4. Rate limiting"
# STEP 6: Tests (verification)
echo "=== Step 6: Testing ==="
codex exec --dangerously-bypass-approvals-and-sandbox \
"Generate comprehensive OAuth2 tests:
1. Unit tests for strategy
2. Integration tests for flow
3. Security tests
4. Run all tests and fix failures"
# STEP 7: Documentation
echo "=== Step 7: Documentation ==="
codex exec --full-auto \
"Generate OAuth2 setup documentation and API docs"
echo "=== OAuth2 implementation complete ==="
```
### Pattern 3: Continuous Verification
Every action followed by verification:
```bash
#!/bin/bash
# Pattern: ACT → VERIFY → DECIDE → ACT
verify_action() {
local description="$1"
local verification="$2"
echo "Action: $description"
# Codex verifies
if codex exec --json --dangerously-bypass-approvals-and-sandbox "$verification" \
| jq -e '.success == true' > /dev/null; then
echo "✓ Verified"
return 0
else
echo "✗ Verification failed"
return 1
fi
}
# Execute with verification
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add input validation to user registration"
verify_action \
"Input validation added" \
"Run validation tests and return JSON with success field"
if [ $? -eq 0 ]; then
# Continue to next step
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add rate limiting to registration endpoint"
else
# Fix the issue
codex exec --dangerously-bypass-approvals-and-sandbox \
"Debug validation test failures and fix"
fi
```
### Pattern 4: Parallel Execution with Synchronization
Claude coordinates multiple Codex tasks:
```bash
#!/bin/bash
# Execute independent tasks in parallel
# Task 1: Update backend
codex exec --dangerously-bypass-approvals-and-sandbox \
"Update backend API with new endpoints" \
> backend-log.txt 2>&1 &
backend_pid=$!
# Task 2: Update frontend (independent)
codex exec --dangerously-bypass-approvals-and-sandbox \
"Update frontend to consume new API" \
> frontend-log.txt 2>&1 &
frontend_pid=$!
# Task 3: Update tests (independent)
codex exec --dangerously-bypass-approvals-and-sandbox \
"Generate integration tests for new endpoints" \
> tests-log.txt 2>&1 &
tests_pid=$!
# Wait for all tasks
wait $backend_pid
wait $frontend_pid
wait $tests_pid
# Claude synchronizes: Run integration tests
codex exec --dangerously-bypass-approvals-and-sandbox \
"Run full integration test suite and fix any failures"
```
## Model Selection Strategy
Choose the right Codex model for each task:
### Decision Matrix
```bash
#!/bin/bash
# Quick tasks: o4-mini (fastest, cheapest)
quick_task() {
codex exec -m o4-mini --dangerously-bypass-approvals-and-sandbox "$@"
}
# Standard development: GPT-5.1-Codex (optimized for code)
dev_task() {
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox "$@"
}
# Complex reasoning: o3 (smartest)
complex_task() {
codex exec -m o3 --dangerously-bypass-approvals-and-sandbox "$@"
}
# General purpose: GPT-5 (balanced)
general_task() {
codex exec -m gpt-5 --dangerously-bypass-approvals-and-sandbox "$@"
}
# Examples:
quick_task "Format code with Prettier"
dev_task "Implement user authentication module"
complex_task "Design scalable microservices architecture"
general_task "Generate project documentation"
```
### Model Characteristics
**GPT-5.1-Codex** (Recommended for most tasks)
- Optimized for software engineering
- Latest model (November 2025)
- Best for: Implementation, refactoring, testing
- Use when: Building features, writing code
**GPT-5.1-Codex-Mini**
- 4x more usage quota
- Cost-efficient
- Best for: Quick fixes, formatting, simple tasks
- Use when: High volume of simple operations
**o3**
- Smartest reasoning model
- Best for: Architecture, complex decisions, debugging
- Use when: Need deep analysis or reasoning
**o4-mini**
- Fast reasoning
- Best for: Quick decisions, simple reasoning
- Use when: Need speed over depth
**GPT-5**
- General purpose
- Best for: Mixed tasks (code + docs + analysis)
- Use when: Varied workflow
### Dynamic Model Selection
```bash
#!/bin/bash
# Claude chooses model based on task complexity
select_model_for_task() {
local task="$1"
local complexity="$2" # simple, standard, complex, reasoning
case $complexity in
simple)
echo "o4-mini"
;;
standard)
echo "gpt-5.1-codex"
;;
complex)
echo "gpt-5.1-codex"
;;
reasoning)
echo "o3"
;;
*)
echo "gpt-5.1-codex" # Default
;;
esac
}
# Example usage
model=$(select_model_for_task "Design database schema" "reasoning")
codex exec -m "$model" --dangerously-bypass-approvals-and-sandbox \
"Design normalized database schema for e-commerce platform"
```
## Complete Feature Development
End-to-end example: Building a real-time notification system
```bash
#!/bin/bash
# Complete feature: Real-time notifications with WebSocket
echo "========================================="
echo "Feature: Real-time Notification System"
echo "========================================="
# PHASE 1: Research & Planning (5 minutes)
echo ""
echo "=== PHASE 1: Research & Planning ==="
# Research (o3 for reasoning)
codex exec -m o3 --search --dangerously-bypass-approvals-and-sandbox \
"Research real-time notification architectures 2025:
1. WebSocket vs SSE vs Long Polling
2. Scaling strategies
3. Security best practices
4. Return recommendation with reasoning" \
> notifications-research.md
# Plan (GPT-5.1-Codex for implementation planning)
codex exec -m gpt-5.1-codex --json --dangerously-bypass-approvals-and-sandbox \
"Create detailed implementation plan based on @notifications-research.md:
1. Technology choices
2. Architecture design
3. File structure
4. Implementation steps
5. Testing strategy
Return as JSON" \
> notifications-plan.json
echo "✓ Research and planning complete"
cat notifications-plan.json | jq '.architecture'
# PHASE 2: Setup & Dependencies (2 minutes)
echo ""
echo "=== PHASE 2: Setup & Dependencies ==="
codex exec -m gpt-5.1-codex-mini --dangerously-bypass-approvals-and-sandbox \
"Install dependencies from @notifications-plan.json:
- socket.io for WebSocket
- redis for pub/sub
- Required types and dev dependencies"
echo "✓ Dependencies installed"
# PHASE 3: Backend Implementation (15 minutes)
echo ""
echo "=== PHASE 3: Backend Implementation ==="
# WebSocket server (GPT-5.1-Codex for complex code)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Implement WebSocket notification server per @notifications-plan.json:
1. Create NotificationService class
2. Implement connection handling
3. Add authentication middleware
4. Create notification queuing with Redis
5. Add reconnection logic
6. Implement clean shutdown
Create file: ./src/services/notifications.js"
# API endpoints (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Create notification REST API in ./src/routes/notifications.js:
1. POST /notifications - Send notification
2. GET /notifications/history - Get user notifications
3. PUT /notifications/:id/read - Mark as read
4. DELETE /notifications/:id - Dismiss
Add proper validation and error handling"
# Database models (GPT-5.1-Codex-Mini for simple models)
codex exec -m gpt-5.1-codex-mini --dangerously-bypass-approvals-and-sandbox \
"Create Notification model in ./src/models/notification.js with fields:
- user, type, title, message, data, read, createdAt
Add indexes for performance"
echo "✓ Backend implementation complete"
# PHASE 4: Frontend Implementation (10 minutes)
echo ""
echo "=== PHASE 4: Frontend Implementation ==="
# React hook (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Create useNotifications React hook in ./src/hooks/useNotifications.js:
1. Manage WebSocket connection
2. Handle incoming notifications
3. Provide send/dismiss methods
4. Auto-reconnect on disconnect
5. TypeScript types included"
# UI components (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Create notification UI components:
1. NotificationBell.tsx - Bell icon with badge
2. NotificationList.tsx - Dropdown list
3. NotificationItem.tsx - Individual notification
4. Toast.tsx - Toast notifications
Use Tailwind CSS for styling"
echo "✓ Frontend implementation complete"
# PHASE 5: Security Hardening (5 minutes)
echo ""
echo "=== PHASE 5: Security ==="
# Security analysis (o3 for reasoning)
codex exec -m o3 --search --dangerously-bypass-approvals-and-sandbox \
"Analyze notification system for security vulnerabilities:
1. Review authentication
2. Check authorization (users see only their notifications)
3. Validate XSS prevention
4. Check rate limiting
5. Implement fixes for any issues found"
echo "✓ Security hardening complete"
# PHASE 6: Testing (10 minutes)
echo ""
echo "=== PHASE 6: Testing ==="
# Generate tests (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Generate comprehensive test suite:
1. Unit tests for NotificationService
2. Integration tests for API endpoints
3. WebSocket connection tests
4. Frontend hook tests
5. E2E tests for notification flow
Achieve >90% coverage"
# Run tests (GPT-5.1-Codex-Mini for execution)
codex exec -m gpt-5.1-codex-mini --json --dangerously-bypass-approvals-and-sandbox \
"Run all notification tests and return results as JSON:
1. Run unit tests
2. Run integration tests
3. Run E2E tests
4. Fix any failures
5. Return coverage report" \
> test-results.json
echo "Test results:"
cat test-results.json | jq '{passed: .passed, failed: .failed, coverage: .coverage}'
# PHASE 7: Documentation (5 minutes)
echo ""
echo "=== PHASE 7: Documentation ==="
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Generate documentation:
1. API documentation (OpenAPI/Swagger)
2. WebSocket protocol documentation
3. Frontend usage guide
4. Deployment guide
5. Add JSDoc comments to all functions
Create: ./docs/notifications/"
echo "✓ Documentation complete"
# PHASE 8: Git Workflow (3 minutes)
echo ""
echo "=== PHASE 8: Git Workflow ==="
codex exec -m gpt-5.1-codex-mini --dangerously-bypass-approvals-and-sandbox \
"Complete git workflow:
1. Review all changes
2. Create semantic commits:
- feat: add WebSocket notification service
- feat: add notification REST API
- feat: add notification UI components
- test: add notification test suite
- docs: add notification documentation
3. Push feature branch
4. Create PR with detailed description"
echo "✓ Git workflow complete"
# PHASE 9: Final Verification (2 minutes)
echo ""
echo "=== PHASE 9: Final Verification ==="
codex exec -m o3 --json --dangerously-bypass-approvals-and-sandbox \
"Final verification checklist:
1. All tests passing
2. Security checks passed
3. Documentation complete
4. Code quality metrics
5. Performance benchmarks
Return JSON report" \
> final-verification.json
echo ""
echo "========================================="
echo "Feature Development Complete!"
echo "========================================="
cat final-verification.json | jq .
# Total time: ~60 minutes
# Total automation: 100%
# Human intervention: Code review only
```
## Safety Patterns
### Pattern 1: Git Backup Before Automation
```bash
#!/bin/bash
safe_automation() {
local task="$1"
# Create git backup
git stash push -m "pre-codex-$(date +%s)"
if codex exec --dangerously-bypass-approvals-and-sandbox "$task"; then
echo "✓ Success! Backup: git stash list"
else
echo "✗ Failed! Restoring..."
git stash pop
return 1
fi
}
# Usage
safe_automation "Refactor authentication module completely"
```
### Pattern 2: Dry-Run First
```bash
#!/bin/bash
# Generate plan without executing
codex exec \
"Plan how to refactor database layer to use TypeORM" \
> refactor-plan.md
# Review plan
cat refactor-plan.md
# Execute if approved
read -p "Execute this plan? [y/N] " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
codex exec --dangerously-bypass-approvals-and-sandbox \
"Execute refactoring plan in @refactor-plan.md"
fi
```
### Pattern 3: Checkpoint Commits
```bash
#!/bin/bash
# Create checkpoints during long refactoring
checkpoint_refactor() {
local scope="$1"
codex exec --dangerously-bypass-approvals-and-sandbox \
"Refactor $scope with checkpoint commits:
1. Create WIP commit at start
2. Make incremental changes
3. Commit after each logical step
4. Run tests after each commit
5. Revert if tests fail
6. Continue until complete"
}
checkpoint_refactor "./src/database"
```
### Pattern 4: Scoped Automation
```bash
#!/bin/bash
# Limit blast radius
codex exec --dangerously-bypass-approvals-and-sandbox \
-C ./src/auth \
"Only modify files in authentication module"
# Multiple scoped directories
codex exec --dangerously-bypass-approvals-and-sandbox \
--add-dir ./docs \
--add-dir ./tests \
"Can write to workspace, docs, and tests only"
```
## Structured Communication
### JSON for Reliability
```bash
#!/bin/bash
# Always use JSON for AI-to-AI communication
# Request structured output
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Analyze ./src and return JSON:
{
'files': number,
'functions': [{name, complexity, issues}],
'recommendations': [{priority, description, impact}]
}" \
> analysis.json
# Parse reliably
high_priority=$(jq -r '.recommendations[] | select(.priority == "high") | .description' analysis.json)
# Execute based on structured data
for rec in $high_priority; do
codex exec --dangerously-bypass-approvals-and-sandbox "Implement: $rec"
done
```
### Structured Workflows
```bash
#!/bin/bash
# Define workflow as JSON
cat > workflow.json << 'EOF'
{
"workflow": "feature-development",
"steps": [
{"step": 1, "action": "research", "model": "o3"},
{"step": 2, "action": "plan", "model": "gpt-5.1-codex"},
{"step": 3, "action": "implement", "model": "gpt-5.1-codex"},
{"step": 4, "action": "test", "model": "gpt-5.1-codex"},
{"step": 5, "action": "document", "model": "gpt-5.1-codex-mini"}
]
}
EOF
# Execute workflow from JSON
for step in $(jq -r '.steps[] | @base64' workflow.json); do
_jq() {
echo "$step" | base64 --decode | jq -r "$1"
}
action=$(_jq '.action')
model=$(_jq '.model')
echo "Step: $action (using $model)"
codex exec -m "$model" --dangerously-bypass-approvals-and-sandbox \
"Execute $action step for current feature"
done
```
## Error Handling
### Pattern 1: Automatic Retry
```bash
#!/bin/bash
retry_codex() {
local task="$1"
local max_attempts=3
local attempt=1
while [ $attempt -le $max_attempts ]; do
echo "Attempt $attempt of $max_attempts..."
if codex exec --json --dangerously-bypass-approvals-and-sandbox "$task" \
> result.json 2>error.log; then
echo "✓ Success on attempt $attempt"
return 0
else
echo "✗ Failed attempt $attempt"
cat error.log
if [ $attempt -lt $max_attempts ]; then
echo "Retrying..."
attempt=$((attempt + 1))
fi
fi
done
echo "✗ Failed after $max_attempts attempts"
return 1
}
# Usage
retry_codex "Run tests and fix any failures"
```
### Pattern 2: Fallback Strategy
```bash
#!/bin/bash
# Try complex approach, fallback to simple
if ! codex exec -m o3 --dangerously-bypass-approvals-and-sandbox \
"Optimize database queries using advanced techniques"; then
echo "Complex optimization failed, trying simpler approach..."
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Add basic database indexes to improve performance"
fi
```
### Pattern 3: Error Analysis and Fix
```bash
#!/bin/bash
# Capture errors and let Codex analyze and fix
codex exec --dangerously-bypass-approvals-and-sandbox \
"Run all tests" \
> test-output.txt 2>&1
if grep -q "FAILED" test-output.txt; then
echo "Tests failed, analyzing..."
# Let Codex analyze failures
codex exec -m o3 --dangerously-bypass-approvals-and-sandbox \
"Analyze test failures in @test-output.txt:
1. Identify root causes
2. Fix all issues
3. Run tests again
4. Repeat until all pass"
fi
```
## Best Practices
### 1. Start with Planning
```bash
# Always start complex tasks with planning
codex exec -m o3 --json \
"Analyze requirement and create detailed plan" \
> plan.json
# Then execute plan
codex exec --dangerously-bypass-approvals-and-sandbox \
"Implement according to @plan.json"
```
### 2. Use Appropriate Models
```bash
# Research: o3 with web search
codex exec -m o3 --search "Research best approach"
# Implementation: GPT-5.1-Codex
codex exec -m gpt-5.1-codex "Implement feature"
# Simple tasks: GPT-5.1-Codex-Mini
codex exec -m gpt-5.1-codex-mini "Format code"
```
### 3. Always Verify
```bash
# After every significant change
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Run tests and return results"
```
### 4. Atomic Changes
```bash
# Break large tasks into atomic steps
codex exec --dangerously-bypass-approvals-and-sandbox "Step 1: Add validation"
codex exec --dangerously-bypass-approvals-and-sandbox "Step 2: Add error handling"
codex exec --dangerously-bypass-approvals-and-sandbox "Step 3: Add tests"
```
### 5. Use Git for Safety
```bash
# Work on branches
git checkout -b feature/new-feature
codex exec --dangerously-bypass-approvals-and-sandbox "Build feature"
# Review changes
git diff
# Commit
codex exec --full-auto "Create semantic commits"
```
### 6. Document Everything
```bash
# Always generate documentation
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add comprehensive documentation to all new code"
```
### 7. Monitor Progress
```bash
#!/bin/bash
# Track progress with JSON reports
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Report progress on current task:
{
'completed': [...],
'in_progress': [...],
'remaining': [...],
'blockers': [...]
}" \
> progress.json
```
## Complete Example: Microservice Development
Building a complete microservice with Claude + Codex:
```bash
#!/bin/bash
# Complete microservice: User Profile Service
echo "Building User Profile Microservice..."
# 1. Architecture (o3 reasoning)
codex exec -m o3 --search --json \
"Design microservice architecture for user profiles:
- API design
- Data model
- Caching strategy
- Security
Return detailed architecture" \
> architecture.json
# 2. Setup (GPT-5.1-Codex-Mini)
codex exec -m gpt-5.1-codex-mini --dangerously-bypass-approvals-and-sandbox \
"Setup project structure per @architecture.json:
- Initialize Node.js project
- Install dependencies
- Setup TypeScript
- Configure ESLint/Prettier"
# 3. Database (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Implement database layer:
- Create User model
- Create Profile model
- Add migrations
- Setup connection pool"
# 4. API (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Implement REST API:
- CRUD endpoints for profiles
- Validation middleware
- Error handling
- OpenAPI documentation"
# 5. Caching (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Add Redis caching layer per @architecture.json"
# 6. Security (o3 analysis)
codex exec -m o3 --search --dangerously-bypass-approvals-and-sandbox \
"Implement security:
- JWT authentication
- Rate limiting
- Input sanitization
- CORS configuration"
# 7. Tests (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Generate test suite with >90% coverage"
# 8. Docker (GPT-5.1-Codex-Mini)
codex exec -m gpt-5.1-codex-mini --dangerously-bypass-approvals-and-sandbox \
"Create Docker setup:
- Dockerfile with multi-stage build
- docker-compose.yml
- .dockerignore"
# 9. CI/CD (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Create GitHub Actions:
- Test pipeline
- Build and push Docker image
- Deploy to staging"
# 10. Documentation (GPT-5.1-Codex)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Generate complete documentation:
- API docs
- Architecture diagram
- Deployment guide
- Development guide"
# 11. Verification (o3 final check)
codex exec -m o3 --json --dangerously-bypass-approvals-and-sandbox \
"Final verification:
- Run all tests
- Check code quality
- Verify security
- Performance benchmarks
Return complete report" \
> final-report.json
echo "Microservice complete!"
cat final-report.json | jq .
```
---
**Result**: Complete production-ready microservice in ~30-45 minutes with 100% automation, Claude orchestrating strategic decisions, and Codex handling tactical implementation.
README.md
# OpenAI Codex CLI Skills for Claude Code
Complete integration between Claude Code and OpenAI Codex CLI, enabling powerful AI-to-AI collaboration with full automation capabilities.
**Last Updated**: December 2025 (GPT-5.2 Release)
## 📦 What's Included
This package provides 6 comprehensive skills for using OpenAI Codex CLI within Claude Code:
1. **codex-cli** - Main integration with full automation modes
2. **codex-auth** - Authentication management (OAuth + API keys)
3. **codex-tools** - Tool execution and automation patterns
4. **codex-chat** - Interactive REPL workflows
5. **codex-review** - Automated code review and PR workflows
6. **codex-git** - Git-aware development and commit automation
**Bonus**: Complete Claude + Codex integration guide (`CLAUDE-CODEX-INTEGRATION.md`)
## 🚀 Quick Start
### 1. Install Codex CLI
```bash
# Via NPM (recommended)
npm install -g @openai/codex
# Via Homebrew
brew install openai/tap/codex-cli
# Verify installation
codex --version # Should show 0.60.1 or later
```
### 2. Authenticate
**Option A: ChatGPT Plus/Pro (Recommended)**
```bash
codex login
# Opens browser for OAuth authentication
# Includes GPT-5-Codex access with subscription
```
**Option B: API Key**
```bash
export OPENAI_API_KEY="sk-your-api-key-here"
# Or create ~/.codex/config.toml with api_key
```
### 3. Test Integration
```bash
# Simple test
codex exec "What is 2+2?"
# Full automation test
codex exec --dangerously-bypass-approvals-and-sandbox \
"List all JavaScript files in current directory"
# With Claude orchestrating
# Claude can now direct Codex to perform tasks with full automation
```
## 🎯 Key Features
### Full Automation Mode
The `--dangerously-bypass-approvals-and-sandbox` flag provides **complete automation** with zero friction:
```bash
# Zero approvals, zero sandbox restrictions
codex exec --dangerously-bypass-approvals-and-sandbox \
"Refactor entire authentication module with tests"
# Shorter alternative: --full-auto (sandboxed)
codex exec --full-auto "Generate tests for all functions"
```
### Available Models (December 2025)
**GPT-5.2 Series (NEW - December 11, 2025):**
- `gpt-5.2` - Latest frontier model (400K context, 128K output)
- `gpt-5.2-pro` - Maximum accuracy (xhigh reasoning)
- `gpt-5.2-chat-latest` - Speed-optimized for routine queries
**GPT-5.1 Codex Series (Recommended for Coding):**
- `gpt-5.1-codex-max` - **DEFAULT** for Codex CLI (best for agentic coding)
- `gpt-5.1-codex` - Optimized for long-running agentic tasks
- `gpt-5.1-codex-mini` - Cost-efficient coding
**o-Series (Reasoning):**
- `o3` - Smartest reasoning model (for architecture, complex decisions)
- `o4-mini` - Efficient reasoning (for quick analysis)
**Model Selection Guide (December 2025):**
```bash
# Quick tasks → o4-mini or gpt-5.1-codex-mini
codex exec -m o4-mini "Format code with Prettier"
# Standard development → gpt-5.1-codex-max (DEFAULT)
codex exec -m gpt-5.1-codex-max "Implement user authentication"
# Long-context tasks → gpt-5.2 (400K context)
codex exec -m gpt-5.2 "Analyze entire codebase"
# Maximum accuracy → gpt-5.2-pro with xhigh reasoning
codex exec -m gpt-5.2-pro --reasoning-effort xhigh "Critical architecture"
# Complex reasoning → o3
codex exec -m o3 "Design scalable microservices architecture"
```
### Git-Aware Workflows
Codex understands git context and can manage commits automatically:
```bash
# Apply Codex changes as git patch
codex apply # or: codex a
# Generate intelligent commits
codex exec --dangerously-bypass-approvals-and-sandbox \
"Review changes and create semantic commits"
# Complete PR workflow
codex exec --dangerously-bypass-approvals-and-sandbox \
"Create feature branch, implement auth, commit, and create PR"
```
### AI-to-AI Collaboration
Claude orchestrates, Codex executes - the **Think-Act-Observe Loop**:
```bash
#!/bin/bash
# Claude THINKS: What needs to be done?
# Claude directs Codex to ACT:
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Analyze ./src and return structured data" \
> analysis.json
# Claude OBSERVES results:
cat analysis.json | jq .
# Claude directs next action:
codex exec --dangerously-bypass-approvals-and-sandbox \
"Implement recommendations from @analysis.json"
```
## 📚 Skills Overview
### 1. codex-cli (Core Integration)
Main integration skill covering:
- Installation and setup
- All automation modes (`--dangerously-bypass-approvals-and-sandbox`, `--full-auto`, `-a`, `-s`)
- All available models (GPT-5.2, GPT-5.1-Codex-Max, o3, o4-mini)
- Claude + Codex collaboration patterns
- Configuration and best practices
**Key Commands (December 2025):**
```bash
# Direct execution
codex exec "prompt"
# Full automation
codex exec --dangerously-bypass-approvals-and-sandbox "task"
# With specific model
codex exec -m gpt-5.1-codex-max "complex code task" # Default
codex exec -m gpt-5.2 "tasks needing 400K context"
codex exec -m gpt-5.2-pro "maximum accuracy tasks"
# With web search
codex exec --search "research and implement"
# JSON output
codex exec --json "structured output"
```
### 2. codex-auth (Authentication)
Complete authentication management:
- ChatGPT Plus/Pro OAuth setup
- API key configuration (environment, config file, per-project)
- Multi-account management
- Secure API key storage (pass, macOS Keychain)
- CI/CD integration (GitHub Actions, GitLab CI, Docker)
- Configuration profiles
**Key Commands:**
```bash
# Login with ChatGPT
codex login
# Set API key
export OPENAI_API_KEY="sk-..."
# Check status
codex exec "What account am I using?"
# Logout
codex logout
```
### 3. codex-tools (Tool Execution)
Comprehensive tool execution patterns:
- Full automation workflows
- Batch processing
- File operations (read, modify, generate, organize)
- Shell commands
- Web search integration
- Safety patterns (backups, scoped execution)
**Key Patterns:**
```bash
# Batch processing
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add JSDoc comments to all *.js files"
# Scoped automation
codex exec --dangerously-bypass-approvals-and-sandbox \
-C ./src/auth \
"Only modify authentication module"
# With backup
git stash push -m "backup"
codex exec --dangerously-bypass-approvals-and-sandbox "refactor"
```
### 4. codex-chat (Interactive Mode)
Interactive REPL workflows:
- Session management (resume, apply changes)
- Multimodal support (code + images)
- Web search in interactive mode
- Automated development sessions
- Continuous development workflows
**Key Commands:**
```bash
# Start interactive session
codex "Let's work on authentication"
# With full automation
codex --dangerously-bypass-approvals-and-sandbox "Auto-execute everything"
# With images
codex -i design.png "Implement this UI"
# Resume last session
codex exec resume --last
```
### 5. codex-review (Code Review)
Automated code review workflows:
- Automated codebase review
- Git diff analysis
- PR review automation
- Apply Codex suggestions
- Complete review workflows with fixes
**Key Patterns:**
```bash
# Full automated review
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Review entire codebase and generate prioritized report" \
> review-report.json
# Review uncommitted changes
git diff | codex exec --dangerously-bypass-approvals-and-sandbox \
"Review this diff and suggest improvements"
# PR review
gh pr view 123 --json diff | \
codex exec --dangerously-bypass-approvals-and-sandbox \
"Review PR and provide detailed feedback"
```
### 6. codex-git (Git Integration)
Git-aware development:
- Intelligent commit generation (conventional commits, semantic commits)
- PR automation (create branch, commit, push, create PR)
- Branch management
- Git history analysis
- Conflict resolution
- Changelog generation
**Key Patterns:**
```bash
# Apply Codex changes
codex apply # or: codex a
# Generate commits
codex exec --dangerously-bypass-approvals-and-sandbox \
"Create semantic commits for all changes"
# Complete PR workflow
codex exec --dangerously-bypass-approvals-and-sandbox \
"Create feature branch feature/auth, implement OAuth2, commit, push, create PR"
# Resolve conflicts
codex exec --dangerously-bypass-approvals-and-sandbox \
"Resolve merge conflicts intelligently"
```
## 🎓 Claude + Codex Integration Guide
See `CLAUDE-CODEX-INTEGRATION.md` for comprehensive guide covering:
- **Think-Act-Observe Loop** - Claude orchestrates, Codex executes
- **Integration Patterns** - Research-driven, sequential decomposition, verification, parallel execution
- **Model Selection Strategy** - When to use o3 vs GPT-5.1-Codex vs o4-mini
- **Complete Feature Development** - Real-time notification system example (60 min, 100% automated)
- **Safety Patterns** - Git backups, dry-run, checkpoints, scoped automation
- **Structured Communication** - JSON for reliability, structured workflows
- **Error Handling** - Retry, fallback, automatic error analysis
- **Best Practices** - Planning, verification, atomic changes, documentation
## 💡 Usage Examples
### Example 1: Quick Code Fix
```bash
# Simple task with full automation
codex exec --dangerously-bypass-approvals-and-sandbox \
"Fix the race condition in user session handling and add tests"
```
### Example 2: Feature Development
```bash
#!/bin/bash
# Complete feature with Claude orchestrating
# 1. Research (Claude directs, Codex searches)
codex exec -m o3 --search --dangerously-bypass-approvals-and-sandbox \
"Research OAuth2 best practices 2025" \
> research.md
# 2. Plan (Claude reviews, Codex plans)
codex exec -m gpt-5.1-codex --json \
"Create implementation plan based on @research.md" \
> plan.json
# 3. Implement (Codex executes with full automation)
codex exec -m gpt-5.1-codex --dangerously-bypass-approvals-and-sandbox \
"Implement OAuth2 according to @plan.json with comprehensive tests"
# 4. Verify (Claude checks results)
codex exec --json --dangerously-bypass-approvals-and-sandbox \
"Run all tests and return results" \
> results.json
```
### Example 3: Code Review Automation
```bash
# Automated PR review with fixes
gh pr view 123 --json diff > pr.json
codex exec --dangerously-bypass-approvals-and-sandbox \
"Review PR in @pr.json, provide feedback, and auto-fix all issues"
```
### Example 4: Refactoring with Safety
```bash
# Safe refactoring with git backup
git stash push -m "pre-refactor"
codex exec --dangerously-bypass-approvals-and-sandbox \
"Refactor authentication module:
1. Apply modern patterns
2. Add error handling
3. Update tests
4. Run tests and fix failures
5. Create semantic commits"
# Review changes
git diff
# Keep or revert
git stash pop # if needed
```
## ⚙️ Configuration
### Config File (~/.codex/config.toml)
```toml
# Default model (December 2025)
model = "gpt-5.1-codex-max" # Best for agentic coding
# Full automation (no approvals)
ask_for_approval = "never"
# Workspace write access
sandbox = "workspace-write"
# Enable web search
search = true
# GPT-5.2 specific settings
reasoning_effort = "high" # medium, high, xhigh
compact = false # Enable context compaction
# Profiles for different workflows
[profiles.safe]
ask_for_approval = "untrusted"
sandbox = "read-only"
[profiles.auto]
ask_for_approval = "never"
sandbox = "workspace-write"
search = true
[profiles.danger]
ask_for_approval = "never"
sandbox = "danger-full-access"
search = true
# GPT-5.2 profiles (NEW)
[profiles.gpt52]
model = "gpt-5.2"
ask_for_approval = "never"
sandbox = "workspace-write"
[profiles.gpt52-pro]
model = "gpt-5.2-pro"
reasoning_effort = "xhigh"
ask_for_approval = "on-request"
```
### Environment Variables
```bash
# Authentication
export OPENAI_API_KEY="sk-your-api-key"
# Default model (December 2025)
export CODEX_MODEL="gpt-5.1-codex-max"
# GPT-5.2 specific
export CODEX_REASONING_EFFORT="high" # medium, high, xhigh
```
## 🔒 Safety & Best Practices
### When to Use `--dangerously-bypass-approvals-and-sandbox`
**✅ Safe Scenarios:**
- Trusted, repeatable workflows
- CI/CD (externally sandboxed)
- Docker containers
- Feature branches (can revert)
- With git backups
**⚠️ Use with Caution:**
- Production environments
- Shared repositories
- Untested workflows
- Without backups
### Safety Checklist
1. **Always Have Backups**
```bash
git stash push -m "backup"
```
2. **Work on Branches**
```bash
git checkout -b experiment
```
3. **Review Changes**
```bash
git diff
codex apply # Only after review
```
4. **Limit Scope**
```bash
codex exec --dangerously-bypass-approvals-and-sandbox \
-C ./specific/directory \
"Only affect this directory"
```
## 🆚 Codex vs Gemini vs Claude
### When to Use Each
**Codex (OpenAI)**
- Best for: Code generation, refactoring, advanced reasoning
- Models: GPT-5.1-Codex, o3 (smartest reasoning)
- Strengths: Latest models, git-aware, multimodal
- Use when: Need cutting-edge models or complex reasoning
**Gemini (Google)**
- Best for: Fast iteration, Google ecosystem integration
- Models: Gemini 2.5 Pro, 2.5 Flash
- Strengths: Speed, web search, MCP servers
- Use when: Need Google integration or rapid development
**Claude (Anthropic)**
- Best for: Orchestration, planning, strategic decisions
- Models: Claude Sonnet 4.5
- Strengths: Context management, systematic thinking
- Use when: Complex workflows, quality-first development
**Recommended**: Use Claude to orchestrate both Codex and Gemini for maximum power!
## 📖 Documentation
- **codex-cli/SKILL.md** - Main integration guide
- **codex-auth/SKILL.md** - Authentication setup
- **codex-tools/SKILL.md** - Tool execution patterns
- **codex-chat/SKILL.md** - Interactive workflows
- **codex-review/SKILL.md** - Code review automation
- **codex-git/SKILL.md** - Git-aware development
- **CLAUDE-CODEX-INTEGRATION.md** - Complete integration guide
## 🔗 Related Skills
### Gemini CLI Skills
- `gemini-cli` - Gemini CLI integration
- `gemini-auth` - Gemini authentication
- `gemini-tools` - Gemini tool execution
- `gemini-chat` - Gemini interactive mode
- `gemini-mcp` - MCP server integration
### Ecosystem Skills
- `skill-builder-generic` - Build Claude Code skills
- `review-multi` - Multi-dimensional skill reviews
- `skill-researcher` - Research patterns and best practices
## 🚀 Getting Started
1. **Install Codex CLI**
```bash
npm install -g @openai/codex
```
2. **Authenticate**
```bash
codex login # or set OPENAI_API_KEY
```
3. **Test Basic Usage**
```bash
codex exec "List files in current directory"
```
4. **Try Full Automation**
```bash
codex exec --dangerously-bypass-approvals-and-sandbox \
"Analyze this codebase and suggest improvements"
```
5. **Read Integration Guide**
- Open `CLAUDE-CODEX-INTEGRATION.md`
- Review Think-Act-Observe Loop
- Try the examples
6. **Build Something**
- Use the complete feature development example
- Let Claude orchestrate, Codex execute
- Enjoy 100% automation!
## 📝 License
Created for Claude Code by the Skrillz ecosystem.
Part of the Self-Sustaining Skill Development Ecosystem.
## 🙏 Acknowledgments
- OpenAI for Codex CLI
- Anthropic for Claude Code
- The Claude Code community
---
**Ready to collaborate with AI?** Start with the integration guide and build your first fully automated feature! 🚀
SKILL.md
---
name: codex-cli
description: Integrate OpenAI Codex CLI into Claude Code for AI collaboration, code generation, and automated development. Use when working with OpenAI models (GPT-5.2, GPT-5.1-Codex-Max, o3, o4-mini), code refactoring, git workflows, or needing full automation with permission bypass.
---
# OpenAI Codex CLI Integration
Integrates OpenAI's Codex CLI into Claude Code, enabling seamless AI collaboration between Claude and Codex for enhanced development workflows.
**Last Updated**: December 2025 (GPT-5.2 Release)
## When to Use
- Working with OpenAI models (GPT-5.2, GPT-5.1-Codex-Max, o3, o4-mini)
- Code generation and refactoring with latest models
- Git-aware workflows and PR reviews
- Full automation with permission bypass
- Reasoning-first development (o3 models, GPT-5.2 with xhigh reasoning)
- Multimodal tasks (code + images)
- Sandboxed execution environments
- Long-context tasks (400K tokens with GPT-5.2)
## Quick Start
### 1. Install Codex CLI
```bash
# Check current installation
codex --version
# Install/Update globally via NPM
npm install -g @openai/codex
# Or use Homebrew (macOS/Linux)
brew install openai/tap/codex-cli
```
### 2. Setup Authentication
#### Option A: ChatGPT Plus/Pro (Recommended)
```bash
# Login with ChatGPT account
codex login
# Opens browser for OAuth authentication
# Includes GPT-5-Codex access with subscription
```
#### Option B: API Key
```bash
# Set OpenAI API key
export OPENAI_API_KEY="your-api-key-here"
# Or create config file
mkdir -p ~/.codex
echo 'api_key = "your-api-key-here"' > ~/.codex/config.toml
```
### 3. Basic Usage
```bash
# Direct execution (like gemini -p)
codex exec "Analyze this codebase and suggest improvements"
# Full automation (BYPASS ALL APPROVALS)
codex exec --dangerously-bypass-approvals-and-sandbox "Refactor authentication module"
# Safe automation (sandboxed)
codex exec --full-auto "Generate tests for all functions"
# Interactive mode
codex "Let's work on improving this code"
# With specific model (December 2025)
codex exec -m gpt-5.2 "Complex task with latest model"
codex exec -m gpt-5.1-codex-max "Best for agentic coding (default)"
codex exec -m o3 "Deep reasoning task"
codex exec -m o4-mini "Quick code generation"
```
## Full Automation Mode - MAXIMUM POWER
**`--dangerously-bypass-approvals-and-sandbox`** - Complete automation, zero friction:
### ✅ When to Use Bypass Mode
```bash
# Trusted, repeatable workflows
codex exec --dangerously-bypass-approvals-and-sandbox "Add JSDoc comments to all ./src functions"
# Automated testing workflows
codex exec --dangerously-bypass-approvals-and-sandbox "Run tests and auto-fix all failures"
# Bulk operations
codex exec --dangerously-bypass-approvals-and-sandbox "Convert all .js files to TypeScript"
# CI/CD pipelines (externally sandboxed)
codex exec --dangerously-bypass-approvals-and-sandbox "Deploy to staging environment"
```
### ⚠️ Safer Automation Options
```bash
# --full-auto: Sandboxed with workspace write access
codex exec --full-auto "Refactor module safely"
# Custom approval + sandbox
codex exec -a never -s workspace-write "Controlled automation"
# On-failure approval (runs until error)
codex exec -a on-failure "Try operations, escalate on error"
```
### Approval Policies
```bash
# -a never: Full automation (no approvals)
codex exec -a never "Complete workflow automation"
# -a on-request: Model decides when to ask
codex exec -a on-request "Intelligent approval requests"
# -a on-failure: Only ask if command fails
codex exec -a on-failure "Run until failure, then ask"
# -a untrusted: Only run trusted commands (default)
codex exec -a untrusted "Safe, limited automation"
```
### Sandbox Modes
```bash
# -s read-only: Cannot modify files
codex exec -s read-only "Analysis only, no changes"
# -s workspace-write: Can modify workspace
codex exec -s workspace-write "Safe file modifications"
# -s danger-full-access: Full system access
codex exec -s danger-full-access "Complete control (use carefully)"
```
## Available Models (December 2025)
### GPT-5.2 Series (NEW - December 11, 2025)
```bash
# GPT-5.2 Thinking - Latest frontier model
# 400K context, 128K output, knowledge cutoff Aug 31, 2025
# Pricing: $1.75/1M input, $14/1M output (90% cached discount)
codex exec -m gpt-5.2 "Complex multi-step task with deep reasoning"
# GPT-5.2 Instant - Speed optimized for routine queries
codex exec -m gpt-5.2-chat-latest "Fast information seeking and writing"
# GPT-5.2 Pro - Maximum accuracy (Responses API only)
# Pricing: $21/1M input, $168/1M output
# Supports reasoning.effort: medium, high, xhigh
codex exec -m gpt-5.2-pro "Critical high-accuracy tasks"
```
### GPT-5.1 Codex Series (Recommended for Coding)
```bash
# GPT-5.1-Codex-Max - DEFAULT for Codex CLI
# Best for agentic coding with native compaction support
codex exec -m gpt-5.1-codex-max "Complex development workflows"
# GPT-5.1-Codex - Optimized for long-running agentic tasks
codex exec -m gpt-5.1-codex "Extended coding sessions"
# GPT-5.1-Codex-Mini - Cost-efficient coding
codex exec -m gpt-5.1-codex-mini "Quick code tasks"
```
### Legacy GPT-5 Series
```bash
# GPT-5 - General model (use GPT-5.2 for latest)
codex exec -m gpt-5 "General tasks"
# GPT-5-Codex - Previous coding model
codex exec -m gpt-5-codex "Code generation"
```
### o-Series (Reasoning Models)
```bash
# o3 - Smartest reasoning model
codex exec -m o3 "Complex architectural decisions"
# o4-mini - Efficient reasoning
codex exec -m o4-mini "Quick reasoning tasks"
```
### New GPT-5.2 Features
```bash
# Extended reasoning with xhigh effort (GPT-5.2 Pro/Thinking)
codex exec -m gpt-5.2-pro --reasoning-effort xhigh "Maximum accuracy task"
# Context compaction for long sessions
codex exec -m gpt-5.2 --compact "Long document analysis"
# Concise reasoning summaries
codex exec -m gpt-5.2 --concise-reasoning "Explain this code"
```
## Claude + Codex Collaboration Patterns
**Claude orchestrates, Codex executes** - The Think-Act-Observe Loop:
### Structured Workflows
```bash
#!/bin/bash
# Claude directs Codex for complete feature development
# THINK: Claude analyzes requirements
echo "Goal: Add user profile caching"
# ACT: Codex researches best practices (with web search)
codex exec --search --dangerously-bypass-approvals-and-sandbox \
"Research Redis caching patterns and create implementation plan" \
> plan.md
# OBSERVE: Claude reviews the plan
cat plan.md
# ACT: Codex implements (full automation)
codex exec --dangerously-bypass-approvals-and-sandbox --json \
"Implement the caching system according to @plan.md" \
> implementation.json
# OBSERVE: Claude verifies
jq '.changes[]' implementation.json
# ACT: Codex tests
codex exec --dangerously-bypass-approvals-and-sandbox \
"Generate and run comprehensive tests"
# Loop continues...
```
### JSON Output for AI Parsing
```bash
# Get structured output for Claude to parse
codex exec --json "List all exported functions in ./src" > functions.json
# Claude processes reliably
for func in $(jq -r '.functions[].name' functions.json); do
echo "Processing: $func"
codex exec --dangerously-bypass-approvals-and-sandbox \
"Add input validation to $func function"
done
```
### Sequential Task Decomposition
```bash
#!/bin/bash
# Claude breaks down complex goal into safe atomic steps
echo "=== Feature: Add OAuth2 Authentication ==="
# Step 1: Research (safe, read-only)
codex exec --search --full-auto "Research OAuth2 best practices 2025" > research.md
# Step 2: Plan (Claude reviews)
codex exec "Create detailed OAuth2 implementation plan based on @research.md"
read -p "Review plan. Continue? [y/N] " -r
# Step 3: Install dependencies
codex exec --dangerously-bypass-approvals-and-sandbox "Install OAuth2 packages"
# Step 4: Generate code
codex exec --dangerously-bypass-approvals-and-sandbox \
"Generate OAuth2 auth module according to plan"
# Step 5: Tests
codex exec --dangerously-bypass-approvals-and-sandbox \
"Generate comprehensive OAuth2 tests"
# Step 6: Verify
codex exec --dangerously-bypass-approvals-and-sandbox "Run all tests and fix failures"
```
## Advanced Features
### Web Search Integration
```bash
# Enable web search for research
codex exec --search --dangerously-bypass-approvals-and-sandbox \
"Research latest React 19 features and create migration guide"
# Research-driven development
codex exec --search --full-auto \
"Find best practices for microservices and implement API gateway"
```
### Multimodal (Code + Images)
```bash
# Attach design screenshots
codex exec -i design.png --dangerously-bypass-approvals-and-sandbox \
"Implement this UI design in React"
# Multiple images
codex exec -i mockup1.png -i mockup2.png --full-auto \
"Compare these designs and implement the better approach"
```
### Git-Aware Workflows
```bash
# Apply Codex changes as git patch
codex apply
# or
codex a
# Work on git branch
git checkout -b feature/new-auth
codex exec --dangerously-bypass-approvals-and-sandbox \
"Implement authentication with clean commits"
# Codex respects .gitignore and git history
```
### Resume Sessions
```bash
# Resume last session
codex exec resume --last
# Pick from previous sessions
codex resume
```
### Configuration Profiles
```bash
# Create profile in ~/.codex/config.toml
[profiles.auto-dev]
model = "gpt-5.1-codex"
ask_for_approval = "never"
sandbox = "workspace-write"
search = true
# Use profile
codex exec -p auto-dev "Develop new feature automatically"
```
### MCP Server Integration
```bash
# Run as MCP server
codex mcp
# Manage MCP servers (experimental)
codex mcp list
codex mcp add <server-name>
```
## Core Workflows
### Automated Code Generation
```bash
#!/bin/bash
# Complete automation for code generation
generate_api() {
local spec="$1"
codex exec --dangerously-bypass-approvals-and-sandbox \
--json \
--search \
"Read API specification @$spec and generate:
1. Data models with validation
2. API endpoints with OpenAPI docs
3. Database migrations
4. Comprehensive tests
5. Error handling middleware
6. Authentication middleware
7. Rate limiting
8. API documentation"
}
# Usage
generate_api "./specs/user-api.yaml"
```
### Automated Refactoring
```bash
#!/bin/bash
# Safe, automated refactoring workflow
refactor_module() {
local module="$1"
# Backup first
git stash push -m "pre-refactor-$(date +%s)"
# Full automation with git safety
codex exec --dangerously-bypass-approvals-and-sandbox \
"Refactor $module:
1. Analyze current code structure
2. Identify improvements
3. Apply modern patterns
4. Add comprehensive tests
5. Run all tests
6. Fix any test failures
7. Update documentation
8. Create clean git commits"
if [ $? -eq 0 ]; then
echo "Refactoring complete!"
else
git stash pop
echo "Refactoring failed, restored backup"
fi
}
# Usage
refactor_module "./src/auth"
```
### Test Generation & Fixing
```bash
#!/bin/bash
# Automated test generation and fixing
automate_testing() {
local target="$1"
codex exec --dangerously-bypass-approvals-and-sandbox \
"Complete testing workflow for $target:
1. Analyze code coverage gaps
2. Generate comprehensive unit tests
3. Generate integration tests
4. Generate end-to-end tests
5. Run all tests
6. Fix any failing tests
7. Achieve 100% coverage
8. Generate test report"
}
# Usage
automate_testing "./src"
```
### CI/CD Integration
```yaml
# GitHub Actions with Codex
name: Codex Automation
on: [push, pull_request]
jobs:
codex-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
- name: Install Codex CLI
run: npm install -g @openai/codex
- name: Run Codex Analysis
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex exec --dangerously-bypass-approvals-and-sandbox \
--json \
"Analyze code changes, run tests, fix issues, generate report" \
> codex-report.json
- name: Upload Report
uses: actions/upload-artifact@v3
with:
name: codex-analysis
path: codex-report.json
```
## Configuration
### Config File (~/.codex/config.toml)
```toml
# Default model (December 2025)
model = "gpt-5.1-codex-max" # Best for agentic coding
# Approval policy
ask_for_approval = "on-request" # or "never", "on-failure", "untrusted"
# Sandbox mode
sandbox = "workspace-write" # or "read-only", "danger-full-access"
# Enable web search
search = true
# Additional writable directories
add_dirs = ["./docs", "./tests"]
# Feature flags
[features]
web_search = true
multimodal = true
mcp = true
# Profiles for different workflows
[profiles.safe]
ask_for_approval = "untrusted"
sandbox = "read-only"
[profiles.auto]
ask_for_approval = "never"
sandbox = "workspace-write"
search = true
[profiles.danger]
ask_for_approval = "never"
sandbox = "danger-full-access"
search = true
# NEW: GPT-5.2 optimized profiles
[profiles.gpt52]
model = "gpt-5.2"
ask_for_approval = "never"
sandbox = "workspace-write"
search = true
[profiles.gpt52-pro]
model = "gpt-5.2-pro"
reasoning_effort = "xhigh"
ask_for_approval = "on-request"
sandbox = "workspace-write"
[profiles.long-context]
model = "gpt-5.2"
ask_for_approval = "never"
sandbox = "workspace-write"
compact = true # Enable context compaction
```
### Environment Variables
```bash
# Authentication
export OPENAI_API_KEY="your-key"
# Default model (December 2025)
export CODEX_MODEL="gpt-5.1-codex-max" # For agentic coding
# export CODEX_MODEL="gpt-5.2" # For general tasks with 400K context
# export CODEX_MODEL="gpt-5.2-pro" # For maximum accuracy
# Default config path
export CODEX_CONFIG_PATH="~/.codex/config.toml"
# GPT-5.2 specific options
export CODEX_REASONING_EFFORT="high" # medium, high, xhigh
```
## Best Practices
### Security with Bypass Mode
When using `--dangerously-bypass-approvals-and-sandbox`:
1. **Use in Controlled Environments**
- CI/CD with external sandboxing
- Docker containers
- Disposable development environments
2. **Always Have Backups**
```bash
git stash push -m "pre-codex-$(date +%s)"
codex exec --dangerously-bypass-approvals-and-sandbox "task"
```
3. **Use Git for Safety**
- Work on feature branches
- Review diffs before pushing
- Use `codex apply` to review changes
4. **Limit Scope**
```bash
codex exec --dangerously-bypass-approvals-and-sandbox \
-C ./specific/directory \
"Only affect this directory"
```
### Model Selection Strategy (December 2025)
```bash
# Quick tasks: o4-mini or gpt-5.1-codex-mini
codex exec -m o4-mini "Format code with Prettier"
codex exec -m gpt-5.1-codex-mini "Quick code fixes"
# Standard development: gpt-5.1-codex-max (DEFAULT)
codex exec -m gpt-5.1-codex-max "Implement user authentication"
# Long-context tasks: gpt-5.2 (400K context)
codex exec -m gpt-5.2 "Analyze entire codebase"
# Complex reasoning: o3 or gpt-5.2-pro with xhigh
codex exec -m o3 "Design scalable microservices architecture"
codex exec -m gpt-5.2-pro --reasoning-effort xhigh "Critical architecture decisions"
# Speed-optimized: gpt-5.2-chat-latest (Instant)
codex exec -m gpt-5.2-chat-latest "Quick information retrieval"
# Maximum accuracy: gpt-5.2-pro
codex exec -m gpt-5.2-pro "High-stakes production code"
```
### Performance Optimization
```bash
# Use JSON for faster parsing
codex exec --json "task" | jq .
# Skip git checks if not needed
codex exec --skip-git-repo-check "task"
# Specify working directory
codex exec -C ./project "task"
# Use profiles to avoid repetitive flags
codex exec -p auto-dev "task"
```
## Troubleshooting
### Common Issues
**Authentication Failed**
```bash
codex logout
codex login
```
**Model Not Available**
```bash
# Check available models (December 2025)
codex exec -m gpt-5.2 "test" || echo "GPT-5.2 not available"
# Fall back to stable coding model
codex exec -m gpt-5.1-codex-max "task"
# Or use previous generation
codex exec -m gpt-5.1-codex "task"
```
**Sandbox Errors**
```bash
# Try different sandbox mode
codex exec -s danger-full-access "task"
# Or bypass entirely (if safe)
codex exec --dangerously-bypass-approvals-and-sandbox "task"
```
## Related Skills
- `codex-auth`: Authentication and API key management
- `codex-chat`: Interactive REPL workflows
- `codex-tools`: Tool execution and file operations
- `codex-review`: Code review and git workflows
- `codex-git`: Git-aware development patterns
## Updates
```bash
# Update Codex CLI
npm update -g @openai/codex
# Check version
codex --version
# Check for new models
codex exec "What models are available?"
```
---
**Created for Claude Code** - Full automation for AI-to-AI collaboration
test-codex-skills.sh
#!/bin/bash
# Test script for OpenAI Codex CLI skills
# Validates all skills work correctly with installed Codex CLI
# Updated: December 2025 - GPT-5.2 Release
set -e
echo "========================================="
echo "Codex CLI Skills Validation Test"
echo "GPT-5.2 Update - December 2025"
echo "========================================="
echo ""
# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Test counters
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0
# Test function
run_test() {
local test_name="$1"
local test_command="$2"
TESTS_RUN=$((TESTS_RUN + 1))
echo -n "Testing: $test_name ... "
if eval "$test_command" > /dev/null 2>&1; then
echo -e "${GREEN}✓ PASS${NC}"
TESTS_PASSED=$((TESTS_PASSED + 1))
return 0
else
echo -e "${RED}✗ FAIL${NC}"
TESTS_FAILED=$((TESTS_FAILED + 1))
return 1
fi
}
# 1. Check Codex CLI Installation
echo "=== 1. Installation Check ==="
run_test "Codex CLI installed" "which codex"
run_test "Codex CLI version" "codex --version"
echo ""
# 2. Check Authentication
echo "=== 2. Authentication Check ==="
if [ -n "$OPENAI_API_KEY" ]; then
echo -e "${GREEN}✓ API key found in environment${NC}"
TESTS_PASSED=$((TESTS_PASSED + 1))
elif [ -f ~/.codex/config.toml ]; then
echo -e "${GREEN}✓ Config file found${NC}"
TESTS_PASSED=$((TESTS_PASSED + 1))
elif [ -f ~/.codex/credentials ]; then
echo -e "${GREEN}✓ OAuth credentials found${NC}"
TESTS_PASSED=$((TESTS_PASSED + 1))
else
echo -e "${YELLOW}⚠ No authentication found${NC}"
echo " Run: codex login OR export OPENAI_API_KEY=..."
fi
TESTS_RUN=$((TESTS_RUN + 1))
echo ""
# 3. Check Skills Files
echo "=== 3. Skills Files Check ==="
SKILL_DIR=".claude/skills/codex-cli"
run_test "codex-cli/SKILL.md exists" "test -f $SKILL_DIR/../codex-cli/SKILL.md"
run_test "codex-auth/SKILL.md exists" "test -f $SKILL_DIR/../codex-auth/SKILL.md"
run_test "codex-tools/SKILL.md exists" "test -f $SKILL_DIR/../codex-tools/SKILL.md"
run_test "codex-chat/SKILL.md exists" "test -f $SKILL_DIR/../codex-chat/SKILL.md"
run_test "codex-review/SKILL.md exists" "test -f $SKILL_DIR/../codex-review/SKILL.md"
run_test "codex-git/SKILL.md exists" "test -f $SKILL_DIR/../codex-git/SKILL.md"
run_test "Integration guide exists" "test -f $SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md"
run_test "README exists" "test -f $SKILL_DIR/README.md"
echo ""
# 4. Validate YAML Frontmatter
echo "=== 4. YAML Frontmatter Validation ==="
validate_yaml() {
local file="$1"
local skill_name="$2"
if grep -q "^---$" "$file" && \
grep -q "^name: $skill_name$" "$file" && \
grep -q "^description:" "$file"; then
return 0
else
return 1
fi
}
run_test "codex-cli frontmatter" "validate_yaml '$SKILL_DIR/../codex-cli/SKILL.md' 'codex-cli'"
run_test "codex-auth frontmatter" "validate_yaml '$SKILL_DIR/../codex-auth/SKILL.md' 'codex-auth'"
run_test "codex-tools frontmatter" "validate_yaml '$SKILL_DIR/../codex-tools/SKILL.md' 'codex-tools'"
run_test "codex-chat frontmatter" "validate_yaml '$SKILL_DIR/../codex-chat/SKILL.md' 'codex-chat'"
run_test "codex-review frontmatter" "validate_yaml '$SKILL_DIR/../codex-review/SKILL.md' 'codex-review'"
run_test "codex-git frontmatter" "validate_yaml '$SKILL_DIR/../codex-git/SKILL.md' 'codex-git'"
echo ""
# 5. Test Basic Codex Commands
echo "=== 5. Basic Codex Commands ==="
if [ -n "$OPENAI_API_KEY" ] || [ -f ~/.codex/credentials ]; then
echo -e "${YELLOW}Testing with actual Codex CLI (rate limits may apply)${NC}"
# Simple test (may hit rate limits)
if codex exec "What is 2+2? Reply with just the number." 2>/dev/null | grep -q "4"; then
echo -e "${GREEN}✓ Codex exec works${NC}"
TESTS_PASSED=$((TESTS_PASSED + 1))
else
echo -e "${YELLOW}⚠ Codex exec test skipped (rate limited or auth issue)${NC}"
fi
TESTS_RUN=$((TESTS_RUN + 1))
else
echo -e "${YELLOW}⚠ Skipping live tests (no authentication)${NC}"
fi
echo ""
# 6. Validate Key Automation Flags
echo "=== 6. Automation Flags Check ==="
check_flag_documented() {
local flag="$1"
local file="$2"
grep -qFe "$flag" "$file"
}
run_test "--dangerously-bypass-approvals-and-sandbox documented" \
"check_flag_documented '--dangerously-bypass-approvals-and-sandbox' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "--full-auto documented" \
"check_flag_documented '--full-auto' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "--json flag documented" \
"check_flag_documented '--json' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "--search flag documented" \
"check_flag_documented '--search' \"$SKILL_DIR/../codex-cli/SKILL.md\""
echo ""
# 7. Validate Models Documented (GPT-5.2 Update)
echo "=== 7. Models Documentation Check (December 2025) ==="
check_model_documented() {
local model="$1"
local file="$2"
grep -q "$model" "$file"
}
# GPT-5.2 Models (NEW)
run_test "gpt-5.2 documented" \
"check_model_documented 'gpt-5.2' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "gpt-5.2-pro documented" \
"check_model_documented 'gpt-5.2-pro' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "gpt-5.2-chat-latest documented" \
"check_model_documented 'gpt-5.2-chat-latest' \"$SKILL_DIR/../codex-cli/SKILL.md\""
# GPT-5.1 Codex Models (Recommended for coding)
run_test "gpt-5.1-codex-max documented" \
"check_model_documented 'gpt-5.1-codex-max' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "gpt-5.1-codex documented" \
"check_model_documented 'gpt-5.1-codex' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "gpt-5.1-codex-mini documented" \
"check_model_documented 'gpt-5.1-codex-mini' \"$SKILL_DIR/../codex-cli/SKILL.md\""
# Reasoning Models
run_test "o3 model documented" \
"check_model_documented 'o3' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "o4-mini model documented" \
"check_model_documented 'o4-mini' \"$SKILL_DIR/../codex-cli/SKILL.md\""
echo ""
# 7b. GPT-5.2 Features Validation
echo "=== 7b. GPT-5.2 Features Check ==="
run_test "400K context window documented" \
"check_model_documented '400K context' \"$SKILL_DIR/../codex-cli/SKILL.md\" || check_model_documented '400,000' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "128K output tokens documented" \
"check_model_documented '128K' \"$SKILL_DIR/../codex-cli/SKILL.md\" || check_model_documented '128,000' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "reasoning.effort parameter documented" \
"check_model_documented 'reasoning.effort' \"$SKILL_DIR/../codex-cli/SKILL.md\" || check_model_documented 'reasoning-effort' \"$SKILL_DIR/../codex-cli/SKILL.md\" || check_model_documented 'xhigh' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "compaction feature documented" \
"check_model_documented 'compact' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "December 2025 update mentioned" \
"check_model_documented 'December 2025' \"$SKILL_DIR/../codex-cli/SKILL.md\""
echo ""
# 8. Integration Guide Validation
echo "=== 8. Integration Guide Check ==="
run_test "Think-Act-Observe Loop documented" \
"grep -q 'Think-Act-Observe Loop' \"$SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md\""
run_test "Integration patterns documented" \
"grep -q 'Integration Patterns' \"$SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md\""
run_test "Model selection strategy documented" \
"grep -q 'Model Selection Strategy' \"$SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md\""
run_test "Complete feature example included" \
"grep -q 'Complete Feature Development' \"$SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md\""
run_test "Safety patterns documented" \
"grep -q 'Safety Patterns' \"$SKILL_DIR/CLAUDE-CODEX-INTEGRATION.md\""
echo ""
# 9. Git Integration Validation
echo "=== 9. Git Integration Check ==="
run_test "codex apply documented" \
"grep -q 'codex apply' \"$SKILL_DIR/../codex-git/SKILL.md\""
run_test "codex a shorthand documented" \
"grep -q 'codex a' \"$SKILL_DIR/../codex-git/SKILL.md\""
run_test "Commit generation documented" \
"grep -q 'commit' \"$SKILL_DIR/../codex-git/SKILL.md\""
run_test "PR automation documented" \
"grep -q 'PR' \"$SKILL_DIR/../codex-git/SKILL.md\""
echo ""
# 10. Cross-References Validation
echo "=== 10. Cross-References Check ==="
run_test "codex-cli references codex-auth" \
"grep -q 'codex-auth' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "codex-cli references codex-tools" \
"grep -q 'codex-tools' \"$SKILL_DIR/../codex-cli/SKILL.md\""
run_test "README references all skills" \
"grep -q 'codex-git' \"$SKILL_DIR/README.md\""
run_test "Integration guide referenced in README" \
"grep -q 'CLAUDE-CODEX-INTEGRATION.md' \"$SKILL_DIR/README.md\""
echo ""
# Summary
echo "========================================="
echo "Test Summary"
echo "========================================="
echo "Tests run: $TESTS_RUN"
echo -e "${GREEN}Tests passed: $TESTS_PASSED${NC}"
if [ $TESTS_FAILED -gt 0 ]; then
echo -e "${RED}Tests failed: $TESTS_FAILED${NC}"
echo ""
echo -e "${RED}✗ Validation FAILED${NC}"
exit 1
else
echo -e "${GREEN}Tests failed: $TESTS_FAILED${NC}"
echo ""
echo -e "${GREEN}✓ All validations PASSED${NC}"
echo ""
echo "The Codex CLI skills package is ready to use!"
echo ""
echo "Quick Start:"
echo " 1. Ensure Codex CLI is installed: codex --version"
echo " 2. Authenticate: codex login (or set OPENAI_API_KEY)"
echo " 3. Test: codex exec \"Hello, Codex!\""
echo " 4. Read: .claude/skills/codex-cli/README.md"
echo " 5. Build something amazing with Claude + Codex!"
exit 0
fi