Codex Deep Dive: The Developer’s Guide - 2026-11-02

What is Codex?

Codex is OpenAI’s software-engineering agent, and in 2026 it has quietly become one of the most consequential tools in the developer stack. Its lineage matters: the original Codex model (2021) powered the first generation of GitHub Copilot, translating natural language into code completions. But the product you install today is a different animal. It is an agentic coding system that runs locally from a CLI, operates inside a sandboxed workspace, reads and writes files, executes tests, and returns reviewable diffs — rather than autocompleting a single line.

The core value proposition is simple to state and hard to deliver: delegate a well-scoped engineering task, get back a verifiable patch. Codex is designed around the assumption that you, the developer, remain the reviewer. It proposes; you approve. That posture — agentic execution with human-in-the-loop review — is what separates it from both autocomplete-style assistants and fully autonomous “AI engineer” products that try to own the whole ticket.

What makes Codex different from alternatives comes down to three things. First, local execution with sandboxing: the agent runs commands in your environment, but with approval gates and network restrictions you control. Second, diff-first output: every change arrives as a patch you can read, reject, or amend — not as a black-box commit. Third, composability: Codex is a CLI citizen. It pipes, it scripts, it fits into CI, and it plays well with the emerging ecosystem of context-management tools like thedotmack/claude-mem, which captures session activity, compresses it, and re-injects relevant context into future sessions across Claude Code, Codex, Gemini, Copilot, and others.

A note on scope: this guide focuses on the Codex CLI and its configuration surface. The underlying models are accessed through your OpenAI account, so model names and availability may shift; the workflows below are written to be resilient to that.


🚀 Getting Started

Installation

Codex ships as a Node.js CLI. You’ll need Node 18+ (Node 20 LTS recommended) and an OpenAI API key or a ChatGPT plan with Codex access.

# Verify your Node version first
node --version   # should be >= 18.0.0

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

# Confirm the binary is on your PATH
codex --version

# Authenticate (interactive; stores credentials in your OS keychain)
codex login

If you prefer not to install globally, use npx:

npx @openai/codex --version

For CI environments, authenticate non-interactively with an API key:

export OPENAI_API_KEY="sk-..."

Configuration

Codex reads configuration from ~/.codex/config.toml (user-level) and .codex/config.toml (project-level, which takes precedence). A minimal, opinionated starting point:

# ~/.codex/config.toml
model = "gpt-5-codex"
approval_policy = "on-request"   # "untrusted" | "on-request" | "on-failure" | "never"
sandbox_mode = "workspace-write"

[sandbox_workspace_write]
network_access = false           # keep the agent offline by default

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

Project-level overrides let teams standardize behavior:

# .codex/config.toml (committed to the repo)
model = "gpt-5-codex"
approval_policy = "on-request"

[profiles.review]
model = "gpt-5-codex"
approval_policy = "untrusted"    # every command needs explicit approval

The three settings that matter most:

Verify your setup with a smoke test:

cd ~/projects/my-app
codex exec "List the top-level directories and summarize what this project does in three sentences."

If you see a coherent summary and no sandbox errors, you’re operational.


💡 Core Features

Feature 1: Agentic Task Execution with Sandboxed Commands

The heart of Codex is its ability to take a natural-language task, plan a sequence of shell commands and file edits, and execute them inside a sandbox. You watch the plan, approve or reject individual steps (depending on your approval_policy), and review the resulting diff.

Usage example. Suppose you want to add input validation to an Express endpoint:

codex exec "In src/routes/users.js, add zod validation to the POST /users handler. \
Reject requests where email is missing or malformed, and return HTTP 400 with a JSON error body. \
Add a test in test/users.test.js covering the invalid-email case."

Codex will read src/routes/users.js, propose an edit, run npm test, and — if the test fails — iterate. With approval_policy = "on-request", it pauses before executing anything that touches the network or writes outside the workspace.

Real-world application. This is the workhorse mode for “small but tedious” tasks: adding a missing null check, converting a callback to async/await, or writing the test you keep deferring. The value isn’t that Codex writes perfect code — it’s that it writes reviewable code and runs the verification loop for you.

Feature 2: Diff-First Review and Selective Application

Every change Codex proposes is presented as a unified diff. You can accept the whole patch, reject it, or ask for revisions in natural language before applying anything.

Usage example. Run in interactive mode and inspect the patch:

codex "Refactor src/utils/date.js to use the Temporal API instead of moment.js. Keep the public function signatures identical."

Codex prints the proposed diff. You can then respond conversationally:

> The diff looks right, but keep the deprecated `formatRelative` export as a thin wrapper for backward compatibility.

Codex amends the patch rather than starting over — it retains the session context. When you’re satisfied, the changes are written to disk.

Real-world application. This is where Codex earns trust on legacy codebases. In the recent HN discussion “When Modernization Breaks Working Code: A Study of LLMs on Legacy PHP,” the recurring failure mode was agents confidently rewriting working code into subtly broken code. Diff-first review is the mitigation: you see exactly what changed, line by line, before it lands. Pair it with approval_policy = "untrusted" on unfamiliar repos and you get a safety net that autocomplete tools simply don’t offer.

Feature 3: Scriptable, Non-Interactive Execution (codex exec)

codex exec runs a task headlessly and prints the result to stdout — no TUI, no prompts. This turns Codex into a Unix tool you can pipe, script, and run in CI.

Usage example. Generate a changelog fragment from the last commit:

codex exec "Summarize the diff of HEAD~1..HEAD as a single changelog bullet, \
imperative mood, under 100 characters. Output only the bullet." \
  | tee changelog.d/$(git rev-parse --short HEAD).md

Or gate a PR on a lint-and-fix pass:

codex exec --profile ci "Run the linter, fix any auto-fixable issues, and report remaining warnings."

Real-world application. Teams wire codex exec into pre-commit hooks, nightly dependency-bump jobs, and documentation generators. Because output goes to stdout, it composes with jq, git, and your existing shell tooling — the same philosophy that made gh and jq indispensable.


🛠️ Advanced Workflows

Workflow 1: Legacy Modernization with a Guardrail Test Suite

The legacy-PHP study’s lesson generalizes: never let an agent modernize code it can’t verify. The pattern below pins behavior with tests before refactoring.

#!/usr/bin/env bash
set -euo pipefail

# 1. Capture current behavior as a baseline
codex exec "Read the legacy module in src/legacy/billing.php. \
Generate a characterization test suite in tests/Characterization/BillingTest.php \
that asserts current outputs for at least 10 representative inputs. Do not modify src/."

# 2. Confirm the baseline passes
php vendor/bin/phpunit tests/Characterization

# 3. Refactor under the guardrail
codex exec --profile review "Refactor src/legacy/billing.php to extract a BillingCalculator class \
with typed properties and constructor injection. All characterization tests must still pass. \
Run the suite after each edit and stop if any test fails."

# 4. Human review of the final diff
git diff --stat
git diff src/legacy/billing.php

The key discipline: step 1 produces no production changes, so a bad characterization suite is caught by review before it can mask a regression. Step 3 runs with approval_policy = "untrusted" so every command is visible. This is slower than letting the agent run free — and that’s the point.

Workflow 2: Persistent Context Across Sessions

Long-running work loses context between sessions. The community tool thedotmack/claude-mem addresses this by capturing session activity, compressing it with an LLM, and injecting relevant summaries into future sessions — and it explicitly supports Codex alongside Claude Code, Gemini, Copilot, and OpenCode.

# Install the context-capture tool
npm install -g claude-mem

# Initialize it in your project (creates a local store)
claude-mem init --agent codex

# Session 1: start a migration
codex "Begin migrating the auth module from session cookies to JWT. \
Document your plan in docs/auth-migration.md and implement the token issuance layer only."

# Session 2 (next day): resume with context
claude-mem recall --agent codex "auth migration JWT"
codex "Continue the auth migration. Read docs/auth-migration.md and the recalled context, \
then implement token verification middleware and update the tests."

The practical benefit is measured in re-orientation time. Without persistence, resuming a multi-day refactor costs 10–15 minutes of re-reading files and re-explaining intent. With a compressed context store, Codex starts the second session already knowing the plan, the conventions you chose, and the open questions.

A caveat worth stating plainly: context injection is only as good as its compression. Review what gets recalled (claude-mem recall --dry-run) before trusting it, especially on repos with secrets in config files.


📊 Comparison with Alternatives

FeatureCodexGitHub CopilotCursor
Agentic multi-file execution✅✅ (agent mode)✅
Local sandbox with configurable network policy✅⚠️ Limited⚠️ Limited
Diff-first review before apply✅⚠️ Partial✅
Headless/scriptable CLI (exec)✅❌❌
Terminal-native workflow✅❌❌ (IDE-first)
IDE integration⚠️ Via extensions✅ Deep✅ Deep
Open config format (TOML, project-level)✅⚠️ Partial⚠️ Partial
CI/CD composability✅❌❌

Comparison reflects general positioning as of late 2026; specific capabilities evolve quickly. Verify against current docs before standardizing.

The honest read: if you live in an IDE and want inline suggestions, Copilot and Cursor are excellent. If you want an agent you can script, sandbox, and run in CI — and you’re comfortable in a terminal — Codex is the strongest fit. Many teams run both: Cursor for interactive editing, Codex for batch and CI work.


🎯 Pro Tips

  1. Scope tasks to one reviewable diff. A prompt that produces a 40-file patch gets rubber-stamped; a prompt that produces a 3-file patch gets read. Break large refactors into sequential codex exec calls, committing between each. Your git log becomes your audit trail.

  2. Write the test in the prompt, not after. Asking Codex to “add validation and a test for the invalid case” produces better code than asking for validation alone, because the test forces the agent to reason about the failure mode. This single habit eliminates most of the “confidently wrong” output the legacy-PHP study documented.

  3. Tier your approval_policy by repo familiarity. Use "untrusted" on inherited or legacy codebases, "on-request" on your daily driver, and "never" only inside CI containers with network_access = false. The sandbox is a seatbelt, not a guarantee — treat "never" as a deliberate, containerized choice.


🔗 Resources

Codex won’t replace your judgment, and it shouldn’t try. Used well — scoped tasks, guardrail tests, diff-first review — it removes the friction between “I know what needs to change” and “the change is tested, reviewed, and merged.” That’s a smaller promise than the autonomous-agent hype, and a far more useful one.


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