💡 What this guide covers: large tasks and long conversations can make Codex lose earlier constraints, leaving you repeating “keep going.” Parallel tasks may overwrite each other, and usage can climb quickly. Learn how to split work, use plan files and Goals to reach evidence-backed completion, manage sessions, choose parallel or cloud execution, and select models and usage limits.
More Codex articles: Save Effort · Codex
Where people get stuck
- Complex changes don’t finish in one pass: migrations, cross-module changes, and end-to-end tests need stages. One conversation turn rarely covers implementation, verification, and exceptions adequately.
- Context and requirements get muddled: long tasks span files, constraints, and earlier decisions. OpenAI recommends lean
AGENTS.mdfiles and Skills, with clear acceptance criteria. - You keep saying “continue”: keep going, try another fix, rerun the benchmark, check tests, keep working until it is actually done.
- Usage gets wasted: repeated scans, repeated explanations, and rework can increase consumption. Compare quality, elapsed time, and human review effort together.
- Parallel tasks overwrite each other: several tasks edit the same files.
- The environment interrupts long tasks: OS compatibility, extension versions, and background execution can stop work. Confirm small tasks run reliably before increasing their length.
- Vibe coding still needs engineering: faster prototypes don’t remove the need to understand code, define boundaries, and check implementation.
Part A: break large tasks into stages
Require evidence at every stage
- Have Codex work in stages. After each one, run checks and report exactly what passed and failed.
- Separate exploration, coding, and verification. Find the relevant files before implementation instead of repeatedly scanning the whole project for a vague request. This can save time and usage, but no fixed savings percentage is guaranteed.
- Keep human review for database migrations and production changes. See safe code changes.
Manage large tasks with plans.md
Use plans.md as a planning template and point to it from AGENTS.md. It tells Codex how to plan a multi-step project.
- Codex creates a Markdown execution plan and treats it as a living working document, checking off work and recording what is done and what comes next.
- It is especially useful for large refactors, changes spanning several code areas, and projects taking hours and many steps.
- Codex then has somewhere to record progress rather than relying entirely on conversation memory. You can inspect its direction and status at any time.
- MCP can supply this information too, but a readable Markdown file committed to Git is often enough. It travels with the project, stays accessible to the team, and gives the model current information without depending on temporary configuration or an external service.
- The OpenAI Cookbook provides a
plans.mdexample: establish a stable planning format, then have Codex follow it.
Separate documents and an updated plan are generally more reliable than one very long prompt.
Build a maintainable engineering harness
For a to-do application, for example, store goals, plans, execution prompts, and verification records separately in the repository. AGENTS.md is an optional file Codex recognizes; the others are project conventions, not universal requirements. Adjust them to the project’s size and compare them with the OpenAI Cookbook workflow.
Resulting structure—phase context files are created during their respective development phases:
.
├── .gitignore
├── AGENTS.md
├── GOALS.md
├── PLANS.md
├── PROMPTS.md
├── README.md
└── harness
├── build
│ ├── phase-00-repository-foundation.md
│ ├── phase-01-create-list.md
│ ├── phase-02-update-complete-delete.md
│ └── phase-03-demo-verification.md
├── build-log.md
├── code_review
│ └── .gitkeep
└── context
└── README.md
What each file owns:
| File | Responsibility |
|---|---|
AGENTS.md | Durable repository guidance and working conventions |
PLANS.md | Planning purpose, roadmap, and phase order: the source of truth |
GOALS.md | Desired outcomes, success criteria, scope, and non-goals |
PROMPTS.md | Reusable prompts to start and advance work |
harness/build/phase.md | Approved scope and plan for a phase |
harness/context/phase.md | Material findings, decisions, constraints, and open questions |
harness/build-log.md | Actual progress and observed verification evidence |
harness/code_review/ | Detailed review findings when needed |
Step 1: write AGENTS.md. Start new projects here. Codex uses it as durable repository guidance before working. Include the repository goal and overview, coding conventions, testing standards, relevant context files, project-specific behavior, scope, and boundaries. /init can draft it from the directory contents. It is a useful home for team knowledge.
Step 2: write PLANS.md. Make it the source of truth for planned execution, including the purpose and roadmap from which phase files can be generated. Teams doing longer tasks may include major decisions and detailed acceptance criteria. Smaller phase files are easier to read and let people review code quality and other outputs along the way.
Step 3: generate GOALS.md and PROMPTS.md. Write them yourself or ask Codex to derive them from AGENTS.md and PLANS.md.
Prompt requirements for GOALS.md and PROMPTS.md
- Read all applicable `AGENTS.md` files from the root downward and `PLANS.md` if present. Create or conservatively update only `GOALS.md` and `PROMPTS.md`.
- Before writing, briefly state the source files found, inferred outcomes and constraints, and assumptions caused by missing or ambiguous information.
- `GOALS.md` describes the project’s purpose, desired outcomes, success criteria, scope, non-goals, technical and operational constraints, source-supported security/reliability/recovery expectations, and unknowns requiring human decisions. Keep it outcome-focused. Don’t copy implementation steps, reusable prompts, or progress reports. Don’t invent capabilities, deadlines, guarantees, or requirements.
- `PROMPTS.md` supplies reusable prompts for repository orientation, planning or phase preparation, executing one approved phase, verification and evidence collection, review or repair, and phase completion and handoff.
- Every prompt should identify files to read; reference goals and plans rather than duplicate them; state scope and non-goals; require a read-only preflight before implementation; present an approval summary before repository writes; use red–green–refactor–verify where appropriate; require observed test evidence; require separate explicit approval for commits, pushes, deployments, credentials, and external writes; and stop after the selected phase without starting the next.
- If `PLANS.md` is missing, infer only high-level goals from `AGENTS.md`. Don’t invent a roadmap, phases, architecture, or product requirements. Use clearly labeled placeholders and make prompts request an explicit plan or phase before implementation.
- Preserve local terminology and filename capitalization. Keep both files concise and avoid duplicating existing guidance. Do not edit application code, tests, dependencies, configuration, planning files, or anything else.
- After writing, check for contradictions and overlapping ownership. Ground substantive content in the source files or label it as an assumption. Run `git diff --check`, then report changed files, assumptions, and open questions.
Step 4: give each phase its own build file. State its purpose, additional references, acceptance criteria, and boundaries. Create harness/build/ and use filenames such as phase-number-phase-title.md. At the start of each phase, provide that file with the harness goals and prompts. This helps prevent agent drift. With version control, it creates a clear, human-reviewed development history and a readable audit trail.
Prompt requirements for phase files
- Start with read-only discovery: read `AGENTS.md`, available `PLANS.md`, `GOALS.md`, `PROMPTS.md`, `harness/build-log.md`, existing build files, relevant application manifests, tests, and verification commands. Use the current repository, not assumptions from another project.
- Before writing, list source files, repository purpose and current state, proposed phases and dependencies, exact files to create, missing or conflicting requirements, and acceptance criteria for the planning task itself. If the sources don’t establish a phase order, propose one for review and stop. Show scope and paths and wait for explicit approval before creating files.
- Each build file plans one bounded implementation phase. It **does not mean the work is complete**. Preserve existing numbering, names, ordering, terminology, and templates.
- Include phase ID and title; initial `Not started` status; source inputs; objective; in-scope work; non-goals; prerequisites and dependencies; likely affected files or components; human decisions; approval gates; a red–green–refactor–verify plan; focused and broader verification commands; relevant security, privacy, reliability, observability, and recovery concerns; acceptance criteria; required evidence; and handoff or stop conditions.
- Follow ten planning rules: keep each phase independently implementable and verifiable; preserve dependency order; make acceptance criteria observable; define the smallest meaningful failing test or check for red; define minimal implementation for green; allow refactoring only within approved behavior and scope; use real commands where discoverable; mark unknown commands or requirements unresolved; identify credentials, external systems, infrastructure, deployment, commits, and pushes needing separate permission; and never claim a planned test, recovery process, or integration passed unless actually run in a separately approved implementation phase.
- Edit only approved files under `harness/build/`. Don’t touch application code, tests, dependencies, manifests, infrastructure, deployment configuration, source guidance, context, logs, review artifacts, README, or Git branches, commits, and remotes. Don’t implement a phase. Inspect existing build files before proposing edits; preserve useful content, decisions, and evidence.
- After writing, verify only approved build files changed, every phase traces to sources, scope has no overlap or gaps, ordering is correct, and each phase has approval gates, acceptance criteria, and verification. Run `git diff --check`. Report files, phase order, checks, assumptions, unresolved questions, and approval needed to begin phase one.
Step 5: record material context for each phase. Save decisions that affect the project in harness/context/phase-NN-phase-slug-context.md. Add instructions in AGENTS.md so Codex maintains it.
Rules for phase context files
- Maintain one context file per approved implementation phase. Create it only after the phase begins and required approval is granted. Read applicable guidance, goals, prompts, the build file, previous context, and build-log evidence first.
- **Materiality test:** record information only if omitting it could change approved scope or implementation; cause repeated discovery or different later decisions; affect interfaces, dependencies, invariants, or ownership; alter acceptance or verification; affect security, privacy, reliability, observability, rollback, or recovery; or hide blockers, unresolved assumptions, accepted limitations, or necessary follow-up. Exclude details with no effect on later work, verification, operations, or decisions.
- **Record:** user decisions and clarifications; scope changes and non-goals; implementation assumptions; architectural and implementation choices with reasons; relevant components, interfaces, dependencies, and ownership; behavior and invariants to preserve; security, privacy, operational, and recovery constraints; missing evidence and verification limits; blockers; discoveries needed later; and superseded decisions, including their replacements and reasons. Give each item enough provenance to recover the reasoning: files, commands, tests, issues, review findings, or user decisions.
- **Exclude:** transcripts, scratch notes, progress narration, routine command output, temporary dead ends without lasting impact, facts owned elsewhere, complete copies of plans, prompts, test output, or code, routine completion status, speculation presented as fact, and credentials, tokens, keys, or sensitive values. Link to authoritative sources instead of copying them.
- **Source-of-truth boundaries:** build files own approved scope, non-goals, acceptance, and planned verification; context files own material discoveries, decisions, constraints, and unresolved items needed later; `harness/build-log.md` owns progress and observed verification; review artifacts own findings and sign-off. Don’t duplicate across them except for a brief summary needed to explain an important decision.
- **Updates and handoff:** update when material decisions arise and review before phase end. Remove nonessential narrative and duplication, preserve reasons and provenance, label assumptions and open questions, link evidence, and explain effects on later phases. Completing a context file does not complete a phase.
Step 6: use build-log.md for actual progress. harness/build-log.md is the source of truth for progress. It should be readable by people but is primarily for Codex; it can also inform user-facing changelogs and documentation. Have AGENTS.md require an update at each phase’s end before committing. Record what happened, not what the plan expected.
Rules for the build log
- **Summarize before writing:** selected phase, recorded status, inspected sources and evidence, proposed entries or status changes, and conflicts, gaps, or unverified information. If documentation writes require approval, wait for it.
- **Initialize:** if absent, create a short purpose statement, phase summary table, and append-only activity section. Derive phases from approved build files and start at `Not started` unless evidence supports another status.
- **Use four statuses** unless the repository defines others: `Not started`, `In progress`, `Blocked`, and `Complete`. Existing code, a focused passing test, or an earlier conversation is not proof of completion.
- **Summary columns:** phase, status, branch, start time, completion time, evidence, and blockers. Keep history in append-only activity entries.
- **Mark** **`Complete`** **only when all conditions hold:** approved acceptance criteria are satisfied; required checks actually ran and passed; review findings are resolved or explicitly accepted; applicable operational, security, recovery, and cleanup requirements are met; remaining limitations are recorded; and repository-specific completion rules are satisfied. Missing evidence means `In progress` or `Blocked`.
- **Add entries when:** a phase is authorized; work begins; a red check fails as expected; focused checks pass after implementation; material refactoring occurs or is explicitly deemed unnecessary; broader verification runs; scope changes materially; blockers appear; findings are reviewed or fixed; limitations are accepted or rejected; or a phase finishes.
- **Entry format:** “timestamp — Phase ID: event,” followed by status transition, observed branch, authorized scope, material changes, red checks and observed expected failures or justified N/A, green checks and results, refactoring and repeated checks or why none was needed, actual verification commands and outcomes, review findings/fixes/sign-off, operational evidence, limitations, blockers or none, next approved action without implied authorization, and evidence paths. Include an unambiguous timezone in timestamps.
- **Evidence:** record exact commands and concise pass/fail results. Distinguish directly observed, reported, and historical evidence. Never claim tests, integrations, recovery, or external checks passed without running and observing them. Planned commands are not evidence. Explain skipped or unavailable checks. Link lengthy output; don’t copy it. Exclude credentials, sensitive values, and unnecessary personal data. Don’t duplicate full context files, plans, diffs, or output. Preserve both sides of conflicting evidence and mark the phase `Blocked` until resolved.
- **History and corrections:** append entries. Don’t silently rewrite evidence or remove failed attempts. Add a correction referencing the earlier entry and update the summary. Meaning-preserving typo fixes can be made in place.
- **Scope:** logging does not authorize edits to code, tests, configuration, context, build files, or plans; branch changes; commits; pushes; or the next phase. Don’t mark completion without evidence. Report other needed updates as follow-up.
- **Final checks:** only `harness/build-log.md` should change, preserving existing implementation and test edits. Every status change needs evidence; planned work must not appear completed; failures, skipped checks, and limits must remain visible. Run `git diff --check`. Report phases, statuses, entries, evidence, blockers, limits, and separate approval needed next.
Step 7: make the workflow a Skill. Long prompts and many files quickly make manual work cumbersome and inconsistent. The Cookbook uses $skill-creator to build $harness-author, a reusable Skill to create, review, and improve an appropriately sized repository harness. It does not start implementation without a separate explicit request and approval.
Requirements for a harness-author Skill
- **Installation:** default to `${CODEX_HOME:-$HOME/.codex}/skills/harness-author`. If the location is unclear or a Skill already exists, show the path and ask whether to update or rename it. Don’t overwrite without approval.
- **Read-only discovery:** read applicable `AGENTS.md`, current harness conventions and examples, available goals/plans/prompts, and existing harness files without editing them. Identify positive and negative triggers and decide what belongs in `SKILL.md`, references, scripts, and tests. Read the full `$skill-creator` guidance and required references. Don’t treat one repository’s structure as universal.
- **Before writing:** show the proposed path, trigger description, exact files and resources, behavioral scope, non-goals, validator and test plan, and acceptance criteria. Wait for approval.
- **Triggers:** create or review repository harnesses; write durable guidance; turn goals or plans into phased build files; define acceptance and approval gates; create or streamline execution/build logs; establish test-driven phase plans; separate planning, implementation, context, and evidence; or improve a harness after observed failures. Explicitly state that “harness-only,” “planning-only,” “just the build files,” and “only these files” **do not authorize application implementation**.
- **Fourteen core behaviors:** inspect instructions and repository first; identify authoritative sources for goals, plans, implementation conventions, phase state, context, review, and evidence; assess repository shape and risk; recommend the smallest useful harness; preserve architecture, naming, ownership, and operational safeguards; freeze an exact approved artifact list; present scope/files/tests/acceptance/risks/gates before edits; authorize planning and implementation separately; use red–green–refactor–verify where appropriate; define observable acceptance and evidence; leave unknowns unresolved instead of inventing requirements; avoid duplicate facts; preserve application files; and require separate approval for credentials, external systems, infrastructure, branch changes, commits, pushes, and deployment.
- **Artifact ownership:** distinguish the roles of `AGENTS.md`, `PLANS.md`, `GOALS.md`, `PROMPTS.md`, build files, context files, build log, and review artifacts. All are optional conventions. Extend existing practices instead of creating everything by default.
- **Planning-only boundaries:** create only approved files; no application code or tests, dependencies, manifests, Docker, infrastructure, or deployment files. Don’t create README or review artifacts without permission, or phase context before that phase starts unless explicitly requested. Don’t change Git state, commit, push, or access external systems. Describe future implementation and tests in plans only. Verify and report the harness artifacts, then stop.
- **Scale to the project:** for tiny projects, prefer existing docs, tests, and a short acceptance checklist. Add phased planning and recovery guidance only when useful. Multi-service projects need ownership, interface contracts, dependency boundaries, degraded behavior, and integration checks. Monorepos need root and applicable package guidance. High-risk changes need security, authorization, rollback, recovery, failure modes, and independent verification regardless of repository size. Don’t impose enterprise processes, mandatory reviewers, or extra documents without a need.
- **Skill structure:** initialize with `$skill-creator` and include only useful resources: broadly, `SKILL.md`, `agents/openai.yaml`, four references covering project types/templates, sources of truth/templates, TDD/verification, and reliability/trade-offs, plus `validate_harness.py` and `test_validate_harness.py` under scripts. No auxiliary README, changelog, or installation guide. Keep the root instructions concise and operational; put detailed templates, matrices, and examples in directly linked references without duplication. Generate `agents/openai.yaml` with the creator tools after reading their references. Include display name, short description, and default prompt; omit optional branding unless provided.
- **Deterministic validator:** standard library only; inspect repositories and proposed harnesses without editing files or printing source. Support repository and optional target paths, shape/risk assessments, harness-only intent, repeatable proposed/allowed paths, JSON, and strict failure on blockers. Reject absolute paths, traversal, application scaffolding hidden in harness-only work, artifacts outside approval, unapproved context/review/implementation, missing required gates/acceptance/verification, and unsupported claims of completed validation. Offer advice for repositories using other conventions. Don’t use the network, read credentials, change Git state, or edit files.
- **At least twelve tests:** valid minimal harness-only work; explicitly approved custom Markdown artifacts; rejection of application code in planning; rejection of dependencies/manifests/Docker/infrastructure; unapproved context/review rejection; safe relative-path normalization; absolute/traversal rejection; filename-case preservation; avoiding oversized harnesses in small repositories; safety/recovery for high risk; JSON and strict mode; and preserving existing conventions. Run scripts and tests directly and report observed results.
- **Validation after implementation:** run validator tests and the creator’s `quick_validate.py`. Check that YAML frontmatter has only `name` and `description`, the name is lowercase and hyphenated, UI metadata matches instructions, the final file list has no extras, and the diff stays within the target. Propose real prompts and obtain approval before forward tests involving subagents or external repositories.
- **Acceptance:** correct harness-authoring/review triggers; appropriate size for repository and risk; preserved conventions and ownership; no silent implementation from harness-only requests; phase context created during the phase unless separately approved; meaningful acceptance and verification; passing validator tests and `quick_validate.py`; no unapproved file changes; all limits and untested behavior reported. Report location, files, triggers, validator behavior, observed tests, forward tests not performed, assumptions, and limitations.
What is worth making into a Skill? Almost any workflow can become one, but useful Skills are usually repeated frequently. The Cookbook gives three everyday examples:
- Commit changes, push to a remote, and create a PR.
- Watch for the latest remote merge, then prepare the next feature branch.
- Find the current phase in the build log, load its goals and prompts, summarize purpose and acceptance criteria, then wait for human review.
A new Skill may need tuning. For example, $harness-author might propose context and phase files while omitting PLANS.md and harness/build-log.md, and adding a context file too early. Correct the scope before approving edits:
Revise the proposed harness-only scope before writing.
Include these missing artifacts:
- PLANS.md: the ordered phase execution plan.
- harness/build-log.md: observed implementation progress and verification evidence.
Do not create a phase-specific context file until that phase begins and has
received the required approval. Include harness/context/README.md only if it
is explicitly approved as an exception to the standard harness-only allowlist.
Check the proposed artifact list for both missing required files and
unapproved additional files. Present the revised exact file list, explain
the ownership of each artifact, and wait for approval before writing.
The corrected list should contain PLANS.md, harness/build-log.md, and the phase build files.
Step 8: run a retrospective after a cycle. After finishing the project to the standards in AGENTS.md and committing it to version control, use Codex to examine what you learned and improve the next round. The initial structure is only a starting point.
Postmortem prompt requirements
- **Goal:** identify what worked and what caused friction; improve the existing harness-author Skill; identify missing reusable Skills without proliferation; improve repository guidance, harness artifacts, validators, and process; and turn verified failures into regression tests or enforceable safeguards. Make no changes during the initial retrospective.
- **Read-only discovery:** inspect global and repository guidance, available plans/goals/prompts, build log, applicable build/context files, review and postmortem artifacts, relevant implementation diffs, observed checks, current branch and workspace state, user corrections and approvals, accepted limits, installed harness-author, other used Skills and their scripts/references/metadata/tests, and existing Skills that might already own a workflow. Current files and observed evidence take precedence. Plans, expectations, earlier conversations, and unverified reports are not proof. Don’t access credentials, production, external services, or remote Git state without separate authorization.
- **Reconstruct the intended process:** phase order, artifact ownership, approval gates, red–green–refactor–verify checkpoints, review and handoff, intended Skill triggers and responsibilities, and boundaries for context, evidence, commits, pushes, deployments, credentials, and external writes. Separate required repository behavior from optional conventions.
- **Reconstruct what happened:** completed work, actual commands/checks, followed/missed/ambiguous gates, scope changes, repeated discovery, wrong assumptions, drift, overbuilding, insufficient/excessive context, misleading status or completion claims, human intervention, review/fixes, failed/skipped/unavailable checks, recovery issues, corrections, success caused by safeguards, and success despite gaps. Don’t invent a root cause from symptoms or correlation.
- **Analyze each material incident:** event, expected behavior, observed evidence, effect on scope/quality/safety/time/confidence, contributing conditions, existing safeguards, whether safeguards worked/failed/were absent/ambiguous/bypassed, whether the lesson is one-off/repository-specific/reusable, proposed owner, and validation. Use a blameless perspective focused on process, missing information, unclear ownership, and verification.
- **Materiality:** include only events affecting or potentially affecting approved scope, correctness, confidence, safety/privacy, reliability/observability/rollback/recovery, human approval/review, later decisions, repeated work, reproducibility, or auditability. Exclude harmless typos, routine failed commands, and temporary exploration without lasting effects.
- **One primary owner per improvement:** repository guidance for durable local conventions/constraints/commands/gates; project harness for local or phase-specific needs; existing Skill instructions for reusable process/triggers/boundaries/decisions; Skill references for detailed guidance/examples/matrices/variants; scripts or validators for mechanically checkable, costly, or recurring failures; regression tests for reproducible failures; a new Skill; or no process change when the issue is immaterial, already handled, or too specific.
- **Create a new Skill only if all seven tests pass:** a distinct intent and trigger; reusable multi-step work; recurrence across repositories or phases; clear bounded ownership; no clean fit in an existing Skill; reduced complexity rather than relocated duplication; and independently verifiable success. Don’t create Skills for single rules, local conventions, one-off incidents, or work already owned elsewhere.
- **Assess existing Skills:** correct positive and negative triggers, missed triggers, scope breadth, concise operational instructions, properly placed and actually loaded references, scripts protecting fragile or safety-critical behavior, safe script failures, explicit approval boundaries, preserved local conventions, unnecessary artifacts/processes, plans confused with evidence, overfitting, consistent UI metadata, and missing regression tests. Tighten an existing Skill when ownership is already clear.
- **Assess the whole process:** orientation, source ownership, harness generation, phase selection, context, approval packets, TDD checkpoints, evidence, independent review, fixes, completion, commit/push gates, post-merge branching, handoff, and retrospective timing. For each change, state the problem, owner, advisory versus enforced nature, added cost, smallest useful adjustment, and how improvement will be verified. Don’t add process just to look comprehensive.
- **Produce a read-only report:** executive summary and main opportunities; evidence-backed practices worth keeping; material friction and effects; existing Skill changes with name/path, affected instructions/resources/metadata/tests, evidence, proposed behavior, overfitting risk, and checks; new Skill candidates with lowercase-hyphenated names, distinct triggers, responsibilities/non-goals, why existing Skills cannot own them, likely resources, example requests, validation/forward tests, and now/later/rejected priority. List rejected candidates and their existing owner too. Include repository/harness improvements; a prioritized backlog—**P0** unsafe or materially incorrect behavior, **P1** repeated failures, approval gaps, or misleading evidence, **P2** meaningful efficiency or clarity, **P3** optional polish—with effort, value, owner, and checks; and open questions.
- **Approval gate:** deliver the report and stop. Don’t edit Skills, create new ones, change repository guidance or harnesses, add scripts/tests, run forward tests, commit, or push. Request separate approval for repository/harness changes, each existing Skill, each new Skill, forward tests, and commits/pushes.
- **Implement approved improvements:** use `$skill-creator` only after explicit approval. For each approved change, confirm paths/files, add a failing regression test first where feasible, make the smallest evidence-backed fix, keep root instructions concise, move details to linked references, change scripts only when enforcement is necessary, run relevant tests and `quick_validate.py`, regenerate UI metadata only if stale, check unrelated diffs, and report observed results and limits. For each new Skill, confirm distinct triggers/ownership and location, initialize with `init_skill.py`, create only necessary resources, run tests and validation, and check for overlap or conflict.
- **Forward tests, after approval:** use fresh independent context, realistic requests and source materials, and no hints about expected answers or suspected defects. Test positive and negative triggers, scope expansion, and unsafe writes. Isolate outputs between runs, compare behavior with explicit criteria, and feed verified failures into instructions, validators, or regression tests. Structural validation alone does not prove a workflow improved; require real-use evidence.
- **Completion:** evidence supports material incidents; every improvement has an owner; existing Skills are preferred; approved changes have regression coverage where feasible; Skills and scripts pass checks; performed forward tests are recorded; local lessons stay in the repository and reusable lessons go to suitable Skills; remaining limits and rejected suggestions are recorded; and no unapproved files, external systems, commits, or pushes changed.
The Cookbook does not prescribe an “improved final structure” because project and phase outcomes cannot be predicted. Start by recording context that materially affects decisions, verification, and later work. As you learn the process, run longer tasks and use earlier cycles to produce more consistent, reliable results within approved boundaries.
Part B: use Goals to keep working toward evidence-backed completion
What a Goal is
A Goal is a persistent objective that keeps a conversation thread moving toward a result over multiple turns. It defines what should become true, how success is checked, and which constraints must stay intact.
- Ordinary prompts work well for bounded tasks: a bug fix, adding tests, explaining a failure, or a focused change.
- Goals fit work where the next step depends on what you discover: profiling, patching, benchmarking, reproducing flaky tests, or turning research into an evidence-backed audit. Official examples include performance optimization, flaky-test investigation, dependency migrations, reproducible bug investigations, multi-step refactors, benchmark-driven tuning, and research with a final artifact.
- These tasks need a lasting objective, not merely a longer prompt. Codex can retain the goal, assess completion, and choose the next action without making you restate it after every intermediate result.
- A Goal is not unlimited background autonomy. It is a bounded, user-controlled completion contract. You define the outcome; Codex works from thread evidence. Goals can pause, resume, clear, complete, or stop at a budget limit.
Prerequisites: a Codex version supporting Goals, starting with 0.128.0; a clear endpoint with checkable evidence such as tests, benchmarks, or an artifact; and enough repository or research context to verify progress rather than narrate it.
Getting started
Update and check your version:
# npm
npm install -g @openai/codex@latest
codex --version
# Homebrew
brew update
brew upgrade --cask codex
codex --version
Then use /goal with the desired outcome:
/goal Reduce p95 latency below 120 ms without regressing correctness tests
Manage its lifecycle:
/goal Show the current Goal
/goal pause Pause the active Goal
/goal resume Resume a paused Goal
/goal clear Remove the current Goal
Once active, Codex can inspect code, run relevant commands, edit, test, and continue until success, a pause, clearing, interruption, a budget limit, or a blocker requiring your input.
If you keep repeating these messages, consider a Goal:
Keep going.
Try the next likely fix.
Run the benchmark again.
Now check the tests.
Continue until this is actually done.
Goals versus ordinary prompts
- A prompt says: do the next thing. Codex performs that instruction, reports, and waits.
- A Goal says: keep working until this result holds. After each turn, Codex checks the evidence. If the goal is unmet, active, and within budget, it continues from the latest state.
Prompt: ask -> work -> result -> wait
Goal: work -> check -> continue or complete
For example:
/goal Reduce p95 checkout latency below 120 ms on the checkout benchmark while keeping the correctness suite green
This provides a measurable outcome, a verification surface, and a constraint—not just “make performance better.” Codex can benchmark, inspect hot paths, make targeted changes, rerun benchmarks and correctness tests, and continue if necessary. The endpoint is defined, but the work still needs evidence-based auditing.
Write a strong Goal
A good Goal is a compact contract covering six things:
- Outcome: what should be true at the end.
- Evidence: tests, benchmarks, reports, artifacts, command output, or original sources that prove it.
- Constraints: what must not regress.
- Boundaries: allowed files, tools, data, repositories, and resources.
- Iteration strategy: how to choose the next attempt.
- Blocked-stop conditions: when to stop and report that no valid path remains within the limits.
A general template:
/goal <desired end state> verified by <specific evidence> while preserving <constraints>. Use <allowed inputs, tools, or boundaries>. Between iterations, <how Codex should choose the next best action>. If blocked or no valid paths remain, <what Codex should report and what would unlock progress>.
From a basic request to a fuller contract:
# Usable, but thin
/goal Reduce p95 checkout latency below 120 ms without regressing correctness tests
# Stronger: a complete operating contract
/goal Reduce p95 checkout latency below 120 ms, verified by the checkout benchmark, while keeping the correctness suite green. Use only the checkout service, benchmark fixtures, and related tests. Between iterations, record what changed, what the benchmark showed, and the next best experiment to try. If the benchmark cannot run or no valid paths remain, stop with the attempted paths, the evidence gathered, the blocker, and the next input needed.
The stronger version also defines when Codex cannot call it done. Improving p95 from 180 ms to 135 ms is not enough. Getting below 120 ms while breaking correctness tests is not enough. If the benchmark cannot run, report that blocker rather than claiming success.
Research tasks need evidence standards too, especially when exact proof may be unavailable:
/goal Produce the strongest evidence-backed reproduction of the paper using the available materials and local resources. Attempt the headline results where feasible, verify outputs where possible, and end with a report that separates confirmed findings, approximate reconstructions, blocked claims, and remaining uncertainty.
This leaves room to investigate while keeping the result honest. It defines completion, blockage, and uncertainty separately.
Not sure how to write one? Ask Codex. Describe the work plainly, ask for a draft Goal, then tighten success criteria, evidence, constraints, and stopping conditions before activating it.
Help me turn this into a strong `/goal`: I want Codex to keep working on this flaky checkout test until we either fix it with evidence or can clearly explain what is blocking progress.
Codex proposes a fuller Goal and asks follow-up questions only when important information is genuinely missing.
Keep scope narrow enough to audit, broad enough to explore
- Weak:
/goal Improve performance. Strong:/goal Reduce p95 latency below 120 ms on the checkout benchmark while keeping the correctness test suite green. - “Fix the failing checkout test” may be too narrow if the fault is upstream. “Improve the entire system” is too broad to audit. “Make the checkout suite pass on the current branch without changing public API behavior” is more useful.
- Documentation needs the same care. “Write docs for this feature” is weak. Try:
/goal Produce a docs page for Goals that explains the lifecycle, command surface, and two examples. Verify that the page builds locally and that all referenced commands match the current CLI behavior.
The stronger request provides checkable things: a page, a build command, and actual command behavior.
- For research, define exact reproduction, partial reconstruction, indirect support, and blockage first. Have Codex make a claim ledger, map claims to evidence, implement feasible parts, identify blockers, and produce an audit distinguishing confirmed findings, supported claims, blocked claims, and uncertainty. Keep the completion standard fixed while letting Codex choose the path.
What happens after activation
- The objective persists. Failed tests do not erase it. A benchmark improvement below the target still allows more work. Missing research data can change the evidence plan without lowering the standard.
- It can continue automatically when idle. It won’t continue while another turn is running, user input is queued, or thread work remains. The thread must be idle, the Goal active, and budget available.
- Completion requires evidence. A feeling of being “mostly done” is not enough. Check files, tests, logs, benchmark output, artifacts, or research evidence.
How Goals are designed
- Thread-level state: a Goal is persistent state for one thread, not global memory or project instructions. It belongs with that thread’s files, commands, diffs, logs, and reasoning, and records the objective, lifecycle, budget, and progress accounting.
- Four states: active, paused, complete, and budget-limited. These determine whether Codex can continue, should wait, or should summarize rather than begin more work.
- Event-driven, not a simple loop: continuation is checked at safe boundaries—after a turn, with no pending work or queued user input and an idle thread. Scheduling is conservative. Planning-only work does not trigger continuation; interruptions pause the Goal; resuming a thread may restore it appropriately; and if an automatic continuation calls no tools, the next is suppressed to avoid spinning.
- Prompts require an audit: continuation instructions keep Codex focused, but completion must be checked against changed files, commands, tests, benchmark output, artifacts, or research evidence.
- Explicit budget handling: at the limit, stop substantive work, summarize progress and blockers, and identify the next step. Hitting the budget is not completing the Goal.
- Bounded authority: the model can start a Goal and mark it complete only with evidence. Pause, resume, clear, and budget-limited transitions are controlled by the user or system.
The design keeps the objective alive until evidence supports completion. It is not an infinite loop.
Research example: reproducing Deep Hedging
Buehler, Gonon, Teichmann, and Wood’s Deep Hedging examines neural trading strategies across risk preferences, transaction costs, and higher-dimensional markets. A useful Goal attempts the headline numerical findings, separates exact mechanics from approximate trained substitutes, and states what cannot be replayed exactly with available materials.
# Weak: no priorities, evidence standard, missing-state handling, or distinction between a close match and exact replay
/goal Reproduce Buehler et al., "Deep Hedging"
# Better: an evidence standard and final artifact
/goal Produce the strongest evidence-backed reproduction of Buehler et al., "Deep Hedging," using the available paper materials and local resources. Attempt every headline result, verify the outputs, and end with a report that separates reproduced mechanics, approximate trained results, blocked exact replay, and remaining uncertainty.
Codex separates headline and supporting claims, maps them to available evidence, rebuilds locally testable parts, and identifies claims blocked from exact reproduction.
- Achieved: rebuilt pricing and hedging mechanics, reproduced Heston reference prices, trained policies for CVaR hedging experiments, reconstructed key histograms and hedge surfaces, reproduced the Black–Scholes transaction-cost slope, and ran training checks for Heston transaction costs and higher-dimensional examples.
- Blocked: the paper did not provide exact seeds, generated training paths, TensorFlow graphs, optimizer state, checkpoints, or complete original simulation state. The honest result is a partial, approximate reproduction—not exact neural-network replay.
Preserve these levels of support in the report instead of compressing everything into “success.” A ledger entry might read:
Claim: Deep hedging approximates complete-market Heston hedge without transaction costs.
Route: Rebuilt model mechanics, reference hedge comparison, and trained neural policy.
Evidence surface: Price checks, histograms, and hedge surfaces.
Status: Close approximate reproduction.
Remaining uncertainty: Original training paths, seeds, and checkpoints are unavailable.
A trained substitute can support a claim, a close numerical match can increase confidence, and reconstructed figures can verify part of a result. None should be described as an exact replay of the original experiment. A Goal keeps the investigation moving without letting a plausible artifact become an exaggerated conclusion.
When not to use a Goal
- Use ordinary prompts for one-line edits, simple explanations, short reviews, or a single answer followed by a stop.
- Don’t use Goals with vague endpoints. “Make this better” has no reliable completion test. “Refactor this code” also needs an end state, tests, and constraints.
- Don’t use a Goal to hide uncertainty. State unavailable data, how to handle unstable benchmarks, and how indirect evidence must be labeled.
Goals suit tasks with a persistent objective, an evidence-based endpoint, and a path requiring several rounds of investigation. You provide the objective, Codex follows evidence, and the Goal connects them until completion or an honest blocker report.
What if a newer model stops too early?
OpenAI’s September 2026 article notes that people used to GPT-5.6 Sol working for long stretches may find GPT-6 Astra more cautious about stopping. It may deliver a first implementation for review while work remains.
- Define “done” before starting, and explicitly ask it to continue to full completion when needed.
- If the task includes running, inspecting, and fixing failures, say so in the request.
- “Stop after the first version for my review” creates an early stopping point. Decide whether you actually need it.
- If you want exploration after the first pass, define what to explore and where to stop.
Part C: manage sessions and context
One task per session
A session contains project background, relevant files, changes, and the current task. Treat each session as a small project container. Use one for tests and another for a frontend feature. Clear responsibilities reduce mixed context.
Continue yesterday’s work
- In the CLI, run
codex resumeand choose a session or point in a conversation. No repeated explanation is needed. If you previously made code labels orange, return and say “Make those labels green.” - Within a session,
/resumeopens history. It suits work across days, migrations, long debugging, staged development, and returning from a fork. - The CLI shows a session ID. Record important IDs; they are quicker than searching from memory.
- The IDE also lets you return to old conversations and search for a task.
- If VS Code history suddenly omits a session, don’t delete files. See troubleshooting.
Long conversations: /compact
Long chats bring more history into each response, making work slower and more expensive. /compact summarizes earlier conversation and continues the task.
- It compresses; it doesn’t clear everything or preserve every detail. Tell it what matters:
/compact Preserve the login-module conclusions, changed files, remaining bugs, and failed-test information.
- Codex models can also automatically compact long conversations, helping long tasks retain key context.
New topics: /new and /clear
/new starts a conversation. /clear clears the terminal display and starts one. Keep it simple: use /compact for an unfinished task and /new or /clear for a new topic.
A quick aside versus another path: /side and /fork
Remember: /side is a quick aside; /fork is a separate path.
/side: ask briefly without interrupting the main task:
/side Does this approach have any obvious risks?
Then return to the main thread. It suits quick judgments, risk checks, and concept explanations without cluttering the main task. It is not for lengthy discussions, serious alternative implementations, or lasting experiments.
/fork: copies the conversation into a new thread, likegit branch. Try another architecture, compare approaches, keep an experimental path alongside the main one, or use a completely different implementation strategy. Return with/resumeand select the original session.
Part D: parallel tasks
What can run together?
Independent tasks need not wait for one another. One project can get a README update while another gets test-failure analysis, a third gets a frontend check, and a fourth gets issue organization.
- Good candidates: documentation, changelogs, API notes; lint, tests, logs, and potential-problem checks; small wording/style/unused-code fixes; and analysis of unfamiliar modules, entry points, and call chains.
- Poor candidates: major architectural refactors, migrations, payment or permission flows, and tasks editing the same core code.
The point is independence, not simply running more tasks. You wouldn’t ask five people to edit one function simultaneously and expect it to improve automatically. Tasks changing the same files can overwrite each other.
Practical checks before parallel work
Give each task its own branch or working directory and a clear deliverable. Avoid concurrent edits to the same files. Time saved depends on dependencies and merge costs; you cannot infer speedup from the number of concurrent tasks.
Part E: cloud, phones, and other devices
What Cloud is for
Codex Cloud runs tasks in its own environment, supports parallel execution, and keeps working when you close your laptop. You can start tasks from your phone while away. Asynchronous work such as code review fits well. Connect GitHub and it works from the repository to produce PRs.
- Good fits: an independent issue, tests for a PR, documentation, a batch of failing cases, or a focused refactor.
- Poor fits: frontend details needing frequent local UI checks, private local environments, complex manual admin sign-ins, or many uncommitted local files.
Connect for the first time
Local Codex works on your computer; cloud Codex works with your GitHub repository. Skip to step three if you already have one.
1. Initialize Git
cd d:\test\
git init
The App gains a Commit button. Click it, write a useful message, and continue to save the change history. Don’t call every commit update.
2. Create a GitHub repository and push—create a repository named test and replace the example URL with your own:
git remote add origin https://github.com/ailot/test.git
git branch -M main
git push -u origin main
After git remote add, the App’s Push button becomes available. git push prompts for GitHub sign-in; afterward, the terminal and repository show the pushed files.
3. Connect Codex to GitHub
- Open
https://chatgpt.com/codex/cloudand click Connect to GitHub. - Continue and choose Authorize.
- Configure the remote repository in cloud Codex. Select test, choose Install & Authorize, and enter the password to authorize.
- Refresh; the repository appears in Codex.
Start by asking what the project does. Open the resulting task and check whether Codex understands the repository.
Use Cloud from VS Code
- Recent cloud tasks appear at the top of the panel. Open and reply there to continue remotely.
- At the bottom, choose local execution or, with Cloud connected, run the agent in a cloud container. Multiple containers can try different changes in parallel for comparison.
Hand work back and forth
- Local → Cloud: continue the same conversation remotely without occupying your computer. The task includes local changes. Save current work, discard it temporarily, or return to the remote task later and bring the result back. Teams can start locally and hand work to a teammate in the cloud without taking over the original computer.
- Cloud → local: start remotely, then bring results into the editor. For a hover-effect task, inspect every returned file change before checking buttons and switches in a browser. Don’t bring unrelated edits along unnoticed.
Ask for several approaches
- For a broad design decision, switch the IDE to cloud mode and request something more interesting than a standard dark-mode button in the header. Choose four attempts to get four independent approaches.
- A real example: at 1:30 a.m. during the Codex Web launch, the team wanted a Lottie animation after each new conversation. It worked locally, but several animations failed in production. Four attempts produced three failures and one discovery: a subtle Content Security Policy blocked inline JavaScript used by an animation. That solution saved this part of the launch.
- For difficult bugs and refactors, use Codex as a second set of eyes. Review approaches, combine strong parts, and choose what to keep.
- Apply one option in the editor, check the browser, and revert if you prefer another. This helps when the shape of a refactor is still unclear; you don’t need a perfect plan first.
- Several cloud conversations can run at once—for hover states and themes, for example—alongside a local conversation when needed.
Phones, multiple devices, and SSH
Keep these three ideas separate:
- Control this Mac from a phone: connect mobile and desktop to check progress, send tasks, and approve actions. Start setup on desktop → scan the QR code with your phone → authorize on the phone → confirm on desktop → select a project and send a task from mobile.
- Control another device from this Mac: useful with a MacBook and Mac mini. The remote Mac must first enable Allow other devices to connect. Then add it from the controlling Mac and choose its remote project in new tasks.
- Use SSH for a remote project: for servers, devboxes, and AI coding machines.
Device connections choose which computer works. SSH chooses the remote directory. Mobile lets you manage work away from the desk. Together, these make Codex more than a local tool.
Part F: automation and team integration
Automations come after the basics
Learn ordinary tasks, diffs, and tests first. Automate work that recurs, has clear rules, and produces checkable results: daily failed-test checks, weekly dependency risk reviews, outdated-link scans, daily issue classification, or weekly change summaries.
Make the request specific. Instead of “Check the project every day,” use:
At 10 a.m. every day, check this repository:
1. Pull the latest main branch.
2. Run npm run lint.
3. Run npm test.
4. If either fails, summarize the failed command, errors, and likely related files.
5. Do not edit code automatically. Report only.
- Start with automatic checks and reports, not automatic fixes. Expand to low-risk repairs only after the findings are reliable.
- Automation is like an assistant arriving on schedule: give it a clear operating procedure. A vague automated task just produces unusable reports every day.
- Record your working conventions—testing after edits, which server to test on, and releasing only after testing—so AI follows your workflow rather than drifting.
Headless mode and structured output
Call Codex CLI programmatically, integrate it with automation, or run it independently in a container.
- Add a file specifying the output format in the
agents.mdproject. Use a JSON schema following OpenAI’s structured-output format. - A code-style report might require files analyzed, total issues, a 0–100 quality score, and an array with file, line, severity, and explanation. Extend as needed.
- Headless execution streams logs, then prints conforming JSON. Define the format → analyze the chosen project → pass structured results to another program or pipeline.
- Process each issue with a separate API request, save findings to a database, or add the workflow to CI/CD.
- Other uses include security triage by type/impact/severity, test coverage assistance, refactoring and cleanup of duplication and technical debt, and release preparation with changelogs and documentation.
Multi-step, multi-role workflows with the Agents SDK
- Direct Codex calls are enough for one-step tasks. For “analyze → edit → recheck,” combine Codex with OpenAI’s Agents SDK. Define repeatable steps with clear inputs and outputs.
- Create frontend, product-manager, and backend agents, each with suitable MCP tools and context. Hand work to the appropriate role. Connect Codex as an MCP server so agents can call it as a tool. This suits major refactors and feature development.
- The SDK records traces: when Codex was called, which context it received, and how agents handed work over. Use them to locate failures. The Cookbook has a full multi-agent example.
Other team integrations
- Automatic PR review: start a cloud task on a pull request, inspect changes, give feedback, and find serious defects before production.
- Tasks from Slack: mention @Codex in a thread. It reads the discussion, understands requirements and boundaries, implements work, and submits a PR without requiring a rewritten prompt.
- SDK integration: run Codex in your own containers and receive structured output.
- Private code review: run review capability in your infrastructure so code stays in the enterprise environment, including repositories not hosted on GitHub. Define objectives and output format as in the JSON example.
- Reuse prompts in pipelines: CLI and Cloud prompts can go into your pipelines, with structured fields for findings.
- Automatic CI fixes: inspect the failed PR branch, investigate tests, make a repair, and open a new PR for team approval. This uses branch context and failure evidence rather than retrying blindly.
- Issue labels: Codex’s open-source project uses Codex to classify new issues with predefined labels. It understands similar problems expressed differently. The team uses labels to decide priority, ownership, and next steps.
Part G: models and usage
Choose a model for the work
- Don’t overspend on small jobs or underspend on hard ones. Switch with
/model. Strong models suit major refactors, complex bugs, unfamiliar repositories, cross-module migrations, architecture, and security-sensitive edits. Small wording changes, simple functions, type errors, explanations, and short scripts don’t need them. - Reasoning levels trade speed for depth. Simple explanations rarely need the highest level; complex work may benefit from more analysis.
- Compare models on the same modal-component task. Record elapsed time, changes, and tests before deciding whether extra reasoning is worthwhile for simple work.
- GPT-5.1 Codex Max is an earlier long-task example, trained specifically for Codex CLI to improve efficient, stable delivery. Training directly in Linux, macOS, and Windows helps with Bash, PowerShell, and sandbox rules. Automatic conversation compaction supports long refactors. The team keeps improving speed, resource use, working duration, and production readiness.
- For speed, create a
fastprofile with a fast model and lower reasoning effort, then use--profile fast. Newer feature settings also includefast_mode; see configuration. - Names and availability change quickly. Follow your local
/modellist, not old recommendations.
Limits and cost
- An official rate card explains usage so administrators can estimate cost. Actual consumption depends on task, model, and workflow.
- Compare Codex and Claude Code using the same tasks, recording subscriptions, extra credits, quality, and rework. Include migration costs for scripts, Skills, and team habits. One task or personal bill does not establish a general cost difference.
- Useful habits include:
- Use concise output to reduce greetings and repetition without dropping approvals, failure explanations, or evidence.
- Use Superpowers for consistent quality; see Skills and configuration.
- Monitor usage: record account usage before and after tasks. Pause and investigate unexpected consumption.
- Open Codex directly for small jobs: a terminal
codexsession can handle bug fixes, formatting, and tests. Keep requests simple: “Fix this file’s null-pointer issue” or “Add tests for this function.” - Split large tasks into independent parallel paths, as described in Part D.
- Separate exploration, coding, and verification; locate files first; compact long conversations; and keep one task per session. These reduce waste, but nobody can promise a fixed savings percentage.
Appendix: the software development lifecycle
OpenAI has a guide to building an AI-native engineering team, covering seven stages from planning and design to documentation and maintenance. Consider how Codex can help throughout:
- Planning and design: clarify requirements and compare options.
- Coding: implement changes and features and investigate problems.
- Testing: generate tests and analyze failures.
- Review and maintenance: inspect changes, update documentation, and reduce technical debt.
Further learning
- Official Codex documentation at
developers.openai.com/codexprovides instructions and practical advice. - The Codex Cookbook covers structured output, reviews, CI repair, and issue classification.
- The changelog tracks frequent product updates.
- Enterprise administration and security guides cover rollout, management, permissions, compliance, and data security.
- The rate card helps estimate usage and cost.
- For team rollout, consult the official customer support, onboarding, and engineering collaboration guides as needed.