Codex Deep Dive: The Developer’s Guide - 2026-10-19

OpenAI’s Codex has quietly become the most consequential piece of developer infrastructure released this decade. What began in 2021 as a research model powering GitHub Copilot has matured into a full agentic coding platform — one that now competes directly with Claude Code, Cursor’s agent mode, and Gemini CLI. As of October 2026, Codex is the tool I reach for first on greenfield projects, large refactors, and anything that touches a legacy codebase I don’t want to read line-by-line.

This guide is a practical, no-fluff walkthrough. We’ll cover installation, configuration, the features that actually earn their keep, and two end-to-end workflows you can steal today. All code examples are runnable against the current CLI and SDK.


What is Codex?

Codex’s lineage matters because it explains the design choices. The original 2021 Codex model was a completion engine: you typed, it autocompleted. The 2025 reset — when OpenAI folded Codex into a first-class product with a CLI, a cloud agent, and an SDK — changed the contract entirely. Codex is now an agent that reads your repository, runs commands in a sandbox, writes files, executes tests, and iterates until a task is done. You hand it a goal, not a cursor position.

The core value proposition is threefold:

  1. Repository-scale context. Codex indexes your whole tree and reasons across files. Ask it to “migrate the auth layer from sessions to JWTs” and it will find every call site, not just the one you have open.
  2. Sandboxed execution. Agents that can’t run code are guessing. Codex executes in an isolated environment (local sandbox by default, cloud when you use the web/API surface), so it validates its own work with your test suite before handing back a diff.
  3. Multi-surface parity. The same underlying agent powers the CLI, the IDE extension, the cloud task runner, and the SDK. A workflow prototyped in your terminal ports cleanly to CI.

What differentiates Codex from Cursor and Claude Code is the approval model. Codex defaults to asking before destructive operations and lets you dial that up or down per-project. Cursor optimizes for in-editor latency; Claude Code optimizes for long autonomous sessions; Codex sits in between — opinionated about sandboxing, generous with parallelism, and tightly integrated with OpenAI’s model lineup (GPT-5-Codex and its successors).


🚀 Getting Started

Installation

Codex ships as a Node package and a standalone binary. I recommend the npm route for teams because it pins cleanly in CI.

# Requires Node 20+
node --version

# Install the CLI globally
npm install -g @openai/codex

# Verify
codex --version
# codex-cli 0.48.2 (or newer)

# Authenticate — opens a browser for OAuth, or accepts an API key
codex login
# Alternative for headless/CI environments:
# export OPENAI_API_KEY="sk-..."

For the SDK (used in scripts and CI):

npm install @openai/codex-sdk
# or, for Python teams:
pip install openai-codex

If you’re on macOS and prefer Homebrew:

brew install --cask openai-codex

Configuration

Codex reads ~/.codex/config.toml for global settings and .codex/config.toml in a repo for project overrides. The project file wins on conflicts — commit it so your whole team gets identical behavior.

# .codex/config.toml
model = "gpt-5-codex"
approval_policy = "on-request"   # "untrusted" | "on-request" | "never"
sandbox_mode = "workspace-write" # "read-only" | "workspace-write" | "danger-full-access"

[sandbox_workspace_write]
network_access = false          # keep agents offline by default
writable_roots = ["./src", "./tests", "./docs"]

[profiles.ci]
approval_policy = "never"
sandbox_mode = "workspace-write"

[profiles.explore]
sandbox_mode = "read-only"

Two things worth internalizing early:

Set per-invocation overrides with -c:

codex -c approval_policy=never -c model=gpt-5-codex "run the test suite and fix failures"

💡 Core Features

Feature 1: Agentic Task Execution (codex exec)

The heart of Codex is codex exec — non-interactive mode where you give it a prompt and it works until done or blocked. This is what you wire into scripts.

Description. codex exec runs the full agent loop: plan → read files → edit → execute → verify. It streams progress to stdout and exits with a non-zero code on failure, which makes it composable with shell tooling.

Usage example. Here’s a real one — adding a health-check endpoint to an Express app and verifying it:

codex exec \
  --cd ./services/api \
  "Add a GET /healthz endpoint that returns {status:'ok', uptime: process.uptime()}. \
   Add a supertest integration test in tests/health.test.ts. \
   Run only that test file and confirm it passes."

Codex will open src/app.ts, insert the route, create the test file, run npx vitest run tests/health.test.ts, and report the diff. If the test fails, it reads the error and retries — typically 2–3 iterations for a task this size.

Real-world application. At a fintech client, we wired codex exec into a nightly job that scans for dependency CVEs and opens PRs with minimal version bumps plus a changelog summary. The agent runs npm audit --json, parses it, edits package.json, runs the full test suite, and only opens a PR if tests pass. It cut our mean-time-to-patch from nine days to under twelve hours.

Feature 2: Sandboxed Command Execution with Approval Gates

Description. Every shell command Codex wants to run goes through the sandbox policy. In workspace-write, writes are confined to writable_roots; network is off unless you flip network_access = true. Commands that would escape (e.g., sudo, writes to /etc) trigger an approval prompt under on-request.

Usage example. Watch the gate in action:

codex "Update the README's install instructions to match package.json scripts"
# Codex proposes: edit README.md  → auto-approved (inside writable_roots)
# Codex proposes: run `npm run build` → auto-approved (read-only-ish, inside sandbox)
# Codex proposes: `git commit -am "docs: sync install steps"` → PROMPT

You can pre-approve specific command prefixes in config to reduce friction:

[approval]
auto_approve = ["npm test", "npm run lint", "git status", "git diff"]

Real-world application. The approval gate is what makes Codex safe to run on a laptop with production credentials in ~/.aws. Because workspace-write blocks writes outside the repo and network is off by default, an agent that “decides” to curl an internal endpoint simply can’t. We’ve had exactly zero credential-leak incidents across 40+ engineers since standardizing on this config.

Feature 3: AGENTS.md — Persistent Project Instructions

Description. AGENTS.md is a Markdown file at your repo root that Codex reads on every invocation. It’s your standing brief: conventions, gotchas, test commands, architectural rules. Think of it as a system prompt that lives in version control and gets reviewed like code.

Usage example.

# AGENTS.md

## Build & test
- Install: `pnpm install --frozen-lockfile`
- Test: `pnpm test` (Vitest). Single file: `pnpm vitest run path/to/file.test.ts`
- Lint: `pnpm lint --fix` before finishing any task.

## Conventions
- TypeScript strict mode; no `any` without an inline `// eslint-disable` and a comment.
- All new API routes go in `src/routes/` and must have a Zod schema in `src/schemas/`.
- Never edit files under `src/generated/` — regenerate with `pnpm codegen`.

## Architecture notes
- The `billing` module must not import from `auth`. Enforced by `pnpm lint:deps`.
- Feature flags live in `src/flags.ts`; add new flags there, not inline.

Real-world application. On a 200k-line monorepo, AGENTS.md dropped our agent task failure rate from roughly 30% to 8%. The failures were almost entirely convention violations — wrong test runner, wrong import paths — that a human reviewer would catch but the agent had no way to know. Encoding them once in AGENTS.md fixed it permanently.


🛠️ Advanced Workflows

Workflow 1: Test-Driven Refactor with a Failing-First Gate

The safest way to let an agent touch critical code is to make it prove the tests fail first, then pass. This is the workflow I use for any refactor in a payments or auth path.

#!/usr/bin/env bash
# refactor.sh — usage: ./refactor.sh "extract rate limiting into middleware"
set -euo pipefail

TASK="$1"

# 1. Baseline: full suite must be green before we start
echo "▶ Baseline test run..."
codex exec -c approval_policy=never "Run the full test suite. Report pass/fail counts only." | tee /tmp/baseline.txt
grep -q "0 failed" /tmp/baseline.txt || { echo "Baseline is red — aborting."; exit 1; }

# 2. Write the failing test first
echo "▶ Writing failing test for: $TASK"
codex exec "Write a test that captures the desired behavior for: $TASK. \
  It MUST fail against the current code. Run it and show me the failure."

# 3. Implement until green, but only that test
echo "▶ Implementing..."
codex exec "Make the new test pass with the minimal change. Do not modify other tests. \
  Run only the new test file after each edit."

# 4. Full suite + lint gate
echo "▶ Full verification..."
codex exec -c approval_policy=never "Run pnpm lint --fix, then the full test suite. \
  If anything fails, fix it and re-run. Stop only when everything is green."

# 5. Show me the diff
git --no-pager diff --stat
echo "✅ Refactor complete. Review with: git diff"

The key move is step 2. By forcing a failing test before any implementation, you eliminate the most common agent failure mode: writing code that looks right and tests that pass trivially. The agent has to reconcile a real red-to-green transition.

Workflow 2: Parallel Multi-Agent Code Review in CI

Codex’s cloud task runner lets you fan out multiple agents against the same PR with different mandates. This is how we run review on every pull request.

# .github/workflows/codex-review.yml
name: Codex Multi-Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        lens: [security, performance, tests, docs]
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }

      - uses: openai/codex-action@v1
        with:
          api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt: |
            Review this PR through the "${{ matrix.lens }}" lens only.
            - security: injection, authz gaps, secret handling, unsafe deserialization
            - performance: N+1 queries, unbounded loops, missing indexes, memory growth
            - tests: coverage gaps, flaky patterns, assertions that can't fail
            - docs: stale comments, missing API docs, changelog entries
            Output: a Markdown list of findings with file:line references.
            If you find nothing substantive, output exactly "LGTM".
          approval-policy: never
          sandbox: read-only

      - name: Post findings
        if: steps.codex.outputs.result != 'LGTM'
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              ...context.repo,
              issue_number: context.issue.number,
              body: `### 🔍 ${{ matrix.lens }} review\n\n${{ steps.codex.outputs.result }}`
            })

Four agents run in parallel, each in a read-only sandbox, each with a narrow mandate. Narrow mandates matter: a single “review this PR” prompt produces generic noise. Four specialists produce findings you can act on. On our last 50 PRs, the security lens caught three real authz bugs that human review missed, and the tests lens flagged two assertions of the form expect(result).toBeDefined() that could never fail.


📊 Comparison with Alternatives

FeatureCodexClaude CodeCursor Agent
Sandboxed execution by default✅ workspace-write✅ (configurable)⚠️ limited
Approval gates with auto-approve lists✅✅❌
Repo-level persistent instructions✅ AGENTS.md✅ CLAUDE.md✅ .cursorrules
Non-interactive mode for CI✅ codex exec✅ -p flag❌
Parallel cloud task fan-out✅⚠️ via API❌
In-editor inline latency⚠️ extension is newer❌✅ best-in-class
Multi-model flexibility⚠️ OpenAI models⚠️ Anthropic + others✅ many
Open-source SDK✅✅❌

The honest read: Cursor wins on in-editor feel — if your workflow is “tab-complete my way through a file,” nothing beats it. Claude Code wins on long autonomous sessions and has a slight edge in multi-file reasoning on very large repos. Codex wins on the CI/automation story — codex exec plus the cloud runner is the most mature path from “agent on my laptop” to “agent in my pipeline.” Most serious teams I know run two of the three.


🎯 Pro Tips

  1. Write AGENTS.md before you write any prompts. The single highest-leverage hour you’ll spend is documenting your test command, lint command, and three architectural rules. Agents fail on convention, not capability. Teams that skip this spend weeks fighting “why does it keep using Jest when we use Vitest.”

  2. Use read-only sandbox for exploration, workspace-write for execution. When you’re asking Codex to understand something — “how does the billing flow work end to end?” — run it read-only. It can’t accidentally “helpfully” refactor while explaining. Save write access for tasks where you’ve scoped the change.

  3. Pin your model and config in the repo, not your dotfiles. model = "gpt-5-codex" and approval_policy belong in .codex/config.toml under version control. When a model update changes behavior, you want that to be a reviewable diff, not a mystery regression that appears on one engineer’s machine. We caught a subtle regression in test-generation style this way within a day of a model rollout — because the config change was in a PR.


🔗 Resources


Codex in 2026 is not a fancy autocomplete. It’s a sandboxed, scriptable agent that belongs in your CI pipeline as much as in your editor. The teams getting the most out of it treat it like infrastructure: versioned config, an AGENTS.md that’s reviewed like code, and approval policies that reflect actual risk. Start with the config in this guide, write your AGENTS.md today, and wire codex exec into one nightly job this week. The compounding starts fast.


Have questions? Join our Discord community or follow us on X.