# Codex - Docs Note

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/codex-docs-note/>). I am continuously working to improve the translation.

# Preface

Until now, I've been living like a caveman—never having used any Agent other than Copilot. To avoid falling behind the times, I subscribed to ChatGPT Plus<del>definitely not because I can't afford Claude Code</del> to use the latest and hottest Codex. In this note, I'll record some of the workflows for developing with Agents that I learned from reading the official Codex documentation.

Reading reference: [Codex | OpenAI Developers](https://developers.openai.com/codex)

# Some Concepts

### Threads

A thread refers to a single session: including the prompts and the subsequent model outputs and tool calls.

When Codex is working on a thread, that thread is "running"; multiple threads can run simultaneously.

As for best practices: for example, let Thread A write code, and open another Thread B to write tests, **making sure the two Threads modify different files**.

Threads can run locally or in the cloud:

- Local threads run in a Sandbox (this concept will be explained later)

- Cloud threads run in an isolated environment, where Codex does the following:

    - Clones the repository
    - Checks out the branch being worked on

    Cloud threads are very useful when you need to parallelize work.

All threads are stored in `~/.codex/threads/`:

```TEXT
~/.codex/threads/
 ├── thread_1/
 ├── thread_2/
 └── thread_3/
```

---

This concept isn't actually that easy to understand. I asked GPT a few times, and here's a summary of the answers I got:

```txt
Thread
 ├── Turn 1: Help me implement a login feature
 │    ├── Item: User message
 │    ├── Item: Codex's answer
 │    ├── Item: Run pytest
 │    └── Item: Modify login.py
 │
 ├── Turn 2: Add the tests too
 │    ├── Item: User message
 │    ├── Item: Modify test_login.py
 │    └── Item: Run the tests again
 │
 └── Turn 3: Update the README while you're at it
      ├── Item: User message
      └── Item: Modify README.md
```

You should think of a thread as **an independent task line**.

It can be compared to opening a separate PR on GitHub: a PR is a new branch, which can have many commits, and is finally merged into main.

> A Project can have multiple Threads; each Thread is a "continuous task session" (usually manifested as a chat)

## Customization

In Codex, customization is achieved through these mechanisms:

- `AGENTS.md`: shaping behavior patterns
- Memories: passing local context
- Skills: encapsulating repeatable processes
- MCP: connecting the Agent to systems beyond the local space
- Subagents

Below is a brief introduction to each of these parts.

## `AGENTS.md`

Write in it the rules you want Codex to follow every time in the codebase, such as Build-and-Test, Review expectations, specific Specs, directory descriptions, etc.

When the Agent does something wrong, correct it in `AGENTS.md` and ask the Agent to update it.

`AGENTS.md` is loaded with multiple levels of priority:

- `~/.codex/AGENTS.md`
- `repo-root/AGENTS.md`

The closer it is, the higher its priority.

### When to Update `AGENTS.md`

- Add rules when the same mistake is repeated
- Add guidance to help it read files correctly
- Use **automated** tools for checking
- **In GitHub**: In a pull request comment, tag `@codex` with a request (for example, `@codex add this to AGENTS.md`) to delegate the update to a cloud task. (Essentially, it adds the content from PR reviews into `AGENTS.md`)

Pair `AGENTS.md` with hooks, linters, and type-checkers to prevent errors.

### Layered Setup

```txt
repo/
 ├── AGENTS.md (global project rules)
 └── services/payments/
      └── AGENTS.override.md (special rules for the payments module)
```

Codex's loading rule: from global → searching downward all the way → stopping at the current directory. Whichever directory you start codex in, it loads up to that layer, and **will not keep searching downward**.

It's recommended to place the `override` as close to the actual working directory as possible.
## Skills

- Reusable capabilities that provide repeatable workflows
- Loaded by the Agent at runtime and visible to it

The composition of a skill, in a `my-skill/` folder:

- `SKILL.md`
- `scripts/`: optional
- `references/`: optional
- `assets/`: optional

An example of a `SKILL.md`:

```markdown
---
name: commit
description: Stage and commit changes in semantic groups. Use when the user wants to commit, organize commits, or clean up a branch before pushing.
---

1. Do not run `git add .`. Stage files in logical groups by purpose.
2. Group into separate commits: feat → test → docs → refactor → chore.
3. Write concise commit messages that match the change scope.
4. Keep each commit focused and reviewable.
```

Like `AGENTS.md`, skills are also divided into global and project-specific ones:

| Layer  | Global                | Repo                    |
| :----- | :-------------------- | :---------------------- |
| Skills | `$HOME/.codex/skills` | `.codex/skills` in repo |

> [!NOTE]
>
> How does Codex progressively use skills?
>
> - First reads metadata (`name`, `description`) for discovery
> - Only loads `SKILL.md` when a skill is selected
> - Only reads scripts or references when needed

Skills can be invoked explicitly, or implicitly by the agent itself.

- You can use `$skill-name` to explicitly invoke a skill
- Implicit invocation relies heavily on the `description`

### Creating a Skill

Invoke `$skill-creator`, then follow the Agent's guidance.

## MCP

Model Context Protocol

The standard capability for connecting Agents to external tools.

> Use MCP when Codex needs capabilities that live outside the local repo, such as issue trackers, design tools, browsers, or shared documentation systems.

### Skills + MCP together

Using the two together is highly efficient: skills define the operational process, while MCP connects the skills to external tools. (A skill defines the workflow and names the MCP tools to use)

## Sandbox

Simply put: a tool that restricts Codex's access permissions.

The implementation differs across operating systems, but the core idea remains the same.

For example, the most common Permissions:

- Default permissions
- Full access

are a manifestation of the Sandbox.

> [!TIP]
>
> Use `/permissions` in the CLI to switch modes during a session

As for the specific Sandbox settings, they are stored in `config.toml`. You can set specific key-value pairs in it to control permissions within the Sandbox.

Common sandbox modes:

- `read-only`
- `workspace-write`: the default mode
- `danger-full-access`: full permissions granted

Common approval policies:

- `untrusted`: asks before running commands not in the trusted set
- `on-request`: runs inside the sandbox by default, only asking when it needs to go beyond boundaries
- `never`: regardless of any approval policy

> If you need Codex to work across multiple directories, writable roots allow you to extend the locations it can modify without fully removing the sandbox. If you need a wider or narrower trust boundary, adjust the default sandbox mode and approval policy rather than relying on one-off exceptions.

## Subagents

- subagent workflow: a workflow that lets Codex run multiple Agents in parallel and consolidate the results
- subagent: an Agent launched by Codex to handle a specific task
- Agent thread: CLI thread for an agent, use `/agent` to inspect and switch

**Advantages of subagent workflows**: Simply put, the main session's context window is precious. If you fill the main session with dirty work like noisy intermediate results from running tests, reliability will degrade. (context pollution and context rot)  
Therefore, use a subagent workflow to move the grunt work out of the main session, letting subagents handle tasks like testing and log analysis. In the end, the subagents return a **summary** of their work.

### Custom Agents

Codex comes with the following built-in agents:

- `default`
- `worker`: focused on implementation and fixes
- `explorer`: focused on reading the codebase

If you need customization, you can add standalone `toml` files under `/.codex/agents`.

> #### Example: PR review
>
> Divide this work among three custom agents:
>
> - `pr_explorer`
> - `reviewer`
> - `docs_researcher`
>
> `.codex/agents/pr-explorer.toml`:
>
> ```toml
> name = "pr_explorer"
> description = "Read-only codebase explorer for gathering evidence before changes are proposed."
> model = "gpt-5.3-codex-spark"
> model_reasoning_effort = "medium"
> sandbox_mode = "read-only"
> developer_instructions = """
> Stay in exploration mode.
> Trace the real execution path, cite files and symbols, and avoid proposing fixes unless the parent agent asks for them.
> Prefer fast search and targeted file reads over broad scans.
> """
> ```
>
> `.codex/agents/reviewer.toml`:
>
> ```toml
> name = "reviewer"
> description = "PR reviewer focused on correctness, security, and missing tests."
> model = "gpt-5.4"
> model_reasoning_effort = "high"
> sandbox_mode = "read-only"
> developer_instructions = """
> Review code like an owner.
> Prioritize correctness, security, behavior regressions, and missing test coverage.
> Lead with concrete findings, include reproduction steps when possible, and avoid style-only comments unless they hide a real bug.
> """
> ```
>
> `.codex/agents/docs-researcher.toml`:
>
> ```toml
> name = "docs_researcher"
> description = "Documentation specialist that uses the docs MCP server to verify APIs and framework behavior."
> model = "gpt-5.4-mini"
> model_reasoning_effort = "medium"
> sandbox_mode = "read-only"
> developer_instructions = """
> Use the docs MCP server to confirm APIs, options, and version-specific behavior.
> Return concise answers with links or exact references when available.
> Do not make code changes.
> """
> 
> [mcp_servers.openaiDeveloperDocs]
> url = "https://developers.openai.com/mcp"
> ```
>
> The third subagent explicitly invokes MCP to read documentation.

### How to Use

Codex does not automatically generate subagents; they are only enabled when explicitly requested.

An example of a good prompt:

> Review this branch with parallel subagents. Spawn one subagent for security risks, one for test gaps, and one for maintainability. Wait for all three, then summarize the findings by category with file references.

For different agents, you can assign different **base models** and different **reasoning depths**.

## Models

Specified in `config.toml`:

```toml
model = "gpt-5.4"
```

In the Codex CLI, use `/model` to switch models.

# Using the Codex App

## Syncing with the IDE Extension

> If you have the Codex IDE extension installed in your editor, when your Codex app and the IDE extension are on the same project, they will sync automatically.
>
> After syncing, you'll see an IDE context option in the Codex app's composer. With "auto context" enabled, the Codex app tracks the files you're viewing, so you can reference them indirectly (e.g., "what is this file about?"). You can also see threads running in the Codex app from the IDE extension, and vice versa.

## Automation

Specifically, it means letting **Codex automatically execute tasks repeatedly in the background, according to rules and schedules**.

<img src="https://image.wendaining.top/image-20260419163638876.png" style="zoom:67%;" />

<img src="https://image.wendaining.top/image-20260419163718646.png"  style="zoom:67%;" />

Each automation run can be executed locally, or in a newly created worktree.

## Worktree

Only applicable to projects managed with Git; it's built on top of [git-worktree](https://git-scm.com/docs/git-worktree).

It's essentially creating a copy of the codebase—each worktree has its own independent copy of all files in the repository, but shares the same `.git` folder.

### Terms:

- Local checkout: the repository you created yourself
- Worktree
- Handoff: the operational process of handing off between local and worktree; the Git operations here are handled by Codex.

### Usage

You can create a new worktree and work inside it, or hand off a thread working in a worktree back to local.

All worktrees are managed in a single location. Since worktrees take up a lot of disk space, Codex automatically cleans up all but the most recent 15. However, specially configured ones will not be cleaned up.

## Local Environments

By default, stored in the `.codex` folder in the project root.

# Codex CLI

The Codex App seems decent enough; I'll skip it for now.

# Configuration

## Configuration File

`~/.codex/config.toml`—it's full of APIs, and there's not much point in taking notes on it.

[Configuration Reference – Codex | OpenAI Developers](https://developers.openai.com/codex/config-reference)

## Plugins

A plugin can contain:

- Skills
- Apps - e.g., connecting to GitHub, GMail
- MCP

Just install them directly in the Codex App.

How to use: invoke with `@` and describe, or just explain in natural language.

# Best Practices

This section is mostly a summary of some excellent usage patterns.

## Context and Prompt

**Prompt principles**: include these four elements in your prompt:

- Goal
- Context, using `@` mentions
- Constraints
- Completion criteria, e.g., which requirements must be met for the task to be considered done.

## Plan First

- Use plan mode: `/plan`, then ask Codex to "interview you"
- Use the `PLANS.md` template: specifically, the practice is to first note in `AGENTS.md` that the planning part is in `@PLAN.md`.

## Make Good Use of `AGENTS.md`

An excellent `AGENTS.md` includes:

* repo layout and important directories
* How to run the project
* Build, test, and lint commands
* Engineering conventions and PR expectations
* Constraints and do-not rules
* What done means and how to verify work

If the `AGENTS.md` file becomes too large, keep the main file concise and reference task-specific Markdown files to handle things like planning, code review, or architecture.

## Code Review

Use `AGENTS.md` to tell Codex what "good" code looks like, and review accordingly.

You can write a `code_review.md` file, then reference it from `AGENTS.md`.

`/review`: follow it with a prompt that specifically tells it how to review.

## Managing Long Sessions

For the CLI:

- `/fork`: creates a new thread while preserving the original conversation
- `/compact`: compresses the context
- `/agent`: use when running agents in parallel and you want to switch between different threads (in the App, just click in the GUI)
