- OpenAI Codex CLI
- Hands-On Implementation
- Automation
- CI/CD
- Project Setup
- codex-cli categories:
- AI Development & Automation author: Claude Code status: hands-on experience_level: practical
OpenAI Codex CLI Hands-On Implementation: From Project Setup to Production Operations [August 2025]¶
Introduction¶
After understanding the overview in OpenAI Codex CLI Complete Guide, the next step is to get hands-on with actual implementation. This article provides step-by-step hands-on learning from concrete project setup to production environment utilization.
Key Points¶
Node.js Project Setup
Automatically build TypeScript projects from scratch
CI/CD Pipeline Automation
Complete automation with GitHub Actions + Codex CLI
Automated Error Fixing
Automatically fix test and build errors
Legacy Code Modernization
Practical upgrade of legacy projects
🏗️ Project 1: Automated Node.js TypeScript Project Setup¶
Step 1: Environment Preparation¶
# Create working directory
mkdir codex-demo-project && cd codex-demo-project
git init
# Start Codex CLI (use Suggest mode first for safety verification)
codex
Step 2: Project Setup Prompt¶
Create a REST API project using TypeScript and Express.
Requirements:
1. package.json configuration (TypeScript, Express, Jest, ESLint, Prettier)
2. TypeScript configuration file (tsconfig.json)
3. Basic Express server (src/app.ts)
4. API routers (/api/users, /api/healthcheck)
5. Test files (Jest)
6. README.md
7. .gitignore
8. npm scripts configuration (build, start, test, lint)
Create each file, install dependencies, and verify that the project starts successfully.
Step 3: Verify Execution Results¶
File structure generated by Codex:
codex-demo-project/
├── package.json
├── tsconfig.json
├── src/
│ ├── app.ts
│ ├── routes/
│ │ ├── users.ts
│ │ └── health.ts
│ └── types/
│ └── index.ts
├── tests/
│ ├── app.test.ts
│ └── routes/
│ └── users.test.ts
├── .gitignore
├── .eslintrc.js
├── .prettierrc
└── README.md
Step 4: Automated Test Execution¶
# Switch to Auto Edit mode for automation
codex --auto-edit
Now that the project setup is complete, please execute the following:
1. Run npm install to install dependencies
2. Run npm run lint for code checking
3. Run npm test for test execution
4. Run npm run build for build verification
5. Run npm start to start the server
If any errors occur, fix them and ensure all commands succeed.
Implementation Points
Codex CLI understands context and generates files while maintaining consistency across the entire project. Start with Suggest mode to review the content, then switch to Auto Edit mode once you trust it.
🔄 Project 2: CI/CD Pipeline Automation¶
GitHub Actions + Codex CLI Integration¶
Create .github/workflows/codex-automation.yml:
name: Codex CLI Automation
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test-and-fix:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install Codex CLI
run: npm install -g @openai/codex
- name: Run initial tests
id: initial-tests
continue-on-error: true
run: npm test
- name: Auto-fix test failures
if: steps.initial-tests.outcome == 'failure'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex --full-auto --prompt "Tests are failing. Analyze the errors, fix them, and ensure npm test succeeds."
- name: Run tests after fix
run: npm test
- name: Build project
run: npm run build
- name: Lint check
run: npm run lint
- name: Auto-commit fixes
if: steps.initial-tests.outcome == 'failure'
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add .
git diff --staged --quiet || git commit -m "Auto-fix: Automatic fixes by Codex CLI [skip ci]"
git push
Staged Deployment Configuration¶
# .github/workflows/codex-deploy.yml
name: Codex Deployment
on:
workflow_run:
workflows: ["Codex CLI Automation"]
types: [completed]
branches: [main]
jobs:
deploy:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Codex CLI
run: npm install -g @openai/codex
- name: Prepare deployment
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex --auto-edit --prompt "Prepare for production deployment:
1. Verify environment variable configuration
2. Update production configuration files
3. Security checks
4. Performance optimization
5. Documentation updates"
- name: Deploy to staging
run: |
# Deployment command
npm run deploy:staging
Important Note
When using API keys in GitHub Actions, always configure them in Repository Secrets or Environment Secrets. Never include them as plain text.
🐛 Project 3: Automated Error Fixing Patterns¶
Complex Test Error Fixing¶
# Example execution on a project with complex errors
codex --full-auto
Practical Prompt Example:
This project has the following issues:
1. TypeScript compilation errors (type inconsistencies)
2. Jest test failures (async processing timeouts)
3. ESLint errors (unused variables, import order)
4. Dependency vulnerability warnings
Fix all of these and perform the following verifications:
- npm run typecheck succeeds
- npm test passes all tests
- npm run lint has no warnings
- npm audit shows no vulnerabilities
- npm run build succeeds
After fixing, commit the changes.
Error Pattern-Specific Solutions¶
| Error Type | Codex CLI Response | Prompt Example |
|---|---|---|
| Type Errors | Automatic type definition fixes | "Analyze TypeScript type errors and fix with appropriate type definitions" |
| Test Failures | Mock/stub adjustments | "Identify test failure causes and fix with appropriate test code" |
| Dependency Errors | package.json updates | "Resolve dependency conflicts and update to compatible versions" |
| Build Errors | Configuration file fixes | "Check build configuration, fix errors, and ensure build succeeds" |
Actual Error Fixing Example¶
Error Encountered:
FAIL tests/users.test.ts
● Users API › GET /api/users › should return user list
TypeError: Cannot read properties of undefined (reading 'map')
Automatic Fix by Codex CLI:
// Before fix
export const getUsers = async (): Promise<User[]> => {
const users = await database.users.findAll();
return users.map(user => ({ ...user, password: undefined }));
};
// After fix (automatically generated by Codex CLI)
export const getUsers = async (): Promise<User[]> => {
try {
const users = await database.users.findAll();
return users?.map(user => ({ ...user, password: undefined })) || [];
} catch (error) {
console.error('Error fetching users:', error);
return [];
}
};
🔄 Project 4: Legacy Code Modernization¶
Modernizing an Old Node.js Project¶
codex --auto-edit
Modernization Prompt:
Modernize this legacy Node.js project to 2025 standards:
Current state:
- Node.js v14, CommonJS format
- JavaScript (no types)
- Old test configuration (Mocha + Chai)
- Manual deployment
Modernization requirements:
1. Node.js v20 + ES Modules support
2. Full TypeScript migration
3. Jest + Testing Library
4. ESLint + Prettier
5. GitHub Actions CI/CD
6. Docker support
7. Security enhancements (Helmet, Rate Limiting)
8. Environment variable management (dotenv)
9. Logging system (Winston)
10. API documentation (OpenAPI/Swagger)
Migrate gradually and ensure tests pass at each stage.
Validating Migration Results¶
Results of modernization by Codex CLI:
# Verify package configuration
npm list --depth=0
# Type checking
npm run typecheck
# Run tests
npm test -- --coverage
# Security audit
npm audit
# Build test
npm run build && npm start
Gradual Migration Tips
For large legacy systems, it's recommended to proceed gradually module by module rather than changing everything at once. By instructing Codex CLI to work "gradually", you can minimize risk.
⚙️ Project 5: Advanced Automation Patterns¶
MCP Server Integration¶
# ~/.codex/config.toml
[mcp]
enabled = true
[[mcp.servers]]
name = "database"
command = "mcp-database-server"
args = ["--url", "postgresql://localhost:5432/mydb"]
[[mcp.servers]]
name = "jira"
command = "mcp-jira-server"
args = ["--domain", "company.atlassian.net"]
Database Integration Prompt:
Reference the database schema and automatically generate the following:
1. TypeScript type definitions (based on table structure)
2. Prisma schema file
3. CRUD API endpoints
4. Validation schemas (Zod)
5. Unit tests (including database mocks)
Target the database tables: users, posts, and comments.
Creating Custom Workflows¶
# Create project-specific workflow file
touch .codex/workflows.toml
# .codex/workflows.toml
[workflows.feature]
description = "New feature development flow"
steps = [
"git checkout -b feature/{{feature_name}}",
"codex --auto-edit --prompt 'Implement {{feature_name}} feature in TypeScript. Include complete implementation with API endpoints, type definitions, and tests'",
"npm test",
"git add . && git commit -m 'feat: Implement {{feature_name}} feature'",
"git push -u origin feature/{{feature_name}}"
]
[workflows.hotfix]
description = "Emergency fix flow"
steps = [
"git checkout main",
"git checkout -b hotfix/{{issue_id}}",
"codex --full-auto --prompt 'Emergency fix for Issue #{{issue_id}}. Verify tests pass'",
"npm test",
"git add . && git commit -m 'fix: Emergency fix #{{issue_id}}'",
"git push -u origin hotfix/{{issue_id}}"
]
Monitoring & Alert Configuration¶
# .github/workflows/codex-monitoring.yml
name: Codex Quality Monitoring
on:
schedule:
- cron: '0 9 * * 1' # Every Monday at 9:00
workflow_dispatch:
jobs:
quality-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Codex CLI
run: npm install -g @openai/codex
- name: Weekly code quality analysis
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex --prompt "Run weekly code quality check:
1. Identify technical debt
2. Detect performance bottlenecks
3. Scan for security vulnerabilities
4. Identify unused code
5. Create improvement proposal report
Output results in ISSUE format."
- name: Create quality issues
uses: actions/github-script@v7
with:
script: |
// Parse Codex output and create issues
// Implementation omitted
🎯 Practical Techniques for Production Environments¶
1. Gradual Permission Transition¶
# Early development: Safety verification emphasis
codex # Suggest mode
# Mid development: Efficiency emphasis
codex --auto-edit # Automatic editing, manual execution approval
# Production environment: Full automation
codex --full-auto # Complete automatic execution in CI environment
2. Team Development Integration¶
Using AGENTS.md:
# AGENTS.md - Team-specific configuration
## Coding Standards
- TypeScript Strict Mode mandatory
- ESLint + Prettier enforcement
- Maintain test coverage above 80%
- Commit messages: Conventional Commits
## Branch Strategy
- feature/*: New features
- hotfix/*: Emergency fixes
- release/*: Release preparation
## Automation Rules
- Run full CI on main push
- Automatic Codex review on PR creation
- Pre-production confirmation before release deployment
3. Enhanced Error Handling¶
# Automatic recovery when errors occur
codex --full-auto --prompt "Identify the cause of CI failure and fix in the following priority order:
1. Syntax errors and type errors
2. Test failures
3. Lint violations
4. Build errors
5. Dependency issues
After fixing, always run tests and verify success before committing."
🚀 Practical Results and Effect Measurement¶
Before/After Comparison¶
| Metric | Manual Development | Codex CLI Utilization | Improvement Rate |
|---|---|---|---|
| Initial Project Setup | 4-8 hours | 30-60 minutes | 80% reduction |
| Bug Fix Time | 2-4 hours | 20-40 minutes | 85% reduction |
| Test Coverage | 60-70% | 85-95% | 25-35% increase |
| Code Quality | Manual review dependent | Automatic quality checks | Continuous improvement |
ROI (Return on Investment) Calculation¶
Monthly Cost: - Codex CLI usage fee: $30-80 (ChatGPT Plus + API usage) - Learning cost: Initial 20 hours (approximately $1,000 equivalent)
Monthly Benefits: - Development time reduction: 60-80 hours (approximately $3,000-4,000 equivalent) - Bug fix efficiency improvement: 20-30 hours (approximately $1,000-1,500 equivalent) - Quality improvement effect: Difficult to measure but significant long-term value
ROI: Achieves 4-6x return from the first month
⚠️ Operational Considerations¶
Security Considerations¶
Handling Confidential Information
# Ensure confidential files are added to .gitignore echo "*.env*" >> .gitignore echo "config/secrets.json" >> .gitignoreAPI Key Management
# Manage with environment variables export OPENAI_API_KEY="sk-..." # Manage with GitHub Secrets (recommended)Code Auditing
# Regular security scanning npm audit codex --prompt "Scan for security vulnerabilities and create fix proposals"
Troubleshooting¶
| Problem | Symptoms | Solution |
|---|---|---|
| API Rate Limiting | 429 errors | Re-execute with intervals, consider paid plan |
| Inaccurate Model Responses | Unintended changes | More specific prompts, verify in Suggest mode |
| Git Conflicts | Merge conflicts | Frequent small commits, review branch strategy |
| Dependency Errors | Installation failures | Delete package-lock.json, clean install |
📚 Summary¶
By practically utilizing OpenAI Codex CLI, we achieved the following:
Skills Acquired¶
- Automated Project Setup: Build full-fledged TypeScript projects from scratch
- Complete CI/CD Automation: Unmanned operations through GitHub Actions integration
- Automated Error Fixing: Automatically identify and fix complex bugs
- Legacy Modernization: Gradual upgrade of legacy systems
Continuous Improvement Points¶
- Gradual Permission Transition: Build trust in the order of Suggest → Auto Edit → Full Auto
- Team Standardization: Unify AGENTS.md and workflows
- Quality Metric Setting: Continuous measurement of coverage, error rate, and development speed
- Security First: Thorough confidential information protection and access control
Codex CLI goes beyond being just a coding assistance tool and becomes a partner that innovates the entire development process. Through practice, you can significantly improve your team's productivity and quality.
📚 Related Articles¶
OpenAI Codex Series¶
- OpenAI Codex CLI Complete Guide - Basic overview and theory
- Codex CLI Pricing Complete Guide - Claude Code vs OpenAI Codex pricing comparison and cost optimization
ChatGPT & OpenAI Related¶
- GPT-5 Finally Released! August 2025 Complete Guide - Latest model technical specifications
- Claude Code Practical Guide - Comparison with competing tools