Skip to content
Back to skills

Cli Codex

ASecurity

Codex CLI executor for OpenAI-backed coding, repo analysis, PR review, web research, and cross-model validation.

  • 36 stars
  • 0 votes
  • 0 copies
  • 5 views
  • Added September 21, 2026
ai-agentspythonrustgoshellbashnodetestingdebuggingcode-reviewgit

Works with

  • cli
  • api
  • mcp

Security analysis

A96/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro shows the line behind each finding and how to fix it

Scanned October 1, 2026

npx -y skills add MichelKerkmeester/opencode--spec-kit-skilled-agent-orchestration --skill cli-codex --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Cli Codex?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Cli Codex
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/michelkerkmeester-cli-codex-b91f0513/badge)](https://www.skillsdirectory.com/skills/michelkerkmeester-cli-codex-b91f0513)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: cli-codex
description: "Codex CLI executor for OpenAI-backed coding, repo analysis, PR review, web research, and cross-model validation."
allowed-tools: [Bash, Read, Glob, Grep]
version: 1.9.5.0
---

<!-- generated by sync-skills-hermes.cjs; do not edit -->
> Canonical source: `.skilled/skills/cli-external-orchestration/cli-codex/`. This is a generated markdown-only copy so Hermes can load the
> skill without scanning the canonical directory; read `references/`, `assets/` and `scripts/`
> from the canonical path above.

<!-- Keywords: codex, codex-cli, openai, cross-ai, web-search, code-generation, code-review, second-opinion, agent-delegation, gpt-5, session-management -->

# Codex CLI Orchestrator - Cross-AI Task Delegation

> **CRITICAL — SELF-INVOCATION PROHIBITED**
>
> This skill dispatches to the OpenAI CLI binary (`codex`). If the agent currently reading this skill is itself running inside Codex (detection signals listed in §2), the skill MUST refuse to load and return the documented error message instead of generating any `codex` invocation.
>
> A running CLI skill never dispatches itself. The cli-X skills are for **cross-AI delegation only** — never self-invocation.

Orchestrate OpenAI's Codex CLI for tasks that benefit from a second AI perspective, real-time web search, deep codebase analysis, built-in code review workflows, or parallel code generation.

**Core Principle**: Use Codex for what it does best. Delegate, validate, integrate. The calling AI stays the conductor.

---

## 1. WHEN TO USE

### Activation Triggers

- **Cross-AI Validation** — code review second perspective, security audit alternative analysis, bug detection, `/review` diff-aware workflow.
- **Web Research** — current internet info via the top-level `--search` flag (`codex --search exec …`), latest library versions, API changes, community solutions.
- **Codebase Architecture Analysis** — onboarding to unfamiliar codebases, cross-file dependency mapping, architecture docs from code.
- **Parallel Task Processing** — offloading generation, simultaneous code generations, background docs/test generation.
- **Agent-Delegated Tasks** — specialized profile matches (`.codex/agents/*.toml`), session management (resume, fork), multi-strategy planning.
- **Specialized Generation** — explicit Codex requests, test suite generation, code translation, batch docs (JSDoc, README, API), visual input via `--image`/`-i`.

### When NOT to Use

- **You ARE Codex already.** If your runtime is Codex (detection signal: `$CODEX_SESSION_ID` or any `CODEX_*` env var set, `codex` in process ancestry, or `~/.codex/state/<id>/lock` present), this skill refuses to load. Self-invocation creates a circular dispatch loop and burns tokens for no value.
- Simple, quick tasks where CLI overhead is not worth it, or tasks needing an immediate response (rate limits may delay).
- Context already loaded and understood by the current agent.
- Interactive refinement requiring the full-screen TUI (use `codex` directly instead).
- Tasks where Codex CLI is not installed.

---

## 2. SMART ROUTING

### Prerequisite Detection

```bash
# Verify Codex CLI is available before routing
command -v codex || echo "Not installed. Run: npm i -g @openai/codex"
```

### Self-Invocation Guard

```python
def detect_self_invocation():
    """Returns a non-None signal when the orchestrator is already running inside Codex."""
    # Layer 1: env var lookup — Codex sets CODEX_SESSION_ID and CODEX_* vars
    for key in os.environ:
        if key == 'CODEX_SESSION_ID' or key.startswith('CODEX_'):
            return ('env', key)
    # Layer 2: process ancestry — codex in parent tree
    try:
        ancestry = subprocess.check_output(['ps', '-o', 'command=', '-p', str(os.getppid())]).decode()
        if '/codex' in ancestry or 'codex ' in ancestry:
            return ('ancestry', 'codex')
    except subprocess.SubprocessError:
        pass
    # Layer 3: state lock-file probe
    state_dir = os.path.expanduser('~/.codex/state')
    if os.path.isdir(state_dir):
        for entry in os.listdir(state_dir):
            if os.path.exists(os.path.join(state_dir, entry, 'lock')):
                return ('lockfile', entry)
    return None

if detect_self_invocation():
    refuse(
        "Self-invocation refused: this agent is already running inside Codex. "
        "Use a sibling cli-* skill or a fresh shell session in a different runtime to dispatch a different model."
    )
```

### Resource Loading Levels

| Level       | When to Load            | Resources                      |
| ----------- | ----------------------- | ------------------------------ |
| ALWAYS      | Every skill invocation  | `references/cli-reference.md`, `assets/prompt-quality-card.md` |
| CONDITIONAL | If intent signals match | Intent-mapped reference docs   |
| ON_DEMAND   | Only on explicit request| Extended templates and patterns |

### Smart Router

Provider-specific dictionaries (used by the shared helper functions in [`system-spec-kit/references/cli/shared-smart-router.md`](../../../.skilled/skills/system-spec-kit/references/cli/shared-smart-router.md)):

```python
INTENT_SIGNALS = {
    "GENERATION":        {"weight": 4, "keywords": ["generate", "create", "build", "write code", "codex create"]},
    "REVIEW":            {"weight": 4, "keywords": ["review", "audit", "security", "bug", "second opinion", "cross-validate", "/review"]},
    "RESEARCH":          {"weight": 4, "keywords": ["search", "latest", "current", "what's new", "web research", "--search", "browse"]},
    "ARCHITECTURE":      {"weight": 3, "keywords": ["architecture", "codebase", "investigate", "dependencies", "analyze project"]},
    "AGENT_DELEGATION":  {"weight": 4, "keywords": ["delegate", "agent", "background", "parallel", "offload", "codex agent"]},
    "TEMPLATES":         {"weight": 3, "keywords": ["template", "prompt", "how to ask", "codex prompt"]},
    "PATTERNS":          {"weight": 3, "keywords": ["pattern", "workflow", "orchestrate", "session", "resume", "fork"]},
    "HOOKS":             {"weight": 4, "keywords": ["hook", "hooks", "advisor brief", "startup context", "userpromptsubmit", "sessionstart", "codex_hooks"]},
    # WHY: DESIGN is an intent signal only. The durable sk-design-md-generator loading contract lives in the
    # always-fires Design Standards Loading rule and the dispatch manifest; RESOURCE_MAP stays
    # limited to same-skill markdown paths.
    "DESIGN":            {"weight": 4, "keywords": ["sk-design-md-generator", "extract design system", "generate design.md", "style reference", "design tokens", "css extraction", "tokens.json"]},
}

RESOURCE_MAP = {
    "GENERATION":        ["references/cli-reference.md", "assets/prompt-templates.md"],
    "REVIEW":            ["references/integration-patterns.md", "references/agent-delegation.md"],
    "RESEARCH":          ["references/codex-tools.md", "assets/prompt-templates.md"],
    "ARCHITECTURE":      ["references/codex-tools.md", "references/agent-delegation.md"],
    "AGENT_DELEGATION":  ["references/agent-delegation.md", "references/integration-patterns.md"],
    "TEMPLATES":         ["assets/prompt-templates.md", "references/cli-reference.md"],
    "PATTERNS":          ["references/integration-patterns.md", "references/cli-reference.md"],
    "HOOKS":             ["references/hook-contract.md", "references/cli-reference.md"],
}

LOADING_LEVELS = {
    "ALWAYS": ["references/cli-reference.md", "assets/prompt-quality-card.md"],
    "ON_DEMAND_KEYWORDS": ["full reference", "all templates", "deep dive", "complete guide", "codex agent", "codex prompt", "web research", "review command", "fork session", "hook contract"],
    "ON_DEMAND": ["references/codex-tools.md", "assets/prompt-templates.md"],
}

UNKNOWN_FALLBACK_CHECKLIST = [
    "Is the user asking about Codex CLI specifically?",
    "Does the task benefit from a second AI perspective?",
    "Is real-time web information needed (--search)?",
    "Would codebase-wide analysis or /review workflow help?",
]
```

**Call sequence** (using shared helpers from `shared-smart-router.md`):

1. `discover_markdown_resources()` — recursively enumerate current `.md` files under existing `references/` and `assets/` folders at routing time.
2. `_guard_in_skill()` + `load_if_available()` — sandbox paths to this skill, reject non-markdown loads, skip missing files, and suppress duplicates.
3. `score_intents(task)` and `select_intents(scores, ambiguity_delta=1.0)` — preserve provider-specific weighted intent scoring and top-2 ambiguity handling.
4. `get_routing_key(task, intents)` — derive the provider routing key from task/provider context, then fall back to `codex`.
5. ALWAYS-load `LOADING_LEVELS["ALWAYS"]`, then return `UNKNOWN_FALLBACK` with `UNKNOWN_FALLBACK_CHECKLIST` when max score is 0.
6. CONDITIONAL-load `RESOURCE_MAP[intent]`, ON_DEMAND-load keyword matches, and return a notice when no provider-specific knowledge base is available beyond always-load resources.

The `route_codex_resources(task)` function body lives in [`shared-smart-router.md`](../../../.skilled/skills/system-spec-kit/references/cli/shared-smart-router.md) — substitute `<PROVIDER>` = `codex`.

---

## 3. HOW IT WORKS

### Prerequisites

Install with `npm i -g @openai/codex` (or `brew install --cask codex`). cli-codex authenticates through **ChatGPT OAuth only** — run `codex login` and complete the browser flow (requires a ChatGPT Plus/Pro/Business/Edu/Enterprise account). It does not use an OpenAI API key. Full install, auth, flag, sandbox, session, and troubleshooting tables live in the ALWAYS-loaded [cli-reference.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/cli-reference.md) — this section keeps only the routing decisions and dispatch-critical gotchas.

### Execution Ownership

This packet owns user-facing routing, the `command -v codex` availability probe, prompt construction, and the self-invocation guard. Research and review lineages delegate process construction and execution to the already-shipped deep-loop runtime at `../../system-deep-loop/runtime/scripts/fanout-run.cjs`, using executor kind `cli-codex`. That runner accepts only the `research` and `review` loop types, so a single build or doc dispatch uses the child dispatch envelope in [providers-and-models.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/providers-and-models.md) §5.

The runtime is the single Codex execution adapter. Do not add a packet-local wrapper, command builder, or spawn path. Direct `codex exec` snippets below are operator reference and manual-testing examples; research and review lineages use the shared runtime, and a one-shot dispatch uses the child envelope.

### Provider Auth Pre-Flight (ChatGPT OAuth)

**MANDATORY before any first dispatch in a session.** cli-codex authenticates through ChatGPT OAuth only. If `codex login` has not been completed on this machine, a dispatch fails with `401 Unauthorized` or `not authenticated` mid-round-trip. Run this check once per session, cache the result, and re-run it only if a dispatch fails with an auth error.

```bash
# One-shot pre-flight: capture ChatGPT OAuth status for routing
CODEX_AUTH=$(codex login status 2>&1)
echo "$CODEX_AUTH" | grep -qi "logged in\|chatgpt-oauth" && CODEX_OAUTH_OK=1 || CODEX_OAUTH_OK=0
```

**Decision tree** (apply in order — first match wins):

| State | CODEX_OAUTH_OK | Action |
|-------|----------------|--------|
| OAuth ready | 1 | Proceed with `codex exec --model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast"` |
| Not logged in | 0 | **ASK user** to run `codex login` — surface the command, do NOT dispatch. Never substitute an API key or a different model. |

**User prompt template — not logged in:**

```
Codex is not authenticated on this machine. cli-codex uses ChatGPT OAuth only.
Run `codex login` (browser flow; requires a ChatGPT Plus/Pro/Business/Edu/Enterprise account),
then confirm when login finishes — the skill will retry the original dispatch.
```

**Error-recovery contract.** If a dispatch returns an auth error after pre-flight passed (OAuth expired or revoked), invalidate the cache, rerun `codex login`, and re-check before retrying. Never substitute a model the user didn't approve.

### Default Invocation (Skill Default)

**Default model + effort + tier**: `gpt-5.5` · `medium` reasoning · `fast` service tier. Balances speed, cost, and quality for the typical delegation.

> **Fan-out fallback:** a deep-loop lineage that pins no model runs **GPT Luna**. The family is named here on purpose, without a version or an effort tier, so this line does not go stale when the family ships a point release; the runner resolves the current id. A drift test keeps the two in the same family.

```bash
codex exec \
  --model gpt-5.5 \
  -c model_reasoning_effort="medium" \
  -c service_tier="fast" \
  -c approval_policy=never \
  --sandbox workspace-write \
  "<prompt>" </dev/null
```

The trailing `</dev/null` is not optional in a non-interactive dispatch; Rule 6 below explains what a backgrounded codex does to an inherited stdin.

**User override** (honor explicit user phrasing verbatim):

| User says | Resolve to |
|-----------|------------|
| (nothing specified) | `--model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast"` |
| "Use gpt 5.5 high fast" | `--model gpt-5.5 -c model_reasoning_effort="high" -c service_tier="fast"` |
| "Use gpt 5.5 low" | `--model gpt-5.5 -c model_reasoning_effort="low" -c service_tier="fast"` (fast stays unless user drops it) |
| "Use gpt 5.5 xhigh" | `--model gpt-5.5 -c model_reasoning_effort="xhigh" -c service_tier="fast"` |
| "Use gpt 6 luna max" | `--model gpt-6-luna -c model_reasoning_effort="max" -c service_tier="fast"` |
| "Use gpt 5.6 terra high" | `--model gpt-5.6-terra -c model_reasoning_effort="high" -c service_tier="fast"` |
| "Use gpt 6 sol ultra" | `--model gpt-6-sol -c model_reasoning_effort="ultra" -c service_tier="fast"` |

Honor whichever dimensions the user names. Model stays on `gpt-5.5` and service tier stays on `fast` unless the user explicitly names a different model or tier; keep the reasoning effort within the chosen model's ceiling (see Model Selection below and the roster in [references/providers-and-models.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/providers-and-models.md)).

### Model Selection

`gpt-5.5` at `medium` on the `fast` service tier (`-c service_tier="fast"`) is the skill default for cross-AI delegation. Alternates: `gpt-6-luna` (≤ `max`), `gpt-5.6-terra` / `gpt-6-sol` (≤ `ultra`) — full roster, per-model effort ceilings, and the 8-level effort ladder in [references/providers-and-models.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/providers-and-models.md). Set effort with `-c model_reasoning_effort="<level>"` (there is **no `--reasoning-effort` flag**).

**Selection Strategy**: default `gpt-5.5 medium`; raise to `high` / `xhigh` for architecture, security, and complex planning; escalate the model when the task wants reasoning past `xhigh`; drop to `low` / `minimal` for trivial lookups. Per-task rationale table: [cli-reference.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/cli-reference.md) §5.

### Codex Agent Delegation

The calling AI is the conductor; Codex profiles in `$CODEX_HOME/<name>.config.toml` shape HOW Codex processes the task (sandbox, reasoning). Route with `-p <name>` when the task matches a specialization. Full roster and invocation patterns: [agent-delegation.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/agent-delegation.md).

| Task Type | Profile |
|-----------|---------|
| Code review / security audit | `review` |
| Architecture exploration | `context` |
| Technical research | `research` (+ top-level `--search`) |
| Documentation generation | `write` |
| Fresh-perspective debugging | `debug` |
| Multi-strategy planning | `ai-council` |

Git diff review uses the built-in subcommand (no `-p`): `codex exec review "..." --commit HEAD`. Profiles may override `model`, `model_reasoning_effort`, `sandbox_mode`, `approval_policy`. The `.codex/agents/*.toml` files define personas for the interactive multi-agent TUI, NOT the `-p` flag.

### Dispatch-Critical Gotchas

The full flag glossary, sandbox modes, unique capabilities (`/review`, `--search`, `codex mcp`, session resume/fork, `--image`, `codex cloud`), essential command examples, and troubleshooting table are in the ALWAYS-loaded [cli-reference.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/cli-reference.md). Five gotchas that break a dispatch, or make a child misreport its result, and must be honored at routing time:

- **`codex exec` defaults to `--sandbox read-only`** — file-modification tasks silently no-op (the agent plans changes but cannot write them). Pass `--sandbox workspace-write`; for headless no-prompt execution use top-level `-a never` before `exec` or `-c approval_policy=never`.
- **`--search` is a top-level flag, not an `exec` flag** — enable live web search as `codex --search exec …` (it precedes the subcommand). On codex ≥ 0.144 `codex exec --search` hard-fails with `unexpected argument '--search'` (older 0.125 builds accepted it), so treat any `exec … --search` example as stale. Without it, `codex exec` has no web access and answers from training data only — every dispatch needing live data (latest versions, repo facts, advisories) MUST use `codex --search exec …`.
- **Always pass `-c service_tier="fast"` explicitly** — this routes through the fast tier instead of whatever the caller's `~/.codex/config.toml` defaults to. Explicit means reproducible regardless of who runs it.
- **No `--reasoning-effort`, `--reasoning`, or `--quiet` flag exists** — set effort with `-c model_reasoning_effort="<level>"`; capture the last message with `-o file.txt`; capture stderr with `2>&1`.
- **`--sandbox workspace-write` blocks local IPC sockets, so a child cannot run checks that start `tsx`** — spec-kit's `npm --prefix runtime/cli run check` fails there with `listen EPERM`, also with `TMPDIR` pointed elsewhere (observed 2026-09-24 on codex-cli 0.156.1), and passes outside the sandbox. Tell the child which checks to leave to you, run them in the orchestrating session after it returns, and read that EPERM as a sandbox limit, not a code failure.

---

## 4. RULES

### ✅ ALWAYS

1. Verify Codex CLI is installed before first invocation (`command -v codex`).
2. Delegate research and review lineages to `../../system-deep-loop/runtime/scripts/fanout-run.cjs` with executor kind `cli-codex`. It rejects every other loop type, so a single build or doc dispatch uses the child dispatch envelope in [providers-and-models.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/providers-and-models.md) §5. Never build a second adapter in this packet.
3. Use `--sandbox read-only` for review/analysis/research; `--sandbox workspace-write` for code generation/file modification — `codex exec` defaults to `read-only`, so omitting it causes silent no-op on edit tasks. For unattended approval, put top-level `-a never` before `exec` or set `-c approval_policy=never`.
4. Validate Codex-generated code (XSS, injection, eval, syntax checks via `node --check`, `tsc --noEmit`, etc.) before applying.
5. Capture stderr (`2>&1`) so rate-limit messages and errors surface.
6. **Redirect codex stdin from `/dev/null` on EVERY non-interactive dispatch** — not only inside a `while read` loop, which is the condition this rule used to name and the reason it was skipped. Pattern: `codex exec "$PROMPT" > "$LOG" 2>&1 </dev/null &`. Without `</dev/null`, the backgrounded codex process inherits the loop's stdin (the file after `done < input.jsonl`) and silently consumes the remaining lines — the loop exits after 3-6 iterations with no error. See `references/integration-patterns.md#background-execution` → "Silent Stdin Consumption".
7. **Specify model + effort + service tier explicitly** — never rely on caller environment. Default: `--model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast"`. Honor user overrides verbatim. Use `high`/`xhigh` for reasoning-heavy tasks (architecture, security, deep planning).
8. Route to the appropriate `-p <profile>` when the task matches a specialization (see Section 3 routing table); use `codex exec review` (built-in subcommand) for git diff reviews.
9. **Pass the spec folder to the delegated agent** in the prompt: if the calling AI has an active Gate-3 spec folder, include `Spec folder: <path> (pre-approved, skip Gate 3)`. If none, ASK the user before delegating — the delegated agent cannot answer Gate 3 in non-interactive mode.
10. **Prompt construction & model-craft (cli-* family precedence).** Compose every dispatch prompt via the 2-tier rule canonical in `../../sk-prompt/assets/cli-prompt-quality-card.md`:
   1. **Fast path (default).** Build from the local `assets/prompt-quality-card.md`, which delegates the framework table + CLEAR check to the canonical card.
   2. **Deep path (escalation).** Dispatch `@prompt-improver` via the Task tool (never load full `sk-prompt` inline) when any canonical **Tier 2** trigger applies — the trigger list lives in `../../sk-prompt/assets/cli-prompt-quality-card.md` under "Tier 2 — Deep path"; do not re-enumerate it here.
11. **Never inject user-level voice/personalization content into AI-orchestrated Codex delegations.** Codex CLI reads user-level voice from `~/.codex/AGENTS.md` (the human's global settings, loaded automatically). When an AI delegates via `codex exec`, the calling AI's own voice rules govern the response — do NOT read `~/.codex/AGENTS.md` and paste into delegation prompts. Keep delegations focused on task/model/sandbox/effort/(spec-folder pre-approval). If the user asks how to make Codex sound more like Claude in *their own* sessions, point to `~/.codex/AGENTS.md` — not any repo asset.
12. **Code Standards Loading (surface-aware contract)** — When dispatching for code review or code generation, instruct the dispatched session to: (1) load `sk-code`; (2) let `sk-code` emit a surface tag matching the detected stack from markers and target files; (3) load the selected surface resources and run its verification commands; (4) add `code-review` only for formal findings-first review output. Fallback: if the surface cannot be determined confidently, ask for the runtime surface and verification command set. NEVER hardcode obsolete sibling code skills in dispatch prompts.
13. **Design Standards Loading (measured-reference contract)** — When dispatching for design or UI work, instruct the dispatched session to: (1) load `sk-design-md-generator`; (2) extract a measured Style Reference DESIGN.md (named color tokens, type scale, components, Quick-Start CSS/Tailwind) from the live source before building UI; (3) build against those measured tokens and run the extraction's validate step to confirm hex/section fidelity. Fallback: if there is no live source to measure, ask for the reference URL or the exact tokens to build against. NEVER treat `mcp-figma` or `sk-design-md-generator` as a taste, visual-direction, or critique authority — the extraction measures real CSS, it does not judge design.
14. **Pass the design reference manifest to the dispatched session** — when dispatching design or UI work, inline a `DESIGN_DISPATCH_MANIFEST v1` block in the prompt (the child cannot resolve skill paths, so the manifest travels in the payload, not by reference): `styleReferenceExtracted` true, the live `source` that was measured, the measured design tokens / type scale / components the child must build against, `loadedFiles`, and `proofDemandBack`. If the manifest cannot be assembled — no Style Reference extracted, or no live source to measure — ASK before launching the child rather than starting a silent design dispatch. The child returns the demanded proof; the parent reconciles it on the return path.
15. **Single-dispatch discipline (operator-gated, session-scoped)** — Default: launch ONE cli-* dispatch at a time across the cli-* family (cli-codex, cli-opencode, cli-claude-code). Wait for the dispatched agent's work to return, verify outputs exist, then SIGKILL only the dispatch THIS skill started: capture its PID at launch (`codex exec ... & CODEX_PID=$!`) and kill that captured PID directly plus its own orphan children (`kill -9 "$CODEX_PID" 2>/dev/null; pkill -9 -P "$CODEX_PID" 2>/dev/null`), then apply the same PID-scoped `gtimeout` cleanup. **Never use a blanket `pkill -9 -f "codex exec --model"` pattern** — that matches and kills EVERY running `codex exec` process on the machine, including the operator's unrelated codex sessions. Only launch the next dispatch (this skill OR a sibling) after the prior one is dead and RSS has dropped. **Within a deep-flow session** (deep-review / deep-research): the operator authorizes the whole multi-iteration session at start — iterations chain back-to-back with kill-between as the safety mechanism, NOT a per-iteration confirmation prompt. **Exception (cross-skill parallel)**: when the operator explicitly authorizes N parallel dispatches, run N concurrently — but still SIGKILL each by its own captured PID as its work returns.
16. **Set `AI_SESSION_CHILD=1` in the dispatched child's env AND state the exemption in the prompt.** The variable makes the waiver true; it does not make it observable. The reader being waived is a model, and a model cannot see an environment variable, so a child given only the variable still stops to ask the documentation-scope question and writes nothing, at exit code zero. Copy the preamble from [`shared/references/child-dispatch-preamble.md`](../../../.skilled/skills/cli-external-orchestration/shared/references/child-dispatch-preamble.md) to the top of every non-interactive prompt. when sessions may be launched through the per-session worktree wrapper (`.skilled/bin/worktree-session.sh`). A dispatched `codex exec` is an orchestrated sub-session, not a new top-level session, so it must SHARE the parent's worktree rather than allocate its own. The wrapper checks `AI_SESSION_CHILD` (plus a `git --git-common-dir` structural backstop) and exec's in place when set. Pattern: `AI_SESSION_CHILD=1 codex exec ... </dev/null`. Harmless when the wrapper is not in use. See `.skilled/bin/README.md` → "Worktree session isolation".

17. **Agent-persona injection (attach identity, not just the task).** Every dispatch composes `{resolved agent persona + task prompt}` — never a bare task. Resolve the persona from the ACTIVE runtime's agent directory per AGENTS.md §9 (`.skilled/agents/<name>.md`, `.claude/agents/<name>.md`, etc. — never hardcode one runtime), and map each subtask to the RIGHT agent (`code`→code, `review`→review, `design`→design, research→`deep-research`, docs→`markdown`), not one default. **Codex has no native persona surface** — `.codex/agents/*.toml` is TUI-only, and `codex exec` / `-p <profile>` load sandbox/effort config, not a persona. So **INLINE** the persona block into the prompt payload on every dispatch, using the same in-payload pattern as the `DESIGN_DISPATCH_MANIFEST` (Rule 14) — the child cannot resolve agent paths by reference. A persona-less dispatch runs the leaf as a generic assistant, silently dropping the agent's tool-scope, verification gates, and output contract. Canonical contract: `../../sk-prompt/assets/cli-prompt-quality-card.md` "Persona Injection"; native precedent: `orchestrate.md` "Agent Loading Protocol". Rare exceptions (focused summary for a small-context model, pure-mechanical command) are declared at the dispatch site.

18. **Never dispatch `codex exec` from inside a running codex session.** A codex process cannot spawn another codex from inside its own sandbox. The nested child dies at startup with `failed to initialize in-process app-server client: Operation not permitted` (observed 2026-09-02 on codex-cli 0.151.0 under `--sandbox workspace-write`), and the parent reads that as a failed iteration rather than a route violation. So when codex is itself the executor of a deep-loop fan-out lineage or any other orchestrating session, it must do each iteration's work in-process with its own tools and never dispatch a second codex. Grep that exact message to confirm you are hitting this and not a model or network fault.

### ⛔ NEVER

1. Use `--sandbox danger-full-access` without explicit user approval (full shell beyond workspace = damage risk). A no-prompt approval policy does not remove the need for explicit scope approval.
2. Trust Codex output blindly for security-sensitive code, send sensitive data (API keys, passwords, credentials) in prompts, or hammer the API with rapid sequential calls.
3. Use Codex for tasks where context is already loaded — direct action by the calling AI is faster.
4. Assume Codex output is correct without verification — cross-reference codebase and project standards.
5. Build or maintain a packet-local Codex execution adapter; the deep-loop runtime is the execution authority.

### ⚠️ ESCALATE IF

1. Codex CLI is not installed and user has not acknowledged (provide `npm i -g @openai/codex`).
2. Rate limits are persistently exceeded (suggest checking the ChatGPT OAuth account's plan and usage limits).
3. Codex output conflicts with existing code patterns (present both perspectives; user decides).
4. Task requires `--sandbox danger-full-access` (describe risks; get explicit user approval). A no-prompt approval policy still requires explicit scope approval.

### Memory Handback Protocol

When the calling AI needs to preserve session context from a Codex CLI delegation, run the canonical procedure (extract `MEMORY_HANDBACK` section → build structured JSON → scrub secrets → invoke `generate-context.js` via `--stdin`/`--json`/temp-file). The continuity writer is the last step; nothing is handed to an index. Full procedure and caveats: [`system-spec-kit/references/cli/memory-handback.md`](../../../.skilled/skills/system-spec-kit/references/cli/memory-handback.md). Codex-specific Memory Epilogue template: [assets/prompt-templates.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/assets/prompt-templates.md) §13.

```bash
printf '%s' "$JSON_PAYLOAD" | node .skilled/skills/system-spec-kit/runtime/cli/dist/continuity/generate-context.js --stdin [spec-folder]
```

---

## 5. REFERENCES

### Core References

- [cli-reference.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/cli-reference.md) - Complete CLI subcommands, flags, sandbox modes, and config reference
- [integration-patterns.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/integration-patterns.md) - Cross-AI orchestration patterns and workflows
- [codex-tools.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/codex-tools.md) - Built-in capabilities documentation (/review, --search, MCP, session management)
- [hook-contract.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/hook-contract.md) - Native hook contract and Spec Kit startup/advisor wiring
- [agent-delegation.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/references/agent-delegation.md) - Codex agent roster, routing table, and invocation patterns

### Templates and Assets

- [prompt-templates.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/assets/prompt-templates.md) - Copy-paste ready prompt templates for common tasks
- [prompt-quality-card.md](../../../.skilled/skills/cli-external-orchestration/cli-codex/assets/prompt-quality-card.md) - Fast-path prompt framework + CLEAR check (ALWAYS loaded)

### Shared (cli-* family)

- [shared-smart-router.md](../../../.skilled/skills/system-spec-kit/references/cli/shared-smart-router.md) - Helper-function bodies for the smart router.
- [memory-handback.md](../../../.skilled/skills/system-spec-kit/references/cli/memory-handback.md) - Canonical 7-step Memory Handback procedure.

### External

- [Codex CLI GitHub](https://github.com/openai/codex) - Official repository
- [OpenAI ChatGPT](https://chatgpt.com) - ChatGPT OAuth account (auth for cli-codex)

### Reference Loading Notes

- Load only references needed for current intent; Smart Routing (Section 2) is the single routing authority.
- `cli-reference.md` is ALWAYS loaded as baseline.

---

## 6. SUCCESS CRITERIA

### Task Completion

- Codex CLI invoked with correct subcommand, flags, model, and sandbox mode.
- Output captured, validated, and integrated appropriately; no security vulnerabilities introduced.
- Rate limits handled gracefully (retry or fallback strategy).
- Appropriate Codex profile and sandbox level matched to task type (read-only for review, workspace-write for generation).
- Orchestrated execution delegated to the shared deep-loop runtime without a packet-local adapter.

### Skill Quality

- All 8 sections present with proper anchor comments.
- Smart routing covers all intent signals with UNKNOWN_FALLBACK.
- Reference files provide deep-dive content without duplication.

---

## 7. INTEGRATION POINTS

### Framework Integration

This skill operates within the behavioral framework defined in [AGENTS.md](../../../AGENTS.md).

Key integrations:
- **Gate 2**: Skill routing via `skill_advisor.py`
- **Tool Routing**: Per AGENTS.md Section 5 decision tree
- **Continuity**: Context preserved by `/speckit:save`, which writes through `generate-context.js`
- **Execution**: Shared deep-loop runtime (`../../system-deep-loop/runtime/scripts/fanout-run.cjs`)

**Tool roles**: Bash dispatches the CLI; Read/Glob/Grep validate output.

---

## 8. REFERENCES AND RELATED RESOURCES

The router discovers reference, asset, and script docs dynamically (Section 5 is the authored index). Start with the ALWAYS-loaded `references/cli-reference.md` and `assets/prompt-quality-card.md`, then load task-specific resources per Smart Routing.

Related skills: `cli-claude-code` for extended reasoning, `cli-opencode` for full OpenCode runtime dispatch, `sk-code` for code-quality contracts, `mcp-code-mode` for external MCP work, and `system-spec-kit` for packet handback.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.