Mastering Codex: Advanced Techniques for AI-Powered Programming

This guide walks developers through Codex’s advanced features—including layered AGENTS.md configuration, Context Compaction, Claude Code + Codex collaboration, sandbox and Rules security, MCP protocol integration, profile switching, pipeline workflow, and session management—showing how each can be combined to turn basic code generation into a high‑efficiency development engine.

Old Meng AI Explorer
Old Meng AI Explorer
Old Meng AI Explorer
Mastering Codex: Advanced Techniques for AI-Powered Programming

1. AGENTS.md: Codex’s "onboarding manual"

AGENTS.md is a hierarchical instruction set that Codex reads at startup, giving higher priority to files closer to the current working directory. The recommended three‑layer structure is:

第1层:~/.codex/AGENTS.md  →  个人长期偏好
第2层:<repo>/AGENTS.md    →  团队通用规范
第3层:<repo>/services/payments/AGENTS.override.md  →  子目录强约束

For example, a global rule may allow "run npm test after modifying a JS file", while a payment‑service override can forbid direct production‑database modifications without review. AGENTS.override.md always overwrites AGENTS.md in the same directory. Codex imposes a 32 KB default size limit on the merged file; exceeding it requires either raising project_doc_max_bytes or splitting rules into nearer directories.

Rules must be executable, not abstract. Concrete examples such as "- 修改前端代码后运行 pnpm test:web" work reliably, whereas vague commands like "- 保持代码整洁" are ignored.

2. Context Compaction: Prevent Forgetting

Long tasks cause Codex to lose early context because token‑based pricing makes long prompts expensive and model performance drops sharply after a certain length. Codex offers two compression mechanisms:

Local handoff: when the context nears capacity, Codex generates a "handoff" containing progress, key decisions, constraints, and remaining steps, stored locally for later retrieval.

Server‑side compression: the OpenAI API’s context_management + compact_threshold options return an encrypted compacted segment for internal use.

Practical tips (ordered list):

Task‑level clear : use run/clear to start a fresh context.

Pre‑emptive compact : trigger /compact before the context fills.

Append‑only strategy : never modify historic messages; always add new records to keep caches valid.

Sub‑agent isolation (useful when also using Claude Code) delegates heavy file‑reading or full‑repo search to a separate agent, returning only a summary to the main thread. The 2026 update adds worktree isolation, giving each session its own code copy.

3. Claude Code + Codex Combo: Leveraging Complementary Strengths

Claude Code excels at complex logical reasoning, long‑text understanding, architecture design, and code review, while Codex shines in fast code generation, multi‑file batch operations, terminal automation, and CI/CD integration. Combining them avoids Claude’s “over‑thinking” slowdown and Codex’s occasional requirement‑misinterpretation.

Two collaboration patterns are recommended:

Claude:理解需求,设计架构
↓
Codex:根据方案生成代码
↓
Claude:审查代码,提出改进
↓
Codex:修改代码
↓
GPT‑5或Claude:生成文档

Serial collaboration provides clear debugging; parallel collaboration lets both models work on different parts of the same task and pick the better result.

Community‑reported metrics:

Claude‑only: 45 min, decent quality but sub‑optimal structure.

Codex‑only: 30 min, fast but occasional requirement drift.

Claude + Codex: 35 min, clearer architecture, higher code quality; cost ≈ 1.5× single‑model runtime but quality gain far exceeds the extra expense.

4. Sandbox Mode and Security Rules

Sandbox mode restricts the file system scope of Codex. Example ~/.codex/config.toml configuration:

sandbox_mode = "workspace-write"
[sandbox_workspace_write]
network_access = false

With workspace-write, Codex can modify files only in the current directory and cannot access the network.

The Rules system allows fine‑grained command control. Sample rules (global or project‑level) include:

Prohibit git push to main.

Disallow deleting files larger than 100 lines.

Block sudo execution.

Prevent modifications to production configuration files.

Approval policies determine how Codex asks for confirmation before risky actions:

approval_policy = "on-request"   →  ask before each operation
approval_policy = "full-auto"    →  fully automatic (dangerous)
approval_policy = "never"        →  never ask (very dangerous)

5. MCP Protocol: Connecting Codex to the World

The Model Context Protocol (MCP) extends Codex so it can call external resources such as databases, APIs, file systems, Git, Figma, and Notion, enabling a one‑stop AI‑augmented development stack.

Typical MCP tool commands:

# File system MCP
claude mcp add --transport stdio filesystem -- npx -y @anthropic/mcp-server-filesystem

# Figma MCP – generate code from designs
claude mcp add --transport http figma https://mcp.figma.com/mcp

# PostgreSQL MCP
claude mcp add --transport stdio postgres -- npx -y @anthropic/mcp-server-postgres

An entertaining example shows McDonald’s offering an MCP service that can fetch the latest calendar events and even claim coupons, demonstrating that any HTTP API can be wrapped for AI use.

6. Profile Configuration: One‑Click Mode Switching

Profiles replace ad‑hoc aliases. Example ~/.codex/config.toml snippet:

[profiles.default]
model = "gpt-5.3-codex"
model_reasoning_effort = "high"
web_search = "cached"

[profiles.review]
model = "gpt-5.3-codex"
sandbox_mode = "read-only"
approval_policy = "never"

[profiles.quick]
model = "o4-mini"
model_reasoning_effort = "medium"

[profiles.ci]
model = "gpt-5.3-codex"
# non‑interactive CI configuration

Use the CLI to select a profile, e.g., codex --profile review. Command‑line flags always override profile settings:

codex -m gpt-5.4 "修复这个bug"  # temporary model switch

7. Pipeline Mode: Embedding Codex in Your Workflow

Codex can be piped into standard CLI streams:

# Code review
git diff | codex -p "review these changes"

# Test failure analysis
npm test 2>&1 | codex -p "分析为什么测试失败"

# Create a commit
codex -p "create commit" --allowedTools "Bash(git diff *),Bash(git commit *)"

Structured JSON output enables downstream automation: codex -p "summarize" --output-format json GitHub Actions integration example:

- name: Run Codex Review
  run: |
    git diff ${{ github.event.before }} ${{ github.sha }} |
    codex -p "security review" --output-format json > review.json

8. Session Management: Never Lose Context

Resume a previous conversation with codex --continue or codex --resume. Sessions persist for 30 days by default; the cleanupPeriodDays setting can extend retention.

Name sessions for easier retrieval, e.g., /codex-rename api-migration then /resume api-migration. This is useful for multi‑step tasks such as refactoring or debugging.

Cross‑device sync is possible via codex --teleport <session_id>, which pulls the session from another machine.

AI codingMCP protocolContext ManagementCodexClaude Codeprofile switchingsandbox mode
Old Meng AI Explorer
Written by

Old Meng AI Explorer

Tracking global AI developments 24/7, focusing on large model iterations, commercial applications, and tech ethics. We break down hardcore technology into plain language, providing fresh news, in-depth analysis, and practical insights for professionals and enthusiasts.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.