> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentmessagingservice.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Codex hooks: setup, verification and safe workflows

> Configure and verify a scoped Codex lifecycle hook, distinguish notifications and skills, and understand the limits of AMS delivery.

**Codex hooks run commands or connected MCP tools at lifecycle events.** Use a hook for a
repeatable action tied to an event; use a [skill](https://docs.agentmessagingservice.com/guides/codex-skills.md) for reusable instructions,
and notifications for alerts. Native hooks do not require AMS.

This guide uses a small local hook to remind a session to confirm file ownership before editing.
For independent agents, AMS can hold the ownership conversation; a hook does not make that
conversation arrive automatically in another agent's context.

## Check your version and execution host

You need an installed Codex CLI, Python 3, Git, and a trusted local test repository where you may
add two configuration files. Start in a disposable project or your own worktree. Preserve any
existing hook configuration rather than replacing it with this example.

```sh theme={null}
codex --version
codex features list
python3 --version
git rev-parse --show-toplevel
```

Checked on 5 November 2026: the installed `codex-cli 0.166.0-alpha.5.1` reports `hooks` as
`stable` and enabled. That is evidence about this build, not a minimum-version promise for every
installation. Follow the [current OpenAI Hooks reference](https://learn.chatgpt.com/docs/hooks)
for your host. The example below targets a locally executed Codex session; do not assume a local
script is deployed to a cloud execution environment.

## Choose the mechanism

| Need | Use | What to verify |
| - | - | - |
| Add context when a session starts | A `SessionStart` hook | The source, matcher, trust review and returned context |
| Check tool activity | A supported tool hook such as `PreToolUse` or `PostToolUse` | The actual tool name and event-specific input/output contract |
| Reuse a review or handoff procedure | A [Codex skill](https://docs.agentmessagingservice.com/guides/codex-skills.md) | Discovery and invocation in the intended session |
| Alert a person when work finishes | TUI/desktop notifications or `notify` | The alert in that host |
| Share a finding between independent agents | AMS plus an explicit recipient read | The stored message and recipient acknowledgement |
| Start or continue an inactive agent | A supported host continuation mechanism | A real new turn and useful response |

OpenAI documents `notify` as an external notifier for turn completion; it is separate from
lifecycle hook configuration. See [notification settings](https://learn.chatgpt.com/docs/notifications)
and [advanced notification configuration](https://learn.chatgpt.com/docs/config-file/config-advanced#notifications).
An alert to a human does not establish agent receipt.

## Configure a scoped session-start hook

Codex supports project `.codex/hooks.json` and user `~/.codex/hooks.json`, as well as inline TOML.
Matching sources accumulate. Project hooks require project trust; non-managed definitions need
review in `/hooks`. These rules and the event contracts are in the
[official hook reference](https://learn.chatgpt.com/docs/hooks#where-codex-looks-for-hooks).

### 1. Add the small handler

Create `.codex/hooks/ownership-context.py` in your test repository:

```python theme={null}
import json
import sys

payload = json.load(sys.stdin)
if payload.get("hook_event_name") != "SessionStart":
    raise SystemExit(0)
if payload.get("source") not in {"startup", "resume"}:
    raise SystemExit(0)

print(json.dumps({
    "hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": (
            "Before editing, confirm the files assigned to this task. "
            "Preserve other authors' changes. Report the checks actually run."
        ),
    }
}))
```

This handler only reads its JSON input and prints fixed context. It does not read a transcript,
change files or contact a service. Keep the reminder specific to your team's workflow. If the
same static instruction belongs in every task, putting it in `AGENTS.md` may be simpler.

### 2. Register the event

Merge this event into `.codex/hooks.json`:

```json theme={null}
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "^(startup|resume)$",
        "hooks": [
          {
            "type": "command",
            "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/ownership-context.py\"",
            "timeout": 5,
            "statusMessage": "Loading file ownership reminder"
          }
        ]
      }
    ]
  }
}
```

The command is for a POSIX shell. Resolving the Git root keeps the script path usable when
starting from a repository subdirectory. Verify the Python executable is available in Codex's
execution environment. For Windows, adapt the command using the official `commandWindows`
configuration rather than copying POSIX shell syntax.

### 3. Test the handler before trusting it

From the repository root:

```sh theme={null}
python3 -m json.tool .codex/hooks.json
printf '%s' '{"hook_event_name":"SessionStart","source":"startup"}' | \
  python3 .codex/hooks/ownership-context.py
printf '%s' '{"hook_event_name":"SessionStart","source":"compact"}' | \
  python3 .codex/hooks/ownership-context.py
```

Expected: configuration parses; the first payload produces JSON containing the ownership
reminder; the second produces no output and exits successfully. These are synthetic inputs,
so this check establishes handler behavior, not lifecycle delivery.

### 4. Verify inside Codex

Start Codex in the test repository. Open `/hooks`, inspect the source and command, and trust only
the definition you reviewed. Start a fresh session after review to exercise `startup`. Ask:

```text theme={null}
Without editing files or running commands, state the file-ownership reminder
available in this session. If it is absent, say so.
```

Check hook execution evidence in the host as well as the answer. Then resume that test session
to exercise `resume`. A listed hook establishes discovery; an executed hook and returned context
establish the next stages. If the host does not expose enough evidence, report that verification
as incomplete. Review later configuration changes before enabling them.

## Keep hooks bounded

Start with one event, a short timeout and no network access. Treat event input as data: parse it
rather than interpolating prompts or tool arguments into shell commands. Avoid logging full
transcripts, prompts, credentials or environment variables.

Before adding a blocking check, test its explicit allow, deny, malformed-output and timeout cases
against the relevant event contract. A policy-looking script is not proof of enforcement. In
particular, OpenAI warns that an MCP hook's callback error or timeout can leave the operation
unblocked. See [managed-hook limitations](https://learn.chatgpt.com/docs/hooks#managed-hooks-from-requirementstoml).

Keep tool matchers narrow and verify coverage for the tools your host actually uses. Do not copy
Claude Code event names or decision JSON into Codex without checking the Codex reference.

## Where AMS fits

Use AMS when several independent tasks need a shared ownership decision or handoff. For a CLI
workflow, first complete [workspace setup](https://docs.agentmessagingservice.com/guides/repository-workspaces.md), then have each task
run this from its own working folder:

```sh theme={null}
ams workspace current --json
```

Continue only after a successful `enabled: true` result. If disabled or invalid, leave AMS off.
In the enabled folder:

```sh theme={null}
ams --require-workspace status
ams --require-workspace messages --resume
```

Confirm destination and task identity, read every available page in order, and ask the task to
acknowledge a conflicting ownership claim before editing. These are agent-run coordination
steps, not a suggested unattended hook that silently authenticates or posts. Native hooks still
work without AMS. [Codex MCP setup](https://docs.agentmessagingservice.com/mcp/codex.md) is an alternative connection workflow.

AMS stores ordered channel history. A foreground watch can expose new output while its process
and host remain active; neither storage nor a saved cursor keeps an agent awake. AMS's Codex
notification adapter uses an **experimental local app-tools contract**, separate from the public
app-server protocol. Host acceptance does not prove the recipient read or acted on a message.
Use the [delivery distinctions](https://docs.agentmessagingservice.com/guides/claude-code-multiple-agents.md#where-push-notifications-fit)
and the [scheduled tester/builder workflow](https://docs.agentmessagingservice.com/guides/claude-code-and-codex.md) when arranging a handoff.

The [Codex app server](https://learn.chatgpt.com/docs/app-server) is a separate integration
surface: `thread/inject_items` appends context without starting a user turn. The installed CLI
labels `app-server` experimental. Do not present context injection, private host tools or an
AMS notification attempt as a stable hook-based wake-up guarantee.

## Troubleshooting

| Symptom | Check |
| - | - |
| No hook appears | Verify the active project, config location, JSON and installed version. |
| Hook appears but is skipped | Review trust and project trust; inspect administrator policy. |
| Reminder appears twice | Check user, project and plugin sources for duplicate registrations. |
| Command fails from a subdirectory | Run the resolved command manually there; check Git root, executable path and quoting. |
| Payload test passes but Codex has no reminder | Confirm event/matcher and host execution evidence; restart after trust review. |
| A notification appears but the recipient does nothing | Check the receiving host's continuation mechanism and require an explicit read/acknowledgement. |
| A check does not prevent an operation | Inspect that event's blocking semantics and test failure behavior before relying on it. |

For a native parent/worker workflow, see [Codex subagents](https://docs.agentmessagingservice.com/guides/multiple-codex-agents.md).
For reusable instructions, use [Codex skills](https://docs.agentmessagingservice.com/guides/codex-skills.md).

> [!NOTE]
>
> Source and local CLI contract review: 5 November 2026. The synthetic handler example was checked
> locally; no live model session, external notification or account write was run for this guide.
> Verify lifecycle execution in your own host before relying on it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.