GuidesRunning & maintaining

Codex hooks: events, hooks.json, exit codes and trust

Every Codex CLI hook event and when it fires, hooks.json or [hooks] in config.toml, the JSON input, exit 2 and deny, /hooks trust, codex exec and notify.

November 23, 2026The Everpod team
The short answer

Codex hooks are commands Codex runs at fixed points in a session: when it starts or ends, when you send a prompt, before and after most tool calls, when it is about to ask for approval, when a turn stops, around compaction and around each model request. Put them in ~/.codex/hooks.json, or under [hooks] in ~/.codex/config.toml; a repository’s .codex/hooks.json loads only once you trust the project. Each command gets the event as one JSON object on standard input. On PreToolUse, exit 2 with a reason on standard error, or print a permissionDecision of "deny", and the call is blocked; exit 0 with no output and Codex carries on. A hook you add runs only after you trust it, at the review prompt Codex shows on startup or in /hooks, and editing it sends it back for review. Hooks are on by default. As of Codex CLI 0.171.0, November 2026.

A first hook: refuse force-pushes

A hook is two pieces: a script, and an entry that says which event runs it. This one refuses the usual force-push and hard-reset commands. It needs jq. This script and the Stop hook further down are examples written to the contract OpenAI documents; try each once and watch it act before you rely on it. Save it as ~/.codex/hooks/guard.sh and run chmod +x on it:

#!/usr/bin/env bash
# PreToolUse: refuse force-pushes and hard resets; let everything else through.
# Without jq this would let everything through, so refuse instead.
command -v jq >/dev/null || { echo "guard.sh needs jq" >&2; exit 2; }
cmd=$(jq -r '.tool_input.command // empty')
if printf '%s' "$cmd" | grep -Eq 'git[[:space:]]+push.*(--force|[[:space:]]-f)|git[[:space:]]+reset.*--hard'; then
  echo "force-push and hard reset are blocked by a hook; ask the user to run it" >&2
  exit 2
fi
exit 0
Copied

Then register it in ~/.codex/hooks.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "~/.codex/hooks/guard.sh",
            "statusMessage": "Checking command"
          }
        ]
      }
    ]
  }
}
Copied

Start codex. Because the hook is new, Codex opens a Hooks need review prompt first, warning that “Hooks can run outside the sandbox after you trust them,” with three choices: Review hooks, Trust all and continue, or Continue without trusting (hooks won’t run). Once it is trusted, a matching command never reaches the shell; in the 0.171.0 source the model gets Command blocked by PreToolUse hook: <your reason>. Command: <the command> as the tool’s result and can tell you why. The match is on text, so a command the patterns don’t cover goes through. OpenAI’s own framing in the hooks documentation: “Treat tool hooks as a useful guardrail, not a complete enforcement boundary.”

Every event, and when it fires

Codex 0.171.0 has fourteen events. The matcher column is what a group’s matcher is compared against; where it says “ignored”, every hook on that event runs.

EventFiresMatcherWhat the hook can do
SessionStart
A session starts, resumes, is cleared, is compacted or is forkedstartup, resume, clear, compact, forkAdd context for the model (plain output counts)
UserPromptSubmit
You send a prompt, before it goes to the modelIgnoredBlock the prompt, or add context (plain output counts)
PreToolUse
Before a shell command, an apply_patch edit, an MCP tool call or another local toolTool nameBlock the call, rewrite its input, or add context
PermissionRequest
Codex is about to ask you to approve somethingTool nameApprove or deny in your place, or leave it to you
PostToolUse
After a tool returns, including shell commands that exit non-zeroTool nameReplace the result with feedback; it can’t undo what ran
PreCompact, PostCompact
Before and after the conversation is compactedmanual, autoStop Codex before compacting, or after it
SubagentStart, SubagentStop
A subagent starts, or finishesSubagent typeAdd context for it; send it back for another pass
Stop
A turn endsIgnoredKeep Codex going with a new prompt
PreModelRequest, PostModelRequest
Before and after every model request attempt, retries includedNot supportedNothing: their output is diagnostic only
Interrupt
You interrupt a running turn on the main threadIgnoredNothing: record it or clean up, within 1 to 3 seconds
SessionEnd
An open conversation is archived or deleted, Codex closes normally, or a conversation sits idle and unopened for 30 minutesother (the only reason today)Nothing: it is advisory, and gets 1 to 3 seconds

Points that decide whether a tool hook fires at all:

Where hooks go: hooks.json or config.toml

ScopeFileLoads
User
~/.codex/hooks.json ($CODEX_HOME/hooks.json; on Windows %USERPROFILE%\.codex\hooks.json)In every project, trusted or not
Project
.codex/hooks.json in any .codex folder from the project root down to the working directoryOnly once the project is trusted
System
/etc/codex/hooks.json; on Windows %ProgramData%\OpenAI\Codex\hooks.jsonIn every project, trusted by policy with no review
Plugin
hooks/hooks.json inside the plugin, or the paths its manifest namesWhile the plugin is enabled
Managed
[hooks] in an administrator’s requirements.tomlTrusted by policy, with no review

Any directory that holds a hooks.json can instead carry the same hooks inline under [hooks] in its config.toml. The structure is the same three levels, event, matcher group, handlers:

# ~/.codex/config.toml: give every new or resumed session the git state
[[hooks.SessionStart]]
matcher = "startup|resume"

[[hooks.SessionStart.hooks]]
type = "command"
command = 'echo "Branch: $(git branch --show-current 2>/dev/null)"; git status --short 2>/dev/null | head -20'
statusMessage = "Reading git status"
Copied

On SessionStart, plain text on standard output is added to the model’s context, so that is the whole hook. The rules for combining files differ from what you might expect:

The rest of the file, its precedence and CODEX_HOME are in the config.toml guide. Hooks that ship inside a plugin follow the same rules, with one extra review step, covered in Codex plugins.

What a hook receives

Every command hook gets one JSON object on standard input. For a shell command on PreToolUse, its fields have this shape:

{
  "session_id": "<session id>",
  "turn_id": "<turn id>",
  "transcript_path": "<path to the transcript, or null>",
  "cwd": "/home/you/project",
  "hook_event_name": "PreToolUse",
  "model": "<model slug>",
  "permission_mode": "default",
  "tool_name": "Bash",
  "tool_use_id": "<call id>",
  "tool_input": { "command": "git push --force origin main" }
}
Copied

The event-specific fields are the ones you will read: tool_input.command (a string) for Bash and apply_patch, the arguments for MCP and other tools, tool_response on PostToolUse, prompt on UserPromptSubmit, source on SessionStart, and last_assistant_message with stop_hook_active on Stop. The docs list five possible values for permission_mode, but the 0.171.0 source sends bypassPermissions when approvals are set to never and default for every other policy. The transcript file is there for convenience; OpenAI says its format “isn’t a stable interface for hooks.”

How the command itself runs: through a shell, so ~, pipes and $(…) work, in the session’s working directory and with the session’s environment. Codex sets no variable naming the project root, and Codex may be started from a subfolder, so for a script kept in the repository OpenAI’s examples build the path from git: "$(git rev-parse --show-toplevel)/.codex/hooks/pre_tool_use_policy.py". Only plugin hooks get extra variables: PLUGIN_ROOT and PLUGIN_DATA, plus CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA with the same values, for existing plugins that read those names. On Windows, commandWindows (or command_windows in TOML) overrides the command.

Exit codes and output: what changes what Codex does

The hookWhat Codex does
Exits 0 and prints nothing
Carries on
Exits 0 and prints JSON
Applies the event’s JSON fields (below)
Exits 0 and prints plain text
Adds it as context on SessionStart, UserPromptSubmit and SubagentStart; ignores it on the tool and compaction events; treats it as invalid, and the run as failed, on Stop, SubagentStop and Interrupt
Exits 2 with a reason on standard error
On the events that can act on it: blocks the tool call or the prompt, denies the permission request, feeds the reason back after a tool, or sends a stopping turn or subagent back to work
Exits 2 with nothing on standard error
Marks the run failed and carries on; on PreToolUse the error is “PreToolUse hook exited with code 2 but did not write a blocking reason to stderr”
Exits 1 or any other code, times out, or can’t start
Marks the run failed (“hook exited with code 1”, “hook timed out after 600s”) and carries on

The last two rows are the ones that let a guardrail down. A PreToolUse hook that crashes, hangs past its timeout (600 seconds unless you set timeout) or exits 1 does not block, and in 0.171.0 a command hook has no setting to make a failure block: its fields are type, command, commandWindows, timeout, async, statusMessage and additionalContextLimit. Test a new gate once and watch it block.

The JSON each event takes, from the hooks reference:

Context a hook adds is capped at roughly 2,500 tokens per message; beyond that Codex saves the full text under <temp_dir>/hook_outputs/<session_id>/ and gives the model a preview with the path. additionalContextLimit on a handler changes the threshold, and since the overflow is written to disk, OpenAI warns against returning secrets in hook output. A handler with "async": true runs in the background, at most eight at a time per session, and “can’t block, approve, rewrite, or otherwise control the operation”; its context arrives at the next safe point.

Keep Codex working until the tests pass

The Stop event is how a hook refuses to let a turn end. This one runs the tests when Codex finishes and, if they fail, sends it back once with the failure. Replace npm test with your project’s command:

#!/usr/bin/env bash
# Stop: if the tests fail, send Codex back for one more pass.
input=$(cat)
# Already sent back once this turn: let it stop rather than loop.
[ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ] && exit 0
if ! npm test >/tmp/codex-tests.log 2>&1; then
  jq -n '{decision: "block", reason: "The tests fail; the output is in /tmp/codex-tests.log. Fix them, then finish."}'
fi
exit 0
Copied
"Stop": [
  {
    "hooks": [
      { "type": "command", "command": "~/.codex/hooks/tests-pass.sh", "timeout": 300 }
    ]
  }
]
Copied

Two details make it safe. Stop wants JSON or nothing on standard output, so the test run’s own output goes to a file. And stop_hook_active is true when “this turn was already continued by Stop”. That check is what keeps a suite Codex can’t fix from sending it round again and again; the docs describe no limit of Codex’s own.

Trusting hooks: /hooks and the review prompt

“Before a non-managed hook can run, Codex requires you to review and trust the exact hook definition.” Codex keeps a hash of each hook you trust, so a new or edited hook is skipped until you review it again, and a plugin hook needs a fresh review when an update changes its script even if the definition is unchanged. At startup Codex shows the review prompt described above whenever hooks are waiting. Later, /hooks opens a browser listing each event with how many hooks are installed, active and waiting for review; from there you can read a hook’s command and source, trust it, or switch a single hook off. In the ChatGPT desktop app it is Review hooks in the composer or Settings > Hooks.

In the 0.171.0 source, your decisions are written to your user configuration under hooks.state, one trusted_hash per hook, and only your user configuration and the settings passed for the session are read for them: a repository can bring hooks but cannot mark them trusted. It also means the trust belongs to one account and one CODEX_HOME. Hooks from requirements.toml and other managed sources are trusted by policy and can’t be switched off from /hooks; an administrator can also set allow_managed_hooks_only = true to ignore everyone else’s.

Project hooks and codex exec

A repository’s hooks pass two gates. The first is project trust: Codex “loads hooks only from trusted project layers,” and since 0.169.0 that holds for codex exec too, even with --sandbox workspace-write: it ignores an untrusted project’s .codex/ folder, hooks included, until the project is trusted; codex exec --trust saves that trust from the command line. The warning it prints, and when not to pass --trust, are in the codex exec untrusted project configuration guide. The second gate is hook trust, and codex exec has no review prompt to grant it. Two ways through:

A skipped hook is easy to miss. Two reports were still open on November 23, 2026: openai/codex#61741, where exec shows hooks skipped for trust only as hook: SessionStart Failed with no reason, and openai/codex#46210, where a SessionStart hook is skipped “with no diagnostic.” Before relying on a hook in a scheduled job, prove it fires with one that leaves a mark, kept in the same file as the hooks you rely on so it passes the same project gate; trust is still per hook, so trust it along with them:

[[hooks.SessionStart]]
[[hooks.SessionStart.hooks]]
type = "command"
command = "date >> /tmp/codex-hooks-fired"
Copied

Notifications: notify, a Stop hook, or the terminal

Codex has no Notification event, so “tell me when it’s done” takes one of three routes.

A working script that sends a phone notification from notify, and why terminal alerts go nowhere on a server you have disconnected from, are in notifications from Claude Code and Codex.

Codex hooks and Claude Code hooks

Codex’s hooks follow Claude Code’s closely: the same event names where they overlap, JSON on standard input in the same shape (Codex adds fields such as model and turn_id), the same permissionDecision output and the same exit-2 rule, and Codex’s /import brings Claude Code hooks over as Codex hooks (OpenAI lists “Hooks whose behavior may differ after import” among what to review afterwards). Where they part, as of Codex 0.171.0 and Claude Code 2.1.330:

CodexClaude Code
Configured in
hooks.json or [hooks] in config.toml, under ~/.codex or .codexsettings.json, under ~/.claude or .claude
Before a hook runs
You trust each hook, and again after every changeYou trust the folder; in claude -p the folder counts as trusted
Handler types that run
command, mcp_toolcommand, http, mcp_tool, prompt, agent
A gate that crashes or times out
The call goes ahead; no setting changes thatThe call goes ahead unless the hook sets onFailure: "block"
Project root in a command
No variable; use $(git rev-parse --show-toplevel)$CLAUDE_PROJECT_DIR
The same hook in two files
Can run twiceRuns once
Events only one has
Interrupt, PreModelRequest, PostModelRequestNotification, PostToolUseFailure, FileChanged and many more

The Claude Code side in depth, including a guardrail script tested in both agents, is in Claude Code hooks.

Run Codex on an always-on developer pod.

A developer pod is a permanent cloud computer (VPS), set up and secured for you, with your pick of Claude Code, Codex, OpenCode, Pi, Hermes and OpenClaw installed. Run more agents at once than your laptop can hold, and keep them working when it’s closed. From $24 a month, built in about ten minutes.