Some coding work is the same step on repeat until a condition is met: run the tests, read the failure, patch the code, run the tests again. Codex was built to automate that pattern as an agentic loop that keeps editing and running until the task is actually done, instead of answering once and stopping.
The agentic loop, concretely
You already know an agent plans, acts, and observes. In Codex that loop is grounded in a real workspace: a checkout of your repo, a shell, and the ability to run commands. Each turn looks like this:
- Read the task and the current repo state.
- Decide on an action (edit a file, run a command).
- Execute it in the sandbox and capture the output.
- Compare the result against the goal. If not met, loop.
The observe step is what separates this from a single prompt. Codex sees stdout, exit codes, and stack traces, then feeds them into the next decision. That is why "make the tests pass" works: the test output is the signal that drives the next edit.
Codex comes in a few shapes that share this engine. The CLI and IDE extension run locally against your working tree. Codex cloud runs tasks in OpenAI-hosted containers against a connected GitHub repo. A non-interactive mode, codex exec, plus a GitHub Action and SDK, lets you run the loop from scripts and CI. See the Codex documentation for the current surface.
When a loop beats a single request
A single request is right when the change is bounded and you can eyeball the diff. Reach for a loop when the task has a verifiable stop condition the agent can check itself:
- Iterate until tests are green. The test suite defines "done", and the agent doesn't need you between attempts.
- Work through a backlog of files: migrate every component off a deprecated API, add type hints to a directory, or bump a pattern across 40 modules.
- Fix until
ruff,mypy, ortscreturn a clean exit code.
The common thread is a machine-checkable oracle. If "done" is subjective ("make the UI nicer"), a loop burns budget chasing a target it can't measure. Keep those as interactive sessions.
Iterate until the tests are green
Codex has no special "loop config". You give it three things in plain language and repo files: the goal, the command that verifies it, and the limits. The durable place for the verify command is AGENTS.md at the repo root, which Codex reads on every run:
# AGENTS.md
## Setup
pip install -e ".[dev]"
## Verify
Run `pytest tests/billing -q`. A task is done only when it exits 0.
Never skip, delete, or weaken tests to make them pass.Then a one-shot unattended run from your terminal or CI:
codex exec --sandbox workspace-write \
"Fix the failing tests in tests/billing. Re-run pytest after each change. \
Stop after 8 attempts if still red and summarize what you tried."What the agent does internally is roughly this pseudocode:
for attempt in range(8):
result = run("pytest tests/billing -q")
if result.exit_code == 0:
break
apply_fix(diagnose(result.stdout))
else:
report("gave up; latest diff attached")The attempt cap lives in your prompt, so treat it as guidance. The hard ceiling comes from outside: a timeout around the command, or timeout-minutes on the CI job. Pair the soft limit with a hard one so nothing runs forever.
Check your reading
What is the critical difference between an agentic loop in Codex and a single one-shot prompt?
Kicking off autonomous and scheduled runs
There are four common ways to start a run you don't sit through:
- Codex cloud, on demand. From chatgpt.com/codex or the IDE, describe the task, pick the repo and environment, and Codex runs it in a container. You review the diff and open a PR from it.
- From GitHub. Mention
@codexin a PR or issue comment to hand it a task or ask for a code review. - From CI. The Codex GitHub Action or
codex execruns the loop inside a workflow, triggered by a push, a label, or a webhook. The Codex SDK does the same from your own code. - Scheduled. Codex has no built-in cron, so you use yours: a GitHub Actions
schedule:trigger that runscodex exec, then opens a PR with the result.
An on-demand run is you pressing go. A scheduled run is a cron job that happens to be an agent. Both should land in a branch and a pull request, never straight onto `main`.
A scheduled backlog example
Say you're migrating off a deprecated logging call. You don't want to babysit 40 files. A nightly workflow runs codex exec with this prompt:
"For up to 6 files still usingold_logger, replace it withstructlogperdocs/logging.md, runpytestfor each touched module, and skip files where tests fail after the change. List skipped files in your final summary."
A later workflow step commits to a branch and opens chore: migrate logging (batch) with the summary as the description. The spec has a batch size for cost control, a per-file verify step, and an escape hatch for the hard cases. Over a week the backlog drains itself, one reviewable PR at a time.
Video
Building with Codex
OpenAI's walkthrough of delegating coding tasks to Codex cloud and reviewing the resulting PRs
Watch on YouTubeStop conditions: what actually ends a loop
An unattended loop needs more than one exit:
- Success: the verify command returns exit code 0.
- An attempt cap stated in the prompt. If eight tries don't get tests green, more rarely will.
- A hard wall-clock limit from the job runner. This one Codex can't talk its way past.
- No-progress detection. If two attempts produce the same failure, tell the agent in
AGENTS.mdto stop and report instead of retrying the identical fix.
The usual failure mode of autonomous runs is an agent thrashing against a problem it can't solve while the meter runs, more often than a single bad edit.
Cost caps and the sandbox
Codex cloud tasks run in isolated containers with your repo and nothing else unless you grant it. Internet access during the agent phase is off by default and can be enabled per environment with a domain allowlist. Locally, codex exec defaults to a read-only sandbox; --sandbox workspace-write lets it edit the repo. Avoid danger-full-access outside a throwaway container.
Spend works differently depending on how you sign in. With a ChatGPT plan, Codex usage counts against your plan's usage limits, and runs stop when you hit them. With an API key (typical in CI), you pay per token, so set organization usage limits so a misconfigured nightly schedule can't quietly run up a bill for a week.
For a test-fixing job the agent needs your repo and package installs, not the open internet. Fewer capabilities means fewer ways to surprise you.
Check your reading
According to the lesson, what is the defining characteristic of a task that is well-suited to an autonomous loop?
Review gates: trust, but verify the diff
The most important safety property: an autonomous Codex run should produce a pull request, not a merge. Your existing GitHub protections still apply:
- Branch protection with required reviews, so a Codex PR can't merge without a human approving it. Treat the agent as a contributor whose PRs always need review.
- CI as a second oracle. The agent ran tests in its sandbox; CI runs them again in your real pipeline. If CI disagrees, the agent's "green" was environment-specific.
- Small batches (six files, one module) keep PRs reviewable. A 3,000-line autonomous diff defeats the purpose.
The loop iterates freely inside the sandbox, and the exit is a narrow, reviewable gate.
Reading a Codex PR fast
Codex cloud tasks keep logs of the commands run and their output, and codex exec prints a final summary. When you review, check that the diff matches the stated goal, that the verify command genuinely passed (no tests disabled or @skip'd), and that the change stays in scope. A loop that "passes tests" by deleting the failing test is the classic cheat. Read for it.
Putting it together
A well-designed autonomous run reads like a contract: a goal, a machine-checkable definition of done in AGENTS.md, a soft attempt cap plus a hard timeout, a narrow sandbox, and a PR-only exit. With all of that in place you can leave Codex alone overnight with the confidence you'd give a junior engineer on a well-specified ticket. It either finishes or tells you why it couldn't.
Key Takeaways
- Use a loop only when "done" is machine-checkable: tests passing, lint clean, a type-check exit code.
- Put the verify command and the no-cheating rules in
AGENTS.md; run unattended work withcodex exec, the GitHub Action, the SDK, or Codex cloud. - Scheduling is your job: a CI cron that calls Codex, with a batch size and per-item verification.
- Back prompt-level attempt caps with a hard CI timeout, keep the sandbox and internet access narrow, and set usage limits for API-key runs.
- The exit is a pull request, never a merge. Enforce branch protection, re-run tests in CI, and read the diff for deleted or skipped tests.
To do
What to do, from this lesson
These actions are compiled in the role's Playbook.
- Set branch protection requiring PR, review, and passing checks before Codex runs
- Run autonomous loops only with a machine-checkable done condition and hard caps
- Review every diff for the deleted-failing-test cheat and scope creep
Quiz
Did the essentials stick?
3 questions, one at a time. Each one right on the first try brings the probe closer to the planet.
Question 1 of 3
Why does the lesson advise keeping a task like 'make the UI nicer' as an interactive session rather than an autonomous loop?
Frequently asked questions
What is an agentic loop in Codex?
In Codex, an agentic loop is a cycle where the agent reads the repo state, edits a file or runs a command, observes the output, then compares the result to the goal and repeats until it is met. The difference with a single prompt is the observe step: Codex reads stdout, exit codes and stack traces, and feeds them into its next decision. That is why an instruction like "make the tests pass" works, since the test output itself drives the next edit.
When should I use a Codex loop instead of a single request?
Use a loop when the task has a stop condition a machine can check on its own: tests green, lint clean, a type checker returning exit code 0, or a batch of files to migrate with per-file verification. A single request is better when the change is bounded and you can eyeball the diff. If "done" is subjective, like "make the UI nicer", a loop just burns budget chasing a target it cannot measure, so keep that work interactive.
What's the difference between the Codex CLI agent and Codex cloud?
Both share the same engine, but the CLI/IDE agent runs locally against your working tree, while Codex cloud runs the loop on OpenAI's infrastructure against a connected GitHub repo. Autonomous and scheduled runs live in the cloud version. A cloud run spins up its own environment, executes the loop and opens a pull request when it finishes.
How do I stop an autonomous Codex run from looping forever?
Give it several exits, not one. The success condition (your verify command returning exit code 0), an iteration cap such as max_iterations: 8, a wall-clock or token ceiling, and no-progress detection that stops when two consecutive attempts produce the same failing output. State every cap explicitly: the usual failure mode of an unattended run is not a bad edit, it is an agent thrashing against a problem it cannot solve while the meter runs.
How do you schedule a recurring Codex job, for example a nightly backlog migration?
Codex cloud supports recurring runs on a connected GitHub repo, using the same mechanism as ChatGPT scheduled tasks; you can also fire runs from CI or a webhook through the Responses API or the Agents SDK. For a backlog migration, specify a batch size, a per-file verify command and an escape hatch: for example, up to 6 files per night, run pytest on each touched module, skip files whose tests fail and note them in the PR description. Over a week the backlog drains itself, one reviewable PR at a time.
How do I review a pull request produced by an autonomous Codex run?
Check three things: does the diff match the stated goal, did the verify command genuinely pass rather than being disabled or skipped, and is the change scoped to what you asked. Codex logs every action, so its PRs come with a trail of commands run and output observed. Watch for the classic cheat of making tests pass by deleting or skipping the failing test, and let CI re-run the suite in your real pipeline as a second oracle, since a sandbox green can be environment-specific.