Codex CLI cheat sheet
The stuff you actually need. Updated 2026-03-23.
🚀 Get productive in 30 seconds
- 1. Inside your repo, run `codex --full-auto "fix the failing test, run the smallest relevant test, and show the diff"` for a fast one-shot edit loop.
- 2. For interactive work, run `codex` then use `/plan` before big changes and `/review` before you commit.
- 3. If Codex needs more scope, add writable roots with `--add-dir` instead of jumping straight to full access.
- 4. Use `codex resume --last` to continue the same thread tomorrow instead of re-explaining context.
- 5. Keep a repo-level `AGENTS.md` with build/test commands and constraints so Codex stops making the same mistakes.
// daily_workflows
The things you'll actually do every day.
Quick one-shot fix
quickdebuggingtestsBest default for small bugs, lint fixes, test failures, or targeted refactors. Ask for the smallest fix plus validation so you get code and proof, not just code.
codex exec --full-auto "fix the failing test, run the narrowest relevant test, and summarize what changed" Interactive debugging in a real repo
interactivedebugginginvestigationUse the TUI when you want to steer, inspect diffs, answer questions, and approve actions live. Better than `exec` when the problem is ambiguous.
codex "investigate why login sometimes fails after refresh; explain root cause before editing" Plan first, then implement
planningarchitecturesaferFor risky or multi-file changes, force a planning pass first. This reduces thrash and catches missing constraints early.
codex "propose a step-by-step plan to add rate limiting to the API; do not edit yet" Resume yesterday's thread
contextresumedailyHuge time saver. Reuse the transcript, approvals, and plan history instead of pasting context back in.
codex resume --last Continue a past non-interactive run
execresumeautomationGreat when an earlier `exec` run found issues but did not finish the implementation. Lets Codex build on prior findings.
codex exec resume --last "implement the fix you proposed and run focused validation" Review your local diff before commit
reviewpre-commitqualityUse Codex as a second reviewer after you or Codex changed code. Good for catching missing tests, regressions, and risky assumptions.
codex exec review "review the current changes for correctness, regressions, and missing tests" Patch across multiple directories safely
monorepomulti-projectsafeWhen frontend and backend live side-by-side, add extra writable roots explicitly. This is the power-user alternative to broad full access.
codex --cd apps/frontend --add-dir ../backend --add-dir ../shared "implement the API + UI change end to end" Headless/remote login setup
authremoteheadlessWhen browser auth breaks in SSH, WSL, containers, or headless boxes, use device auth instead of fighting localhost callback issues.
codex login --device-auth Machine-readable CI run
ciautomationjsonUse JSONL output when another script needs progress events and the final answer. Pair it with a file for the last assistant message.
codex exec --json -o /tmp/codex-last.txt "summarize the CI failure and propose the smallest fix" Launch a Codex Cloud task from the terminal
cloudautomationremoteTriage, start, and apply Codex Cloud tasks without leaving the terminal. Use --attempts for best-of-N runs on important tasks.
codex cloud exec --env ENV_ID "implement the feature described in the issue"
codex cloud exec --env ENV_ID --attempts 3 "fix the bug with three candidate solutions" ⚡ power_moves
Stuff most people don't know about.
Parallel worktree army
Create several git worktrees and run one `codex exec --full-auto` task in each. Use this for parallel bugfixes, audits, or independent feature slices.
git worktree add ../repo-bug-1 -b bug-1 && git worktree add ../repo-bug-2 -b bug-2 && (cd ../repo-bug-1 && codex exec --full-auto "fix bug A and run focused tests") & (cd ../repo-bug-2 && codex exec --full-auto "fix bug B and run focused tests") & wait Beginners run one long thread. Power users isolate context and file changes per task, which reduces agent confusion, merge pain, and context bloat.
Plan → implement → review loop
Use one thread for planning, then implementation, then a dedicated review pass with explicit review criteria.
codex "plan the migration" # then /review after changes This gets better results than treating Codex like a one-shot code generator. You turn it into planner, implementer, and reviewer in sequence.
Scoped autonomy instead of YOLO
Keep Codex in workspace-write and widen scope only with `--add-dir`, repo config, or network toggles when needed.
codex --cd services/api --add-dir ../shared "update the contract and consumers" Power users rarely jump straight to `--yolo`. They give exactly enough access for the task, which is safer and usually easier to reason about.
Codify your workflow in AGENTS.md
Put build/test/lint commands, architecture constraints, and 'done when' rules in AGENTS.md so Codex loads them automatically.
codex # in a repo with AGENTS.md describing conventions and validation commands This removes repeated prompt boilerplate and makes Codex more consistent across sessions and teammates.
Use `/compact` before the thread gets dumb
After a long debugging or implementation session, compact the transcript to preserve key facts while freeing context.
/compact Long unmaintained threads degrade. Compacting keeps the important state while reducing context rot.
JSON schema output for structured pipelines
When you need Codex to feed another tool, constrain the final answer with a schema instead of regexing prose.
codex exec --output-schema ./result.schema.json "analyze the repo and return structured risks" This is much more robust for CI, dashboards, checklists, and bulk analysis than parsing human-oriented text.
Multi-agent for bounded parallel work
Subagents are enabled by default. Ask Codex to spawn one agent per concern (e.g. explorer, reviewer, worker) and wait for consolidated results. Define custom agents as TOML files in `.codex/agents/` (project) or `~/.codex/agents/` (global).
codex # ask: 'Spawn one agent per review point, wait for all, summarize'
# Custom agent: .codex/agents/reviewer.toml with name/description/developer_instructions Useful when a task is naturally parallel. Power users use it for exploration, review, and evidence gathering—not for every tiny change. Each subagent consumes its own tokens, so use intentionally.
Device auth + copied auth cache for remote boxes
Authenticate once on a local machine, then reuse trusted auth on headless machines when browser callbacks are painful.
codex login --device-auth This avoids one of the most common setup blockers for SSH boxes, containers, and remote dev environments.
🔥 common_gotchas
Save yourself 30 minutes of debugging.
Codex exec refuses to run outside a Git repo by default.
Run it inside a repo, `git init` first, or deliberately bypass with `codex exec --skip-git-repo-check ...` if you know what you're doing.
`--full-auto` is not full machine access.
It means workspace-write plus on-request approvals. Codex will still stop for out-of-workspace edits or network access.
Protected paths like `.git` and `.codex` can still be read-only even in writable mode.
Expect commands like `git commit` or direct edits under protected paths to require approval or fail under the sandbox.
Browser login fails on SSH, WSL, remote boxes, or locked-down networking.
Use `codex login --device-auth`, or authenticate locally and copy `~/.codex/auth.json` only within trusted environments.
Beginners overuse `--yolo` / danger-full-access.
Prefer workspace-write plus `--add-dir` and selective config changes. Use dangerous full access only inside an externally sandboxed environment you trust. Note: `--yolo` also defaults web search to live results instead of cached.
Long threads get worse over time.
Use one thread per task, `codex resume --last` for continuation, `/fork` when the task branches, and `/compact` when context gets bloated.
Web search behavior changes with sandbox/access level.
Default local mode uses cached web search. `--search` forces live results, and full-access/YOLO modes default to live web results. Treat all web content as untrusted.
People forget to tell Codex how to validate the change.
Always include 'run the narrowest relevant test/lint/typecheck' or put those commands in AGENTS.md so Codex can prove the change worked.
Running Codex in the wrong directory causes bad edits or irrelevant reasoning.
Use `--cd` explicitly and check `/status` before asking for multi-file work.
Subagent approval prompts from inactive threads can interrupt your main thread.
When an approval overlay appears showing a thread label, press `o` to open that thread and review it before approving or rejecting. In non-interactive/exec flows, actions needing new approval fail and surface the error back to the parent.
Shell completions can fail in zsh with `compdef` errors.
Add `autoload -Uz compinit && compinit` before `eval "$(codex completion zsh)"` in `~/.zshrc`.
📋 cli_flags
----full-auto Convenience alias for `--sandbox workspace-write --ask-for-approval on-request`. Best default for hands-off local edits inside the repo.
Daily one-shot fixes, focused refactors, and scripted local automation with sane safety rails.
codex exec --full-auto "fix the flaky test and run it 5 times"
----dangerously-bypass-approvals-and-sandbox Disables both sandboxing and approval prompts. Highest-risk mode.
Only inside a disposable VM/container or another environment that is already strongly sandboxed.
codex exec --dangerously-bypass-approvals-and-sandbox "run the full migration"
----sandbox, --s Sets sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`.
When you want to reason safely before allowing edits, or deliberately widen/narrow execution scope.
codex --sandbox read-only "explain this service and identify likely bugs"
----ask-for-approval, --a Controls when Codex asks before executing commands: `untrusted`, `on-request`, or `never` (plus deprecated `on-failure`).
Useful for CI, read-only audits, or tightening control during risky investigations.
codex --sandbox read-only --ask-for-approval never "summarize this codebase"
----cd, --C Sets the working root without manually changing directories.
Great for monorepos, scripts, and launching Codex from anywhere.
codex --cd apps/web "trace the checkout flow"
----add-dir Adds extra writable roots alongside the primary workspace.
The safe way to work across multiple packages or sibling repos.
codex --cd apps/web --add-dir ../packages/ui "update the component and its consumers"
----skip-git-repo-check Allows `codex exec` to run outside a Git repository.
Useful for scratch dirs, temp repros, and generated experiments.
codex exec --skip-git-repo-check "generate a tiny prototype in this temp dir"
----json Streams newline-delimited JSON events instead of human-formatted output in `exec` mode.
Automation, dashboards, CI pipelines, and any system that needs machine-readable progress.
codex exec --json "analyze CI failures"
----output-last-message, --o Writes the final assistant message to a file in `exec` mode.
Handy when you want JSONL event logs plus one clean summary artifact.
codex exec --json -o /tmp/final.txt "summarize the patch"
----output-schema Constrains the final response shape using a JSON Schema file.
Reliable downstream automation, reports, and structured audits.
codex exec --output-schema ./report.schema.json "audit dependencies and return structured findings"
----ephemeral Runs without persisting session files to disk.
Temporary runs, sensitive environments, and cleaner automation hosts.
codex exec --ephemeral "inspect this repo and summarize the architecture"
----model, --m Selects the model for the run or session.
Use stronger reasoning for hard debugging/review or cheaper/faster models for light exploration.
codex --model gpt-5.4 "review this codebase"
----profile, --p Loads a named config profile from `config.toml`.
Switching between personal modes like deep review, lightweight edit, or read-only audit.
codex --profile deep-review "review the branch vs main"
----search Enables live web search instead of cached web results.
When you need fresh docs, release notes, or current ecosystem information.
codex --search "check the latest Next.js docs for this API"
----image, --i Attaches one or more images to the initial prompt.
Debugging screenshots, design handoff, diagrams, and visual bug reports.
codex -i screenshot.png "explain this runtime error screen"
----config, --c One-off override for any config key; values are parsed as TOML.
Advanced one-run tweaks without editing your persistent config.
codex -c 'shell_environment_policy.include_only=["PATH","HOME"]' "run the test command" / commands
/plan Switches into planning mode before coding.
/review Runs a dedicated local code review on your branch, commit, or working tree.
/permissions Changes approval behavior mid-session.
/status Shows model, permissions, writable roots, and token/context state.
/diff Shows the Git diff including untracked files.
/compact Summarizes earlier conversation to free context.
/fork Branches the current conversation into a new thread.
/resume Loads a saved conversation from the session list.
/agent Switches between active agent threads in multi-agent mode. Approval requests from inactive threads surface as an overlay showing the source thread label.
/statusline Configures which metadata appears in the TUI footer interactively.
/init Scaffolds an `AGENTS.md` file in the current directory.
/model Changes model (and reasoning when supported) mid-session.
/mcp Lists configured MCP tools available in this session.
💡 pro_tips
- › The highest-leverage prompt pattern is: goal + relevant context/files + constraints + done-when. This consistently beats vague requests.
- › Always tell Codex how to verify success: specific test, lint, typecheck, or repro command. Otherwise it may stop at 'I changed the code.'
- › Use one thread per task. Resume the thread if the task continues; fork only if the task truly branches.
- › For big repos, mention files or set `--cd` explicitly so Codex starts in the right part of the tree.
- › Use `/review` even on your own changes. Codex is much more useful as a second reviewer than as a blind first drafter.
- › If a workflow repeats, move it into `AGENTS.md`, config, or a custom slash command/skill instead of rewriting the same mega-prompt.
- › In monorepos, `--add-dir` is one of the biggest quality-of-life flags. It is safer and more precise than broad full access.
- › Use `codex exec --json` for tooling, but pair it with `-o` or `--output-schema` so humans and machines both get a clean artifact.
- › When remote auth is flaky, device auth is usually faster than debugging browser callbacks.
- › Default web search is cached for a reason. Prefer cached unless you specifically need the latest docs or releases.
- › For parallel work, separate branches/worktrees beat one overloaded thread every time.
- › If Codex keeps making the same repo-specific mistake, that is a documentation/config problem, not a prompt problem. Fix it in AGENTS.md.
⚙️ configuration
model approval_policy sandbox_mode [sandbox_workspace_write].network_access web_search model_reasoning_effort [agents] codex features (subcommand) [features].shell_snapshot [profiles.<name>] cli_auth_credentials_store [shell_environment_policy] notify [history].persistence