OpenAI Codex Commands Cheat Sheet (2026 Update)

Codex commands cheat sheet for developers: CLI commands, slash commands, flags, config keys, environment variables, sandbox settings, MCP, and real workflows.

Codex CLI is OpenAI’s terminal coding agent for inspecting repositories, editing files, running tests, and reviewing changes. Run codex to open an interactive session, codex exec "TASK" for a non-interactive task, or type / inside the terminal UI to open the slash-command menu.

This Codex commands cheat sheet provides CLI commands, slash commands, flags, keyboard shortcuts, configuration keys, sandbox settings, MCP commands, and ready-to-use examples for coding, reviews, and automation.

Last audited: October 13, 2026

Codex Quick Reference

CommandTask
codexOpen an interactive session
codex exec "TASK"Run a task non-interactively
codex reviewReview code from the shell
codex resume --lastResume the latest session
codex --versionCheck the installed version
codex updateUpdate Codex CLI
codex --helpList command-line options
/Open the slash-command menu in the TUI
/statusView session details in the TUI
/reviewReview changes in the TUI
/permissionsChange permissions in the TUI
codex mcp listList configured MCP servers

Install and Start Codex CLI

Install Codex with one of the commands below, open a project directory, and run codex. The first launch opens the sign-in flow.

CommandPlatform / purpose
curl -fsSL https://chatgpt.com/codex/install.sh | shmacOS or Linux installer
powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"Windows PowerShell
npm install -g @openai/codexnpm
brew install --cask codexHomebrew on macOS
codex --versionCheck the installed version
codex updateUpdate Codex
cd /path/to/your-project
codex

Codex Command Types

Command / syntaxType and use
codex exec "Fix the failing tests"CLI command. Run in a shell or terminal.
/statusSlash command. Type inside the interactive Codex TUI.
@ or TabTUI shortcut. Press or type inside the TUI composer.
--sandbox workspace-writeGlobal flag. Pass to codex or a compatible subcommand.
codex exec --jsonSubcommand flag. Pass only to the documented subcommand.
approval_policy = "on-request"Config key. Save in $CODEX_HOME/config.toml.
CODEX_HOMEEnvironment variable. Set in a shell, installer, or automation run.

Codex CLI Commands

CommandUse
codex [PROMPT]Open the terminal UI, optionally with an initial prompt.
codex app [PATH]Launch the ChatGPT desktop app on macOS or Windows. On macOS, Codex can open a workspace path; on Windows, it prints the path to open.
codex apply <TASK_ID>Apply the latest diff from a Codex cloud chat to the local working tree. Alias: codex a.
codex archive <SESSION>Archive a saved interactive session by ID or name.
codex remote-control pairPrint a short-lived manual pairing code for a running remote-control daemon.
codex completion <shell>Generate completion scripts for Bash, Zsh, Fish, PowerShell, or Elvish.
codex delete <SESSION>Permanently delete a saved interactive session by ID or name.
codex doctorGenerate a diagnostic report for installation, config, auth, runtime, Git, terminal, and session issues.
codex exec "TASK"Run Codex non-interactively. Alias: codex e.
codex exec forkFork a saved non-interactive session into a new session while preserving the original.
codex exec resume --last "TASK"Resume the latest non-interactive session and add a follow-up task.
codex features listList feature flags and their effective states.
codex features enable <FEATURE>Persistently enable a feature in config.toml.
codex features disable <FEATURE>Persistently disable a feature in config.toml.
codex fork <SESSION>Fork a saved interactive session into a new chat.
codex loginAuthenticate through the default ChatGPT login flow.
codex login --device-authUse device-code authentication for remote or headless environments.
printenv OPENAI_API_KEY | codex login --with-api-keyRead an API key from stdin and persist the login.
printenv CODEX_ACCESS_TOKEN | codex login --with-access-tokenRead an access token from stdin for trusted automation.
codex login statusPrint the active authentication mode and return success when logged in.
codex logoutRemove stored authentication credentials.
codex mcp ...List, add, inspect, authenticate, and remove MCP servers.
codex mcp-serverDeprecated. Older command for exposing Codex over MCP.
codex plugin ...Install, list, or remove plugins.
codex plugin marketplace ...Manage plugin marketplace sources.
codex resume [SESSION]Resume a saved interactive session. Add --last for the latest session.
codex reviewRun a non-interactive review of uncommitted changes, a branch diff, a commit, or custom instructions.
codex sandbox <platform> -- <COMMAND>Run a command under a Codex-provided macOS, Linux, or Windows sandbox helper.
codex unarchive <SESSION>Restore an archived interactive session by ID or name.
codex updateInstall the latest available Codex CLI update.

Codex CLI Slash Commands

Slash commands work inside the interactive terminal UI after codex starts. Type / to open the current command list for the installed version.

Sessions and Conversation History

Slash commandUse
/statusShow model, permissions, writable roots, token use, cost estimate, and session details.
/usageView token activity, rate limits, and available usage-reset credits.
/new [NAME]Start a new chat inside the same CLI session; an optional name helps find it later.
/resumeResume a saved chat from the session list.
/forkFork the current chat into a new chat.
/side or /btwStart a temporary side chat and return to the parent without closing it.
/clear [NAME]Clear the terminal and start a fresh, optionally named chat.
/renameRename the current saved chat; recent versions can suggest an editable title.
/compactSummarize the visible chat to free context tokens.
/recapShow a manual recap of the current chat.
/copyNavigate transcript blocks and copy a complete response, code block, or blockquote. Copied selections preserve Markdown tables and significant whitespace.
/exportExport the complete TUI conversation to Markdown, copy it, or save it to a file.
/archiveArchive the current session and exit Codex.
/deletePermanently delete the current session and exit Codex.
/memoriesConfigure memory use and generation.
/logoutSign out from inside the TUI.
/exit or /quitExit the terminal UI.

Code, Repositories, and Tasks

Slash commandUse
/initCreate an AGENTS.md scaffold.
/ideAttach IDE files, selections, and editor context to the current chat.
/mention <PATH>Attach a file or folder to the chat.
/cd <PATH>Change the current working directory.
/pwd or /cwdShow the current working directory.
/diffShow the current Git diff, including untracked files.
/reviewReview the working tree or compare against a base branch.
/planToggle plan mode and optionally send a planning prompt.
/goalSet, edit, pause, resume, view, or clear a task goal.
/worktreeStart or continue a conversation in a new Git worktree when worktree support is enabled.
/psShow background terminals and recent output.
/stopStop background terminal work.

Models, Permissions, and Settings

Slash commandUse
/modelChoose an available model and reasoning effort. GPT-6.1 Sol is the bundled default; account, workspace, provider, and saved-session settings determine your available choices.
/fastToggle the current model’s Fast service tier when advertised by its catalog. The command is hidden when that model has no eligible Fast tier. Fast mode consumes usage at a higher rate.
/permissionsChoose permissions and approval behavior. Select Approve for me for automatic review of eligible approval requests.
/approveRetry one action denied by automatic review.
/experimentalView and toggle experimental features.
/keymapInspect, remap, and persist TUI keyboard shortcuts.
/vimToggle Vim editing mode for the composer, including draft search, undo, and redo.
/setup-default-sandboxSet up the Windows agent sandbox.
/debug-configPrint config layering and requirements diagnostics.
/statuslineChoose and order TUI footer fields.
/titleConfigure terminal title fields.
/themeChoose a syntax-highlighting theme.
/tuiChoose the terminal UI mode for the next launch.
/daybreakToggle Daybreak after opting in with --enable cli_daybreak. Requires eligible ChatGPT authentication, the OpenAI provider, and supported model and program access.

Agents, MCP, and Integrations

Slash commandUse
/agentsOpen the agent Command Center to browse tasks and older history. Use /subagents to switch between delegated-agent threads.
/appsBrowse apps and insert a connector into the prompt.
/pluginsBrowse categorized plugins, recommendations, and installed plugin state.
/skillsBrowse and attach local skills.
/hooksInspect, trust, or disable lifecycle hooks.
/mcpView connected MCP servers and tools. Add verbose for details.
/mcp login <NAME>Start authentication for an MCP server from the active TUI session.
/appContinue the current session in the desktop app on macOS or Windows.
/importImport supported setup, project files, recent chats, and other supported artifacts from Claude Code or Cursor.
/daemonManage the local background server.

Terminal Utilities

Slash commandUse
/feedbackOpen the feedback flow and optionally include logs.
/rawToggle copy-friendly raw scrollback mode.
/pets or /petChoose or hide a terminal pet.
/voice or /voice settingsStart or stop voice, or open voice settings. Choose microphone, speaker, and input channels where supported; device preferences are saved locally.
/warningsReview retained warnings and diagnostic details. Closing the viewer dismisses reviewed warnings; press k to keep one for later.

Codex TUI Shortcuts and Controls

ShortcutUse
@Open the mentions menu for files, plugins, skills, and other Codex tasks.
Tab while Codex is workingQueue a prompt, slash command, or shell command for the next turn.
Enter while Codex is workingSend a new instruction to steer the active turn. Instant steering can interrupt a model response or a long code-mode call when enabled by the session.
Esc twice with an empty composerEdit the previous user message and fork from that point.
. in Vim modeRepeat the last edit.
u in Vim modeUndo the last edit.
/ or ? in Vim modeSearch within the current draft; use n or N to move between matches.
Ctrl+CStop or exit according to the current TUI state.
Ctrl+RSearch prompt history; in Vim mode, redo the last change.
Ctrl+OCopy the latest completed output.
Ctrl+InsertCopy the selected transcript text.
p in the agent Command CenterPin a task in the shared Pinned group when the connected server supports pinning.
Show more in the agent Command CenterLoad older tasks through the keyboard-accessible history action.
Middle-click in fullscreen mode on supported local Linux X11 terminalsPaste the primary selection.

Global Codex CLI Flags

Global flags apply to the base codex command and supported runtime subcommands. Check codex <subcommand> --help before assuming that every global flag propagates.

FlagUse
--add-dir <PATH>Grant write access to another directory. Repeat for multiple paths.
--ask-for-approval, -a <POLICY>Set approval behavior: untrusted, on-request, or never.
--cd, -C <PATH>Set the working directory before Codex starts.
--config, -c key=valueOverride one config value for the current invocation.
--dangerously-bypass-approvals-and-sandbox or --yoloDisable approvals and sandboxing. Use only inside an externally isolated environment.
--dangerously-bypass-hook-trustRun enabled hooks without persisted hook trust for the current invocation.
--disable <FEATURE>Disable a feature flag for one run.
--enable <FEATURE>Enable a feature flag for one run.
--image, -i <PATH[,PATH...]>Attach one or more images to the initial prompt.
--local-provider <lmstudio|ollama>Choose the local provider used with --oss.
--model, -m <MODEL_ID>Override the configured model for one run, for example codex -m gpt-6.1-sol.
--no-alt-screenDisable alternate-screen TUI mode.
--ossUse a configured local open-source model provider.
--profile, -p <NAME>Layer $CODEX_HOME/NAME.config.toml over the base user config.
--remote <ENDPOINT>Connect the CLI to a remote app-server endpoint.
--remote-auth-token-env <ENV_VAR>Read the bearer token used for a secure remote app-server connection.
--sandbox, -s <MODE>Select read-only, workspace-write, or danger-full-access.
--searchEnable live web search for the run.
--strict-configFail when the installed version does not recognize fields in config.toml.
PROMPTOptional initial instruction for the TUI.

codex exec Flags

Use codex exec for scripts, CI jobs, and tasks that should finish without an interactive TUI.

OptionUse
--cd, -C <PATH>Set the workspace root.
--color <always|never|auto>Control ANSI color in output.
--ephemeralRun without saving session rollout files.
--ignore-rulesSkip user and project execpolicy rule files.
--ignore-user-configIgnore $CODEX_HOME/config.toml while retaining authentication state.
--image, -i <PATH>Attach one or more images to the first message.
--jsonEmit newline-delimited JSON events.
--model, -m <MODEL_ID>Override the model for the run.
--output-last-message, -o <PATH>Write the final assistant message to a file.
--output-schema <PATH>Validate the final response against a JSON Schema.
--profile, -p <NAME>Load a named profile file.
--sandbox, -s <MODE>Set the sandbox for generated commands.
--skip-git-repo-checkAllow a run outside a Git repository.
codex exec resume [SESSION_ID] --last --allResume a previous exec session by ID or choose the latest eligible session.
PROMPT or -Pass the task as text or read it from stdin.
--full-autoDeprecated compatibility flag. Prefer explicit sandbox and approval settings.
--cyber-access-program <PROGRAM>Select standard, daybreak-blue, or daybreak-red for the run. The override does not change your saved choice and works independently of the cli_daybreak feature flag. Daybreak programs require approved access; this option is not supported with review.

Codex Configuration Keys

Codex stores user settings in $CODEX_HOME/config.toml. The default path is ~/.codex/config.toml.

Config keyUse
model = "<MODEL_ID>"Set the default model.
model_reasoning_effort = "medium"Set the default reasoning effort.
model_reasoning_summary = "auto"Control reasoning-summary behavior.
model_verbosity = "medium"Set response verbosity.
model_provider = "openai"Select the configured model provider.
oss_provider = "ollama"Choose the provider used by --oss.
sandbox_mode = "workspace-write"Persist the default sandbox mode.
sandbox_workspace_write.writable_roots = ["/path"]Add writable roots in workspace-write mode.
sandbox_workspace_write.network_access = trueAllow outbound network access in workspace-write mode.
approval_policy = "on-request"Persist approval behavior with untrusted, on-request, or never.
approvals_reviewer = "auto_review"Route eligible approval requests to automatic review. Use "user" for manual approval.
web_search = "live"Use live web search instead of the default cached mode.
history.persistence = "none"Disable transcript persistence in history.jsonl.
history.max_bytes = 10485760Cap saved history size and discard the oldest entries when the cap is exceeded.
hide_agent_reasoning = trueSuppress reasoning events in TUI and exec output.
check_for_update_on_startup = falseDisable startup update checks when updates are centrally managed.
cli_auth_credentials_store = "auto"Choose file, OS keyring, or automatic credential storage.
tui.alternate_screen = "auto"Control alternate-screen mode.
tui.status_line = ["model", "context"]Choose and order footer fields.
tui.keymap.<context>.<action> = "ctrl-a"Bind a TUI action in a specific keymap context.
tui.auto_recap = falseDisable automatic recaps while keeping manual /recap.
tui.disable_paste_burst = trueDisable burst-paste detection in the TUI; the top-level key remains a fallback.
tools.update_plan.enabled = trueEnable the planning tool when it is disabled by default.
features.context_management.experimental_mode = trueEnable experimental token-budget context management and history notes for eligible ChatGPT sessions.
mcp_servers.<id>.command = "node"Define a stdio MCP launcher command.
mcp_servers.<id>.args = ["server.js"]Define arguments for a stdio MCP server.
mcp_servers.<id>.url = "https://example.com/mcp"Define a streamable HTTP MCP endpoint.
mcp_servers.<id>.bearer_token_env_var = "MCP_TOKEN"Read an HTTP bearer token from an environment variable.
mcp_servers.<id>.enabled = falseDisable an MCP server without deleting its config.
mcp_servers.<id>.tools.<tool>.output_token_limit = <N>Set an output-token budget for one MCP tool.
hooks and hooks.<Event>Configure lifecycle hooks, including the Interrupt event.
model_context_window = <TOKENS>Set the context budget for the active model. Stay within the model’s supported window; provider and server defaults can differ from the bundled catalog.
model_auto_compact_token_limit = <TOKENS>Set the token threshold that triggers automatic context compaction.
service_tier = "fast"Request Fast mode for a model that supports it. Available speed tiers depend on the model catalog, account, workspace, and feature settings.
tui.mouse_scroll_speed = 1.0Set the transcript mouse-wheel multiplier. Positive values below 1.0 slow scrolling; values above 1.0 speed it up.
features.cli_daybreak = trueOpt in to Daybreak controls and eligible automatic Cyber routing. Setting daybreak = true alone does not enable this feature.
features.instant_interrupt = trueEnable experimental immediate steering during model responses and long code-mode calls. Explicit configuration controls the feature even when a rollout changes its default.
model_providers.<id>.capabilities.external_web_access = trueDeclare live hosted web-search support for a custom Responses-compatible provider. The provider must implement that capability.
model_providers.<id>.capabilities.remote_compaction = "v2"Use the provider’s Responses-based remote compaction protocol. Use "unsupported" for local compaction; omission keeps provider defaults.

Sandbox Modes and Approval Policies

Sandboxing limits what generated shell commands can access. Approval policy controls when Codex pauses and asks before an action. Set both controls explicitly in automation. Approved filesystem escalation can grant broader write access while explicit read denials and network restrictions continue to apply. Codex protects .aws directories inside writable roots by default.

Sandbox modeAccess and typical use
read-onlyRead project files. File writes are blocked. Network access is restricted by policy. Use for repository explanations, audits, and reviews that should not edit files.
workspace-writeWrite within the workspace and configured writable roots. Network access is off unless enabled in config. Use for normal coding, fixes, refactoring, and test-driven edits.
danger-full-accessNo Codex filesystem sandbox. Network access follows host environment controls. Reserve for externally isolated containers or runners.

With ChatGPT sign-in, Auto-review evaluates eligible approval requests without consuming plan usage. Enable it through /permissions and Approve for me, or set approvals_reviewer = "auto_review". Auto-review checks the proposed action against your instructions and permissions. Use /approve to request a one-time retry after a denial.

Approval policyBehavior and typical use
untrustedPrompts for commands that do not match trusted rules. Use for high-control interactive work.
on-requestCodex can request approval for broader access. Use for normal interactive coding.
neverCodex does not open approval prompts. Blocked actions fail. Use for non-interactive automation with an appropriate sandbox.
Granular approval tableControls sandbox escalation, rules, MCP elicitations, permission requests, and skill approvals. Intended for managed or advanced environments.

Do not treat --yolo as a faster form of workspace-write. It disables both sandboxing and approvals. Use --add-dir, writable roots, or a narrower approval policy before removing isolation.

MCP Commands

MCP server definitions are stored in ~/.codex/config.toml unless CODEX_HOME changes the config location. Package-style server names may include :, @, /, and ..

CommandUse
codex mcp listList configured MCP servers. Add --json for machine-readable output.
codex mcp get <NAME>Show one server definition. Add --json for raw config output.
codex mcp add <NAME> -- <COMMAND...>Register a stdio MCP server.
codex mcp add <NAME> --env KEY=VALUE -- <COMMAND...>Pass environment variables to a stdio server.
codex mcp add <NAME> --url https://example.com/mcpRegister a streamable HTTP MCP server.
codex mcp add <NAME> --url https://example.com/mcp --bearer-token-env-var MCP_TOKENRead an HTTP bearer token from an environment variable.
codex mcp add <NAME> --url ... --oauth-client-id <ID> --oauth-resource <RESOURCE>Register OAuth client metadata for an HTTP server.
codex mcp login <NAME> --scopes scope1,scope2Start OAuth login with optional scopes.
codex mcp logout <NAME>Remove stored OAuth credentials.
codex mcp remove <NAME>Delete a server definition.
codex mcp-serverDeprecated. Older command for exposing Codex over MCP.
/mcp or /mcp verboseInspect connected MCP servers and tools inside the TUI.
/mcp login <NAME>Authenticate an MCP server inside an active terminal session.

Cloud and Plugin Commands

CommandUse
codex cloud or codex cloud-tasksOpen the interactive cloud task picker.
codex cloud exec --env <ENV_ID> [--attempts <1-4>] "TASK"Submit a cloud task directly with an optional retry limit.
codex cloud list [--limit <N>] [--cursor <CURSOR>] [--env <ENV_ID>] --jsonList recent cloud chats with JSON output and optional pagination or environment filtering.
codex plugin list [--available] --jsonList installed plugins or include available plugin metadata from configured or remote marketplaces.
codex plugin add <PLUGIN[@MARKETPLACE]> --jsonInstall a plugin from a configured or remote marketplace.
codex plugin remove <PLUGIN[@MARKETPLACE]> --jsonRemove an installed plugin.
codex plugin marketplace list --jsonList marketplace sources.
codex plugin marketplace add <SOURCE> [--ref <REF>] [--sparse] --jsonAdd a Git or local marketplace source and optionally return JSON.
codex plugin marketplace upgrade [NAME] --jsonRefresh one Git marketplace or all configured Git marketplaces.
codex plugin marketplace remove <NAME> --jsonRemove a configured marketplace.

Environment Variables

Use environment variables for shell-scoped state, installer behavior, authentication secrets, network certificates, and diagnostics. Use config.toml for durable preferences.

VariableUse
CODEX_HOMESet the root directory for config, auth, logs, sessions, skills, and package metadata.
CODEX_SQLITE_HOMESet the location for SQLite-backed state. The sqlite_home config key takes precedence.
CODEX_NON_INTERACTIVESkip prompts in the standalone installer when set to 1, true, or yes.
CODEX_INSTALL_DIRChange where the standalone installer places the visible codex command.
CODEX_API_KEYProvide an API key for a single codex exec run.
CODEX_ACCESS_TOKENProvide an access token for trusted automation or pipe it to codex login --with-access-token.
CODEX_CA_CERTIFICATEPoint HTTPS, login, and WebSocket clients at a custom PEM CA bundle.
SSL_CERT_FILEFallback custom CA bundle when CODEX_CA_CERTIFICATE is unset.
RUST_LOGControl Rust log filtering and verbosity for CLI and app-server diagnostics.
Provider-specific env_keyName the environment variable that stores a custom provider API key.

Pipe OPENAI_API_KEY into codex login --with-api-key to store API-key authentication. The standard codex login command opens the ChatGPT sign-in flow. Credential storage follows cli_auth_credentials_store; credentials can be stored in an OS keyring or a file.

Experimental, Deprecated, and Changed Commands

Command or syntaxNotes
codex app-server [--stdio|--listen <URL>]Start the experimental app-server. Stdio JSONL is the default; use --listen ws://... or --listen unix://... for other transports.
codex cloudExperimental cloud interface with picker, cloud exec, and cloud list commands.
codex debug ...Experimental commands for model catalog, prompt input, and app-server debugging.
codex execpolicyExperimental command for testing execpolicy rules.
codex sandbox ... --permission-profile <NAME>Run sandbox commands with a named permissions profile on supported platforms.
codex remote-controlExperimental app-server remote control. Use codex remote-control pair for a short-lived manual pairing code or add --json for machine-readable output.
--full-autoDeprecated compatibility flag. Use explicit --sandbox and approval settings.
--experimental-jsonLegacy alias. Use --json.
codex --upgradeOutdated syntax. Use codex update.
codex cloud status, cloud diff, cloud applyOutdated cloud syntax. Use codex cloud, codex cloud exec, codex cloud list, and codex apply <TASK_ID>.
/approvals and /cleanOlder aliases. Use /permissions and /stop.
codex --enable cli_daybreakExpose opt-in Daybreak controls. Without this flag or features.cli_daybreak = true, /daybreak and automatic routing are hidden, including in saved Daybreak threads. Saved preferences are retained.
codex --enable instant_interruptEnable experimental immediate steering for this launch. Availability and default state depend on the session and rollout.
/personalityRemoved from the current stable TUI. Put communication preferences in your instructions.
/agentUse /agents for the task Command Center or /subagents for delegated-agent threads.
/sandbox-add-read-dirAbsent from the current stable command list. Configure additional read access through your environment’s permission settings.
tui.prompt_suggestionsRemoved with automatic follow-up suggestions in the TUI. Desktop composer predictions are a separate feature.

Codex CLI Command Examples

Start Codex in an Existing Repository

Open the repository root before starting Codex. The session can then read project files, Git state, and local instructions.

cd /path/to/project
codex

Create Repository Instructions

Generate an AGENTS.md scaffold, then add the project’s build commands, test commands, code conventions, directory rules, and review requirements.

codex
/init

Understand an Unfamiliar Codebase

Use read-only mode to map the application before making changes. Ask for entry points, major modules, data flow, build commands, tests, and areas tied to the task.

codex --sandbox read-only "Map this codebase. Explain the entry points, major modules, data flow, build commands, test setup, and files related to authentication."

Plan a Change Before Editing Files

Switch to plan mode for migrations, cross-file features, architectural changes, and tasks that need an agreed implementation sequence before code changes begin.

codex
/plan Add rate limiting to the public API without changing existing client behavior. Identify affected files, tests, migration risks, and the implementation order.

Implement a Feature and Run Its Tests

Give Codex a bounded feature request, name the expected behavior, require existing project patterns, and ask it to run the relevant tests before reporting completion.

codex --sandbox workspace-write --ask-for-approval on-request "Implement user profile editing. Follow existing patterns, validate input, update affected tests, run the relevant checks, and summarize the changed files."

Diagnose and Fix a Failing Test

Ask Codex to reproduce the failure first, identify the root cause, make the smallest safe correction, and rerun the affected test set.

codex --sandbox workspace-write --ask-for-approval on-request "Run the failing test, identify the root cause, make the smallest safe fix, rerun the affected tests, and explain why the failure occurred."

Fix a Bug From an Error Message or Stack Trace

Include the observed error, reproduction path, and expected behavior. Ask Codex to trace the relevant code path, reproduce the defect, patch it, and add a regression test.

codex --sandbox workspace-write "Reproduce the null-reference error shown below, trace its source, fix it without changing the public API, add a regression test, and run the affected test suite.
PASTE_ERROR_OR_STACK_TRACE_HERE"

Refactor Code Without Changing Behavior

State the boundary of the refactor and require tests before and after the change. This keeps Codex focused on structure rather than new behavior.

codex --sandbox workspace-write --ask-for-approval on-request "Refactor src/auth to remove duplication and clarify responsibilities. Preserve the public API and runtime behavior. Run the existing auth tests before and after the change."

Add Tests for Existing Code

Point Codex at a module or changed behavior. Request tests for successful paths, failures, boundary cases, and regressions instead of a target percentage.

codex --sandbox workspace-write "Review src/parser and its current tests. Add focused tests for boundary inputs, malformed data, and the recent regression. Run only the parser test suite."

Upgrade a Dependency and Resolve Breakages

Use a narrow upgrade request that names the package, target version, affected APIs, lockfile expectations, and verification commands.

codex --sandbox workspace-write --ask-for-approval on-request "Upgrade PACKAGE_NAME to TARGET_VERSION. Update changed APIs, preserve existing behavior, refresh the lockfile, run lint and tests, and list any unresolved migration issues."

Review Uncommitted Changes Inside the TUI

Inspect the exact working-tree diff, then run Codex review mode to find behavior changes, regressions, missing tests, and implementation risks before committing.

/diff
/review

Review a Branch Against Main

Run a non-interactive branch review from the shell when you want Codex to inspect the full diff against the base branch without opening the TUI.

codex review --base main

Draft a Commit Summary From the Current Diff

Use read-only mode to summarize the actual diff and produce a concise commit title and body without changing the working tree.

codex --sandbox read-only "Inspect the current git diff. Draft a concise conventional commit title and a short body that explains the behavior change and tests."

Resume Work From the Previous Session

Resume the most recent session in the current repository when the earlier chat already contains the plan, decisions, and implementation context.

codex resume --last

Run a One-Off Task Without Opening the TUI

Use codex exec for a bounded task that should finish in the shell, such as updating generated files, applying a repetitive edit, or checking a package.

codex exec --sandbox workspace-write "Update the generated API client, run its tests, and summarize the changed files and any remaining errors."

Capture Machine-Readable Output for Automation

Use JSONL output for scripts or CI jobs, and save the final response separately for later steps or build artifacts.

codex exec --sandbox workspace-write --json --output-last-message codex-report.md "Run lint and tests without editing files. Report each failure, its likely cause, and the command that failed."

Debug a Frontend Issue From a Screenshot

Attach a screenshot when a visual defect is easier to identify from the rendered result than from a written description.

codex --image screenshot.png --sandbox workspace-write "Find the layout issue shown in this screenshot, inspect the relevant components and styles, fix the defect, and run the frontend checks."

FAQs

What is the difference between Codex CLI and slash commands?

Run a CLI command such as codex review from your shell. Enter a slash command such as /review inside an active Codex terminal session.

How do I find the commands available in my Codex CLI version?

Run codex --version and codex --help. Use codex <subcommand> --help to check subcommand flags. Inside the interactive terminal UI, type / to open the command list.

How do I run Codex commands in scripts or CI?

Use codex exec "TASK" for non-interactive runs. The --json flag emits JSONL events, and --output-last-message saves the final answer to a file. Set sandbox permissions explicitly for automation.

How do I change a Codex setting for only one command?

Use codex -c key=value to override a configuration value for that invocation. Persistent settings belong in $CODEX_HOME/config.toml.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest & top AI tools sent directly to your email.

Subscribe now to explore the latest & top AI tools and resources, all in one convenient newsletter. No spam, we promise!