These are practical tips for getting very good with Codex CLI, Codex in the IDE/app, and Codex automation. The point is not "ask Codex to code." The valuable parts are the details people usually miss: AGENTS.md layering, config.toml profiles, sandbox and approval combinations, codex exec, JSONL output, skills, hooks, MCP, subagents, worktrees, and the boring verification loops that make agentic coding actually work.
I used the official Codex docs, the open source Codex repo, and local CLI behavior while writing this. See RESEARCH.md and the references at the end if you want to check the exact docs.
- Tip 0: Start from the CLI, even if you like the app or IDE
- Tip 1: Keep one alias for interactive Codex and one for automation
- Tip 2: Use Git before you trust any agent
- Tip 3: Learn
/statusbefore anything goes wrong - Tip 4: Learn the slash commands that change control flow
- Tip 5: Use
/diffinstead of asking Codex what it changed - Tip 6: Use
/copy, files, and stdout intentionally - Tip 7: Voice input works well because Codex can tolerate messy prompts
- Tip 8: Treat
AGENTS.mdas durable team memory - Tip 9: Understand
AGENTS.mdprecedence - Tip 10: Use
AGENTS.override.mdfor temporary experiments - Tip 11: Keep instruction files under the token cap
- Tip 12: Use
/initto scaffold, then cut aggressively - Tip 13: Mention exact files when the task is narrow
- Tip 14: Use
/sidefor questions that should not steer the main task - Tip 15: Use
/forkwhen you want to try a different approach - Tip 16: Write handoff files before context gets stale
- Tip 17: Separate sandboxing from approvals
- Tip 18: Pick the sandbox for the job
- Tip 19: Use
--add-dirinstead of launching from your home folder - Tip 20: Use profiles for modes you repeat
- Tip 21: Use
-coverrides for one-off experiments - Tip 22: Use
/permissionsmid-session - Tip 23: Keep dangerous autonomy inside a container
- Tip 24: Test the sandbox itself
- Tip 25: Ask for the write-test-read loop explicitly
- Tip 26: Build the verifier before the implementation
- Tip 27: Use manual exponential backoff for CI and long builds
- Tip 28: Use
codex reviewas a second pass - Tip 29: Use
codex execfor repeatable jobs - Tip 30: Use stdin as context
- Tip 31: Use
--jsonwhen another program reads the run - Tip 32: Use
--output-schemafor stable automation - Tip 33: Use clean automation flags
- Tip 34: Use
codex applycarefully - Tip 35: Add MCP servers only when they replace real work
- Tip 36: Prefer small internal CLIs over fragile UI automation
- Tip 37: Use apps/connectors for authenticated systems
- Tip 38: Make browser and computer use prove what it saw
- Tip 39: Turn repeated workflows into skills
- Tip 40: Package reusable skills as plugins
- Tip 41: Use hooks for deterministic guardrails
- Tip 42: Use notifications, title, and statusline for long tasks
- Tip 43: Use subagents only for independent parallel work
- Tip 44: Give subagents ownership boundaries
- Tip 45: Create custom agents for real roles
- Tip 46: Use worktrees for parallel branches
- Tip 47: Use Codex as an MCP server for another agent
Codex exists in a few surfaces now: CLI, IDE extension, app, and web/cloud. I would still start with the CLI because it exposes the most obvious mental model: there is a current directory, a Git repo, a sandbox, an approval policy, config files, shell commands, and a transcript.
The CLI also makes it easier to learn the mechanics that apply everywhere else. If you understand codex --sandbox workspace-write --ask-for-approval on-request, ~/.codex/config.toml, AGENTS.md, /status, /diff, and codex exec, the IDE and app stop feeling like magic.
Install with one of these:
npm i -g @openai/codex
brew install --cask codexThen run:
codexI like short aliases because Codex becomes something you open constantly, not a special tool you remember once a week.
alias cx='codex'
alias cxe='codex exec'
alias cxr='codex resume --last'
alias cxf='codex fork --last'
alias cxro='codex --sandbox read-only'
alias cxw='codex --sandbox workspace-write'The important thing is not the exact letters. The important thing is that codex exec deserves its own shortcut. Interactive Codex and non-interactive Codex are different workflows, and you will use both a lot once you get comfortable.
Before you let Codex edit, make sure the project is under version control and that you know what is already dirty.
git status --shortCodex is much easier to use when you can say things like:
Only touch files related to the auth middleware. Do not touch the existing uncommitted changes in
docs/.
For bigger tasks, create a branch first:
git switch -c codex-auth-refactorThis is boring advice, but it changes how brave you can be. The difference between "I hope this works" and "I can inspect and revert a patch" is huge.
/status is the fastest way to answer "what mode am I in?" It shows the active model, permissions, sandbox, writable roots, token usage, and other session details.
Run it at the beginning of a serious session:
/status
This is especially helpful when Codex seems too cautious or too powerful. Many weird sessions are not model problems. They are mode problems: wrong sandbox, wrong approval policy, wrong working directory, wrong profile, or stale instructions.
You do not need every slash command on day one. These are the ones I would learn first:
/status- inspect model, permissions, context, and roots/permissions- change what Codex can do without asking/model- switch model and reasoning effort/fast- toggle fast mode for supported models/plan- force a planning step before implementation/diff- inspect current changes, including untracked files/compact- summarize a long conversation/fork- branch the current conversation/side- ask a side question without polluting the main thread/review- ask Codex to review the working tree
The subtle one is queued slash commands. If Codex is already running, you can type a slash command and press Tab to queue it for the next turn. That is useful when you realize mid-run that you want /status, /diff, or /review next.
Asking "what did you change?" is useful, but /diff is better because it shows the actual Git diff, including untracked files.
/diff
This is the Codex equivalent of making the agent show its work. I use it before tests, before commits, and especially before letting Codex continue on top of its own changes.
A good review rhythm is:
- Let Codex make the narrow change.
- Run
/diff. - Ask questions about suspicious lines.
- Only then ask it to run tests or simplify.
Terminal selection is not always a clean way to get Codex output. Use the built-in copy command for the latest finished response:
/copy
For longer artifacts, ask Codex to write to a file. For scripts, use codex exec and stdout:
codex exec "write release notes for the last 10 commits" > release-notes.mdFor automation, prefer -o:
codex exec -o /tmp/codex-summary.md "summarize the repo risks"This keeps the transcript, the final artifact, and your terminal scrollback from becoming one messy blob.
For large tasks, I find voice input faster than typing. This works especially well with Codex because a good prompt often sounds like explaining a task to a teammate:
Look at the checkout flow. I think the bug is around the coupon validation. First trace the request path, then make a plan, then only change the minimal files. Do not run the full test suite yet. Use the narrow checkout tests if they exist.
You do not need perfect transcription. You need enough intent, constraints, and examples. Codex is usually good at recovering from minor transcription mistakes.
AGENTS.md is where you put instructions that should be loaded before Codex starts work. It is the Codex version of "here is how this repo works."
Good AGENTS.md content:
## Verification
- Run `pnpm test -- --runInBand` after changing backend TypeScript.
- Run `pnpm lint` only after formatting has passed.
- Use `pnpm`, not `npm`, in this repo.Weak AGENTS.md content:
- Write high-quality code.
- Be careful.
- Follow best practices.If a human would roll their eyes at the instruction, Codex probably does not need it either.
Codex builds an instruction chain. At the global level it reads from ~/.codex by default. At the project level it walks from the project root down to your current working directory. More specific files appear later, so they override earlier guidance.
The practical pattern is:
~/.codex/AGENTS.md- your personal defaults<repo>/AGENTS.md- repository-wide setup and verification<repo>/services/api/AGENTS.md- service-specific commands<repo>/services/api/payments/AGENTS.md- local exceptions
This is very powerful. You can keep the root file short and put the weird instructions exactly where they apply.
AGENTS.override.md is useful when you want to test a new instruction without deleting your normal AGENTS.md.
For example, if you are doing a temporary migration:
# AGENTS.override.md
For this migration only:
- Do not introduce new helper libraries.
- Prefer mechanical edits.
- Stop after each package and show the diff.When the experiment is done, delete the override file. This is cleaner than leaving temporary instructions in the permanent project memory and forgetting about them.
Codex has a default project-doc size limit. The exact config knob is project_doc_max_bytes, and the docs mention 32 KiB as the default.
That means a giant AGENTS.md is not just annoying. It can crowd out useful context, and parts of your guidance may not load if you hit the limit.
I would rather have three short files in nested directories than one enormous root file. The closer the instruction is to the code it affects, the easier it is to keep accurate.
/init can create a starter AGENTS.md for the current directory:
/init
The trick is not to accept the generated file as sacred. Use it as a first pass, then ask Codex to remove generic lines and keep only instructions that will change future behavior.
Good follow-up prompt:
Review this
AGENTS.md. Delete anything generic, duplicated, or already obvious from package files. Keep only instructions that would prevent a real mistake.
Codex can search, but for narrow tasks you can save context and reduce drift by pointing at the exact files.
In the CLI, use /mention or paste absolute paths:
/mention src/auth/session.ts
/mention test/auth/session.test.ts
For cross-repo work, use realpath:
realpath ../other-repo/docs/api.mdThen tell Codex what relationship matters:
Compare this API doc against our implementation. Only report mismatches. Do not edit yet.
Sometimes you want to ask a question while Codex is in the middle of a serious implementation:
What does this Rust lifetime mean?
That question can pollute the main context if you ask it inline. /side starts an ephemeral side conversation so you can ask without pulling the main task off course.
/side
Use it for explanations, quick syntax checks, and "am I thinking about this right?" questions.
Forking is better than arguing with one long conversation. If Codex has one approach and you want to test another, fork the conversation.
/fork
Or from the shell:
codex fork --lastI use this when I have two plausible designs. Let one thread continue with design A, fork, then ask the second thread to attempt design B. Git decides the winner.
For long tasks, ask Codex to write a HANDOFF.md before you start fresh:
Create
HANDOFF.mdwith the goal, current state, files changed, commands run, failed attempts, and exact next steps. Assume the next Codex session has no transcript.
Then start a new session and give it the file:
codex "Read HANDOFF.md and continue from there."There is a small sample skill in skills/handoff/SKILL.md in this repo. The point is to move from fuzzy conversation memory to an explicit artifact.
This is one of the most important Codex concepts.
The sandbox is the technical boundary: what files and network resources commands can access.
The approval policy is the interaction boundary: when Codex must stop and ask you.
You can have a strict sandbox with low approval friction, or a loose sandbox with more approvals. Do not mix these up. If Codex is blocked, ask whether the problem is "the command cannot technically access this" or "Codex is waiting for permission."
The common CLI sandbox modes are:
codex --sandbox read-only
codex --sandbox workspace-write
codex --sandbox danger-full-accessMy default recommendation:
- Use
read-onlyfor exploration, code review, and debugging plans. - Use
workspace-writefor normal implementation. - Use
danger-full-accessonly in a container, VM, throwaway worktree, or CI runner you are comfortable losing.
workspace-write is usually the sweet spot. It gives Codex enough room to edit and test inside the project without turning your whole machine into the workspace.
If Codex needs one extra directory, do not start it from ~ just to make everything visible.
Use:
codex --cd /path/to/app --add-dir /path/to/shared-libThis keeps the working root clear while allowing the one extra directory the task needs. It also makes /status more meaningful because writable/readable roots describe the actual job.
Put repeatable modes in ~/.codex/config.toml:
[profiles.readonly]
sandbox_mode = "read-only"
approval_policy = "on-request"
[profiles.agent]
sandbox_mode = "workspace-write"
approval_policy = "never"Then launch with:
codex --profile readonly
codex --profile agentProfiles are useful because they make your intent explicit. "I am doing read-only exploration" and "I am letting an agent work inside the repo" should not feel like the same launch command.
You do not need to edit config.toml for every experiment. Use -c key=value:
codex -c model_reasoning_effort='"high"'
codex -c sandbox_mode='"read-only"'
codex -c 'features.multi_agent=true'The value is parsed as TOML, which is why strings need quotes inside the shell argument. This is slightly annoying, but it is worth learning because it lets you test config changes without making them permanent.
If a session starts too restricted or too loose, use:
/permissions
This is faster than quitting and relaunching. It is also a good habit because permission changes become an explicit part of the transcript.
For example, you can start read-only, let Codex inspect the bug, ask for a plan, then switch to workspace-write when you are ready for edits.
Codex has an escape hatch:
codex --dangerously-bypass-approvals-and-sandboxI would not use that on the host machine. Use it inside Docker, a VM, a disposable Codespace, or a temporary worktree where the blast radius is clear.
The useful pattern is:
- Create an isolated environment.
- Mount or copy only the repo you want changed.
- Run Codex with broad autonomy inside that environment.
- Review the resulting diff outside the environment.
The power is real, but so is the risk.
Codex includes sandbox subcommands so you can test what a command can do under the sandbox.
Examples from local CLI help and docs:
codex sandbox macos --log-denials ls
codex sandbox linux ls
codex sandbox windows powershell -NoProfile -Command Get-LocationThis is useful when a test or package manager fails in a confusing way. Sometimes the dependency is broken. Sometimes the sandbox is blocking a path or network call.
Do not ask Codex to "fix it" and then wait. Ask it to close the loop:
Make the minimal fix. Run the narrowest relevant test. If it fails, read the failure and iterate up to three times. Stop and explain if the failure looks unrelated.
This works because Codex is good at tool loops when the loop is explicit. The important part is "read the failure." Otherwise agents sometimes rerun commands without changing the hypothesis.
For tricky bugs, ask Codex to find or create the command that proves the bug before editing.
Good prompt:
Before changing code, find the smallest command that reproduces this bug. If no test exists, add a failing test first and show me the failure.
This is just TDD, but Codex makes it easier because it can do the tedious search for the right test harness.
If the verifier is too slow, ask for a narrower one. A 15-second test is much better agent fuel than a 15-minute test suite.
For long jobs, ask Codex to check status with increasing waits:
Check the CI run. If it is still running, wait 60 seconds, then 120, then 240, and keep the output short.
This is often better than a live watch command that floods the transcript. For GitHub Actions:
gh run view <run-id> --json status,conclusion,jobsThe goal is to keep Codex informed without spending half the context window on progress logs.
Codex has a dedicated review command:
codex review --uncommitted
codex review --base main
codex review --commit <sha>I would not use this as a replacement for understanding the diff. Use it as an extra reviewer after you have tests and a human-readable diff.
Good custom instruction:
codex review --uncommitted "Focus on behavioral regressions, missing tests, and security issues. Ignore style unless it changes behavior."codex exec runs Codex non-interactively. This is great for scripts, CI, and repeated local jobs.
codex exec "summarize this repository and list the top 5 risky areas"It prints progress separately and sends the final answer to stdout, which means you can pipe or redirect it:
codex exec "generate release notes for the last 10 commits" > release-notes.mdOnce you start using codex exec, Codex becomes a programmable command, not just a chat UI.
If stdin is piped and you also provide a prompt, Codex treats the prompt as the instruction and the piped content as context.
git diff main...HEAD | codex exec "Review this diff for likely bugs. Return only findings."This is one of the cleanest ways to make Codex operate on exact data. It is also less ambiguous than saying "look at my recent changes" when the working tree has unrelated files.
For automation, use JSONL:
codex exec --json "summarize the repo structure" | jqCodex emits events such as thread start, turn start, command execution, file changes, final messages, and usage. That means your script can distinguish "the agent said this" from "the agent ran this command."
There is a tiny starter jq filter in templates/extract-jsonl.jq.
If you need a structured result, use a JSON Schema:
codex exec --output-schema risk-report.schema.json "Analyze this repo for migration risk."This is much better than parsing prose. For example, you can require:
summaryrisk_levelfindings[]recommended_next_commands[]
When the downstream consumer is a script, make Codex produce data, not a mini blog post.
For automation, three flags are easy to miss:
codex exec --ephemeral "triage this repository"
codex exec --ignore-user-config "run with clean defaults"
codex exec --ignore-rules "skip execpolicy rules for this controlled run"--ephemeral avoids persisting session rollout files. --ignore-user-config is useful when your personal config would make CI non-reproducible. --ignore-rules is useful only when the automation environment already has its own controls.
codex apply applies the latest diff produced by a Codex agent as a git apply to your local working tree.
That can be useful when you have Codex generate a patch in one place and apply it in another. But treat it like applying any patch from an agent:
codex apply
git diffReview after applying. Do not turn patch application into blind trust.
MCP is powerful, but every tool adds surface area. Add servers when they save real work:
codex mcp add context7 -- npx -y @upstash/context7-mcp
codex mcp listGood MCP uses:
- Fetching current framework docs.
- Querying internal systems.
- Driving a browser or design tool.
- Reading an API that would otherwise require lots of manual copying.
Bad MCP uses:
- Adding a server because it sounds cool.
- Duplicating a CLI Codex can already run.
- Loading huge tool lists for one rare task.
If Codex needs to interact with your product admin API every day, do not make it click the web UI forever. Ask it to create a small CLI.
Example:
internal-admin user lookup --email someone@example.com
internal-admin invoice refund --id inv_123 --dry-runCodex is very good at composing CLIs. A stable CLI gives it structured output, safer dry-run modes, and fewer browser failures.
This is one of the highest-leverage things you can build for agentic coding inside a company.
Codex can use apps/connectors when available. In the CLI, /apps lets you browse and insert apps into the prompt.
/apps
Use connectors when the task needs authenticated context from GitHub, Slack, Linear, or similar systems. This is often better than pasting screenshots or copying fragments because the connector can preserve structure.
The safety rule is simple: understand whether a tool is read-only or destructive before you let Codex use it.
For browser or computer-use tasks, ask Codex to capture evidence:
Use the browser to reproduce the bug. Record the exact route, controls clicked, visible error text, console errors, and screenshot path if you take one. Do not edit code until reproduction is clear.
The important part is not "use a browser." The important part is making the browser session produce a small test report. Without that, UI automation can become vibes with a cursor.
Skills are reusable workflows. Codex sees the skill metadata first and loads the full SKILL.md only when needed. That is the main advantage over dumping everything into AGENTS.md.
Basic shape:
.agents/skills/my-skill/SKILL.md
---
name: my-skill
description: Use when ...
---
Steps Codex should follow.Good skills have clear triggers, explicit inputs and outputs, and a narrow job. There are examples in skills/.
Skills are for authoring workflows. Plugins are for distribution.
If a skill is only for one repo, keep it in .agents/skills. If you want other people or other repos to install it, package it as a plugin.
This is the Codex version of moving from "I have a handy script" to "I have a tool my team can install."
Hooks let you run scripts during the Codex lifecycle. Use them for deterministic checks, not for vague advice.
Good hook ideas:
- Block prompts that appear to contain secrets.
- Run a formatting check after a turn.
- Write a compact session log.
- Warn when a command touches protected paths.
Hook config can live in ~/.codex/hooks.json, ~/.codex/config.toml, <repo>/.codex/hooks.json, or <repo>/.codex/config.toml. Project hooks load only when the project config layer is trusted.
Codex can configure status-line fields and terminal title fields:
/statusline
/title
For long-running tasks, this matters more than it sounds. A useful terminal title might include project, branch, model, and task state. A useful statusline might include model, context, limits, Git state, and session.
The goal is to make multiple Codex sessions scannable without opening every tab.
Subagents are not magic extra intelligence. They are parallel workers with their own context and token cost.
Good prompt:
Spawn three agents: one reviews security, one reviews test coverage, and one traces the data model. They should not edit files. Wait for all results and summarize disagreements.
Bad prompt:
Spawn agents to figure this out.
Subagents work best when each one has a clear question, bounded files, and a concrete output.
When subagents edit code, give them separate ownership:
Worker 1 owns
packages/api. Worker 2 ownspackages/web. Worker 3 owns docs only. Do not edit outside your assigned area. Report conflicts instead of resolving them silently.
This avoids merge chaos and makes the final review possible.
Also remember that subagents inherit the current sandbox policy. If your parent session is in workspace-write, the children are working under that same basic permission model unless you configure a custom agent differently.
Codex ships with built-in roles like default, worker, and explorer. You can define custom agents under:
~/.codex/agents/
.codex/agents/
A custom agent needs name, description, and developer_instructions. Optional fields can set model, reasoning effort, sandbox, MCP servers, and skill configuration.
Use this for real roles:
- migration planner
- security reviewer
- frontend visual verifier
- docs maintainer
Do not create ten personality variants. That usually adds confusion without improving output.
If you want multiple Codex sessions changing the same repo at the same time, use Git worktrees:
git worktree add ../myrepo-codex-auth -b codex-auth
git worktree add ../myrepo-codex-ui -b codex-uiThen launch a Codex session in each directory. This keeps branches, dependencies, and diffs separated.
Worktrees pair especially well with subagents and forks. The conversation can fork, and the code can fork too.
Codex can run as an MCP server:
codex mcp-serverThat means another MCP client can use Codex as a coding tool. This is advanced, but it opens up interesting orchestration patterns:
- A research agent asks Codex to inspect and patch a repo.
- A team workflow calls Codex for a constrained local code action.
- Another coding agent delegates a specific task to Codex.
Start by testing with the MCP inspector:
npx @modelcontextprotocol/inspector codex mcp-serverThe best Codex users will have their own small lab:
~/.codex/AGENTS.mdfor personal defaults~/.codex/config.tomlprofiles- a few trusted skills
- a few scripts around
codex exec - a scratch repo for testing new features
- a habit of deleting stale rules
Review it periodically. Bad rules accumulate. Old MCP servers linger. Profiles that made sense three months ago become weird defaults. The tool changes quickly, so your setup should be easy to inspect and easy to prune.
- OpenAI Codex CLI docs: https://developers.openai.com/codex/cli
- Codex slash commands: https://developers.openai.com/codex/cli/slash-commands
- Codex config reference: https://developers.openai.com/codex/config-reference
- Codex sandboxing: https://developers.openai.com/codex/concepts/sandboxing
- Custom instructions with
AGENTS.md: https://developers.openai.com/codex/guides/agents-md - Codex skills: https://developers.openai.com/codex/skills
- Codex MCP: https://developers.openai.com/codex/mcp
- Codex hooks: https://developers.openai.com/codex/hooks
- Codex subagents: https://developers.openai.com/codex/subagents
- Codex non-interactive mode: https://developers.openai.com/codex/noninteractive
- Open source Codex repo: https://github.com/openai/codex