Codex CLI Best Practices

repository·main·Indexed 21 days ago

https://github.com/shanraisshan/codex-cli-best-practice

A framework for transitioning from 'vibe coding' to 'agentic engineering' using the Codex CLI. It provides structured patterns for implementing subagents, skills, and MCP servers, alongside detailed development workflows such as Spec Kit, gstack, and Compound Engineering. The documentation covers configuration via config.toml, the use of AGENTS.md for team instructions, cross-session memories, and automation through Codex Hooks.

Tokens
15.6K
Snippets
50
Records
87
Agent score
72%

What's inside codex-cli-best-practice

  1. Overview of Codex CLI Development Workflows

    main

    The project outlines several major development workflows that follow a core architectural pattern: Research → Plan → Execute → Review → Ship. These workflows represent different methodologies for using Codex CLI and related tools to manage the software development lifecycle, from initial brainstorming to deployment.

    Key workflows include:

    • Superpowers: Focuses on brainstorming, writing plans, subagent-driven development, TDD, code review, and finishing development branches.
    • Spec Kit: A specification-driven approach using /speckit.constitution, /speckit.specify, /speckit.plan, /speckit.tasks, and /speckit.implement.
    • gstack: A structured review-heavy workflow involving /office-hours, multiple review stages (/plan-ceo-review, /plan-eng-review, /plan-design-review), implementation, /review, /qa, /ship, and /land-and-deploy.
    • Get Shit Done (GSD): A project-centric workflow moving through /gsd--new--project, /gsd--discuss--phase, /gsd--plan--phase, /gsd--execute--phase, /gsd--verify--work, /gsd--ship, and /gsd--complete--milestone.
    • oh-my-codex: Uses $deep-interview, $ralplan, and $ralph.
    • Compound Engineering: An iterative loop of /ce--ideate, /ce--brainstorm, /ce--plan, /ce--work, /ce--code--review, /ce--compound, and repeat.

    Note: Steps marked as sub-loops (indicated by yellow tags in the original documentation) are processes that repeat within a parent step, such as per task or until a verification condition is met.

  2. Core Concepts of Codex CLI

    main

    Codex CLI is built around several key abstractions that enable agentic engineering:

    • Commands: Built-in slash commands used for session control (e.g., /plan, /review, /status).
    • Subagents: Custom agents defined in .codex/agents/<name>.toml. They support parallel orchestration and CSV batch processing. Global settings like max_threads and max_depth are configured under the [agents] key.
    • Skills: Reusable instruction packages located in .agents/skills/<name>/SKILL.md. They can be invoked explicitly via /skills or $skill-name.
    • Plugins: Bundles that combine skills, app integrations, and MCP servers, distributed via .codex-plugin/plugin.json.
    • MCP Servers: Implementation of the Model Context Protocol for external tools via STDIO or HTTP. Managed via codex mcp commands.
    • Memories: A cross-session memory pipeline enabled via [features] memories = true in the configuration.
    • Rules: Starlark-based command execution policies defined in .codex/rules/ to allow, prompt, or forbidden specific command prefixes.
    • Hooks: User-defined shell scripts in .codex/hooks.json that inject into the agentic loop (requires codex_hooks = true).
  3. Understand Codex CLI Skills

    main

    Skills are reusable, composable instruction packages used to extend Codex CLI. They follow the SKILL.md standard and are designed to be narrow, trigger cleanly, and maintain a small context.

    Skills can be invoked in two ways:

    1. Explicit invocation: Mention the skill directly in the prompt using /skills or by typing $ to open the mention menu.
    2. Implicit invocation: Codex automatically selects a skill when the user's task matches the skill's description field.

    Because of implicit invocation, the description field is the most critical part of your skill's metadata.

  4. Use Sandbox-State Metadata for trusted MCP servers

    main

    Experimental support allows trusted MCP servers to advertise the codex/sandbox-state-meta capability during the initialize phase.

    When a server provides this metadata, Codex automatically augments every tools/call request with a _meta object containing sandbox details, such as sandboxPolicy, codexLinuxSandboxExe, sandboxCwd, and useLegacyLandmark. This enables the MCP server to spawn child processes within the same sandbox environment as the Codex session. This is controlled entirely by the server's initialization response; there is no client-side configuration switch.

    {
      "codex/sandbox-state-meta": {
        "sandboxPolicy": { "...": "..." },
        "codexLinuxSandboxExe": "/path/to/codex-linux-sandbox",
        "sandboxCwd": "/workspace",
        "useLegacyLandlock": false
      }
    }
  5. How subagents work in Codex

    main

    Subagents are specialized agents spawned by Codex in parallel to handle complex, highly parallel, or domain-specific tasks (e.g., codebase exploration, multi-step feature plans, or large-scope PR reviews).

    Key Characteristics:

    • Orchestration: Codex manages spawning, routing instructions, waiting for results, and closing threads. It returns a consolidated response once all subagents complete.
    • Parallelism: Subagents run independently, allowing multiple threads (like security, quality, and tests) to run at once.
    • Resource Usage: Because each subagent performs its own model and tool work, subagent workflows consume more tokens than single-agent runs.
    • Sandbox Inheritance: Subagents inherit the parent's sandbox policy, including live runtime overrides like --yolo or /approvals changes. However, you can override this per custom agent (e.g., setting a custom agent to read-only).
    I would like to review the following points on the current PR (this branch vs main).
    Spawn one agent per point, wait for all of them, and summarize the result for each point.
    1. Security issue
    2. Code quality
    3. Bugs
    4. Race conditions
    5. Test flakiness
    6. Maintainability of the code
  6. Develop and use Codex Skills

    main

    Skills allow you to extend Codex's capabilities.

    Implementation Guidelines:

    • Structure: Skills should be folders, not single files. Use subdirectories like references/, scripts/, and examples/ for progressive disclosure.
    • Discovery: Use clear names and description frontmatter in the skill to enable auto-discovery.
    • Triggering: Write the description field as a trigger for the model (e.g., "when should I fire?") rather than a summary.
    • Content: Focus on "Gotchas" (failure points) and information that pushes Codex out of its default behavior. Avoid stating the obvious or providing prescriptive step-by-step instructions; instead, provide goals and constraints.
    • Scaffolding: Use the built-in skill creator to scaffold new skills and maintain a consistent invocation style.
  7. How Codex invokes skills

    main

    Codex activates skills using two methods:

    1. Explicit invocation: Mention the skill directly in your prompt. In the CLI or IDE, use /skills or type $ to insert a skill mention.
    2. Implicit invocation: Codex automatically selects a skill when your task matches the skill's description.

    Codex uses progressive disclosure: it initially only loads metadata (name, description, path, and agents/openai.yaml) and only loads the full SKILL.md content once the skill is actually selected.

  8. How Subagents work in Codex CLI

    main

    Subagents are custom agents used for specialized tasks. They are registered using TOML configuration files located in .codex/agents/<name>.toml under the [agents.<name>] header.

    Key capabilities include:

    • Parallel Orchestration: Running multiple subagents simultaneously.
    • Batch Processing: Processing tasks via CSV files.
    • Global Configuration: You can control subagent behavior globally in your config using the [agents] section with the following keys:
      • max_threads: Limits concurrent subagent execution.
      • max_depth: Limits the depth of agentic reasoning/recursion.
      • job_max_runtime_seconds: Sets a timeout for jobs.

    Built-in subagent types include default, worker, and explorer.

    [agents.my_special_agent]
    role = "..."
    # Other agent-specific config
    
    [agents]
    max_threads = 4
    max_depth = 3
    job_max_runtime_seconds = 300
  9. Understand the Codex Marketplace on-disk layout

    main

    Codex manages marketplace data and plugin caches within $CODEX_HOME (typically ~/.codex/).

    • config.toml: Stores marketplace registration entries (e.g., [marketplaces.<name>]).
    • .tmp/marketplaces/<marketplace_name>/: The cloned root of the marketplace manifest.
    • plugins/cache/<marketplace_name>/<plugin_name>/<version>/.codex-plugin/plugin.json: The actual cached plugin files and their metadata.
  10. How Codex Hooks Discovery and Priority Work

    main

    Codex searches for hooks.json configuration files at two distinct levels. Both levels are loaded simultaneously, meaning hooks from both locations will execute. Higher-precedence layers do not replace lower-precedence hooks; they are additive.

    PriorityLocationScope
    1.codex/hooks.jsonProject (team-shared)
    2~/.codex/hooks.jsonGlobal (personal)
  11. How Memory Extensions work

    main

    Memory Extensions are plugins that provide persistent instructions and transient per-run evidence. They are stored in $CODEX_HOME/memories_extensions/<extension_name>/.

    • instructions.md: Always loaded if present.
    • resources/: Contains per-run artifacts (e.g., 2026-04-18T14-32-05-notes.md).

    Lifecycle & Cleanup:

    • Resource files in the resources/ directory are automatically pruned if they are older than 7 days during the Phase 2 consolidation process.
    • A full memory reset via the TUI or codex debug clear-memories wipes the entire memories_extensions/ directory tree.
    $CODEX_HOME/memories_extensions/
    └── <extension_name>/
        ├── instructions.md              # always loaded if present
        └── resources/
            └── 2026-04-18T14-32-05-notes.md   # per-run artifact, auto-pruned
  12. Understand the Agent → Skill orchestration pattern

    main

    The core orchestration pattern in Codex CLI is Agent → Skill. Unlike other systems that use a 'Command → Agent → Skill' flow, Codex uses an Agent as the primary entry point to orchestrate workflows.

    In this pattern:

    1. Agent: Acts as the entry point. It handles data fetching (often via inlined developer_instructions) and decides when to invoke a skill.
    2. Skill: An independent component invoked by the agent to perform specific tasks, such as rendering visual output or writing files. It receives necessary data from the conversation context established by the agent.

    Key Constraint: Codex CLI does not currently support mid-turn user interaction (e.g., an agent asking the user a question). Therefore, users must specify all necessary preferences (like units or formats) directly in the initial prompt.

    User Prompt (specifies preferences) → Agent (fetches data) → Skill (renders output)