Agentic AI AcademyAgentic AI Academy

Best Practices & Common Pitfalls

What separates productive Codex users from frustrated ones

Intermediate 12 minBuilderDecision-maker
What you'll be able to do
  • Be able to write a non-trivial Codex prompt using the four elements: Goal, Context, Constraints, and Done-when
  • Be able to set Codex up to verify its own work and break a large task into small, reviewable steps
  • Be able to practice session hygiene — one thread per coherent unit of work — using /fork, /compact, and sub-agents
  • Be able to decide what belongs in AGENTS.md or a skill versus what belongs in a single prompt
  • Be able to choose tight default approvals and sandbox settings and loosen them deliberately
  • Be able to decide when to run locally and when to delegate a fire-and-forget task to Codex Cloud, and to recognize the six common mistakes
At a glance

This is the playbook that separates people who ship with Codex from people who fight it. You'll learn the four-element prompt, why letting Codex verify its own work is the single highest-leverage habit, how to manage threads and permissions, when to delegate to the cloud — and the verbatim list of mistakes that bite newcomers.

  1. 1The frame: you are delegating, not autocompleting
  2. 2The four-element prompt
  3. 3Let Codex verify its own work (the top lever)
  4. 4Session hygiene: one thread per unit of work
  5. 5Durable rules go in AGENTS.md, not every prompt
  6. 6Start tight on approvals and sandbox; loosen on purpose
  7. 7Local for control, cloud for fire-and-forget
  8. 8The six common mistakes (the verbatim list)

The frame: you are delegating, not autocompleting

Most frustration with Codex traces back to one mismatch: people prompt it like a search box and then act surprised when an agent runs off and does something they didn't fully specify. Fix the frame first.

Codex is an autonomous teammate you delegate to — it reads the repo, plans, edits across files, runs commands, runs tests, and proposes a PR. That means the skills that make you productive are the skills of a good delegator: state the goal precisely, give the right context, set the constraints, define what "done" means, and let the agent verify itself. Everything in this lesson is a corollary of that one idea.

The good news is that the whole playbook is short and it's a checklist, not a theory. There are roughly six habits and six mistakes, and they mirror each other. Internalize the habits and the mistakes mostly stop happening on their own.

Do thisInstead of this
Lead with Goal / Context / Constraints / Done-whenDumping a one-line wish and hoping
Give Codex a way to verify (tests, lint, repro steps)Eyeballing the diff and trusting it
Break work into small, reviewable stepsOne giant "build the whole feature" turn
Put durable rules in AGENTS.md / skillsRe-pasting the same rules every prompt
Start with tight approvals + sandboxGranting full access before you trust the workflow
One thread per unit of workOne endless thread per project

Key insight

The whole lesson in one sentence

Productive Codex use is good delegation: say what you want, give it what it needs, tell it how to know it's done — and let it check its own work.

The four-element prompt

For anything beyond a trivial one-liner, lead with the four elements. OpenAI's best-practices guidance frames every good prompt as answering four questions:

  • Goal — what are you trying to change or build?
  • Context — which files, folders, docs, examples, or error messages matter?
  • Constraints — what standards, architecture, or safety rules should Codex follow?
  • Done-when — what should be true before the task is considered complete?

The Done-when element is the one people skip, and it's the one that pays the most. It does double duty: it tells Codex when to stop, and — if you phrase it as something runnable — it becomes the agent's own success check.

text
Goal:       Add rate limiting to the POST /login endpoint.
Context:    Auth lives in src/auth/; tests in tests/auth/.
            See src/middleware/throttle.ts for the existing pattern.
Constraints: Reuse the throttle middleware — don't add a new dependency.
            Keep the public API of loginHandler unchanged.
Done-when:  npm test passes, including a new test that a 6th login
            attempt within 60s returns HTTP 429.

Notice the prompt names specific files rather than making Codex hunt, points at an existing pattern to imitate, and ends with a check that is literally runnable. That last line is what lets Codex close its own loop instead of handing you something that merely looks finished.

When you genuinely don't know how to decompose the work, don't guess — ask Codex to propose a plan first (use /plan, or ask it to interview you). Reviewing a plan is cheaper than reviewing a wrong diff.

Tip

Make Done-when runnable

A Done-when you can run — a test command, a lint pass, a repro that should now succeed — turns into the agent's verifier. "It compiles" is weak; "npm test passes including a new 429 test" is strong.

Let Codex verify its own work (the top lever)

If you remember one habit from this lesson, make it this one. OpenAI's own guidance is blunt: "Codex produces higher-quality outputs when it can verify its work." Give it the means to check itself and quality jumps; withhold it and you become the verification step — slower, and easy to skip.

Concretely, hand Codex three kinds of feedback so it can close the loop:

  • Steps to reproduce a bug, so it can confirm the bug exists before fixing and is gone after.
  • A way to validate the feature — a test to write or run, an endpoint to hit, an output to compare.
  • Lint and pre-commit checks to run, so style and obvious errors are caught by the machine, not by you in review.

This pairs directly with breaking big work into small steps. As the docs put it, "smaller tasks are easier for Codex to test and for you to review." A focused step has a tight verifier and a small diff; a sprawling one has neither, and a single bad assumption early on poisons everything after it.

The two habits reinforce each other: small steps make verification cheap, and a working verifier makes it safe to take many small steps quickly.

Example

Same task, with and without a verifier

Without: "Fix the flaky checkout test." → Codex guesses, you re-run it five times to see if it's actually fixed. With: "The checkout test in tests/checkout.spec.ts flakes ~1 in 5 runs. Reproduce by running it 20× in a loop, find the race, fix it, and prove it by running it 50× green." → Codex now has a repro AND a pass criterion.

Session hygiene: one thread per unit of work

A thread is Codex's working memory. The best-practices rule is: one thread per coherent unit of work — not one thread per project. A single endless thread accumulates stale context, half-finished tangents, and contradictory instructions; Codex starts getting distracted by things you stopped caring about three tasks ago.

Start a fresh, focused thread when you switch to a genuinely different task. Within a long piece of work, three tools keep the context clean:

ToolWhen to reach for it
/fork (or codex fork)You want to try a variation or risky direction while preserving the original transcript to return to
/compactThe thread is getting long; summarize the visible conversation to free tokens before continuing
/newStart a fresh conversation inside the same CLI session for an unrelated task
Sub-agentsHand off a self-contained chunk so its context stays isolated from your main thread

Note the distinction newcomers from other tools trip on: there is no /undo in Codex. Rollback is your normal git workflow — Codex surfaces a transcript of every action it took, so you git status, git diff, and revert as you would any other change. And /approvals is gone; the command is /permissions (covered next).

Note

Recovering after a cancel

Pressed Ctrl+C to interrupt a turn and lost your prompt? Press Up in the composer to recover it. To revise an earlier message instead, press Esc Esc on an empty composer to walk back through the transcript. There is no checkpoint-style file undo — git is your safety net.

Durable rules go in AGENTS.md, not every prompt

If you find yourself pasting the same instructions into prompt after prompt — "use pnpm not npm," "run the linter before you say you're done," "never touch the generated/ folder" — that's a signal those rules belong somewhere durable, not in your working memory and definitely not in every prompt.

Where durable knowledge lives:

  • AGENTS.md — the cross-tool Markdown standard ("a README for agents"). Put repository layout, build/test/lint commands, engineering conventions, and do-not rules here. Codex loads it automatically and merges files from the Git root down to your cwd, so the closest file wins. Scaffold one with /init.
  • Skills — when you keep reusing the same multi-step prompt or correcting the same workflow, package it as a skill. "Skills define the method." Start with 2–3 concrete use cases; keep them local while iterating.
  • The prompt — only the task-specific details: this goal, these files, this done-when.

The guiding maxim from the docs: "A short, accurate AGENTS.md is more useful than a long file full of vague rules." Resist the urge to write an essay. Vague rules ("write clean code") cost tokens and change nothing; specific, verifiable ones ("all new endpoints need a test in tests/api/") earn their place. Codex caps the injected project docs at 32 KiB (project_doc_max_bytes) by default, so brevity isn't just style — it's a budget.

Tip

The litmus test

Ask: "Would I want Codex to follow this on every task in this repo?" If yes → AGENTS.md. "Is this a repeatable multi-step procedure?" → a skill. "Is this only true for the thing I'm doing right now?" → the prompt.

Start tight on approvals and sandbox; loosen on purpose

Codex has two independent controls, and conflating them is a classic mistake. Sandbox = WHERE Codex can act (the OS-enforced read/write/network boundary). Approvals = WHEN Codex must stop and ask you. They're related but not interchangeable, and you set them separately.

Sandbox mode (--sandbox/-s)What it allows
read-onlyInspect files only; no edits or commands without approval
workspace-writeRead + edit within the workspace + run routine local commands. Network is OFF by default. The default low-friction local mode
danger-full-accessNo filesystem or network boundary — use only when you truly mean it

Approval policy (--ask-for-approval/-a) is the orthogonal axis: untrusted (auto-run only known-safe reads), on-request (works in the sandbox, asks to go beyond it — the recommended interactive default), or never (no prompts, stays in the sandbox).

The best practice is defense by default: start tight and loosen deliberately, per repo, once you understand the workflow — never the reverse. When you need a little more room, prefer the narrow tool over the nuclear one:

bash
# Grant one extra writable dir instead of dropping the sandbox
codex --add-dir ../shared-lib "..."

# Switch posture mid-session
/permissions

Reach for --add-dir or a tighter network allowlist before you ever reach for --dangerously-bypass-approvals-and-sandbox (alias --yolo), which disables both controls and belongs only inside a hardened container or VM.

Watch out

Don't start at full access

Granting full permissions before you understand a workflow is on the official list of common mistakes. You can't learn what Codex tends to do wrong if it never pauses to ask. Loosen one notch at a time, for one repo, once you've seen the pattern.

Local for control, cloud for fire-and-forget

Codex runs the same agent locally (CLI/IDE) and in the cloud (isolated containers in OpenAI's infrastructure that check out your repo, run setup scripts, and execute in the background — even in parallel). They're not competitors; they're for different moments.

Local CLI / IDECodex Cloud
Best forInteractive, control-heavy, latency-sensitive workHeavy lifting you want to fire and forget
You getInstant feedback, full visibility, repo privacyBackground + parallel runs, no local resource use
ExamplesPairing on a bug, exploratory refactor, anything you want to watchBig migrations, deep multi-step debugging, risky experiments, parallel batches
InternetNetwork off by default in workspace-writeOff during the agent phase; setup scripts can install deps

The rule of thumb: default to local when you want to steer and see every step; delegate to cloud when the task is large, well-specified, and you'd rather kick it off and come back to a PR. Cloud tasks finish as a PR you review, and you can pull a cloud diff down locally with codex apply TASK_ID to test it on your machine.

A related lever: once a manual workflow is reliable, you can wrap it in an automation to run on a schedule — "skills define the method, automations define the schedule." But note the ordering — automations come after the workflow works by hand, never before.

Key insight

Cloud rewards good specs

Cloud is fire-and-forget, which means you don't get to course-correct mid-run. That makes the four-element prompt — especially a runnable Done-when — more important for cloud tasks, not less.

The six common mistakes (the verbatim list)

OpenAI's best-practices page ships an explicit list of mistakes to avoid. Print it, pin it, return to it. Every one is the inverse of a habit above:

MistakeThe fix (and where it's covered)
Overloading prompts with durable rules instead of moving them into AGENTS.md or a skillPut durable knowledge in AGENTS.md / skills; keep prompts task-specific
Not showing the agent how to run builds and testsGive Codex its verifier — test, lint, repro steps
Skipping planning on multi-step tasksUse /plan or ask Codex to interview you first
Granting full permissions before understanding the workflowStart with tight approvals + sandbox; loosen deliberately
Creating automations before workflows are reliable manuallyMake it reliable by hand first, then schedule it
Using one thread per project instead of per taskOne thread per coherent unit of work; /fork, /compact, sub-agents

Three of these (durable rules, planning, threads-per-task) are about not overloading context. Two (verifier, automations) are about not skipping verification. One (permissions) is about not over-trusting too early. If you keep those three principles in mind — protect context, always verify, earn trust gradually — you'll avoid the whole list without memorizing it.

Watch out

These are volatile too

The exact best-practices wording, the slash roster, model names, and defaults move fast (Codex shipped token-based pricing and new models in 2026). Treat this lesson as the durable shape and confirm specifics at developers.openai.com/codex/learn/best-practices and the linked live pages.

Try it: Run the same task twice — sloppy prompt vs. the playbook

Goal: feel how much the habits in this lesson change the outcome, on a real bug. 1) Pick a target. In a small repo of yours that has a test command, find or plant a simple bug (e.g. an off-by-one, a missing validation). 2) Round one — the sloppy prompt. Start codex and give it a one-liner with no structure, e.g. "fix the bug in the cart code." Watch what it does: does it hunt for files? Does it know when it's done? Note how much you have to verify by hand. 3) Reset. Roll back with git (git checkout .) — remember there is no /undo. Start a fresh thread (/new) so round two has clean context. 4) Round two — the four-element prompt. Write Goal / Context (name the files) / Constraints / Done-when as a runnable check, e.g. "...Done-when: npm test passes including a new test for the empty-cart case." 5) Tighten the loop. Before you start, confirm your sandbox/approvals are set conservatively (read-only or workspace-write + on-request); use /plan if the change is multi-step. 6) Move a durable rule out. Take one instruction you'd want on every task (a lint command, a do-not rule) and add it to AGENTS.md via /init; confirm Codex now follows it without you re-typing it. 7) Write four sentences: how did the structured prompt change Codex's behavior, where did the runnable Done-when let it verify itself, what did session hygiene (/new) feel like, and which one common mistake were you about to make in round one?

Key takeaways

  1. 1Lead every non-trivial task with the four elements — Goal, Context, Constraints, Done-when — and make the Done-when runnable so it becomes the agent's own success check.
  2. 2Letting Codex verify its own work (repro steps, tests, lint/pre-commit) is the single highest-leverage habit; pair it with breaking big work into small, reviewable steps.
  3. 3Practice session hygiene: one thread per coherent unit of work, not per project. Use /fork, /compact, and sub-agents to keep context clean — and remember there's no /undo, rollback is git.
  4. 4Keep durable rules in AGENTS.md or a skill, not in every prompt — 'a short, accurate AGENTS.md is more useful than a long file full of vague rules.'
  5. 5Sandbox (WHERE) and approvals (WHEN) are independent; start both tight and loosen deliberately per repo. Prefer --add-dir over --yolo.
  6. 6Default to local for interactive, control-heavy work; delegate large, well-specified tasks to Codex Cloud as fire-and-forget. Avoid the six common mistakes: durable rules in prompts, no build/test commands, skipped planning, premature full permissions, premature automations, one-thread-per-project.

Quiz

Lock in what you learned

Check your understanding

0 / 4 answered

1.A teammate writes the prompt: "Make the login flow better." Which element of the four-element prompt template is most critically missing, and why does it matter most?

2.Why is 'let Codex verify its own work' described as the single highest-leverage habit?

3.You keep pasting 'use pnpm, run the linter before finishing, never edit the generated/ folder' into every Codex prompt. According to the best-practices playbook, what should you do?

4.Which statement correctly reflects the best-practice posture for approvals, sandbox, and choosing local vs. cloud?

Go deeper

Hand-picked sources to keep learning