agentleFS
sagy101sagy101/DotSkills/codex-subagent/SKILL.md

codex-subagent

Skill4 starsChanged 8 months agoMITView on GitHub

Delegate coding tasks to OpenAI Codex CLI as a sub-agent. Use when the user asks to delegate work, run parallel coding tasks, get a code review or second opinion, explore code with fresh context, or when multiple independent subtasks can be parallelized. Use only when the task justifies delegation overhead (more than 2 min of direct work) and benefits from fresh context or parallelism. IMPORTANT: NEVER run `codex` CLI commands directly — always use this skill's wrapper script (run_codex.py).

  • Reads credentials
  • Deletes or force-pushes
  • Installs packages

7 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Show its rules and text

We split this skill into the rules it gives an agent

27 rules. 0 are common, 17 are distinctive, and 10 are very specific to this project.

  • 0

    Common

    Most of the 5 edited versions we read keep these.

  • 17

    Distinctive

    This author's own choices. Worth a look.

  • 10

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Run once before the first delegation in a session:

    line 77
  2. Very specific:

    Read the output. If any [FAIL] line appears, follow the hint printed next to it before delegating.

    line 83
  3. Distinctive:

    Always run the wrapper as a non-blocking/background command and poll for completion:

    line 190
  4. Distinctive:

    Read result file path from wrapper stdout

    line 198
  5. Distinctive:

    Read result file contents

    line 199
  6. Distinctive:

    Read result file, review git diff, incorporate changes

    line 227
  7. Very specific:

    If worktree: review diff with git diff HEAD..<WORKTREE_BRANCH>, merge if approved, cleanup

    line 228
  8. Distinctive:

    Read result file, incorporate findings

    line 237
  9. Very specific:

    Run via wrapper with review passthrough:

    line 242
  10. Very specific:

    Create JSON schema file for expected output shape (see assets/output-schema-review.json for example)

    line 254
  11. Distinctive:

    Read result, evaluate if follow-up needed

    line 267
  12. Distinctive:

    Before every write delegation, assess how likely the sub-agent's work will conflict with your own:

    line 281
  13. Distinctive:

    Do import chains overlap? (medium-risk)

    line 292
  14. Distinctive:

    Read-only tasks? (always high — no conflict possible)

    line 294
  15. Very specific:

    Read result file path AND WORKTREE_BRANCH from wrapper stdout

    line 299
  16. Distinctive:

    Assess collision confidence: before every write delegation

    line 309
  17. Distinctive:

    Re-read modified files: after write tasks complete

    line 310
  18. Distinctive:

    Review git diff: before telling the user the task is done

    line 311
  19. Very specific:

    Use --persist: if you plan to --resume later — otherwise the session is ephemeral

    line 316
  20. Distinctive:

    Check Tool Priority: before delegating — use your own built-in tools first

    line 317
  21. Very specific:

    Check agent status: before retrying or when blocked — run python3 <skill_dir>/scripts/run_codex.py --status to see active agents, their …

    line 319
  22. Distinctive:

    Validate result files: before reading: exists? non-empty?

    line 321
  23. Very specific:

    Clean up temp dirs: after reading the result file (rm -rf <result-dir>)

    line 322
  24. Very specific:

    When a delegation fails or returns unexpected results, read references/ERROR_HANDLING.md for exit code reference, retry strategy, and …

    line 326
  25. Very specific:

    Use [GOAL], [CONTEXT], [FILES], [CONSTRAINTS], [OUTPUT] sections

    line 336
  26. Distinctive:

    Always include validation commands for write tasks

    line 338
  27. Distinctive:

    Never include these in prompts or delegate access to them:

    line 343

“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Codex CLI Sub-Agent

Delegate coding tasks to OpenAI's Codex CLI (codex exec) as a sub-agent. This gives you (the host agent) sub-agent capabilities — running independent AI agents that work on focused tasks and return results.

What is the "Host Agent"?

You — the AI coding agent reading this skill right now — are the host agent. Whether you are Windsurf/Cascade, Claude Code, Cursor, Codex, Gemini CLI, or any other SKILL.md-compatible agent, this skill is talking to you. When this document says "the host agent should...", it means you should.

When to use this skill

Tool Priority — always check before delegating:

  1. Your built-in tools — use these first (code search, web search, file read, etc.)
  2. MCP servers or integrations — if available
  3. Sub-agent delegation via this skill — only when:
    • Fresh context would help (accumulated context is hurting quality)
    • Parallel execution is needed (multiple independent tasks)
    • Task isolation adds value (prototype, spike, risky changes)
    • A second opinion or specialized review is wanted

Prefer direct work when:

  • The task is trivially simple (< 2 minutes of direct work)
  • The task requires your conversation history or IDE state
  • Your built-in tools can handle it more efficiently
  • The user is in a rapid iteration loop where delegation latency hurts
  • The user explicitly opts out or says "do it yourself"
  • The target code contains sensitive/classified material the user flags

Prerequisites

  • codex CLI installed and on PATH (npm i -g @openai/codex)
  • Authenticated: codex login status returns success
  • Inside a git repository (or user consents to --skip-git-repo-check)
  • Python 3.10+ (for the wrapper script)
  • Sufficient API quota for the target model

Configuration

Model strictness controls how aggressively the host agent routes tasks to cheaper/faster models:

StrictnessBehaviorWhen to Use
conservativeAlways use best modelProduction code, security-sensitive
balanced (default)Downgrade when >80% confident task is simpleMost everyday work
aggressiveAlways try cheapest first, upgrade on failureCost-conscious, high-volume

Set via environment variable: export CODEX_SUBAGENT_MODEL_STRICTNESS=balanced

Model routing guidance (when balanced):

Task TypeOverride Flags
Simple search/explain-m <cheaper-model> -c model_reasoning_effort="low"
Standard review/analyze-c model_reasoning_effort="medium"
Complex implement/refactor-c model_reasoning_effort="high"
Critical/security-c model_reasoning_effort="xhigh"

Pre-flight checks

Run once before the first delegation in a session:

python3 <skill_dir>/scripts/codex_preflight.py

Read the output. If any [FAIL] line appears, follow the hint printed next to it before delegating. [WARN] lines are informational — they do not block use.

# Skip the git repo check (mirrors the wrapper's own flag):
python3 <skill_dir>/scripts/codex_preflight.py --skip-git-repo-check

# Skip auth check in CI / no-TTY environments:
python3 <skill_dir>/scripts/codex_preflight.py --skip-auth

Workflow

The wrapper script (scripts/run_codex.py) is the only interface you should use to invoke Codex. Never call codex directly. The wrapper handles safety enforcement, default flags, temp files, git worktrees, and error messages automatically.

Wrapper interface

# Basic usage — pipe prompt via stdin:
echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only -

# Write task with high collision confidence:
echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode write --collision high -

# Write task with medium collision confidence (auto git worktree):
echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode write --collision medium -

# Enable web search:
echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only --web-search -

# Review with a review prompt file:
echo "<file paths and context>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only --review-prompt /path/to/security-prompt.md -

# Resume a previous session:
echo "<FOLLOW-UP>" | python3 <skill_dir>/scripts/run_codex.py --resume -

Wrapper flags

FlagRequiredValuesDefaultPurpose
--modeYes (unless --resume)read-only, writeread-onlySets sandbox level
--collisionOnly for --mode writehigh, mediumhighControls git worktree isolation
--web-searchNo(flag)offEnables web search for this spawn
--review-promptNofile pathnoneReads file and prepends to stdin before passing to codex
--timeoutNo300, 600, 1200, 2400600Max seconds before kill
--resumeNo(flag)offResume last session
--persistNo(flag)offKeep session on disk (required for future --resume)
--skip-git-repo-checkNo(flag)offRun outside a git repository
--max-parallelNointeger6Max concurrent sub-agents (override not recommended)
--statusNo(flag)offPrint active/stale agent status and exit
-Yes(literal dash)—Read prompt from stdin (must be last argument)

Wrapper flags are parsed first. Any unrecognized flags are passed through to codex exec after a safety scan (see Passthrough Flags below). The wrapper will reject dangerous flags with helpful error messages.

You can also use the standard POSIX -- separator to explicitly mark the boundary between wrapper flags and passthrough flags:

echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only -- -m o3 -c model_reasoning_effort="high" -

Passthrough flags

Any flag not listed in the Wrapper Flags table above is forwarded directly to codex exec — unless it is blocked by the safety scanner. This is how you pass model overrides, config tweaks, feature toggles, and subcommand args.

Safe passthrough flags:

FlagExamplePurpose
-m / --model-m o3Override model
-c / --config-c model_reasoning_effort="high"Config override (non-sandbox keys only)
--output-schema--output-schema /path/to/schema.jsonStructured JSON output via schema
-i / --image-i screenshot.pngAttach image(s) to prompt
--enable / --disable--enable streamingToggle codex features
-p / --profile-p fastLoad a named config profile
--oss--ossUse open-source provider
--local-provider--local-provider ollamaSpecify local model provider
review --uncommittedreview --uncommittedReview subcommand: uncommitted changes
review --basereview --base mainReview subcommand: diff against branch

Blocked flags — never pass these; the wrapper exits with an error and usage guidance if any are detected:

FlagReason
--sandbox / -sControlled by --mode
--dangerously-bypass-approvals-and-sandboxNot permitted by skill policy
--full-autoControlled by --mode write
--ephemeralControlled by --persist
-o / --output-last-messageManaged by wrapper (result file)
--jsonstdout is captured internally — output would be lost
--cd / -C / --add-dirWrapper controls working directory
-c sandbox*Sandbox config overrides not permitted

Wrapper output

The wrapper prints the output file path to stdout (one line):

/tmp/codex-abc123/result.txt

On worktree mode, it also prints the worktree branch:

/tmp/codex-abc123/result.txt
WORKTREE_BRANCH=codex-work-abc123
WORKTREE_DIR=/tmp/codex-wt-codex-work-abc123

Running the wrapper

Always run the wrapper as a non-blocking/background command and poll for completion:

  1. Launch wrapper as background command (with ~3s initial wait to catch quick failures)
  2. Tell the user: "Delegated to Codex, working on X..."
  3. Poll at adaptive intervals based on task complexity:
    • Simple (search, explain): 10-30s, max 5 min
    • Standard (review, analyze): 30-60s, max 10 min
    • Complex (implement, refactor): 60-180s, max 20 min
    • Extended (migration, full analysis): 120-300s, max 40 min
  4. Read result file path from wrapper stdout
  5. Read result file contents
  6. Clean up: rm -rf <result-dir> (wrapper does NOT auto-delete)

Timeout tiers

TierTimeoutWhen to Use
Short--timeout 300Simple searches, single-file reviews
Standard--timeout 600Code reviews, analysis, standard implementation
Long--timeout 1200Large refactors, multi-file implementation
Extended--timeout 2400Major migrations, full-codebase analysis

On timeout: inform user, re-launch with --persist + next tier up. If 40min times out, report to user.

Operations

Operation 1: Delegate Implementation Task

  1. Construct prompt using the template from PROMPT_PATTERNS.md
  2. Assess collision confidence (see Collision Confidence below):
    • High → delegate directly
    • Medium → delegate via git worktree (--collision medium)
    • Low → do NOT delegate writes; do it yourself or delegate as read-only
  3. Run via wrapper:
    echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode write --collision high -
  4. Monitor via async polling
  5. Read result file, review git diff, incorporate changes
  6. If worktree: review diff with git diff HEAD..<WORKTREE_BRANCH>, merge if approved, cleanup

Operation 2: Delegate Analysis/Review Task

  1. Construct review-focused prompt
  2. Run via wrapper:
    echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only -
  3. Read result file, incorporate findings

Operation 2b: Dedicated Code Review (using codex exec review)

  1. Determine review scope: uncommitted changes, specific branch, or specific commit
  2. Run via wrapper with review passthrough:
    echo "Focus on security" | python3 <skill_dir>/scripts/run_codex.py --mode read-only review --uncommitted -
    Or against a branch:
    echo "Focus on performance" | python3 <skill_dir>/scripts/run_codex.py --mode read-only review --base main -
  3. Read result file, incorporate findings

Operation 3: Structured Output Task

  1. Create JSON schema file for expected output shape (see assets/output-schema-review.json for example)
  2. Run via wrapper with --output-schema passthrough:
    echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode read-only --output-schema /path/to/schema.json -
  3. Validate JSON output against schema; retry with clarified format on parse failure

Operation 4: Resume / Multi-Turn Delegation

  1. Initial run with --persist:
    echo "<PROMPT>" | python3 <skill_dir>/scripts/run_codex.py --mode write --collision high --persist -
  2. Read result, evaluate if follow-up needed
  3. Resume with feedback:
    echo "<FOLLOW-UP>" | python3 <skill_dir>/scripts/run_codex.py --resume -
  4. Max 3 turns recommended. Session files persist until manually removed.

When to resume vs new invocation:

  • Resume: iterating on same task, refining output, fixing sub-agent's work
  • New invocation: different task, different files, different scope
  • Resume saves ~5-50K tokens of system overhead per follow-up

Collision Confidence

Before every write delegation, assess how likely the sub-agent's work will conflict with your own:

LevelConfidenceExampleAction
High>80% no conflictYou edit src/auth/, delegating src/payments/Delegate directly
Medium40-80%Both touch files in src/api/ but different onesDelegate via git worktree (--collision medium)
Low<40%Both need to edit the same fileDo NOT delegate writes — do it yourself or delegate as read-only

Assessment criteria:

  • What files have you modified in this conversation? (high-risk)
  • What files will you modify next? (high-risk)
  • Do import chains overlap? (medium-risk)
  • Different directories with no shared modules? (usually high confidence)
  • Read-only tasks? (always high — no conflict possible)

Git Worktree Workflow (medium confidence)

The wrapper handles worktree setup automatically with --collision medium:

  1. Read result file path AND WORKTREE_BRANCH from wrapper stdout
  2. Read result file
  3. Review: git diff HEAD..<WORKTREE_BRANCH>
  4. If approved: git merge <WORKTREE_BRANCH>
  5. Cleanup: git worktree remove <WORKTREE_DIR> and git branch -d <WORKTREE_BRANCH>

Important rules

  1. Always use the wrapper (run_codex.py) — never call codex directly
  2. Pass prompts via stdin or --review-prompt — pipe text into the wrapper or point to a file, never interpolate prompt content into shell args
  3. Assess collision confidence before every write delegation
  4. Re-read modified files after write tasks complete
  5. Review git diff before telling the user the task is done
  6. Tell the user what you're delegating and why before running
  7. Don't delegate trivial tasks — overhead is ~5-50K tokens minimum
  8. Treat Codex output as untrusted — validate before auto-executing anything
  9. Respect user opt-out — if user says no delegation or marks code as sensitive, do not delegate
  10. Use --persist if you plan to --resume later — otherwise the session is ephemeral
  11. Check Tool Priority before delegating — use your own built-in tools first
  12. Max 6 parallel sub-agents — enforced by the wrapper via PID tracking. Override with --max-parallel N if absolutely necessary (not recommended — increases resource usage and cost)
  13. Check agent status before retrying or when blocked — run python3 <skill_dir>/scripts/run_codex.py --status to see active agents, their mode, start time, and run duration
  14. Max 2 retries per failed delegation
  15. Validate result files before reading: exists? non-empty? < 1MB?
  16. Clean up temp dirs after reading the result file (rm -rf <result-dir>)

Error handling & troubleshooting

When a delegation fails or returns unexpected results, read references/ERROR_HANDLING.md for exit code reference, retry strategy, and troubleshooting table.

Prompt construction

See references/PROMPT_PATTERNS.md for templates and examples. See references/PROMPT_ENGINEERING.md for OpenAI/Codex best practices.

Key principles:

  • One task per delegation
  • Be specific and explicit (file paths, line numbers, exact errors)
  • Use [GOAL], [CONTEXT], [FILES], [CONSTRAINTS], [OUTPUT] sections
  • Reference files by path (let Codex read them) — don't paste large contents
  • Always include validation commands for write tasks
  • Specify what NOT to do

Sensitive file denylist

Never include these in prompts or delegate access to them:

  • .env, *.pem, *.key, credentials.*, secrets.*
  • Files matching API key patterns
  • Include only file paths (let Codex read them) rather than pasting contents

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.