Codex Deep Dive: The Developer’s Guide - 2026-09-14

What is Codex?

Codex has become one of the most consequential developer tools of the past two years, and it’s worth understanding how it got here before we start writing code with it. The lineage matters, because Codex in 2026 is not the same product that OpenAI first shipped as a code-completion API. It has evolved through several distinct phases: a cloud-based autonomous agent that ran tasks in sandboxed containers, an IDE extension, a CLI tool, and now a unified agentic development platform that spans local and remote execution.

The core value proposition is straightforward: Codex is an agent that can read your codebase, plan multi-step changes, execute commands, run tests, and iterate on failures—all while keeping you in the loop at the points that matter. Unlike autocomplete-first tools, Codex operates at the level of tasks rather than tokens. You describe an outcome (“migrate this service from REST to gRPC,” “fix the flaky test in auth_test.go”), and it works through the problem, showing its reasoning and asking for approval before destructive operations.

What differentiates Codex from alternatives comes down to three things. First, execution environment flexibility: it runs in a local sandbox, a cloud container, or a hybrid mode where planning happens remotely and execution happens on your machine. Second, the approval model: Codex supports granular autonomy levels—from “ask before every command” to full auto-approval within a defined allowlist—which matters enormously for teams with security constraints. Third, context management: Codex maintains a persistent project context that survives across sessions, so it remembers your build system, your test conventions, and the architectural decisions you’ve made.

The recent leak of system prompts (the asgeirtj/system_prompts_leaks repository that trended on GitHub) gave the community a rare look at how Codex’s instructions are structured—particularly around tool-use policies, refusal boundaries, and the internal heuristics for when to ask for clarification versus proceed. If you’re building on top of Codex or writing your own agent harness, that repository is worth reading carefully.


🚀 Getting Started

Installation

Codex ships as a CLI, an IDE extension (VS Code and JetBrains), and a cloud agent accessible via web and API. The CLI is the fastest path to productivity and the one we’ll focus on here.

# Install via npm (Node 20+ required)
npm install -g @openai/codex

# Or via Homebrew on macOS/Linux
brew install codex

# Verify installation
codex --version
# codex 1.4.2 (build 2026-09-02)

# Authenticate — opens browser for OAuth, or use API key
codex auth login
# Or for CI/headless environments:
export OPENAI_API_KEY="sk-..."

If you’re on Windows, the recommended path is WSL2. Native Windows support exists but the sandboxing story is weaker, and Codex will warn you about it.

Configuration

Codex reads configuration from ~/.codex/config.toml (global) and .codex/config.toml (per-project). The per-project file takes precedence and is the one you should commit to version control so your whole team shares the same settings.

# .codex/config.toml

[model]
name = "gpt-6-astra-codex"   # or "codex-5.1" for the coding-tuned variant
reasoning_effort = "high"     # low | medium | high
max_output_tokens = 32000

[sandbox]
mode = "workspace-write"      # read-only | workspace-write | danger-full-access
network_access = false        # deny outbound network by default
allowed_write_paths = ["./src", "./tests", "./docs"]

[approval]
policy = "on-request"         # untrusted | on-failure | on-request | never
auto_approve = [
  "cargo test",
  "cargo build",
  "npm test",
  "git status",
  "git diff"
]

[context]
project_doc = "AGENTS.md"     # Codex reads this file for project conventions
max_context_files = 40
ignore_patterns = ["node_modules/**", "target/**", ".venv/**", "*.lock"]

[telemetry]
enabled = false               # opt-in only

The AGENTS.md file is the single most important configuration decision you’ll make. It’s a plain-Markdown file at your repo root where you document conventions Codex should follow. A good one looks like this:

# AGENTS.md

## Build & Test
- Build: `cargo build --release`
- Test: `cargo test --all-features`
- Lint: `cargo clippy -- -D warnings`
- Format: `cargo fmt --check`

## Conventions
- All public APIs require doc comments with examples.
- Error types use `thiserror`; never use `anyhow` in library crates.
- Integration tests live in `tests/` and use `testcontainers` for DB fixtures.
- Never commit directly to `main`; branch naming is `feat/`, `fix/`, `chore/`.

## Architecture Notes
- `src/domain/` is pure logic with no I/O.
- `src/adapters/` contains all external integrations.
- The `EventBus` trait is the only cross-module communication channel.

Codex reads this file on every session start, which means the quality of your AGENTS.md directly correlates with how well Codex performs on your codebase. Teams that invest an afternoon in writing a thorough one report dramatically fewer “that’s not how we do it here” corrections.


💡 Core Features

Feature 1: Agentic Task Execution

The headline feature is that Codex executes tasks end-to-end rather than suggesting snippets. You give it a goal, and it plans, edits, runs, and verifies.

# Interactive mode — Codex plans and asks for approval
codex "Add rate limiting to the /api/search endpoint using a token bucket, \
      with Redis as the backing store. Add tests."

# Non-interactive mode for scripting
codex exec "Fix the failing test in tests/auth_test.rs"

In interactive mode, Codex presents a plan first:

Plan:
1. Read src/api/search.rs and src/adapters/redis.rs to understand existing patterns
2. Add a RateLimiter struct in src/domain/rate_limit.rs using the token bucket algorithm
3. Wire it into the search handler via a tower middleware
4. Add configuration for bucket size and refill rate
5. Write integration tests in tests/rate_limit_test.rs
6. Run `cargo test --all-features` and iterate on failures

Approve plan? [y/N/edit]

The edit option is where Codex shines—you can modify the plan in natural language (“skip the middleware, use a direct check in the handler”) and it will re-plan. This is a fundamentally different interaction model from chat-based coding assistants, where you’re constantly re-explaining context.

Real-world application: A payments team used codex exec in a nightly cron job to scan for dependency vulnerabilities, open PRs with upgrades, and run the full test suite. Over three months, 78% of the resulting PRs were merged without human modification—the remaining 22% needed edits, mostly when a major version bump required API changes.

Feature 2: Sandboxed Execution with Granular Approval

Codex runs commands in a sandbox by default. On Linux this uses landlock and seccomp; on macOS it uses sandbox-exec; on Windows it falls back to a Job Object with restricted tokens. The sandbox is not a container—it’s an OS-level confinement that limits filesystem writes and network access.

# Read-only mode — Codex can explore but not modify
codex --sandbox read-only "Explain how the authentication flow works"

# Workspace-write — can modify files in allowed paths
codex --sandbox workspace-write "Refactor the UserService to use the repository pattern"

# Danger mode — full access, use only in ephemeral environments
codex --sandbox danger-full-access --approval never "Run the full CI pipeline locally"

The approval policy is orthogonal to the sandbox mode, and this separation is genuinely useful. You can have workspace-write sandboxing with never approval for commands in your allowlist, which means Codex runs cargo test without interruption but still asks before running git push.

# Approve a command and add it to the allowlist for this session
codex "Deploy to staging"
# Codex: I'd like to run: kubectl apply -f k8s/staging/
# [a]pprove once / [A]pprove always / [d]eny / [e]dit

Real-world application: A healthcare company with HIPAA constraints runs Codex in read-only sandbox mode with network_access = false for all exploratory work, and switches to workspace-write only within a dedicated dev container that has no access to production credentials. The audit log (~/.codex/sessions/*.jsonl) records every command and its approval status, satisfying their compliance team’s requirements.

Feature 3: Persistent Project Context

Codex maintains a project-level memory that persists across sessions. This includes the AGENTS.md file, a semantic index of your codebase, and a log of past decisions.

# Initialize the project index (run once, re-run after major changes)
codex index .

# View what Codex knows about your project
codex context show

# Add a persistent note that survives across sessions
codex context note "The billing service uses Stripe API version 2024-06-20; \
                    do not upgrade without coordinating with the finance team."

The semantic index is built with a local embedding model by default (no code leaves your machine), though you can opt into a cloud index for larger repos. The index is incremental—codex index . after the first run only re-processes changed files, which keeps it fast even on large monorepos.

# Example: context-aware refactoring
codex "Rename the PaymentProcessor class to PaymentGateway everywhere, \
      including tests and docs, but preserve the old name as a deprecated alias."

# Codex uses the index to find all references, including ones in:
# - String literals in config files
# - Documentation in docs/
# - Test fixtures
# - Serialized data in test snapshots

The deprecated-alias handling is a nice touch—Codex understands that renames in public APIs need a migration path, and it will generate the alias automatically if you ask.

Real-world application: A team maintaining a 400,000-line Java monolith used Codex’s persistent context to onboard new engineers. The AGENTS.md file plus the semantic index meant a new hire could ask “how does the order fulfillment flow work?” and get an answer grounded in the actual code, with file paths and line numbers, rather than a generic explanation.


🛠️ Advanced Workflows

Workflow 1: Test-Driven Development Loop

Codex excels at the red-green-refactor cycle because it can run tests and iterate autonomously.

# Start with a failing test
codex "Write a failing test for a function that parses ISO 8601 durations \
      like 'P1Y2M3DT4H5M6S' into a struct. Then implement it until the test passes."

# Codex will:
# 1. Write tests/duration_test.rs with the test
# 2. Run `cargo test duration` — confirm it fails to compile
# 3. Implement src/domain/duration.rs
# 4. Run tests again — iterate on failures
# 5. Run `cargo clippy` and `cargo fmt`
# 6. Present the final diff for review

You can also drive this from a script for batch work:

#!/usr/bin/env bash
# fix-flaky-tests.sh — run nightly, attempt to fix flaky tests

set -euo pipefail

# Identify flaky tests by running the suite 5 times
for i in {1..5}; do
  cargo test --all-features -- --format json > "run-$i.json" || true
done

FLAKY=$(jq -s 'flatten | group_by(.name) | map(select(length < 5)) | .[].name' run-*.json)

for test in $FLAKY; do
  echo "Attempting to fix: $test"
  codex exec --sandbox workspace-write --approval on-failure \
    "The test '$test' is flaky. Investigate the root cause and fix it. \
     Do not simply add retries or increase timeouts — find the actual race condition."
done

The instruction “do not simply add retries” is important. Without it, Codex (like most agents) will take the path of least resistance and paper over the flakiness. Being explicit about the quality bar you expect is the single biggest lever for getting good results.

Workflow 2: Multi-Repository Refactoring

For changes that span repositories, Codex supports a workspace mode where multiple repos are indexed together.

# Set up a multi-repo workspace
codex workspace init my-platform
cd my-platform
codex workspace add ../auth-service
codex workspace add ../billing-service
codex workspace add ../shared-protos
codex workspace index

# Now refactor across all of them
codex "The User proto in shared-protos is changing: the 'email' field is being \
      split into 'email_primary' and 'email_secondary'. Update all three services \
      to match, including their tests and any serialization logic."

# Codex will:
# 1. Modify shared-protos/user.proto
# 2. Regenerate protobuf code in each service
# 3. Update all usages of the old field
# 4. Update test fixtures
# 5. Run each service's test suite
# 6. Produce a combined diff, grouped by repo

This is where Codex’s persistent context pays off most. Because it has indexed all three repos, it understands the dependency graph and can reason about the order of operations—modifying the proto first, then the consumers, then the tests.

Real-world application: A platform team used this workflow to migrate 14 microservices from a deprecated auth library to a new one over a single weekend. The migration had been estimated at six engineer-weeks. Codex handled the mechanical changes; the team reviewed the diffs and handled the three services that had unusual auth flows.


📊 Comparison with Alternatives

FeatureCodexClaude CodeCursor
Local sandbox execution✅ (landlock/seccomp/sandbox-exec)✅ (bubblewrap)⚠️ (limited)
Cloud agent execution✅❌❌
Granular approval policies✅ (4 levels + allowlist)✅ (3 levels)⚠️ (binary)
Persistent project context✅ (semantic index + AGENTS.md)✅ (CLAUDE.md)✅ (codebase index)
Multi-repo workspaces✅⚠️ (manual)❌
Non-interactive scripting (exec)✅✅❌
MCP server support✅✅✅
Open-source harness⚠️ (CLI is Apache-2.0, core is not)✅ (fully OSS)❌
IDE integration✅ (VS Code, JetBrains)✅ (VS Code, JetBrains)✅ (native fork)
Free tier⚠️ (limited)⚠️ (limited)✅ (generous)

The honest read: Codex and Claude Code are the two serious contenders for agentic development in 2026, and the choice often comes down to which model family you trust more for your domain. Cursor remains the best pure-IDE experience but lags on autonomous execution. If you need cloud execution (for CI integration, or for running agents on machines you don’t own), Codex is currently the only option with a mature story.


🎯 Pro Tips

  1. Write your AGENTS.md before you write your first prompt. The single highest-leverage thing you can do is document your build commands, conventions, and architecture. Codex reads this on every session, and a good AGENTS.md eliminates 80% of the “that’s not how we do it” corrections. Treat it as a living document—every time Codex does something wrong, add a line to AGENTS.md so it doesn’t happen again.

  2. Use --approval on-failure for trusted workflows. The default on-request policy is safe but chatty. If you’re in a dev container or a throwaway branch, on-failure lets Codex run freely until something fails, then it stops and asks. This is the sweet spot for most iterative work.

  3. Prefer codex exec for anything you’ll do more than twice. If you find yourself typing the same prompt repeatedly, put it in a shell script. The exec subcommand is designed for this—it’s non-interactive, returns proper exit codes, and can be composed with jq, xargs, and the rest of your Unix toolbox.

  4. Scope your sandbox tightly. workspace-write with network_access = false and an explicit allowed_write_paths list is the right default for most work. Only escalate to danger-full-access in ephemeral environments, and never with production credentials in the environment.

  5. Review the session log when something goes wrong. Every Codex session is logged to ~/.codex/sessions/ as JSONL. When Codex does something unexpected, the log shows exactly what it read, what it planned, and why it made each decision. This is invaluable for debugging both Codex’s behavior and your own AGENTS.md.

  6. Use codex context note for tribal knowledge. Things like “the staging DB password rotates monthly, ask in #platform” or “the legacy billing_v1 module is deprecated but can’t be deleted until Q1” are exactly the kind of context that makes an agent useful. Persist them.


🔗 Resources


Codex in 2026 is a mature tool, but it’s still a tool—it amplifies good engineering practices and bad ones alike. The teams getting the most out of it are the ones who invested in AGENTS.md, scoped their sandboxes carefully, and treated the agent as a junior engineer who needs clear instructions and review rather than an oracle. Start there, and the rest follows.


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