Contents

Codex Best Practices

OpenAI Codex now spans Codex CLI, IDE extensions, the Codex desktop app, Codex Cloud containers, and GitHub PR review workflows under one configuration and rule model. On the OpenAI Developers Showcase, builders have already shipped full-stack Next.js/React applications, Three.js interactive 3D worlds, and retro handheld or procedural games end-to-end.

Turning Codex into a dependable engineering teammate has less to do with clever prompt tricks and everything to do with engineering discipline: picking the right surface, writing issue-grade specs, investing in repo rules and offline verification, keeping sandboxes and network boundaries tight, using worktrees and /goal for long-horizon tasks, and reviewing every diff rigorously (see openai/codex).

Pick the Right Surface First

Each Codex surface fits a distinct interaction cadence and isolation model:

CLI: Local Pairing and Fast Iteration

Codex CLI is built for tight local feedback loops: exploring unfamiliar modules, fixing repro-driven bugs, scoped refactors, adding unit tests, and running pre-commit reviews directly against your local toolchain.

IDE Extension: Editor-Native Context

When you already have the relevant file, selection, or diagnostic open in your editor, the IDE extension avoids re-explaining paths in a terminal—especially handy for UI tweaks and localized edits.

Codex App: Multi-Repo, Multi-Thread Workspace

Codex App acts as a desktop workbench supporting parallel agents, cross-repo threads, isolated Git worktrees, Skills, Automations, and built-in Git views (track ongoing updates in the Codex Changelog). Use it when juggling two or three independent workstreams or recurring maintenance routines.

Codex Cloud: Asynchronous Isolated Containers

Codex Cloud provisions a fresh container per task, checks out your target branch or commit, runs your setup script, edits and tests inside an isolated sandbox, and outputs a reviewable diff or PR draft. Delegate well-specified issues, test backlogs, and parallel explorations here; stay in local CLI or IDE whenever requirements are still shifting.

Write Prompts Like GitHub Issues and Tune Reasoning Effort

Structure every non-trivial prompt around four elements:

  • Goal: What changes and why;
  • Context: Explicit @filename references to code, schemas, error logs, screenshots, or reference patterns;
  • Constraints: Public contracts, shipped migrations, or dependencies that must not change;
  • Done When: Exact test, lint, typecheck, and behavioral acceptance criteria.

Compare the difference:

# Too loose (invites sprawling edits with no verification anchor)
optimize the checkout flow

# Issue-grade spec (bounded scope and verifiable acceptance)
Goal: Consolidate duplicate payment parameter validation under @src/checkout/.
Context: Match the Zod validation style in @src/orders/validation.ts.
Constraints: Keep POST /api/checkout request and response shapes unchanged; leave unrelated UI files untouched.
Done When: Add unit tests for invalid amounts and currency mismatches, pass `pnpm vitest run src/checkout` and `pnpm typecheck`, and summarize changed files plus residual risks.

Match reasoning depth (model_reasoning_effort) to task complexity (none, minimal, low, medium, high, xhigh):

  • low: Boilerplate unit tests, docs, mechanical renames—fast and inexpensive;
  • medium: Everyday feature endpoints, clear bug fixes, single-module refactors;
  • high / xhigh: Concurrency races, security audits, performance regressions, and cross-module architecture changes.

Override effort for a single session inline without editing config files:

codex -c model_reasoning_effort="high"

Plan Complex Work First and Persist PLANS.md

For cross-module refactors, schema migrations, auth/billing logic, or partially defined features, follow a seven-step loop: read code → explain current state → propose plan → confirm scope → implement → verify → review diff.

Start with a read-only exploration turn:

Read the current authentication flow first without editing any files.
Trace the request path, list the files affected by token refresh,
and propose a minimal implementation plan with validation commands.

For multi-turn or multi-day work, persist the agreed plan into a temporary PLANS.md at the repo root, spend two minutes trimming unnecessary scope, and have Codex execute item by item:

# Plan: Async Order Export

## Agreed Constraints
- Exports over 500 rows run asynchronously; <=500 rows remain synchronous streaming.
- Exported files expire in object storage after 24 hours; signed URLs live for 15 minutes.

## Scope Boundaries
- Edit: `src/app/api/orders/export/route.ts`, `src/services/export.ts`
- Add: `src/jobs/export-orders.ts`, `src/services/export.test.ts`
- Leave untouched: `prisma/migrations/` history, legacy frontend download button contract

## Step-by-Step Verification
- [ ] Step 1: Extract pure query and CSV serialization helpers with unit tests
- [ ] Step 2: Wire async job enqueueing and status polling endpoints
- [ ] Step 3: Pass `pnpm vitest run src/orders && pnpm typecheck && pnpm lint`

When picking up a long task the next day, run codex resume with the saved thread ID instead of re-explaining context; start a fresh thread whenever switching to an unrelated task.

Capture Durable Conventions in Layered AGENTS.md

AGENTS.md loads hierarchically from ~/.codex/AGENTS.md through the repository root down to your current working directory, with closer directories taking precedence.

Keep three concrete loading rules in mind:

  1. AGENTS.override.md replaces rather than merges at the same level: Placing AGENTS.override.md in ~/.codex/ or any repo directory substitutes for that directory’s AGENTS.md—useful for personal local overrides without touching tracked repo files.
  2. Watch project_doc_max_bytes: Combined instruction files exceeding the byte cap are silently truncated (raise it in config.toml, e.g., project_doc_max_bytes = 65536). Keep root AGENTS.md under ~80–120 lines and never append one-off debugging logs or generic slogans.
  3. Zero-duplication coexistence with Claude Code: If your repo already maintains CLAUDE.md (see Claude Code Best Practices), set project_doc_fallback_filenames = ["CLAUDE.md"] in config.toml so Codex falls back cleanly without duplicate files.

Bootstrap with /init and put your single-file test command at the very top:

# Validation
- Single test file (run after every edit): `pnpm vitest run <path/to/file.test.ts>`
- Typecheck & lint: `pnpm typecheck && pnpm lint`
- For database schema edits, run `pnpm prisma generate`

# Constraints
- Do not change public API response shapes without explicit approval
- Do not add production dependencies unless requested
- Do not read or write secret files; only reference env var names
- Never edit shipped migrations under `prisma/migrations/`

# Patterns
- For request validation, follow `src/orders/validation.ts`
- For background jobs, follow `src/jobs/send-digest.ts`
- For outbound HTTP calls, use `packages/http` (no raw `fetch` wrappers)

A durable habit: the second time Codex makes the same mistake, encode the fix in AGENTS.md—or better yet, in a custom repo static lint whose error message tells the agent the exact replacement (see Harness Engineering).

Environment Quality Sets the Ceiling

Many apparent “model failures” are actually broken environments. In Codex Cloud, every task moves through six stages: container creation → repo checkout → setup script → network policy application → agent loop → diff output.

Invest early in five fundamentals:

  • Pin Node / Python / Go runtime versions and package managers;
  • Pre-install linters, formatters, and typecheckers;
  • Keep setup scripts idempotent and non-interactive;
  • Split offline unit tests (test:unit) from network-bound integration tests (test:integration);
  • Respect the Cloud secrets lifecycle: Secrets are available during the setup script phase and removed before the agent phase begins. Always reference secret environment variable names rather than expecting the agent to read raw secret values.
#!/usr/bin/env bash
set -euo pipefail

corepack enable
pnpm install --frozen-lockfile
pnpm prisma generate
pnpm build --filter=@repo/schemas

Tighten Sandboxes, Approvals, and Network Defaults in config.toml

Codex CLI and IDE extensions share ~/.codex/config.toml (global) and .codex/config.toml (project-level, active only for trusted repositories—never assume untrusted CI folders load it silently).

Two independent knobs govern safety (see Agent Approvals & Security):

  • sandbox_mode (OS-enforced boundary):
    • read-only: Blocks all writes; ideal for exploration and code review;
    • workspace-write: Permits edits inside the workspace while automatically keeping .git and .codex read-only;
    • external-sandbox: For runs already isolated inside Docker or CI containers;
    • danger-full-access: Removes restrictions entirely; disposable environments only.
  • approval_policy (when to pause for confirmation): Supports on-request (interactive default), granular (per-category controls), and never (unattended automation). The legacy untrusted policy is retired.

A critical default to know upfront: under workspace-write, outbound network access is disabled by default (network_access = false). Running pnpm install or live-network tests inside the sandbox will fail unless you either pre-install dependencies in setup or explicitly enable network access in [sandbox_workspace_write] (or inline via -c sandbox_workspace_write.network_access=true). Use writable_roots if you need to grant write access to sibling directories outside the repo:

# .codex/config.toml baseline
model = "gpt-5.4"
model_reasoning_effort = "medium"
project_doc_max_bytes = 65536
project_doc_fallback_filenames = ["CLAUDE.md"]

sandbox_mode = "workspace-write"
approval_policy = "on-request"

[sandbox_workspace_write]
writable_roots = []
network_access = false

Tier permissions by risk: give higher autonomy to low-risk tasks (formatting, unit tests, read-only exploration, docs, local lint fixes), and keep human sign-off on high-risk tasks (new dependencies, deploy scripts, outbound network, credentials, migrations, bulk deletes, auth/billing logic). Keep agent internet access closed by default and scoped to minimal domains/methods when required, to limit prompt injection and exfiltration exposure.

Verification Loops Matter More Than Generation Speed

Never treat a confident summary as proof of correctness. Verify through objective signals—passing tests, clean lint/typecheck, reproducing bug scripts turning green, tight diffs, and visual checks—following a five-step loop:

  1. Codex implements;
  2. Codex runs tests and static checks;
  3. Codex reviews its own diff;
  4. You review high-risk semantics, concurrency, and permissions;
  5. CI provides the final backstop.

Connect Only High-Leverage MCP Context

MCP bridges external context outside the repository (GitHub issues/PRs, Linear/Jira tickets, read-only database schemas, internal docs). Before attaching a server, check four questions: does this context change frequently, is manual copy-paste error-prone, does Codex need live tool execution rather than static prose, and will the integration be reused regularly?

Register and inspect servers via CLI (use -- before local stdio commands):

# Local stdio MCP servers (for GitHub, use the official github-mcp-server; legacy @modelcontextprotocol/server-github is archived)
codex mcp add docs -- npx -y mcp-server-docs
codex mcp add github -- docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN ghcr.io/github/github-mcp-server

# Inspect, authenticate, or remove
codex mcp list --json
codex mcp get docs
codex mcp login internal-docs
codex mcp remove docs

For remote Streamable HTTP servers, configure env-var auth, timeouts, and per-tool allow/deny lists in config.toml:

[mcp_servers.internal-docs]
url = "https://mcp.example.com/mcp"
bearer_token_env_var = "DOCS_MCP_TOKEN"
startup_timeout_sec = 10
tool_timeout_sec = 60
enabled_tools = ["search_docs", "get_page"]
disabled_tools = ["delete_page"]

Run /mcp inside any interactive session to verify live connections and exposed tools.

Skills Capture Methods; Automations Capture Cadence

Four extension layers divide cleanly:

  • AGENTS.md: Persistent repository rules;
  • MCP: Live external tools and context;
  • Skills: Reusable on-demand runbooks;
  • Automations: Scheduled execution cadence.

Codex natively discovers .agents/skills/<name>/SKILL.md from your working directory up to the repo root and user home using progressive disclosure—loading only name and description on startup and reading the full runbook on demand (so avoid adding duplicate symlinks if your team already uses .agents/skills/).

---
name: safe-db-migration
description: Create and verify a backward-compatible Prisma migration with rollback notes.
---

1. Inspect `prisma/schema.prisma` and confirm the change is additive (no destructive drops in one step).
2. Run `pnpm prisma migrate dev --create-only --name <desc>` and review the generated SQL.
3. Verify existing tests pass against the updated schema via `pnpm test`.
4. Summarize deployment order and rollback steps in the final response.

Once a skill is reliable, promote it into a scheduled automation—daily CI failure triage, weekly commit digests, dependency checks, or periodic session reviews that feed recurring friction back into AGENTS.md. In short: Skills define how; Automations define when.

Run Parallel Tasks in Worktrees Without Skipping Review

Parallelism pays off when write scopes stay disjoint (backend vs. docs, tests vs. root-cause investigation, implementation vs. read-only review, or Best-of-N explorations). Avoid running multiple agents concurrently on the same files or uncoordinated schema/caller changes.

Use git worktree locally so parallel threads never collide:

git fetch origin
git worktree add ../wt-orders-export -b feat/async-export origin/main
git worktree add ../wt-stripe-fix -b fix/webhook-idempotency origin/main

# Clean up after merge
git worktree remove ../wt-orders-export

For Best-of-N comparisons, ask every candidate to state five things: key assumptions, edit scope, risks, verification steps, and why it beats alternatives.

Drive Long-Horizon Tasks with /goal

/goal is Codex CLI’s goal-driven mode for multi-turn autonomous execution toward an objective stopping condition rather than halting after every turn. Enable it via /experimental or goals = true under [features] in config.toml, then manage runs with /goal <objective>, /goal, and /goal pause / resume / clear.

A strong goal loop rests on a clear contract:

  1. One concrete objective and an objective stopping condition;
  2. Required files, docs, issues, or PLANS.md to read first;
  3. Exact commands or build artifacts proving progress;
  4. Checkpoint-based execution with compact progress logs;
  5. Periodic /goal check-ins—tighten checkpoint definitions if updates grow vague;
  6. Pause or clear as soon as the contract is met or priorities shift.

Three high-fit examples:

# 1. Library migration
/goal Migrate the payment module from stripe-v2 to stripe-v3.
Read docs/stripe-v3-migration.md first.
Work one endpoint per checkpoint, running `pnpm test --filter payment` after each.
Stop when all payment tests pass and zero v2 references remain. Keep public API responses unchanged.

# 2. End-to-end prototype (same milestone pattern behind Showcase builds)
/goal Build the CLI tool specified in PLANS.md to a runnable state.
Checkpoint by milestone in PLANS.md, verifying build and smoke tests at each stage.
Stop when all milestones pass final smoke checks.

# 3. Eval-driven prompt tuning
/goal Improve the summarization prompt in prompts/summarize.txt.
Measure accuracy with `python evals/run.py`, inspect failures, update the prompt, and re-run.
Stop at >=85% accuracy or 20 iterations, logging score and prompt version per round.

Automate Scripts and Reviews with codex exec and codex review

For scripts and CI pipelines, use codex exec (alias codex e). Because newer Codex CLI releases removed the legacy --full-auto flag, unattended runs should explicitly pass --sandbox and -c approval_policy="never". Combine --json (JSONL event stream) and --output-schema (strict JSON Schema output validation) so downstream scripts parse outputs reliably:

# 1. Define strict output schema
cat <<'EOF' > /tmp/review-schema.json
{
  "type": "object",
  "properties": {
    "blocking_issues": { "type": "array", "items": { "type": "string" } },
    "summary": { "type": "string" }
  },
  "required": ["blocking_issues", "summary"],
  "additionalProperties": false
}
EOF

# 2. Run headless typecheck fixes inside an isolated worktree
cd ../wt-orders-export
codex exec \
  --sandbox workspace-write \
  -c approval_policy="never" \
  --json \
  "Fix all pnpm typecheck errors under packages/api without adding any casts. Pass pnpm typecheck && pnpm test." \
  > ../codex-run.jsonl

# 3. Run a structured read-only pre-PR review
codex exec \
  --sandbox read-only \
  -c approval_policy="never" \
  --output-schema /tmp/review-schema.json \
  "Review git diff main...HEAD. Report only logic bugs, race conditions, security flaws, and breaking API changes. Ignore formatting."

For everyday diffs, you can also invoke codex review directly or trigger @codex review on GitHub PRs (see How OpenAI Uses Codex and Unrolling the Codex Agent Loop for how OpenAI integrates Codex into internal engineering loops). Store your team’s review criteria in code_review.md referenced from AGENTS.md, and treat Codex review as a fast first-pass filter rather than final architectural sign-off.

Cost Control and Rate Card Reference

Codex meters usage in token-based credits (roughly $0.01 per credit), with wide spreads across models and cached vs. uncached input. Reference figures below—always check the official Codex Rate Card for current rates:

Model Input (per 1M tokens) Cached Input Output (per 1M tokens)
GPT-5.5 125 credits 12.5 credits 750 credits
GPT-5.4 62.5 credits 6.25 credits 375 credits
GPT-5.4 mini 18.75 credits 1.875 credits 113 credits
GPT-5.3-Codex 43.75 credits 4.375 credits 350 credits

Three practical cost levers jump right off the table:

  1. Maximize prompt caching: Cached input is ~10x cheaper than uncached input—keep AGENTS.md and prefix instructions stable (see GPT-5.5 and Modern OpenAI Prompting Best Practices).
  2. Match model tier and reasoning effort to the task: Use mini tiers or low effort for routine tests and docs; save flagship high effort for hard debugging and architecture.
  3. Start fresh threads between tasks: Avoid paying to re-ingest stale context from finished work.

A Repeatable Eight-Step Workflow

  1. Establish baselines: Maintain a lean AGENTS.md (single-file test command on top) and .codex/config.toml.
  2. Write issue-grade specs: Specify Goal, Context, Constraints, Done When, and appropriate model_reasoning_effort.
  3. Plan complex work: Inspect read-only and sign off on PLANS.md before editing.
  4. Isolate scope: Use git worktree for parallel threads or /goal for checkpointed multi-turn tasks.
  5. Ship small diffs: Target ~200–400 lines per reviewable PR.
  6. Verify objectively: Run tests, lint, typecheck, builds, or visual checks.
  7. Review in two passes: Run codex review / read-only codex exec, then human-review high-risk logic.
  8. Compound lessons: Feed recurring issues back into AGENTS.md, custom lints, .agents/skills/, or Automations.

Six Common Anti-Patterns

  • Dropping giant unbounded requests: “Rebuild the billing system” invites sprawling diffs—break it into a signed-off PLANS.md first.
  • Omitting verification commands: Without runnable checks, Codex can only reason statically.
  • Pasting raw secrets into prompts: Always reference environment variable names and commit only .env.example.
  • Bloating AGENTS.md with vague slogans: Generic advice dilutes real constraints and risks hitting project_doc_max_bytes.
  • Leaving sandbox networking wide open: Keep network_access = false by default and install dependencies in setup scripts.
  • Rubber-stamping diffs: Skipping review simply trades coding time for production debugging time.

Teams pairing Codex with Claude Code or GitHub Copilot CLI can share the same foundation: targeted tests up top, worktree isolation, least-privilege sandboxes, and one canonical .agents/skills/ directory.

References