Production-grade tutorial | Codex CLI, IDE extension, repository skills, dynamic intent recognition, lifecycle hooks, and automated validation | November 2026
This guide covers how to create, update, deploy, and test reusable Codex Skills, including two working examples:
refactor— an explicitly invoked skill for safe code refactoring.db-performance-review— an implicitly discoverable skill for database performance analysis, with an optional lifecycle hook for automatic file-change checks.
1. First, understand the actual Codex architecture
Three distinctions are essential before writing any configuration.
| Feature | Correct mechanism | Invocation |
|---|---|---|
| Explicit reusable skill | SKILL.md | $refactor |
| Automatic intent-based skill selection | SKILL.md description | Codex chooses a relevant skill |
| Actual custom slash command | Legacy custom prompt | /prompts:refactor |
| Repository-wide instructions | AGENTS.md | Loaded as project guidance |
| Deterministic event interception | Codex lifecycle hooks | Events such as PostToolUse |
| Deterministic CI enforcement | GitHub Actions or other CI | Push or pull request |
Important corrections to the proposed architecture:
Codex’s documented repository skill location is .agents/skills/<skill-name>/SKILL.md, not .codex/skills/. The .codex/ directory is useful for repository-specific Codex configuration and hooks.
Skills are explicitly invoked with $skill-name, rather than automatically becoming /skill-name slash commands. The /skills interface helps discover skills. Legacy custom prompts still provide /prompts:name, but that mechanism is deprecated in favor of skills.
Finally, implicit skill recognition is model-directed, not a guaranteed filesystem event listener. To guarantee a particular validation command runs after a supported edit operation, use a hook or CI pipeline rather than relying on a skill description alone. ChatGPT Learn+2
These distinctions determine the implementation below.
2. Directory blueprint
Use this structure in the root of a Git repository:
my-project/
├── AGENTS.md
│
├── .agents/
│ └── skills/
│ ├── refactor/
│ │ ├── SKILL.md
│ │ └── agents/
│ │ └── openai.yaml
│ │
│ └── db-performance-review/
│ ├── SKILL.md
│ └── agents/
│ └── openai.yaml
│
├── .codex/
│ ├── hooks.json
│ └── hooks/
│ └── db_performance.py
│
├── .github/
│ └── workflows/
│ └── db-performance.yml
│
└── tests/
└── test_db_performance.py
There are three configuration layers to understand:
| Layer | Purpose |
|---|---|
~/.codex/AGENTS.md | Global instructions for your local Codex environment |
my-project/AGENTS.md | Repository-specific engineering standards and conventions |
my-project/.agents/skills/ | Reusable skills discoverable by Codex within the repository |
You can also install personal skills at ~/.agents/skills/, or organization-managed skills at /etc/codex/skills/. Codex discovers repository skills from the current working directory up through the repository root. ChatGPT Learn+1
Standard SKILL.md blueprint
The minimum valid skill uses YAML frontmatter with two required fields:
---
name: example-skill
description: Describe the task this skill performs and the circumstances in which Codex should select it.
---
# Example Skill
## Instructions
1. Inspect the relevant project files.
2. Identify the requested changes.
3. Apply the required workflow.
4. Run the appropriate validations.
5. Report changes, results, and limitations.
name is the skill identifier. description is its primary discovery and intent-matching metadata. Instructions in the Markdown body become relevant after the skill is selected.
For Codex-specific presentation and invocation policy, put optional configuration in agents/openai.yaml, not invented frontmatter keys such as hooks, triggers, on_file_change, or file_patterns.
3. Production-ready explicit skill: $refactor
Save this source as .agents/skills/refactor/SKILL.md.
---
name: refactor
description: Safely refactor existing application code while preserving externally observable behavior, public APIs, and data contracts. Use only when the user explicitly requests the $refactor workflow to improve readability, modularity, maintainability, or complexity without changing features.
---
# Behavior-Preserving Refactor
## Input contract
Accept a file, module, function, folder, or explicitly
identified code region and optional goals.
If scope is ambiguous, inspect the current changes and ask
for a bounded target before touching unrelated code.
Treat the user's requirements as the source of truth.
## Procedure
1. Inspect `AGENTS.md`, nested instructions, relevant files,
nearby tests, and `git status --short`. Leave unrelated
work untouched.
2. State a concise refactor plan: target, invariants,
proposed changes, and verification commands.
3. Identify behavior contracts: return values, errors,
side effects, API shape, serialization, persistence,
concurrency, performance-critical paths, and security.
4. Establish a baseline by running the narrowest available
tests. Add characterization tests when appropriate.
5. Apply the smallest coherent change. Prefer named helpers,
clearer control flow, reduced duplication, and bounded
functions over broad rewrites.
6. Do not silently add dependencies, modify database schema,
change public APIs, or alter runtime behavior.
7. Re-run targeted tests, type checks, and linters.
Compare against the baseline where possible.
8. Review `git diff --check` and `git diff` for regressions,
unrelated edits, secrets, and formatting churn.
## Safety rules
- Never delete, reset, or overwrite uncommitted user work.
- Never run destructive commands without authorization.
- Never claim successful testing when tests were not run.
- Separate behavior changes from behavior-preserving work.
- Never commit or push unless explicitly requested.
## Output contract
Return four sections:
- Scope: what changed and why.
- Behavior preserved: key invariants.
- Verification: commands, results, and tests not run.
- Risks / follow-ups: remaining issues.
Next, save .agents/skills/refactor/agents/openai.yaml:
interface:
display_name: "Refactor"
short_description: "Safely refactor existing code without behavior changes"
default_prompt: "Use $refactor to refactor the specified files while preserving behavior and verifying tests."
policy:
allow_implicit_invocation: false
The documented allow_implicit_invocation: false policy makes the skill explicit-only while retaining $refactor invocation. Test this behavior against your installed CLI version because some releases have had explicit-skill discovery issues. ChatGPT Learn+1
Execute it in Codex
From the project root:
codex
Then enter this in the Codex conversation:
$refactor Refactor src/services/userService.ts.
Goals:
- Reduce cyclomatic complexity.
- Extract duplicated validation logic.
- Preserve all public APIs and return values.
- Keep the existing error behavior.
- Run the relevant tests.
- Show the final diff and verification results.
Expected behavior: Codex resolves the named skill, follows its instructions, edits only the relevant files, runs supported tests, and reports the result. The outcome still depends on available tools, approvals, and repository state.
4. Production-ready dynamic skill: db-performance-review
Unlike $refactor, this skill allows implicit invocation. Codex can select it when the user’s task involves SQL queries, Prisma schemas, migrations, indexes, or ORM operations.
Save as .agents/skills/db-performance-review/SKILL.md:
---
name: db-performance-review
description: Review database query, SQL migration, ORM query, or schema changes for performance regressions. Use when tasks involve editing or reviewing .sql or .prisma files, database schemas, indexes, query builders, ORM repositories, or data access paths; assess query plans, indexes, cardinality, locks, and migration safety.
---
# Database Performance Review
## Input contract
Accept a planned or completed change to SQL queries,
migration files, Prisma schemas, ORM query builders,
or data access modules.
Do not treat every code edit as database work.
## Procedure
1. Read repository instructions, schema, and query files.
Determine the database engine and deployment context.
2. Find changed database files using `git diff --name-only`,
`git status --short`, and the user's specified scope.
3. Run the repository's static checker, when available:
`python3 .codex/hooks/db_performance.py --check-all`
Treat this as an anti-pattern scan, not a performance
benchmark.
4. Inspect filters, joins, sorting, pagination, cardinality,
returned columns, N+1 queries, and index coverage.
5. For migrations, assess lock duration, backfills,
uniqueness constraints, transactional behavior,
deployment compatibility, and recovery strategy.
6. When an authorized non-production database is available,
inspect representative query plans with
`EXPLAIN (FORMAT JSON)`.
7. Run `EXPLAIN ANALYZE` only when separately authorized
and safe. Do not analyze writes against production.
8. Compare actual query plans and benchmarks against
verified baselines whenever available.
9. Propose minimal fixes, verify them, and distinguish
demonstrated improvements from hypotheses.
## Safety rules
- Never print database credentials or customer records.
- Never silently connect to a production database.
- Never execute production migrations as part of a review.
- Never invent performance metrics.
- Never present static heuristics as proof of query speed.
## Output contract
Return:
- Changed paths
- Findings and severity
- Index and query-plan recommendations
- Commands executed and actual results
- Remaining risks and next actions
Save as .agents/skills/db-performance-review/agents/openai.yaml:
interface:
display_name: "DB Performance Review"
short_description: "Check database changes for query and schema risks"
default_prompt: "Use $db-performance-review to inspect the changed SQL, ORM, and schema files for performance risks."
policy:
allow_implicit_invocation: true
Test implicit recognition
Enter this in a new Codex session, without referencing the skill by name:
I modified prisma/schema.prisma and two SQL queries.
Review these changes for performance regressions,
missing indexes, migration risks, and expensive query patterns.
Codex should consider the database review skill because the task matches its description. Whether it selects the skill is a model decision, not a guaranteed event. ChatGPT Learn
5. Deterministic event automation with Codex hooks
For the stronger requirement — run a check when Codex updates a database-related file — use PostToolUse hooks.
The complete starter implements this sequence:
SessionStart
Record SHA-256 hashes of monitored database files
Codex edits a SQL, Prisma, or database module
Through a supported local tool
PostToolUse
Compare hashes and scan changed SQL files
No flagged patterns
Report clean static checks
Potential issue
Send findings to Codex for review
Hook registration
Save as .codex/hooks.json:
{
"description": "Database change detection and static performance review for Codex local sessions.",
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume|clear|compact|fork",
"hooks": [
{
"type": "command",
"command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/db_performance.py\" --seed",
"timeout": 30,
"statusMessage": "Initializing database change detection"
}
]
}
],
"PostToolUse": [
{
"matcher": "Bash|apply_patch|Edit|Write",
"hooks": [
{
"type": "command",
"command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/db_performance.py\" --post",
"timeout": 45,
"statusMessage": "Checking database file changes"
}
]
}
]
}
}
The matcher identifies supported tool operations, not filenames. The accompanying Python implementation checks which database-related files actually changed and sends feedback to Codex.
The full db_performance.py implementation (approximately 300 lines) is included in both downloadable packages. It includes SHA-256 snapshots, session-specific state, basic concurrency protection, file classification, SQL heuristics, and CI operation.
Codex hooks support events such as SessionStart, PreToolUse, and PostToolUse, with tool-specific matchers and structured responses. They require an enabled, trusted, supported runtime. They do not monitor every external filesystem write. ChatGPT Learn+2
6. Deployment, testing, and deliverables
Complete 2026 Codex Skills guide
1,200+ lines of Markdown containing the complete source files, architecture, installation steps, testing matrix, and troubleshooting reference.
Download full Markdown guide
Deployable repository starter kit
Both skills, metadata, AGENTS.md, hooks, Python checker, tests, CI workflow, safe installer, and the guide.
Download repository starter ZIP
Individually validated skill packages
For installing just one skill instead of the whole starter repository.
Refactor skill ZIP
Database Performance Review skill ZIP
Quick deployment
Download and extract the starter ZIP to a temporary directory. Then run the included conflict-aware installer from that directory:
python3 scripts/install.py --repo /absolute/path/to/my-project
If your repository already has AGENTS.md, use:
python3 scripts/install.py \
--repo /absolute/path/to/my-project \
--skip-agents
Manually merge the relevant guidance into the existing AGENTS.md. The installer refuses to overwrite differing existing files.
Verification commands
Run from the target repository root:
# Validate hook configuration
python3 -m json.tool .codex/hooks.json
# Compile the checker
python3 -m py_compile .codex/hooks/db_performance.py
# Run the unit test suite
python3 -m unittest discover -s tests -v
# Static database performance scan
python3 .codex/hooks/db_performance.py --check-all
# Strict scan, suitable for an enforcement gate
python3 .codex/hooks/db_performance.py --check-all --strict
# Check repository changes
git diff --check
git status --short
Next, start Codex:
codex
Use /skills to check discovery, /hooks to inspect and trust the configured lifecycle hooks, and $refactor to test explicit invocation.
Test matrix
| Test | Expected outcome |
|---|---|
Explicit $refactor | Refactor skill selected |
| Natural-language database performance request | DB skill considered through intent matching |
| Unrelated UI edit | No database-specific skill needed |
Codex changes .sql file | PostToolUse detects the modified file |
Codex changes .prisma file | Schema change detected |
| Codex edits unrelated file | No DB change report |
SQL contains SELECT * | Static checker reports an advisory |
| Pull request introduces a flagged pattern | Strict GitHub Actions check fails |
| Restart after skill update | Updated skill discoverable |
| Hook not trusted | Hook execution not assumed |
Validation results
4 of 4 local tests passed
Both skill structures validated successfully.
The hook JSON parsed successfully, the Python checker compiled, and the ZIP archive passed its integrity check. I also tested the installer in a disposable Git repository, including its refusal to overwrite an existing modified AGENTS.md.
Remaining runtime verification: Codex CLI is not installed in this environment, so live skill invocation, model-driven intent matching, and hook trust/execution have not been tested here. The Markdown guide provides the exact steps to complete those tests on your machine.
The recommended production setup is to use skills for reusable agent behavior, AGENTS.md for project policy, trusted lifecycle hooks for immediate local feedback, and CI for independent enforcement. That gives you both the convenience of intelligent skill selection and a reliable validation layer.
Behavior-Preserving Refactor
Safely refactor existing application code while preserving externally observable behavior, public APIs, and data contracts. Use only when the user explicitly requests the $refactor workflow to improve readability, modularity, maintainability, or complexity without changing features.
Try in chat
Database Performance Review
Review database query, SQL migration, ORM query, or schema changes for performance regressions. Use when tasks involve editing or reviewing .sql or .prisma files, database schemas, indexes, query builders, ORM repositories, or data access paths; assess query plans, indexes, cardinality, locks, and migration safety.
Try in chat