OpenAI Codex Best Practices: A Practical Guide for Engineering Teams
Getting good results from Codex is less about clever prompts and more about the scaffolding you put around it: how you configure the sandbox, how you write your AGENTS.md file, how you structure tasks, and how you review what comes back. Teams that follow solid codex best practices treat Codex like a fast, tireless junior engineer who needs clear instructions and a strict code review process, not a black box that magically writes production code. This guide walks through the setup, workflow, and guardrails that make Codex genuinely useful on real codebases instead of a source of subtle bugs.
What Codex Best Practices Actually Means in 2026
Codex, OpenAI's coding agent, ships as both a CLI tool (codex) and an IDE extension, and it can run locally, in a cloud sandbox, or as part of a CI pipeline. The core best practice underneath everything else is this: Codex is a capable pattern-matcher operating on the context you give it. It doesn't know your team's conventions, your production incidents, or which parts of the codebase are load-bearing unless you tell it. Every other practice in this article is really one idea applied in different places: give Codex tight, accurate context and a narrow task, then verify the output before it touches anything that matters.
This matters more in 2026 than it did in the early days of AI coding assistants, because Codex is now commonly wired into CI, given push access to feature branches, and trusted with multi-file refactors. The blast radius of a bad instruction is bigger. Codex best practices today are as much about process (approval modes, review gates, sandboxing) as they are about prompt wording.
Three things determine whether a Codex session goes well:
- The quality and specificity of your instructions (prompt plus repo context).
- The sandbox and approval mode you run it in.
- Whether a human (or a strict automated check) reviews the diff before it merges.
Get those three right and Codex becomes a real productivity multiplier. Skip any of them and you get plausible-looking code that quietly breaks something three sprints from now.
Setting Up Codex the Right Way
Start with a clean install and check you're running a current version, since Codex ships frequent updates:
npm install -g @openai/codex
codex --versionAuthenticate once, either with your ChatGPT account (subscription-based usage) or an API key (usage-based billing):
codex loginCodex reads a config file at ~/.codex/config.toml. This is where most of your best-practice setup lives. A sane starting config looks like this:
model = "gpt-5.1-codex"
approval_policy = "on-request"
sandbox_mode = "workspace-write"
[projects."/Users/you/code/your-repo"]
trust_level = "trusted"A few settings worth understanding before you run Codex against a real repo:
- `approval_policy` controls how often Codex stops to ask before acting.
untrustedasks for almost everything,on-requestlets Codex decide when to ask, andneverruns fully autonomously. Start new projects onon-requestor stricter until you've built trust in how Codex behaves in that specific codebase. - `sandbox_mode` controls filesystem and network access.
read-onlyis for exploration and planning.workspace-writelets Codex edit files inside the project directory but blocks network access and writes outside the workspace.danger-full-accessremoves the sandbox entirely and should be reserved for containerized CI environments you already treat as disposable. - Per-project trust lets you loosen the policy for repos you've vetted, without loosening it globally.
Run Codex interactively from inside the repo you want it to work on:
cd your-repo
codexOr run a single task non-interactively, which is the mode you'll use for scripting and CI:
codex exec "Add input validation to the signup form handler in src/routes/signup.ts"Writing Effective Prompts and AGENTS.md Files
The single highest-leverage codex best practice is writing a good AGENTS.md file at the root of your repository. Codex reads this file automatically at the start of every session, so it functions as persistent context you'd otherwise have to repeat in every prompt. Nest additional AGENTS.md files in subdirectories for module-specific rules; Codex merges them, with the more specific file taking precedence.
A useful AGENTS.md covers:
## Project overview
This is a Next.js 15 app with a Postgres backend accessed through Prisma.
Auth is handled by Clerk. Payments go through Stripe and Razorpay.
## Conventions
- Use TypeScript strict mode. No `any` unless justified with a comment.
- Server actions live in `app/actions/`, one file per domain.
- Never write raw SQL. Use the Prisma client.
- Run `npm run lint` and `npm run typecheck` before considering a task done.
## Testing
- Unit tests live next to the file they test, suffixed `.test.ts`.
- Run `npm test -- --run` after any change to `lib/` or `app/actions/`.
- Do not delete or skip failing tests to make a task pass.
## Off-limits
- Do not modify files under `db/migrations/` directly; generate new
migrations with `npx prisma migrate dev`.
- Do not touch `.env`, `.env.local`, or anything in `secrets/`.That last section, an explicit off-limits list, is one of the most underused codex best practices. Codex will happily "fix" a broken migration file or refactor a config it thinks looks messy unless you tell it not to. Naming the danger zones up front costs you five lines and saves you an afternoon.
For the prompt itself, in the CLI or IDE, the same rules that make a good ticket make a good Codex instruction:
- State the goal, not just the mechanism. "Add rate limiting to the
/api/uploadendpoint using the existinglib/rate-limit.tshelper" beats "make uploads more secure." - Point to existing patterns. "Follow the same structure as
app/actions/createOrder.ts" gives Codex a template instead of forcing it to guess your idioms. - Constrain the blast radius. "Only touch files under
app/api/upload/" stops Codex from wandering into unrelated modules while trying to be helpful. - State the definition of done. "This is done when
npm run typecheckand the new test inupload.test.tsboth pass."
Vague prompts are the number one cause of Codex producing correct-looking code that solves the wrong problem.
Using the Codex CLI Safely: Sandboxing and Approval Modes
Sandboxing is not optional hardening, it's the mechanism that makes autonomous runs safe to leave unattended. Understand the three sandbox tiers before you pick one for a task:
- `read-only`: Codex can read the repo and run read-only shell commands, but cannot write files or make network calls. Use this for planning sessions, code audits, or "explain this codebase to me" tasks where you don't want any side effects.
- `workspace-write`: Codex can edit and create files inside the current working directory and run commands, but writes outside the workspace and network access are blocked by default. This is the right default for day-to-day development work.
- `danger-full-access`: no sandbox. Reserve this for ephemeral containers in CI, never for your laptop with your real filesystem and credentials on it.
Combine sandbox mode with approval policy deliberately rather than defaulting to the loosest setting because it's less annoying. A good pattern for local development:
codex --sandbox workspace-write --ask-for-approval on-requestThis lets Codex move through routine edits without interrupting you, but stops to ask before running anything it flags as risky, like installing a new dependency or running a destructive shell command.
For fully autonomous runs, for example a scheduled Codex job that fixes lint errors across a large repo overnight, pair never approval with a sandbox and a git worktree so the blast radius is contained to a disposable branch:
git worktree add ../repo-codex-run codex/lint-fixes
cd ../repo-codex-run
codex exec --sandbox workspace-write --ask-for-approval never \
"Fix all ESLint errors in this repo without changing behavior. Run npm run lint after each file to confirm."If it goes wrong, you delete the worktree and branch. Your main working tree never saw the bad state.
Codex Best Practices for Code Review and Verification
No matter how good the prompt or how tight the sandbox, treat every Codex diff as an unreviewed pull request from a fast but inexperienced contributor. The practices that hold up:
Never let Codex merge its own work. Even with never approval and full autonomy, output should land on a branch that goes through your normal PR process, with CI and at least one human reviewer, before touching main.
Ask Codex to write or update tests as part of the task, not as an afterthought. "Implement X and add a test covering the empty-input case" produces meaningfully more reliable code than asking for the implementation alone, because Codex has to reason about the edge case to write the test.
Run the verification loop yourself, don't trust a self-report. Codex will tell you a task is complete; confirm it independently:
git diff --stat
npm run typecheck
npm test -- --run
npm run lintRead the diff, don't just skim the summary. Codex is good at producing plausible-sounding explanations of what it did. The only way to catch a case where the explanation and the actual diff diverge is to read the diff.
Watch for scope creep. A Codex session asked to fix one function will sometimes also "clean up" nearby code, rename variables, or reformat unrelated lines. This is often harmless but occasionally hides the real change in noise. If a diff touches more files than the task implies, ask why before approving.
Be specific about what "done" means for security-sensitive code. For anything touching auth, payments, or user data, add an explicit instruction like "do not weaken any existing validation, and flag anywhere you're unsure rather than guessing." Codex responds well to being told to surface uncertainty instead of resolving it silently.
Structuring Multi-Step Tasks with Codex
Large tasks fail more often than small ones, not because Codex can't handle complexity, but because ambiguity compounds across steps. Break multi-step work into checkpoints:
- Plan first, execute second. Ask Codex to read the relevant code and propose a plan before writing anything: "Read
lib/billing/andapp/actions/subscriptions.ts. Propose a plan for adding a proration step to plan upgrades. Don't write code yet." Review the plan, correct it, then let Codex implement it. - One logical change per session. A session that adds a feature, refactors an unrelated helper, and updates three tests is harder to review and harder to roll back than three focused sessions. Split them, even if it means repeating some setup.
- Use git commits as checkpoints. Ask Codex to commit after each coherent step: "After each file is working and tests pass, commit with a descriptive message before moving to the next file." This gives you a rollback point per step instead of an all-or-nothing diff.
- Hand off context explicitly between sessions. If a task spans multiple Codex sessions, don't rely on memory across sessions unless you're using a mode that preserves it. Summarize state in a scratch file or the PR description: what's done, what's left, what decisions were made and why.
For genuinely large refactors, run Codex against a narrow slice first, review it thoroughly, and only then ask it to repeat the pattern across the rest of the codebase. This catches misunderstandings while the cost of being wrong is still one file, not fifty.
Integrating Codex into CI/CD Pipelines
Codex's non-interactive exec mode is what makes CI integration practical. A few patterns that work well in practice:
Automated lint and type fixes on a schedule, run in a disposable container, opening a PR rather than pushing directly:
codex exec --sandbox workspace-write --ask-for-approval never \
"Fix all failing typecheck errors. Do not change any logic, only types and imports."
git checkout -b codex/typefix-$(date +%Y%m%d)
git add -A && git commit -m "Fix typecheck errors"
git push origin HEAD
gh pr create --title "Automated: typecheck fixes" --body "Generated by scheduled Codex run. Needs human review before merge."PR-triggered review comments. Some teams run Codex against the diff of an incoming PR in read-only sandbox mode and post its findings as a comment, functioning as an extra reviewer rather than an author. This keeps Codex's output in an advisory role for anything that reaches production code paths.
Gate autonomous runs behind branch protection. Whatever Codex produces in CI should land on a branch that cannot merge without passing your existing required checks and at least one approval. Don't create a separate, looser path for AI-authored changes; run them through the same gate as everything else, possibly with an extra required reviewer for anything Codex-authored.
Keep credentials out of the sandbox. If a CI job runs Codex with workspace-write or full access, make sure it doesn't have production credentials in scope. Use a scoped, short-lived token if Codex needs API access at all, and prefer giving it none over giving it broad access "just in case."
Common Mistakes to Avoid
Running everything at `never` approval from day one. It feels efficient until an ambiguous instruction runs to completion and you're cleaning up. Build trust in a specific repo and task type before removing approval checkpoints.
Skipping the AGENTS.md file. Every session that starts without it re-derives your conventions from scratch, and it will occasionally derive the wrong ones. The five minutes it takes to write one pays for itself in the first week.
Treating Codex output as done because it compiles. Compiling and passing existing tests are necessary, not sufficient. New code paths need new tests, and Codex should be asked for them explicitly.
Giving one session too many unrelated goals. "Fix the bug in checkout, also update the README, also see if you can speed up the build" produces a diff that's hard to review and hard to revert cleanly if one part is wrong.
Not pinning the model or CLI version in CI. Behavior can shift between versions. Pin the Codex CLI version in your CI image and update deliberately, the same way you'd pin a compiler or test runner.
Forgetting the off-limits list. Migrations, secrets, and generated files are the recurring casualties when a repo has no AGENTS.md boundary section. State them once, in writing, rather than relying on Codex to infer them from file paths.
FAQ
What's the difference between Codex's sandbox modes and just running it in a Docker container? Codex's built-in sandbox operates at the OS level (filesystem and network permissions) regardless of where the process runs. Running it inside a container is a complementary layer, not a replacement: containers isolate the whole process from your host machine, while sandbox_mode controls what that process can do to the filesystem and network it can already see. Use both for autonomous CI runs: a disposable container plus a workspace-write or stricter sandbox inside it.
Should I let Codex write directly to my main branch? No. Even with high trust in a given task type, route Codex's output through a branch and your normal PR review. This isn't distrust of the model specifically, it's the same discipline you'd apply to any automated commit generator: a review gate catches the rare bad diff before it becomes a rare bad incident.
How specific does an AGENTS.md file need to be? Specific enough that a new human contractor reading it could follow your conventions without asking a teammate. If you find yourself repeating the same instruction in multiple Codex prompts across different sessions, that instruction belongs in AGENTS.md instead.
Can Codex handle a task that spans a large, unfamiliar codebase? Better if you front-load orientation. Ask it to read and summarize the relevant modules first, in read-only mode, before asking it to change anything. A short planning pass catches a lot of the misunderstandings that would otherwise show up as a wrong-but-plausible diff.
Is it worth using Codex for security-sensitive code like auth or payments? Yes, with tighter constraints: explicit instructions not to weaken existing checks, a requirement to flag uncertainty rather than guess, mandatory new tests for any new code path, and a human security-aware reviewer on the resulting PR. Treat the review bar as higher for this code, not the same as a UI tweak.
What's the biggest single change that improves Codex output quality? Writing a real AGENTS.md file and keeping it current as conventions change. It's the one piece of context that carries into every session automatically, so it has more leverage than any individual prompt.
AI CodingShip full-stack AI apps at conversation speed — specs, agents, deploys, all from the terminal.
CodexLearn to drive OpenAI's coding agent: real tasks, safe sandboxing, and terminal-to-cloud workflows that ship.