references/claude-code-advanced.md
# Claude Code CLI Advanced Reference
## Configuration Deep Dive
### Configuration Files
```
~/.claude/settings.json # User settings (all projects)
.claude/settings.json # Project settings (shared)
.claude/settings.local.json # Local settings (gitignored)
```
### Settings Hierarchy
Local > Project > User (more specific wins)
### Full Settings Example
```json
{
"model": "claude-sonnet-4-5-20250929",
"verbose": false,
"theme": "dark",
"permissions": {
"allow": ["Bash(git:*)", "Read", "Edit"],
"deny": ["Bash(rm -rf:*)"]
},
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-server-filesystem", "/path/to/allowed"]
}
}
}
```
### Environment Variables
| Variable | Purpose |
|----------|---------|
| `ANTHROPIC_API_KEY` | API authentication |
| `CLAUDE_CODE_USE_BEDROCK` | Use AWS Bedrock |
| `CLAUDE_CODE_USE_VERTEX` | Use Google Vertex |
| `CLAUDE_CODE_DEBUG` | Enable debug logging |
| `CLAUDE_CODE_MAX_TURNS` | Default max turns |
## Print Mode Patterns
### Basic Patterns
```bash
# Simple query
claude -p "explain this function"
# With model selection
claude -p --model opus "complex analysis"
# Process file
cat code.py | claude -p "review this code"
# Multiple files
cat file1.ts file2.ts | claude -p "find inconsistencies"
```
### Output Formats
```bash
# Plain text (default)
claude -p "summarize" --output-format text
# Single JSON object
claude -p "extract data" --output-format json
# Streaming JSON (real-time)
claude -p "long task" --output-format stream-json
# With partial messages
claude -p --output-format stream-json --include-partial-messages "task"
```
### Streaming Input/Output
```bash
# Full streaming pipeline
claude -p \
--input-format stream-json \
--output-format stream-json \
--include-partial-messages \
--replay-user-messages
```
### Structured Output
```bash
# JSON Schema validation
claude -p --json-schema '{
"type": "object",
"properties": {
"bugs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": {"type": "string"},
"line": {"type": "integer"},
"severity": {"enum": ["low", "medium", "high"]}
}
}
}
}
}' "find bugs in src/"
```
### Budget & Turn Limits
```bash
# Spending limit
claude -p --max-budget-usd 2.50 "expensive analysis"
# Turn limit (prevent runaway)
claude -p --max-turns 5 "quick fix"
# Combined
claude -p --max-turns 10 --max-budget-usd 5.00 "complex refactor"
```
## Session Management
### Continue vs Resume
```bash
# Continue: last conversation in current directory
claude -c
claude -c -p "check for issues"
# Resume: specific session (any directory)
claude -r "session-id"
claude -r "session-name" "continue this"
claude --resume abc123 --fork-session "try different approach"
```
### Session ID Control
```bash
# Use specific UUID
claude --session-id "550e8400-e29b-41d4-a716-446655440000" "task"
# Disable persistence
claude -p --no-session-persistence "one-off task"
```
### Remote Sessions (Experimental)
```bash
# Create web session on claude.ai
claude --remote "complex task"
# Resume web session in terminal
claude --teleport
```
## Custom Agents
### Defining Subagents
```bash
claude --agents '{
"security-reviewer": {
"description": "Security expert. Use proactively for auth/crypto code.",
"prompt": "You are a security expert. Focus on: injection vulnerabilities, auth bypasses, crypto weaknesses, data exposure.",
"tools": ["Read", "Grep", "Glob"],
"model": "opus"
},
"test-writer": {
"description": "Test specialist for generating comprehensive tests.",
"prompt": "You write thorough tests. Cover edge cases, error paths, and boundary conditions.",
"tools": ["Read", "Write", "Edit", "Bash"],
"model": "sonnet"
},
"quick-fixer": {
"description": "Fast fixes for simple issues.",
"prompt": "Make minimal, focused changes. No refactoring.",
"model": "haiku"
}
}'
```
### Agent Fields
| Field | Required | Description |
|-------|----------|-------------|
| `description` | Yes | When to invoke (shown in Task tool) |
| `prompt` | Yes | System prompt for agent |
| `tools` | No | Available tools (inherits all if omitted) |
| `model` | No | sonnet/opus/haiku (inherits if omitted) |
### Using Agents
```bash
# Claude automatically invokes based on description
# Or force specific agent
claude --agent security-reviewer "review auth module"
```
## Custom Commands
### Project Commands
Location: `.claude/commands/<name>.md`
Example `.claude/commands/fix-issue.md`:
```markdown
Fix GitHub issue #$ARGUMENTS
Steps:
1. Fetch issue details from GitHub
2. Understand the problem
3. Locate relevant code
4. Implement fix
5. Write/update tests
6. Create commit with conventional format
```
Usage: `/project:fix-issue 1234`
### User Commands
Location: `~/.claude/commands/<name>.md`
Example `~/.claude/commands/daily-standup.md`:
```markdown
Generate daily standup report:
1. Check git log for yesterday's commits
2. List current WIP branches
3. Identify blockers from TODO comments
4. Suggest today's priorities
```
Usage: `/user:daily-standup`
### Command Arguments
- `$ARGUMENTS` - All arguments as string
- Arguments passed after command name
## MCP Server Patterns
### Transport Types
```bash
# Stdio (default) - subprocess
claude mcp add my-server -- npx @org/mcp-server
# SSE (Server-Sent Events)
claude mcp add -t sse sse-server https://api.example.com/sse
# HTTP (Streamable HTTP)
claude mcp add -t http http-server https://api.example.com/mcp
```
### Scopes
```bash
# Local (current machine, not committed)
claude mcp add -s local my-server -- cmd
# Project (committed to repo)
claude mcp add -s project shared-server -- cmd
# User (all projects for this user)
claude mcp add -s user global-server -- cmd
```
### Environment & Headers
```bash
# Environment variables
claude mcp add -e API_KEY=xxx -e DEBUG=true my-server -- cmd
# HTTP headers
claude mcp add -t http \
-H "Authorization: Bearer token" \
-H "X-Custom: value" \
api-server https://api.example.com/mcp
```
### Import from Claude Desktop
```bash
# Auto-import (Mac/WSL only)
claude mcp add-from-claude-desktop
```
### Running Claude as MCP Server
```bash
# Start Claude as MCP server
claude mcp serve
# With debug
claude mcp serve --debug
```
## Permission Modes
### Available Modes
| Mode | Behavior |
|------|----------|
| `default` | Normal prompting |
| `acceptEdits` | Auto-accept file edits |
| `plan` | Read-only planning mode |
| `dontAsk` | Never prompt, fail on denied |
| `delegate` | Delegate to permission tool |
| `bypassPermissions` | Skip all (requires flag) |
### Usage
```bash
# Start in plan mode
claude --permission-mode plan "analyze architecture"
# Auto-accept edits
claude --permission-mode acceptEdits "refactor"
# Full bypass (dangerous)
claude --dangerously-skip-permissions "trusted task"
# Enable bypass as option
claude --allow-dangerously-skip-permissions --permission-mode default
```
### Permission Prompt Tool (CI/CD)
```bash
# Use MCP tool for permission decisions
claude -p --permission-prompt-tool my_auth_tool "task"
```
## Tool Configuration
### Restrict Tools
```bash
# Only specific tools
claude --tools "Bash,Read,Edit"
# Disable all tools
claude --tools ""
# Default set
claude --tools "default"
```
### Allow/Deny Lists
```bash
# Auto-approve specific patterns
claude --allowedTools "Bash(git:*)" "Read" "Grep"
# Block dangerous patterns
claude --disallowedTools "Bash(rm -rf:*)" "Bash(curl|wget:*)"
```
### Tool Pattern Syntax
```
Bash(git:*) # All git commands
Bash(npm test:*) # npm test with any args
Read # All Read operations
Edit(src/**:*) # Edit files in src/
```
## Plugin System
### Installation
```bash
# From default marketplace
claude plugin install code-review
# From specific marketplace
claude plugin install code-review@anthropic
# Project scope
claude plugin install -s project team-plugin
# User scope (default)
claude plugin install -s user my-plugin
```
### Management
```bash
# List installed
claude plugin list
claude plugin list --all # Include disabled
# Enable/disable
claude plugin enable code-review
claude plugin disable code-review
# Update
claude plugin update code-review
claude plugin update --all
# Remove
claude plugin uninstall code-review
```
### Plugin Development
```bash
# Validate manifest
claude plugin validate ./my-plugin
# Marketplace management
claude plugin marketplace list
claude plugin marketplace add https://my-marketplace.com/manifest.json
```
## Debug & Diagnostics
### Debug Mode
```bash
# All debug output
claude --debug
# Filtered categories
claude --debug "api,mcp"
claude --debug "!statsig,!file" # Exclude categories
```
### Doctor Command
```bash
claude doctor
```
Checks:
- Authentication status
- API connectivity
- MCP server health
- Plugin status
- Configuration validity
## Integration Patterns
### CI/CD Pipeline
```yaml
# GitHub Actions
- name: Claude Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p \
--output-format json \
--max-turns 5 \
--max-budget-usd 2.00 \
"Review changes and output JSON report" > review.json
```
### Git Hooks
```bash
#!/bin/bash
# .git/hooks/pre-commit
claude -p --max-turns 2 "Check staged files for issues" || exit 1
```
### Shell Aliases
```bash
# ~/.bashrc or ~/.zshrc
alias cc="claude"
alias ccp="claude -p"
alias ccr="claude -c" # resume
alias ccm="claude --model opus"
```
### VS Code Integration
```json
// .vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "Claude Explain",
"type": "shell",
"command": "claude -p 'explain ${file}'",
"problemMatcher": []
}
]
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `Authentication failed` | Invalid/expired token | `claude setup-token` |
| `Rate limited` | Too many requests | Use `--fallback-model` |
| `Model overloaded` | High demand | Use `--fallback-model haiku` |
| `Context exceeded` | Too much content | Use `/compact` or fresh session |
| `Permission denied` | Tool blocked | Check `--allowedTools` |
### Graceful Degradation
```bash
# Auto-fallback on overload
claude -p --fallback-model haiku "task"
# Manual retry logic
claude -p "task" || claude -p --model haiku "task"
```
## Performance Tips
### Reduce Latency
```bash
# Use faster model
claude --model haiku "simple task"
# Disable persistence for one-off
claude -p --no-session-persistence "quick query"
# Limit turns
claude -p --max-turns 3 "focused task"
```
### Manage Context
```bash
# In interactive: /compact
# Fresh start for unrelated work
claude --session-id "$(uuidgen)" "new topic"
```
### Batch Operations
```bash
# Process multiple files
for f in src/*.ts; do
claude -p "review $f" >> reviews.txt
done
# Parallel (careful with rate limits)
parallel -j2 'claude -p "review {}"' ::: src/*.ts
```
references/codex-advanced.md
# Codex CLI Advanced Reference
## Configuration Deep Dive
### Config File Location
```
~/.codex/config.toml
```
### Full Configuration Example
```toml
# Default model
model = "gpt-5-codex"
# Approval policy: untrusted | on-failure | on-request | never
approval_policy = "on-request"
# Enable features
[features]
web_search = true
mcp = true
# Sandbox configuration
[sandbox]
mode = "workspace-write" # read-only | workspace-write | danger-full-access
permissions = ["disk-full-read-access"]
# Shell environment
[shell_environment_policy]
inherit = "all" # all | none | allowlist
# allowlist = ["PATH", "HOME", "USER"]
# Named profiles
[profiles.ci]
model = "gpt-4.1"
approval_policy = "never"
[profiles.review]
model = "gpt-5"
approval_policy = "on-request"
# MCP servers
[mcp_servers.my-server]
command = ["npx", "my-mcp-server"]
env = { API_KEY = "xxx" }
[mcp_servers.http-server]
url = "https://api.example.com/mcp"
bearer_token_env_var = "API_TOKEN"
```
### Config Override Syntax
```bash
# Simple value
codex -c model="gpt-5"
# Nested value (dotted path)
codex -c sandbox.mode="workspace-write"
# Array value (TOML syntax)
codex -c 'sandbox_permissions=["disk-full-read-access"]'
# Complex nested
codex -c 'shell_environment_policy.inherit=all'
```
## Exec Mode Patterns
### Pipeline Integration
```bash
# Read prompt from file
cat prompt.txt | codex exec -
# Chain with other tools
codex exec --json "analyze" | jq '.messages[-1].content'
# Save structured output
codex exec --output-schema schema.json -o result.json "generate"
# CI error handling
codex exec "fix" || echo "Codex failed" && exit 1
```
### Output Schema Validation
```json
// schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"files_changed": {
"type": "array",
"items": { "type": "string" }
},
"summary": { "type": "string" }
},
"required": ["files_changed", "summary"]
}
```
```bash
codex exec --output-schema schema.json "refactor and report changes"
```
### Resume Patterns
```bash
# Resume with new context
codex resume <id> "now also add tests"
# Resume in exec mode
codex exec resume <id>
codex exec resume --last
```
## Review Command Patterns
### Branch Comparison
```bash
# Current branch vs main
codex review
# Against specific base
codex review --base develop
codex review --base origin/release-2.0
# Uncommitted changes (staged + unstaged + untracked)
codex review --uncommitted
# Specific commit
codex review --commit abc123
codex review --commit HEAD~3
# With custom focus
codex review "focus on security vulnerabilities"
codex review --base main "check for breaking changes"
```
### Review in CI
```bash
#!/bin/bash
# pr-review.sh
codex review --base origin/main \
--title "PR #${PR_NUMBER}: ${PR_TITLE}" \
"Check for: security issues, performance regressions, missing tests"
```
## Cloud Tasks (Experimental)
### Submit and Monitor
```bash
# Submit task
TASK_ID=$(codex cloud exec "fix all bugs" --env prod-env --json | jq -r '.task_id')
# Poll status
while true; do
STATUS=$(codex cloud status $TASK_ID --json | jq -r '.status')
echo "Status: $STATUS"
[ "$STATUS" = "completed" ] && break
sleep 30
done
# Review and apply
codex cloud diff $TASK_ID
codex cloud apply $TASK_ID
```
### Environment Management
```bash
# List environments (via TUI)
codex cloud
# Target specific environment
codex cloud exec "task" --env my-env-id
# Multiple attempts for complex tasks
codex cloud exec "complex refactor" --env prod --attempts 4
```
## MCP Server Patterns
### Stdio Server with Environment
```bash
codex mcp add my-db \
--env DATABASE_URL="postgres://..." \
--env LOG_LEVEL="debug" \
-- npx @my-org/db-mcp-server
```
### HTTP Server with Auth
```bash
codex mcp add github-api \
--url https://api.github.com/mcp \
--bearer-token-env-var GITHUB_TOKEN
# OAuth flow (for servers that support it)
codex mcp login github-api --scopes repo,workflow
```
### Verifying MCP Tools
```bash
# List all available tools from MCP
codex mcp list --json | jq '.[].tools'
# In interactive session
# Type: /mcp
```
## Sandbox Deep Dive
### macOS Seatbelt
```bash
# Basic sandbox
codex sandbox macos -- npm test
# With workspace write
codex sandbox macos --full-auto -- npm run build
# Custom config
codex sandbox macos -c 'sandbox_permissions=["network-client"]' -- curl example.com
```
### Linux Landlock
```bash
# Read-only
codex sandbox linux -- cat /etc/passwd
# With write access
codex sandbox linux --full-auto -- npm install
```
### Permission Model
| Permission | Description |
|------------|-------------|
| `disk-full-read-access` | Read any file |
| `disk-write-access` | Write to workspace |
| `network-client` | Outbound network |
| `network-server` | Listen on ports |
## Feature Flags
### List Features
```bash
codex features list
```
### Enable/Disable
```bash
# Via flag
codex --enable mcp --enable web_search "task"
codex --disable telemetry "task"
# Via config
codex -c 'features.mcp=true' "task"
```
### Common Features
| Feature | Description |
|---------|-------------|
| `mcp` | Model Context Protocol support |
| `web_search` | Web search capability |
| `telemetry` | Usage analytics |
| `experimental_tools` | Bleeding edge tools |
## Error Handling
### Exit Codes
| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error |
| 2 | Invalid arguments |
| 3 | Authentication error |
| 4 | Network error |
| 5 | Sandbox violation |
### Handling in Scripts
```bash
#!/bin/bash
set -e
codex exec "task" 2>&1 | tee codex.log
EXIT_CODE=${PIPESTATUS[0]}
if [ $EXIT_CODE -ne 0 ]; then
echo "Codex failed with code $EXIT_CODE"
cat codex.log | tail -20
exit $EXIT_CODE
fi
```
## Performance Optimization
### Reduce Latency
```bash
# Use faster model for simple tasks
codex -m gpt-4.1-mini "simple formatting fix"
# Skip unnecessary checks
codex exec --skip-git-repo-check "standalone task"
```
### Manage Context
```bash
# In interactive session, use /compact regularly
# Or start fresh for independent tasks
codex --no-cache "new unrelated task"
```
### Parallel Execution
```bash
# Run multiple independent tasks
codex exec "fix file1.ts" &
codex exec "fix file2.ts" &
wait
```
## Integration Examples
### Git Hooks
```bash
# .git/hooks/pre-commit
#!/bin/bash
codex exec -m gpt-4.1-mini "check staged files for issues" || exit 1
```
### VS Code Task
```json
{
"label": "Codex Review",
"type": "shell",
"command": "codex review --uncommitted",
"problemMatcher": []
}
```
### GitHub Action
```yaml
name: Codex Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Codex
run: npm i -g @openai/codex
- name: Login
run: echo "${{ secrets.OPENAI_API_KEY }}" | codex login --with-api-key
- name: Review PR
run: codex review --base origin/${{ github.base_ref }}
```
references/comparison-and-edge-cases.md
# CLI Comparison & Edge Cases
## Feature Comparison Matrix
| Feature | Codex CLI | Claude Code CLI |
|---------|-----------|-----------------|
| **Provider** | OpenAI | Anthropic |
| **Auth** | ChatGPT OAuth / API key | Claude Pro/Max / API key |
| **Models** | GPT-5-Codex, GPT-5, GPT-4.1 | Opus, Sonnet, Haiku |
| **Local OSS** | Yes (Ollama/LM Studio) | No |
| **Web Search** | Yes (`--search`) | Via MCP/Chrome |
| **Image Input** | Yes (`-i`) | Via file reference |
| **MCP Support** | Yes | Yes |
| **Plugins** | Via skills | Yes (marketplace) |
| **Cloud Tasks** | Yes (experimental) | Remote sessions |
| **Sandbox** | Seatbelt/Landlock | Permission modes |
| **Code Review** | `codex review` | Via prompt |
| **IDE Integration** | VS Code extension | VS Code, JetBrains |
| **Session Resume** | Yes | Yes |
| **Custom Agents** | Via AGENTS.md | `--agents` JSON |
| **Structured Output** | `--output-schema` | `--json-schema` |
| **Spending Limits** | No | `--max-budget-usd` |
| **Turn Limits** | No | `--max-turns` |
| **Shell Completions** | Yes | No (yet) |
## When to Use Which
### Use Codex CLI When:
- You have ChatGPT Plus/Pro/Enterprise
- You need web search built-in
- You want local OSS model support (Ollama)
- You need dedicated code review (`codex review`)
- You're working with cloud tasks
- You need fine-grained sandbox control
- You prefer TOML configuration
### Use Claude Code CLI When:
- You have Claude Pro/Max or Anthropic API
- You need spending/turn limits for CI
- You want plugin marketplace access
- You need custom subagent definitions
- You prefer JSON configuration
- You want IDE auto-connect
- You need structured output validation
## Edge Cases & Gotchas
### Authentication Edge Cases
**Codex:**
```bash
# API key with special characters - use stdin
echo 'sk-xxx-with-$pecial' | codex login --with-api-key
# Check if logged in (exit code 0 = logged in)
codex login status && echo "logged in" || echo "not logged in"
# Multiple accounts - not supported, logout first
codex logout && codex login
```
**Claude:**
```bash
# API key via environment (preferred for CI)
export ANTHROPIC_API_KEY="sk-ant-xxx"
claude -p "task"
# Token refresh issues
claude setup-token # Re-authenticate
# Bedrock/Vertex auth
export CLAUDE_CODE_USE_BEDROCK=1
# Uses AWS credentials chain
```
### Path & Directory Edge Cases
**Both CLIs:**
```bash
# Paths with spaces - quote them
codex --add-dir "/path/with spaces/dir"
claude --add-dir "/path/with spaces/dir"
# Relative vs absolute paths
codex -C ./subdir # Relative OK
codex --add-dir ../sibling # Relative OK
# Symlinks - behavior varies by OS
# Generally resolved to real path
# Non-existent directory
codex -C /nonexistent # Error
claude --add-dir /missing # Validation error
```
### Model Edge Cases
**Codex:**
```bash
# Model not available in plan
codex -m gpt-5 "task" # May fail if not in subscription
# OSS model not running
codex --oss "task" # Error if Ollama not started
# Model aliases
codex -m codex # Resolves to gpt-5-codex
codex -m mini # Resolves to gpt-4.1-mini
```
**Claude:**
```bash
# Model aliases
claude --model sonnet # Latest Sonnet
claude --model opus # Latest Opus
claude --model haiku # Latest Haiku
# Full model name
claude --model claude-sonnet-4-5-20250929
# Fallback when overloaded
claude -p --model opus --fallback-model sonnet "task"
# Model in config but overloaded
# Use fallback or explicit model flag
```
### Session Edge Cases
**Codex:**
```bash
# Resume non-existent session
codex resume abc123 # Error: session not found
# Resume from different directory
codex resume --all # Shows all sessions
codex resume <id> # Works from any directory
# Session corruption
rm -rf ~/.codex/sessions/<id> # Manually clean
```
**Claude:**
```bash
# Resume with search
claude -r "partial-name" # Opens picker with filter
# Fork to new session
claude -r <id> --fork-session "new direction"
# Session ID format
claude --session-id "not-a-uuid" # Error: must be valid UUID
# Disabled persistence
claude -p --no-session-persistence "task"
# Cannot resume this session
```
### MCP Edge Cases
**Both:**
```bash
# Server startup timeout
# Default ~30s, then fails
# Server crashes mid-session
# Tools become unavailable, may need restart
# Conflicting tool names
# Last registered wins, or use qualified name
```
**Codex:**
```bash
# Stdio server with interactive prompts
# Hangs - server must be non-interactive
# HTTP server without CORS
# Connection fails - server must allow origin
# OAuth token expiry
codex mcp login <server> # Re-authenticate
```
**Claude:**
```bash
# Project-scope server not in git
# Other devs won't have it
# Headers with special characters
claude mcp add -H "Auth: Bearer token=with=equals" server url
# May need escaping
# Resetting all project choices
claude mcp reset-project-choices
```
### Input/Output Edge Cases
**Codex:**
```bash
# Very long prompt
echo "$(cat huge-file.txt)" | codex exec -
# May hit token limits - will truncate
# Binary in stdout
codex exec --json "task" > output.json
# Output is valid JSON, but content may be truncated
# Non-UTF8 input
cat binary.bin | codex exec -
# Undefined behavior
```
**Claude:**
```bash
# Stream JSON with malformed input
echo '{"bad json' | claude -p --input-format stream-json
# Parse error
# Schema validation failure
claude -p --json-schema '{"type":"number"}' "say hello"
# Output may not match, error or empty
# Large file piping
cat 10mb-log.txt | claude -p "summarize"
# Truncated to context limit
```
### Permission Edge Cases
**Codex:**
```bash
# Sandbox + network
codex -s read-only --search "web task"
# Web search may fail in strict sandbox
# Full auto in strict environment
codex --full-auto "task"
# Still respects workspace boundaries
# YOLO in production
codex --yolo "task" # NEVER DO THIS
# Bypasses all safety, can destroy system
```
**Claude:**
```bash
# Permission mode conflicts
claude --permission-mode plan --dangerously-skip-permissions
# --dangerously-skip-permissions wins
# Tool in disallowedTools used in allowedTools
claude --allowedTools "Bash" --disallowedTools "Bash(rm:*)"
# Disallow takes precedence for pattern
# Custom permission tool failure
claude -p --permission-prompt-tool broken_tool "task"
# Falls back to deny
```
### CI/CD Edge Cases
**Codex:**
```bash
# No TTY in CI
codex exec "task" # Works (non-interactive)
codex "task" # May fail (expects TTY)
# Parallel jobs same API key
# Rate limiting may occur
# Use different API keys or queue
# Git not initialized
codex exec --skip-git-repo-check "task"
```
**Claude:**
```bash
# Headless environment
claude -p "task" # Works
claude "task" # Fails (needs TTY)
# Budget exceeded mid-task
claude -p --max-budget-usd 0.01 "complex task"
# Stops immediately, partial work may be lost
# Turn limit reached
claude -p --max-turns 1 "multi-step task"
# Only one response, task incomplete
```
### Concurrency Edge Cases
```bash
# Multiple Codex sessions same repo
# Session files may conflict
# Use different working directories
# Multiple Claude sessions same project
# Sessions are isolated
# But file edits may conflict
# Parallel tool execution
# Neither CLI parallelizes tools internally
# But multiple CLI processes can conflict
# Lock files
# Neither uses lock files
# Manual coordination needed
```
### Unicode & Encoding Edge Cases
```bash
# Unicode in prompts
codex "fix 中文 comments" # Works
claude "fix 中文 comments" # Works
# Unicode in file paths
codex --add-dir "./路径" # OS-dependent
claude --add-dir "./路径" # OS-dependent
# RTL text
# Rendering may be incorrect in terminal
# But processing is correct
# Emoji in prompts
codex "add 🚀 to readme" # Works
claude "add 🚀 to readme" # Works
```
### Network Edge Cases
```bash
# Proxy required
export HTTP_PROXY=http://proxy:8080
export HTTPS_PROXY=http://proxy:8080
codex "task" # Uses proxy
claude "task" # Uses proxy
# Offline mode
# Neither has true offline mode
# But cached sessions can be viewed
# VPN/firewall blocking
# API calls fail
# Check connectivity with curl
# SSL certificate issues
export NODE_TLS_REJECT_UNAUTHORIZED=0 # DANGEROUS
# Only for debugging
```
### Recovery Patterns
**After Crash:**
```bash
# Codex
codex resume --last # Try to resume
# Claude
claude -c # Continue last
claude -r <id> # Specific session
```
**After Bad Edit:**
```bash
# Both: Use git
git checkout -- <file>
git stash
# Codex cloud: Apply selectively
codex cloud diff <task> # Review first
```
**After Rate Limit:**
```bash
# Wait and retry
sleep 60 && codex exec "task"
# Or use fallback
claude -p --fallback-model haiku "task"
```
**After Auth Expiry:**
```bash
# Codex
codex logout && codex login
# Claude
claude setup-token
```
## Best Practices Summary
1. **Always work in git repos** - enables recovery
2. **Use appropriate safety modes** - start restrictive
3. **Set budget/turn limits in CI** - prevent runaway
4. **Use sessions** - don't lose work
5. **Test MCP servers** - verify before critical work
6. **Quote paths** - especially with spaces
7. **Use print mode in scripts** - consistent behavior
8. **Handle errors** - check exit codes
9. **Manage context** - compact or fresh sessions
10. **Commit checkpoints** - before major changes
SKILL.md
---
name: ai-coding-agents
description: Comprehensive guide for using Codex CLI (OpenAI) and Claude Code CLI (Anthropic) - AI-powered coding agents. Use when orchestrating CLI commands, automating tasks, configuring agents, or troubleshooting issues.
---
# AI Coding Agents Skill
Expert knowledge for Codex CLI and Claude Code CLI — the two leading AI coding agents.
**Note:** This skill documents both tools for reference. VMark development primarily uses **Claude Code CLI**. The Codex CLI sections are retained for completeness and cross-tool workflows.
## When to Use
- Orchestrating complex coding tasks via CLI
- Configuring MCP servers for either tool
- Setting up automation pipelines (CI/CD)
- Troubleshooting authentication or sandbox issues
- Comparing capabilities between agents
- Custom agent/subagent configuration
## Quick Reference
### Starting Sessions
| Task | Codex CLI | Claude Code CLI |
|------|-----------|-----------------|
| Interactive session | `codex` | `claude` |
| With prompt | `codex "fix the bug"` | `claude "fix the bug"` |
| Non-interactive | `codex exec "task"` | `claude -p "task"` |
| Resume last | `codex resume --last` | `claude -c` |
| Resume by ID | `codex resume <id>` | `claude -r <id>` |
### Safety Modes
| Mode | Codex CLI | Claude Code CLI |
|------|-----------|-----------------|
| Read-only | `-s read-only` | `--permission-mode plan` |
| Workspace write | `-s workspace-write` | (default) |
| Full access | `-s danger-full-access` | `--dangerously-skip-permissions` |
| Auto mode | `--full-auto` | `--permission-mode default` |
| YOLO mode | `--yolo` | `--dangerously-skip-permissions` |
### Model Selection
| Task | Codex CLI | Claude Code CLI |
|------|-----------|-----------------|
| Select model | `-m gpt-5-codex` | `--model opus` |
| Use local OSS | `--oss` | N/A |
| Fallback model | N/A | `--fallback-model sonnet` |
---
## Codex CLI (OpenAI)
### Installation
```bash
npm i -g @openai/codex
# or
brew install --cask codex
```
### Authentication
```bash
codex login # OAuth via ChatGPT
codex login --with-api-key # Read API key from stdin
codex login status # Check auth status
codex logout # Remove credentials
```
### Core Commands
#### `codex` - Interactive Mode
```bash
codex # Start TUI
codex "fix all TypeScript errors" # With initial prompt
codex -i screenshot.png "explain" # With image
codex --full-auto "refactor" # Low-friction mode
codex --search "find docs" # Enable web search
```
#### `codex exec` - Non-Interactive
```bash
codex exec "write tests" # Run and exit
codex e "task" # Short alias
echo "task" | codex exec - # From stdin
codex exec --json "task" # JSONL output
codex exec -o result.txt "task" # Save to file
codex exec --output-schema schema.json "task" # Validate output
```
#### `codex resume` - Continue Sessions
```bash
codex resume # Interactive picker
codex resume --last # Most recent
codex resume --all # Show all (any directory)
codex resume <session-id> # Specific session
codex resume <id> "continue with this" # With prompt
```
#### `codex review` - Code Review
```bash
codex review # Review current branch vs main
codex review --uncommitted # Review uncommitted changes
codex review --base develop # Against specific branch
codex review --commit abc123 # Review specific commit
codex review "focus on security" # Custom instructions
```
#### `codex apply` - Apply Cloud Task
```bash
codex apply <task-id> # Apply diff from cloud task
```
#### `codex cloud` - Cloud Tasks (Experimental)
```bash
codex cloud # Browse cloud tasks
codex cloud exec "task" --env <env-id> # Submit task
codex cloud status <task-id> # Check status
codex cloud diff <task-id> # Show diff
codex cloud apply <task-id> # Apply changes
```
#### `codex mcp` - MCP Server Management
```bash
codex mcp list # List servers
codex mcp list --json # JSON output
codex mcp get <name> # Server details
codex mcp add <name> -- npx my-server # Add stdio server
codex mcp add <name> --url https://... # Add HTTP server
codex mcp add <name> --env API_KEY=xxx -- cmd # With env vars
codex mcp remove <name> # Remove server
codex mcp login <name> --scopes read,write # OAuth for HTTP
codex mcp logout <name> # Remove OAuth
```
#### `codex sandbox` - Run Sandboxed Commands
```bash
# macOS
codex sandbox macos -- npm test
codex sandbox seatbelt --full-auto -- ./script.sh
# Linux
codex sandbox linux -- npm test
codex sandbox landlock -- ./script.sh
```
#### `codex completion` - Shell Completions
```bash
codex completion bash >> ~/.bashrc
codex completion zsh >> ~/.zshrc
codex completion fish > ~/.config/fish/completions/codex.fish
```
### Slash Commands (Interactive)
| Command | Purpose |
|---------|---------|
| `/model` | Switch model (gpt-5-codex, gpt-5, etc.) |
| `/approvals` | Change approval policy |
| `/compact` | Summarize conversation, free context |
| `/diff` | Show git diff |
| `/review` | Analyze working tree |
| `/status` | Show config and token usage |
| `/mcp` | List available MCP tools |
| `/mention` | Attach files |
| `/fork` | Branch conversation |
| `/resume` | Reopen previous session |
| `/new` | Fresh conversation |
| `/init` | Create AGENTS.md scaffold |
| `/feedback` | Submit logs/diagnostics |
| `/quit`, `/exit` | Exit CLI |
### Configuration (`~/.codex/config.toml`)
```toml
model = "gpt-5-codex"
approval_policy = "on-request"
[sandbox]
mode = "workspace-write"
[features]
web_search = true
[profiles.ci]
model = "gpt-4.1"
approval_policy = "never"
```
### Global Flags
```
-m, --model <MODEL> Model selection
-s, --sandbox <MODE> read-only|workspace-write|danger-full-access
-a, --ask-for-approval <P> untrusted|on-failure|on-request|never
-c, --config <KEY=VALUE> Override config
-C, --cd <DIR> Working directory
-i, --image <FILE> Attach image(s)
-p, --profile <NAME> Config profile
--full-auto Low-friction mode
--yolo Bypass all safety (DANGEROUS)
--search Enable web search
--add-dir <DIR> Grant additional write access
--enable <FEATURE> Enable feature flag
--disable <FEATURE> Disable feature flag
--oss Use local OSS model
```
---
## Claude Code CLI (Anthropic)
### Installation
```bash
npm install -g @anthropic-ai/claude-code
```
### Authentication
```bash
claude # First run prompts login
claude setup-token # Set up long-lived token
# Requires Claude Pro/Max subscription OR API key
```
### Core Commands
#### `claude` - Interactive Mode
```bash
claude # Start REPL
claude "explain this project" # With prompt
claude -c # Continue last conversation
claude -r "session-name" # Resume by name/ID
claude --model opus # Select model
claude --chrome # Enable Chrome integration
claude --ide # Auto-connect to IDE
```
#### `claude -p` - Print Mode (Non-Interactive)
```bash
claude -p "explain this function" # Query and exit
cat file | claude -p "explain" # Process piped input
claude -p --output-format json "q" # JSON output
claude -p --output-format stream-json "q" # Streaming JSON
claude -p --max-turns 3 "task" # Limit agent turns
claude -p --max-budget-usd 5 "task" # Spending limit
claude -p --json-schema '{...}' "q" # Validate output schema
```
#### `claude mcp` - MCP Server Management
```bash
claude mcp list # List servers
claude mcp get <name> # Server details
claude mcp add <name> <cmd> # Add stdio server
claude mcp add -t http <name> <url> # Add HTTP server
claude mcp add -e KEY=val <name> -- cmd # With env vars
claude mcp add -H "Auth: Bearer x" <name> <url> # With headers
claude mcp add -s project <name> <cmd> # Project scope
claude mcp remove <name> # Remove server
claude mcp serve # Run as MCP server
claude mcp add-from-claude-desktop # Import from desktop app
claude mcp reset-project-choices # Reset approvals
```
#### `claude plugin` - Plugin Management
```bash
claude plugin list # List plugins
claude plugin install <name> # Install plugin
claude plugin install <name>@marketplace # From specific marketplace
claude plugin uninstall <name> # Remove plugin
claude plugin enable <name> # Enable disabled plugin
claude plugin disable <name> # Disable plugin
claude plugin update <name> # Update plugin
claude plugin validate <path> # Validate manifest
claude plugin marketplace # Manage marketplaces
```
#### `claude update` - Self-Update
```bash
claude update # Check and install updates
```
#### `claude doctor` - Diagnostics
```bash
claude doctor # Check health/issues
```
#### `claude install` - Native Build
```bash
claude install # Install native build
claude install stable # Specific version
claude install latest # Latest version
```
### Slash Commands (Interactive)
| Command | Purpose |
|---------|---------|
| `/init` | Generate CLAUDE.md |
| `/clear` | Reset context |
| `/compact` | Summarize conversation |
| `/bug` | Report issues |
| `/doctor` | Run diagnostics |
| `/model` | Switch model |
| `/config` | View/edit settings |
| `/permissions` | Manage permissions |
| `/memory` | View/edit memory |
| `/project:<cmd>` | Project-specific commands |
| `/user:<cmd>` | User-specific commands |
### Custom Commands
Create `.claude/commands/fix-issue.md`:
```markdown
Fix GitHub issue #$ARGUMENTS
1. Read the issue details
2. Identify the problem
3. Implement the fix
4. Write tests
5. Create a commit
```
Usage: `/project:fix-issue 1234`
### Configuration
**User settings** (`~/.claude/settings.json`):
```json
{
"model": "claude-sonnet-4-5-20250929",
"verbose": false,
"theme": "dark"
}
```
**Project settings** (`.claude/settings.json`):
```json
{
"allowedTools": ["Bash(git:*)", "Read", "Edit"],
"disallowedTools": ["Bash(rm:*)"]
}
```
### CLI Flags
#### Core
```
-p, --print Non-interactive mode
-c, --continue Continue last conversation
-r, --resume <ID> Resume specific session
-v, --version Show version
```
#### Model & Config
```
--model <MODEL> sonnet|opus|haiku or full name
--fallback-model <MODEL> Fallback when overloaded
--settings <FILE> Load settings JSON
--setting-sources <LIST> user,project,local
--session-id <UUID> Use specific session ID
```
#### System Prompt
```
--system-prompt <TEXT> Replace default prompt
--append-system-prompt <T> Append to default
--system-prompt-file <F> Replace with file (print only)
--append-system-prompt-file Replace with file (print only)
```
#### Agent & Tools
```
--agent <NAME> Specify agent
--agents <JSON> Define custom subagents
--tools <LIST> Restrict built-in tools
--allowedTools <LIST> Auto-approve tools
--disallowedTools <LIST> Remove tools from context
```
#### Permissions
```
--permission-mode <MODE> acceptEdits|bypassPermissions|default|delegate|dontAsk|plan
--dangerously-skip-permissions Skip all prompts (DANGEROUS)
--allow-dangerously-skip-permissions Enable bypass option
```
#### Output
```
--output-format <FMT> text|json|stream-json
--input-format <FMT> text|stream-json
--include-partial-messages Include streaming chunks
--verbose Verbose logging
--debug [FILTER] Debug mode with filtering
```
#### Advanced
```
--max-turns <N> Limit agent turns (print only)
--max-budget-usd <AMT> Spending limit (print only)
--json-schema <SCHEMA> Validate JSON output
--chrome / --no-chrome Chrome integration
--ide IDE auto-connect
--fork-session Create new session on resume
--no-session-persistence Don't save session
--add-dir <DIRS> Additional directories
--plugin-dir <DIRS> Load plugins
--disable-slash-commands Disable all skills
--mcp-config <FILES> MCP server configs
--strict-mcp-config Only use specified MCP
--betas <HEADERS> Beta API headers
```
### Custom Subagents
```bash
claude --agents '{
"reviewer": {
"description": "Code reviewer. Use after changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob"],
"model": "sonnet"
}
}'
```
---
## Common Patterns & Edge Cases
### CI/CD Integration
**Codex in GitHub Actions:**
```yaml
- name: Run Codex
run: |
echo "${{ secrets.OPENAI_API_KEY }}" | codex login --with-api-key
codex exec --json -o result.txt "fix linting errors"
```
**Claude in CI:**
```yaml
- name: Run Claude
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p --output-format json "review this PR" > review.json
```
### Handling Rate Limits
**Codex:** Automatic backoff built-in.
**Claude:** Use `--fallback-model`:
```bash
claude -p --fallback-model haiku "quick task"
```
### Working with Large Codebases
```bash
# Codex: Use /compact to free context
# In session: /compact
# Claude: Use /compact or start fresh
claude --no-session-persistence -p "analyze src/"
```
### Multi-Directory Access
```bash
# Codex
codex --add-dir ../shared-lib --add-dir ../config
# Claude
claude --add-dir ../shared-lib ../config
```
### Structured Output
**Codex:**
```bash
codex exec --output-schema schema.json "generate API spec"
```
**Claude:**
```bash
claude -p --json-schema '{"type":"object","properties":{"name":{"type":"string"}}}' "extract data"
```
### Image Input
**Codex:**
```bash
codex -i screenshot.png "explain this UI"
codex -i img1.png -i img2.png "compare these"
```
**Claude:**
```bash
# Via file reference in prompt
claude "analyze the image at ./screenshot.png"
```
### Session Forking
```bash
# Codex: /fork in session
# Claude
claude -r "session-id" --fork-session "try alternative approach"
```
### MCP Server Debugging
**Codex:**
```bash
codex mcp list --json | jq .
```
**Claude:**
```bash
claude --debug "mcp" --mcp-config ./mcp.json
```
---
## Troubleshooting
### Authentication Issues
| Problem | Codex | Claude |
|---------|-------|--------|
| Not logged in | `codex login status` | `claude doctor` |
| Token expired | `codex logout && codex login` | `claude setup-token` |
| API key issues | Check `OPENAI_API_KEY` | Check `ANTHROPIC_API_KEY` |
### Sandbox Issues
| Problem | Solution |
|---------|----------|
| Permission denied | Use `--add-dir` for specific directories |
| Can't run commands | Check sandbox mode, use `workspace-write` |
| Network blocked | Sandbox may block network; use `danger-full-access` carefully |
### MCP Server Issues
| Problem | Solution |
|---------|----------|
| Server not found | Check `mcp list`, verify installation |
| Connection failed | Check server logs, verify URL/command |
| Auth required | Use `mcp login` (Codex) or add headers (Claude) |
### Performance Issues
| Problem | Solution |
|---------|----------|
| Slow responses | Use lighter model (gpt-4.1-mini / haiku) |
| Context overflow | Use `/compact` to summarize |
| High costs | Set `--max-budget-usd` (Claude) |
---
## Best Practices
1. **Start with read-only** for exploration, escalate as needed
2. **Use sessions** - resume work instead of starting fresh
3. **Create AGENTS.md/CLAUDE.md** for project-specific instructions
4. **Leverage MCP servers** for external integrations
5. **Use structured output** in CI/CD for parsing
6. **Set spending limits** with `--max-budget-usd`
7. **Review diffs** before applying (`/diff`, `codex cloud diff`)
8. **Commit checkpoints** before major changes