The Agent Loop & the Four-Element Prompt
How Codex thinks, and how to brief it well
- Trace the Codex agent loop — gather context, propose changes/commands, pause for approval, iterate — and explain why it surfaces a transcript instead of a /undo
- Write a four-element prompt (Goal, Context, Constraints, Done-when) for a real coding task
- Apply the top lever — give Codex a way to verify its own work — by including reproduction, validation, and lint/pre-commit steps
- Decide when to break a task into small steps and when to ask Codex for a plan first
- Explain what belongs in a short, accurate AGENTS.md versus a one-off prompt
- Avoid the common briefing mistakes: overloading prompts, hiding build/test commands, and skipping planning
Codex runs a simple but powerful loop: it gathers context by reading and searching your repo, proposes edits and commands, pauses for approval according to your settings, and iterates conversationally — always surfacing a transcript you can review or roll back through git. Once you can see that loop, the single highest-leverage skill is briefing it well, and OpenAI gives you a four-element template — Goal, Context, Constraints, Done-when — plus one top lever: let Codex verify its own work and break big tasks into small steps.
- 1Open the hood: the Codex agent loop
- 2The brief is the highest-leverage skill
- 3The four-element prompt template
- 4The top lever: let Codex verify its own work
- 5Break work into small steps; ask for a plan when unsure
- 6Durable rules go in AGENTS.md, not the prompt
- 7The briefing mistakes to avoid
Open the hood: the Codex agent loop
Before you tune a single prompt, fix the right mental model of what happens after you press Enter. Codex is not answering a question in one shot — it is running a loop, the same loop a careful engineer runs by hand:
- Gather context — it reads relevant files and searches your repository to understand what's actually there.
- Propose changes or commands — based on your prompt, it suggests edits to apply or commands to run.
- Pause for approval — depending on your active approval mode, it stops and asks before editing files or running commands.
- Iterate — you respond, it adjusts, and the cycle repeats conversationally until the work is done.
The official description is exactly this: Codex "can read your repository, make edits, and run commands as you iterate together." Two design choices make the loop trustworthy. First, Codex always surfaces a transcript of its actions, so you can see every file it read, every command it ran, and every change it made. Second — and this is the Codex-specific detail people get wrong — there is no /undo command. Rollback is done with your normal git workflow: the transcript shows you what changed, and git (diff, restore, checkout, reset) is how you take it back.
This is why the loop, not the model alone, is what makes Codex an agent. A chat model predicts text; the loop is what turns that text into reading, editing, running, and checking — with you in the approval seat.
Watch out
There is no /undo
Codex has no /undo slash command. Every action is in the transcript, and you roll back with git (git restore, git checkout, git reset). Work in a clean, committed tree so the diff Codex creates is easy to review and easy to revert.
Key insight
Approval is independent of the sandbox
The loop's pause is governed by your approval mode (WHEN Codex asks). That's a separate control from the sandbox (WHERE Codex can act). This lesson is about the loop and the prompt; the approvals × sandbox matrix gets its own lesson later.
The brief is the highest-leverage skill
Here's the leverage point. The loop is fixed — gather, propose, approve, iterate — but how well each pass goes is almost entirely decided by the brief you hand Codex at the start. A vague prompt sends the agent off to gather the wrong context, propose the wrong change, and burn an approval cycle (and tokens) on work you'll throw away. A precise prompt aims the very first pass at the target.
Think of Codex as a sharp new teammate who has never seen your codebase. They will read code fast and write it well — but only if you tell them what to change, where to look, what rules to respect, and how you'll both know it's done. Leave any of those implicit and they'll guess. That's not a Codex quirk; it's the nature of delegating a task to anyone capable but unbriefed.
The good news: OpenAI distilled "a good brief" into a four-element template that you can reach for on every non-trivial task. The rest of this lesson is that template, the one lever that beats all others, and the handful of mistakes that quietly wreck otherwise good prompts.
Tip
Lead non-trivial tasks with the four elements
For anything beyond a one-line fix, open your prompt with Goal, Context, Constraints, and Done-when. It feels like overhead the first few times and then becomes muscle memory — and it is the difference between one clean pass and three muddled ones.
The four-element prompt template
OpenAI's best-practices guidance frames every good Codex prompt around four questions. Answer them and the agent has everything it needs to aim its first pass at the goal.
| Element | The question it answers | What to put there |
|---|---|---|
| Goal | What are you trying to change or build? | The concrete outcome — "add rate limiting to the login endpoint", not "improve security" |
| Context | Which files, folders, docs, examples, or errors matter? | Point Codex at the relevant code (@-mention files), the failing test, the error text, a design doc |
| Constraints | What standards, architecture, or safety rules apply? | "Match the existing middleware pattern", "don't add new dependencies", "don't touch the public API" |
| Done-when | What must be true before the task is complete? | The finish line — "the new test passes and npm run lint is clean" |
A worked example pulls them together:
Goal: Add a 5-requests-per-minute rate limit to the POST /login route.
Context: Auth lives in @src/routes/auth.ts; existing middleware in @src/middleware/.
The integration test is @test/auth.test.ts.
Constraints: Reuse the existing rateLimit middleware pattern — don't add a new
dependency. Don't change the response shape on success.
Done-when: A new test proves the 6th request in a minute returns 429, the full
suite passes, and `npm run lint` is clean.Notice what the Context line is doing: the @ prefix opens Codex's fuzzy file search over the workspace root, and pressing Tab or Enter drops the highlighted path into your message. You're not pasting whole files — you're handing the agent precise pointers and letting it read them. That keeps your prompt short and your context window clean.
Example
Goal sharpness test
If your Goal could be satisfied two very different ways, it's too vague. "Make the dashboard faster" fails the test; "Memoize the ProductList render so it doesn't re-render on unrelated cart updates" passes it. Sharpen the Goal and the other three elements get easier to write.
The top lever: let Codex verify its own work
Of all the prompting advice OpenAI publishes, one tip outranks the rest: "Codex produces higher-quality outputs when it can verify its work." Give the agent a way to check itself and it closes its own loop — running the check, reading the failure, fixing, and re-running — instead of stopping the moment the code merely looks right.
Concretely, fold verification into your brief:
- Steps to reproduce an issue, so Codex can confirm the bug exists before and after.
- A way to validate a feature — the exact command or test that proves it works.
- Lint and pre-commit checks to run, so the change meets your standards, not just compiles.
This is why the Done-when element is so powerful: a good Done-when is usually a runnable check. "The new test passes and npm run lint is clean" doesn't just describe success — it hands Codex the verifier it needs to drive the loop to completion. Withhold a verifier and you become the verification step, eyeballing diffs the agent could have checked itself.
The failure mode to recognize: an agent with no way to verify will confidently declare victory on code that doesn't run. The fix is almost never a smarter model — it's showing the agent how to test, then letting it.
Tip
Show the build and test commands
If Codex doesn't know how to run your build, tests, or linters, it can't verify anything. Put the exact commands in the prompt for one-offs, or — better for anything you'll repeat — in AGENTS.md so every session has them.
Break work into small steps; ask for a plan when unsure
The second-biggest lever is scope. OpenAI's guidance is blunt: break big work into small, focused steps, because "smaller tasks are easier for Codex to test and for you to review." A tight task gives the agent a verifier it can actually run and gives you a diff you can actually read. A sprawling one — "refactor the whole auth system" — gives both of you a mess where errors compound and nobody can tell what broke.
But sometimes you don't yet know how to slice the work — the code is unfamiliar or the change touches many files. The move then is to ask Codex to propose a plan first rather than guessing. You can switch to plan mode with /plan (and optionally send a prompt with it), letting the agent map the work into ordered steps before it touches anything. You review the plan, correct the slicing, and then let it execute — turning one risky leap into a sequence of small, reviewable, verifiable steps.
The deeper mechanics of plan mode and the /goal completion criterion get their own lesson next. For now, hold the judgment call: small clear change → just brief it well and go; large or uncertain change → get a plan, then break it down.
Key insight
Small steps make the loop work for you
Every section of this lesson points the same way: a small, well-bounded task is one Codex can verify, one you can review, and one git can cleanly revert. Scope discipline is what makes the loop, the verifier, and the transcript actually pay off.
Durable rules go in AGENTS.md, not the prompt
As you write four-element prompts, you'll notice some lines repeat every session: "use our middleware pattern", "run npm run lint before finishing", "don't add dependencies." Those are durable rules about your project, and retyping them into every prompt is both tedious and easy to forget. Their home is AGENTS.md — an open Markdown standard that acts as "a README for agents," read automatically at the start of a session.
The guiding principle is the line worth memorizing: "A short, accurate AGENTS.md is more useful than a long file full of vague rules." Put the things that are always true — build/test/lint commands, code style, architecture constraints, do-not rules, and how to verify work — into a tight AGENTS.md (scaffold one with /init). Keep the per-task specifics — this goal, these files, this finish line — in the prompt.
The division of labor is clean:
| Put it in AGENTS.md | Put it in the prompt |
|---|---|
| Build / test / lint commands | The specific Goal for this task |
| Code style & architecture rules | Which files/errors are relevant now |
| Standing "do not" constraints | One-off constraints for this change |
| How to verify work in this repo | The Done-when for this task |
Get this split right and your prompts stay short, your standards stay consistent, and Codex stops re-learning your project on every run.
Watch out
Don't overload the prompt with durable rules
The most common briefing mistake is stuffing every project rule into every prompt. It bloats the message, it's inconsistent across sessions, and it's the exact thing AGENTS.md (or a reusable skill) exists to hold. Prompt = this task; AGENTS.md = how this project always works.
The briefing mistakes to avoid
Most disappointing Codex sessions trace back to a handful of avoidable briefing errors. OpenAI publishes them as common mistakes; here are the three that matter most for this lesson, each with its fix.
- Overloading prompts with durable rules instead of moving them into AGENTS.md or a skill. Fix: prompt holds the task; AGENTS.md holds how the project works.
- Not showing the agent how to run builds and tests. This is the quiet killer — without a verifier, Codex can't close its loop and you inherit the checking. Fix: include the exact build/test/lint commands (in the prompt or AGENTS.md).
- Skipping planning on multi-step tasks. Leaping straight into a sprawling change invites compounding errors and an unreviewable diff. Fix: ask for a plan (
/plan), then break the work into small steps.
Two more from the same list are worth keeping on your radar even though they belong to later lessons: granting full permissions before you understand the workflow (keep approvals and sandbox tight early, loosen only once you trust the task) and using one thread per project instead of one per coherent unit of work (session hygiene). You'll go deep on both later — but knowing they're mistakes now will save you from forming the habits.
Put positively: a good brief is a sharp Goal, precise Context, real Constraints, a runnable Done-when, durable rules pushed into AGENTS.md, and a plan when the work is big. That's the whole craft.
Note
These compound with the loop
Each mistake breaks a different part of the loop: overloaded prompts pollute context-gathering, missing test commands break verification, and skipped planning wrecks iteration. Fixing the brief fixes the loop.
Try it: Brief a real task with the four elements and a verifier
Goal: turn a vague request into a four-element brief and watch the loop pay off.
1) Pick a small, verifiable task in a repo of yours that has a test or lint command — a real bug fix or a small feature, not a sprawling refactor. Make sure your working tree is clean and committed (your only undo is git).
2) Write the bad version first. Type a one-line vague prompt (e.g. "clean up the auth code") into a scratch file — don't run it. This is your baseline.
3) Rewrite it with all four elements. Produce a brief with:
- Goal: one concrete, sharp outcome.
- Context: the relevant files (use
@in the composer to fuzzy-search and insert paths) and any error text. - Constraints: at least one real rule (a pattern to follow, a dependency not to add).
- Done-when: a runnable check — the exact test/lint command that proves success.
4) Run it in codex and watch the transcript: where does it gather context, where does it propose changes, where does it pause for approval, and does the Done-when command let it verify and iterate on its own?
5) Promote a durable rule. Identify one line in your brief that would repeat every session (e.g. the lint command or a style rule). Move it into AGENTS.md — run /init first if the repo doesn't have one — and confirm your next prompt got shorter.
6) Write three sentences: how the four-element version changed the agent's first pass versus your vague baseline, where the verifier let Codex know it was done, and which rule you moved to AGENTS.md and why. This cements the core craft the rest of the workflow module builds on.
Key takeaways
- 1The Codex loop is gather context (read/search) → propose changes/commands → pause for approval → iterate, and it always surfaces a transcript so you can review every action.
- 2There is no /undo — roll back changes with your normal git workflow (the transcript shows what changed); approval (WHEN it asks) is a separate control from the sandbox (WHERE it can act).
- 3Brief every non-trivial task with four elements: Goal (what to change), Context (relevant files/errors, via @-mentions), Constraints (standards/safety), and Done-when (completion criteria).
- 4The top lever is letting Codex verify its own work: include reproduction steps, a validation command, and lint/pre-commit checks — a good Done-when is usually a runnable check.
- 5Break big work into small, focused steps; when the slicing is unclear, ask Codex for a plan first with /plan, then execute step by step.
- 6Put durable rules (build/test/lint commands, style, do-not constraints) in a short, accurate AGENTS.md, not in every prompt — overloading prompts and hiding test commands are the most common mistakes.
Quiz
Lock in what you learned
Check your understanding
0 / 4 answered
1.After Codex edits several files in a session, you decide the change was wrong. What is the correct way to roll it back?
2.A teammate's prompt reads: 'Make the login flow more secure.' Using the four-element template, what is the single biggest problem with it?
3.Why does OpenAI single out 'let Codex verify its own work' as the top prompting lever?
4.You find yourself typing the same lines — 'run npm run lint before finishing', 'use our middleware pattern', 'no new dependencies' — into every Codex prompt. What's the better practice?
Go deeper
Hand-picked sources to keep learning
Source of the four-element prompt, the 'let Codex verify its own work' lever, small-steps guidance, and the common-mistakes list.
Deeper guidance on writing effective prompts for the agent.
Describes the interactive session: read repo, make edits, run commands as you iterate, and the transcript.
How @ fuzzy file search works, attaching context, and reviewing the working tree.
What to put in AGENTS.md, the 32 KiB cap, discovery/merge rules, and 'a short, accurate AGENTS.md is more useful than a long file of vague rules'.
The cross-tool Markdown standard — 'a README for agents' — used by Codex and many other agents.