Codex · EN · Part 4
Ch 14 Advanced Skills Authoring
14-ch-14-Advanced-Skills-Authoring.md
第14章 Advanced Skills Authoring
When-to-Use Criteria
Every skill has a trigger mechanism. In Codex, this lives in the frontmatter's description field—the primary signal that determines whether your skill activates for a given request.
---
name: docx-processor
description: Process Microsoft Word documents with tracked changes, comments, and formatting preservation. Use when working with .docx files for document creation, editing, redline review, or content extraction.
---
The description field serves two audiences: the Codex runtime (which parses it for trigger criteria) and humans reading the skill metadata. Writing effective trigger criteria is the most important skill in skill authoring.
When-to-use Field
The description field is the primary mechanism for skill activation. When Codex receives a request, it:
- Scans the request for explicit mentions (
$skill-nameor[skill-name](skill://...)) - Matches the request content against skill descriptions
- Evaluates file types and programming languages in context
- Considers the task description and intent
Let's look at a real example from the codebase:
// codex-rs/core-skills/src/injection.rs:92-109
/// Collect explicitly mentioned skills from structured and text mentions.
///
/// Structured `UserInput::Skill` selections are resolved first by path against
/// enabled skills. Text inputs are then scanned to extract `$skill-name` tokens, and we
/// iterate `skills` in their existing order to preserve prior ordering semantics.
/// Explicit links are resolved by path and plain names are only used when the match
/// is unambiguous.
pub fn collect_explicit_skill_mentions(
inputs: &[UserInput],
skills: &[SkillMetadata],
disabled_paths: &HashSet<PathBuf>,
connector_slug_counts: &HashMap<String, usize>,
) -> Vec<SkillMetadata>
The mention extraction logic searches for $skill-name patterns and linked references like [$skill](skill://path/to/skill). When a skill name is ambiguous (multiple skills with the same name), Codex requires explicit path resolution to avoid conflicts.
Context Matching
Codex matches requests against skill descriptions using semantic similarity, not just keyword matching. A request like "rotate this PDF" should activate a PDF processing skill even if the word "rotation" doesn't appear literally in the skill description.
⚠️ 避坑指南: Avoid overly generic descriptions. A skill with description "Help with coding" will match virtually every programming request, causing false positives and context bloat. Be specific about domains, file types, and operations.
Trigger Patterns
Effective trigger patterns follow four categories:
File type triggers specify file extensions or patterns:
description: |
Process CSV files with large dataset handling, memory-efficient parsing, and
schema inference. Use when working with .csv files larger than 100MB or
requiring streaming operations.
Programming language triggers specify languages and frameworks:
description: |
React component development with TypeScript, hooks patterns, and Next.js
integration. Use when building React components, writing TypeScript types,
or working with Next.js app router patterns.
Explicit mention triggers rely on users naming the skill:
description: |
Legacy database migrations for the billing microservice. Invoke with
$billing-migrations when working with the billing schema or migration
scripts.
Task description triggers describe the type of work:
description: |
API endpoint design following REST conventions, OpenAPI specification
generation, and HTTP method routing. Use when designing new endpoints,
writing API documentation, or planning resource hierarchies.
Debugging Activation
When a skill doesn't trigger as expected, check the following:
-
Is the skill enabled? Skills can be disabled via config:
[skills.config] name = "my-skill" enabled = false -
Is the description specific enough? Generic descriptions fail to match specific requests.
-
Is there a name conflict? Multiple skills with the same name require explicit path resolution.
-
Is the skill in scope? Skills are discovered from specific directories based on scope (system, user, repo, admin).
The skills system includes caching based on working directory and config state:
// codex-rs/core-skills/src/manager.rs:89-104
/// Load skills for an already-constructed [`Config`], avoiding any additional config-layer
/// loading.
///
/// This path uses a cache keyed by the effective skill-relevant config state rather than just
/// cwd so role-local and session-local skill overrides cannot bleed across sessions that happen
/// to share a directory.
pub fn skills_for_config(&self, input: &SkillsLoadInput) -> SkillLoadOutcome {
let roots = self.skill_roots_for_config(input);
let skill_config_rules = skill_config_rules_from_stack(&input.config_layer_stack);
let cache_key = config_skills_cache_key(&roots, &skill_config_rules);
if let Some(outcome) = self.cached_outcome_for_config(&cache_key) {
return outcome;
}
// ... load and cache
}
Skill Patterns
Beyond the basic markdown file structure, effective skills follow recognizable patterns. Understanding these patterns helps you choose the right approach for your skill's purpose.
Checklist Skills
Checklist skills encode step-by-step procedures that must be followed in order. They're ideal for operations where sequence matters and skipping steps causes problems:
---
name: release-deploy
description: Deploy releases to production with pre-flight checks, rollback preparation, and post-deploy validation. Use when deploying to production environments.
---
# Release Deployment
## Pre-flight Checklist
1. Verify git tag matches intended release version
2. Confirm all tests pass in CI/CD pipeline
3. Check database migration compatibility
4. Verify feature flags are properly configured
5. Confirm rollback script is available
## Deployment Procedure
Execute deployment script:
```bash
./scripts/deploy.sh $VERSION
Monitor deployment logs for errors.
Post-deploy Validation
- Run smoke tests against production endpoints
- Check error rates in monitoring dashboard
- Verify critical user flows are functional
- Monitor database performance metrics
Checklist skills work well because they provide clear structure and prevent omission of critical steps. The `release-deploy` skill demonstrates this pattern—each section represents a phase, and the checklist items are specific, verifiable actions.
> ☕ **茶水间时间**: Why checklist skills over scripts? Scripts execute automatically but hide the steps. Checklist skills make each step explicit, allowing Codex to explain what's happening, adapt to unexpected situations, and provide context about *why* each step matters. For deployment, this transparency is valuable—when something goes wrong, you know exactly what step failed.
### Workflow Skills
Workflow skills guide multi-phase processes where different approaches might be valid based on context. They provide structure while preserving flexibility:
```markdown
---
name: architecture-review
description: Conduct architecture reviews covering system design, scalability, security, and operational concerns. Use when reviewing system designs, planning major changes, or evaluating technical decisions.
---
# Architecture Review Framework
## Phase 1: Understanding
Gather context about the proposed change:
- What problem does this solve?
- What are the constraints and requirements?
- What alternatives were considered?
## Phase 2: Analysis
Evaluate across dimensions:
**Scalability**: Can this handle 10x current load?
**Security**: Are there authentication/authorization implications?
**Operational**: How do we monitor, debug, and deploy this?
**Maintainability**: Is this code approachable for future developers?
## Phase 3: Recommendations
Provide specific, actionable feedback. Avoid vague suggestions.
Workflow skills differ from checklist skills in their degree of freedom. Checklist skills specify exact steps; workflow skills provide guidance and let Codex adapt based on context.
Tool-wrapping Skills
Tool-wrapping skills provide convenient interfaces to complex tools, abstracting away complexity while preserving access to advanced features:
---
name: ffmpeg-helper
description: Video/audio processing with FFmpeg for format conversion, editing, and compression. Use when working with media files, transcoding, or extracting streams.
---
# FFmpeg Helper
## Common Operations
**Convert video to MP4:**
```bash
ffmpeg -i input.mov -c:v libx264 -crf 23 output.mp4
Extract audio:
ffmpeg -i video.mp4 -vn -acodec copy audio.aac
Trim video:
ffmpeg -ss 00:01:00 -i input.mp4 -to 00:02:00 -c copy output.mp4
Advanced
See FFMEPEG-ADVANCED.md for:
- Multi-pass encoding
- Filter chains
- Streaming protocols
- Hardware acceleration
Tool-wrapping skills strike a balance between convenience and power. Common operations are immediately available; advanced features are documented but not loaded unless needed.
### When to Use Each Pattern
Choose your pattern based on the task's nature:
| Pattern | Use when | Example |
|---------|----------|---------|
| Checklist | Steps must happen in sequence; skipping breaks things | Deployment, security reviews |
| Workflow | Multiple valid approaches; context determines the right path | Architecture design, debugging |
| Tool-wrapping | Complex tool with common and advanced use cases | FFmpeg, Docker, Git |
## Skill Composition and Meta-Skills
Skills don't exist in isolation. Complex workflows often require coordinating multiple skills, and some skills exist specifically to manage other skills.
### Skill Composition
When multiple skills apply to a request, Codex must decide which to use. The skills are sorted by scope priority (repo > user > system > admin) and then by name:
```rust
// codex-rs/core-skills/src/loader.rs:166-183
outcome.skills.sort_by(|a, b| {
scope_rank(a.scope)
.cmp(&scope_rank(b.scope))
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.path_to_skills_md.cmp(&b.path_to_skills_md))
});
This ordering ensures that repo-specific skills (closest to the current work) take precedence over user skills, which take precedence over system skills.
Meta-Skills
Meta-skills are skills that coordinate other skills. They don't provide domain expertise themselves; instead, they determine which other skills to invoke based on context:
---
name: workflow-coordinator
description: Coordinate multi-step development workflows by selecting and sequencing appropriate skills. Use when requests span multiple domains or require phased approaches.
---
# Workflow Coordinator
## Skill Selection
When a request involves multiple domains, select skills in priority order:
1. **Core domain skills first** - Start with the primary domain (e.g., database for schema changes)
2. **Supporting skills next** - Add related skills (e.g., migration-scripter, testing)
3. **Infrastructure skills last** - Apply deployment/ops skills only when needed
## Example Sequences
**Adding a new API endpoint:**
1. Use $api-designer to design the endpoint schema
2. Use $rust-backend for implementation
3. Use $test-writer for tests
4. Use $docs-generator for documentation
**Database migration:**
1. Use $schema-reviewer to review changes
2. Use $migration-writer to write migration
3. Use $test-generator to create test data
The workflow-coordinator skill demonstrates a meta-skill pattern: it doesn't contain domain knowledge but instead knows which skills to apply and in what order.
Conditional Activation
Skills can conditionally activate based on file context or command patterns. Codex supports implicit invocation through several mechanisms:
// codex-rs/core-skills/src/invocation_utils.rs:29-43
pub fn detect_implicit_skill_invocation_for_command(
outcome: &SkillLoadOutcome,
command: &str,
workdir: &Path,
) -> Option<SkillMetadata> {
let workdir = normalize_path(workdir);
let tokens = tokenize_command(command);
// First check: is user running a script from a skill's scripts/ directory?
if let Some(candidate) = detect_skill_script_run(outcome, tokens.as_slice(), workdir.as_path())
{
return Some(candidate);
}
// Second check: is user reading a SKILL.md file?
detect_skill_doc_read(outcome, tokens.as_slice(), workdir.as_path())
}
When you run python .agents/skills/my-skill/scripts/process.py, Codex detects that the script lives under a skill's directory and implicitly activates that skill. Similarly, running cat .agents/skills/my-skill/SKILL.md triggers the skill for documentation access.
Conflict Avoidance
Skill conflicts arise when multiple skills claim overlapping domains. Avoid conflicts through:
- Specific descriptions - Narrow the trigger criteria to reduce overlap
- Scope differentiation - Place specific skills in repo scope, general skills in user/system scope
- Explicit coordination - Use meta-skills to sequence conflicting skills rather than letting them compete
Priority Mechanisms
When skills do overlap, the scope system provides priority resolution:
// codex-rs/core-skills/src/loader.rs:166-173
fn scope_rank(scope: SkillScope) -> u8 {
match scope {
SkillScope::Repo => 0, // Highest priority
SkillScope::User => 1,
SkillScope::System => 2,
SkillScope::Admin => 3, // Lowest priority
}
}
Repo skills always override user skills, which override system skills. This makes sense locally-specific knowledge should win over general advice.
Testing and Debugging Skills
Skills operate in an unusual testing environment: they're instructions for another AI system, not code that executes directly. This creates unique testing challenges.
Unit Testing Triggers
The first level of testing verifies that your skill activates when it should. The skills system includes unit tests for trigger logic:
// codex-rs/core-skills/src/injection_utils_tests.rs
#[test]
fn text_mentions_skill() {
let text = "Use $pdf-processor to handle this file";
assert!(text_mentions_skill(text, "pdf-processor"));
assert!(!text_mentions_skill(text, "docx-processor"));
}
#[test]
fn extract_linked_tool_mention() {
let text = "Use [$pdf-processor](skill://path/to/skill) for this";
let mentions = extract_tool_mentions(text);
assert!(mentions.names.contains("pdf-processor"));
assert!(mentions.paths.contains("skill://path/to/skill"));
}
When writing your own skills, you can test activation by creating a minimal test environment and verifying that mentions trigger correctly.
Integration Testing Behavior
Unit tests verify triggers fire; integration tests verify the skill actually guides behavior. The skills system uses snapshot testing for skill output validation:
// From AGENTS.md:103
// cargo-insta for snapshot testing
For your skills, integration testing means:
- Create test scenarios - Specific requests that should trigger your skill
- Verify activation - Confirm the skill loads for those scenarios
- Check guidance quality - Ensure the skill's instructions lead to correct behavior
🤿 深入底层: The
render_skills_sectionfunction generates the skills list that Codex sees in its system prompt. This list includes only skill names, descriptions, and paths—the full skill body loads only when triggered. This progressive disclosure keeps context small while maintaining discoverability.
// codex-rs/core-skills/src/render.rs:5-47
pub fn render_skills_section(skills: &[SkillMetadata]) -> Option<String> {
if skills.is_empty() {
return None;
}
let mut lines: Vec<String> = Vec::new();
lines.push("## Skills".to_string());
lines.push("### Available skills".to_string());
for skill in skills {
let path_str = skill.path_to_skills_md.to_string_lossy().replace('\\', "/");
lines.push(format!("- {}: {} (file: {})",
skill.name, skill.description, path_str));
}
// ... usage instructions
}
Manual Testing Workflows
The most effective skill testing is manual: use the skill on real tasks and observe where it struggles. The skill-creator sample includes validation scripts:
# From skill-creator SKILL.md
python3 <path-to-skill-creator>/scripts/quick_validate.py <path/to/skill-folder>
For manual testing:
- Start with edge cases - Unusual requests, malformed input, ambiguous scenarios
- Test failure modes - What happens when files are missing? When commands fail?
- Verify context efficiency - Is the skill loading more than necessary?
- Check for conflicts - Does this skill interfere with others?
Debugging Techniques
When a skill misbehaves, debug systematically:
Issue: Skill doesn't trigger
- Check the
descriptionfield—Is it specific enough? - Verify the skill is enabled (not disabled via config)
- Test with explicit mention (
$skill-name) to isolate the issue
Issue: Skill triggers too often
- Narrow the
descriptionto be more specific - Move the skill to a narrower scope (repo instead of user)
- Add negative examples to clarify when not to use the skill
Issue: Skill guidance is unclear
- Test the skill on varied requests to find ambiguity
- Add concrete examples to the skill body
- Split complex skills into multiple focused skills
Issue: Context bloat
- Move detailed content to
references/files - Use progressive disclosure—link to details rather than including them
- Remove information Codex already knows (general programming knowledge, common tool usage)
⚠️ 避坑指南: A common mistake is including explanations of concepts Codex already knows. If your skill explains what "environment variables" are or how "for loops work" in Python, you're wasting tokens. Assume Codex is competent and focus on domain-specific knowledge, procedural guidance, and your project's specific conventions.
Chapter Exercises
-
Create a skill with conditional activation: Write a skill that triggers only when working with a specific file type or programming language. Test both positive and negative cases to verify the trigger criteria.
-
Build a meta-skill: Create a skill that coordinates two or more existing skills. The meta-skill should determine which skills to use based on request context and specify the order of application.
-
Debug a non-triggering skill: Given a skill that should trigger but doesn't, systematically identify the issue. Check description specificity, config status, name conflicts, and scope.
Skills extend Codex's capabilities by encoding domain knowledge and procedural guidance. But skills and tools are still local to your development environment—integrating Codex into an IDE requires understanding the extension architecture and the app-server protocol.