Agent Skills
A skill is a selectively loaded folder of instructions and optional references, scripts, and assets. Use it for a repeatable procedure that would otherwise crowd global instructions. Keep the entry file focused and direct the agent to supporting material when needed; do not impose invented universal token or decision-count thresholds.
Preserved Long-Form Material: skill md building reusable skills
Pattern-library note: The restored examples below preserve useful teaching depth from the earlier manuscript. Their bookmark, chat, password-reset, or other sample domains are secondary exercises. TaskFlow audit export is the canonical running system, and the current definitions and policies earlier in this guide take precedence over tool-specific legacy wording.
Learning Objectives
By the end of this chapter, you will be able to:
- Define what a Skill is and explain its role in extending AI coding agents
- Describe current skill packaging conventions and their adoption across platforms
- Master SKILL.md anatomy: YAML frontmatter and markdown body
- Structure skill directories with references, scripts, and assets
- Understand skill discovery directories and their priority order
- Explain progressive loading: Discovery → Activation → Execution
- Create a complete "spec-writer" skill for SDD-compliant specifications
- Create a complete "code-reviewer" skill that reviews code against specifications
- Apply the Skill vs Rule decision framework
- Install and use community skills
- Apply best practices: token limits, reference files, when-to-use specificity
What Is a Skill?
A Skill is a packaged, reusable capability that extends what an AI coding agent can do. Unlike rules (which provide persistent context) or AGENTS.md (which provides project-level instruction), skills are task-specific and on-demand. The agent discovers skills by name and description, activates them when relevant, and follows their instructions to perform specialized workflows.
Think of a skill as a teachable moment: when the user asks for something the agent doesn't fully know—writing SDD-compliant specifications, performing a specific code review format, generating commit messages in a team format—the skill provides the missing knowledge. The agent applies it, produces better output, and the skill remains available for future use.
Skills vs. Rules vs. AGENTS.md
| Aspect | Skill | Rule | AGENTS.md |
|---|---|---|---|
| Purpose | Task-specific capability | Project convention | Project context |
| Loading | On-demand when relevant | Conditional (always, intelligent, file, manual) | Always |
| Scope | Reusable across projects | Project-specific | Project-specific |
| Size | Typically <5000 tokens | Typically <500 lines | Variable |
| When | Agent deems task relevant | Based on activation mode | Every prompt |
Skill: "When the user asks for a specification, use this template and process." Rule: "When editing TypeScript files, follow these conventions." AGENTS.md: "This project uses Express, follows REST conventions, and requires tests."
Skills Packaging Conventions
Skills currently follow a set of emerging conventions for packaging AI agent capabilities. In practice, implementations differ by platform. Common elements include:
- File format (SKILL.md with YAML frontmatter)
- Directory structure
- Discovery mechanism
- Metadata schema
Platform Support (Implementation Varies)
| Platform | Skills Support | Discovery Paths |
|---|---|---|
| Cursor | Yes | .cursor/skills/, ~/.cursor/skills/ |
| Claude Code | Yes | .claude/skills/ |
| Codex | Yes | .codex/skills/ |
| Roo Code | Via Memory Banks | .roo/ |
| Gemini CLI | Yes | Compatible paths |
| VS Code | Via extensions | Varies |
These conventions enable partial portability: a skill written for one platform can often be adapted to another with minor changes, but metadata fields, discovery paths, and activation behavior may differ.
Practical rule: treat skills as "portable with adaptation," not "write once, run everywhere."
SKILL.md File Anatomy
Every skill centers on a SKILL.md file. It has two parts: YAML frontmatter (metadata) and markdown body (instructions).
YAML Frontmatter
The frontmatter appears at the top of the file, between --- delimiters:
---
name: spec-writer
description: Writes SDD-compliant specifications from user stories and feature descriptions. Use when creating specifications, writing requirements, or converting product descriptions into structured specs.
version: 1.0.0
license: MIT
compatibility:
- cursor
- claude
- codex
metadata:
author: Your Team
category: specification
allowed-tools:
- read_file
- write
---
Required Fields
| Field | Type | Purpose |
|---|---|---|
name | string | Unique identifier. Lowercase, hyphens. Max 64 chars. |
description | string | What the skill does and when to use it. Max 1024 chars. Critical for discovery. |
Optional Fields
| Field | Type | Purpose |
|---|---|---|
version | string | Semantic version for tracking |
license | string | License (MIT, Apache-2.0, etc.) |
compatibility | array | Platforms that support this skill |
metadata | object | Author, category, tags |
allowed-tools | array | Tools the skill may use (constrains agent) |
The Description: Critical for Discovery
The agent uses the description to decide when to apply the skill. It is injected into the system prompt during discovery. Write it in third person and include both WHAT and WHEN:
Bad:
description: Helps with specs
Good:
description: Writes SDD-compliant specifications from user stories and feature descriptions. Use when creating specifications, writing requirements, converting product descriptions into structured specs, or when the user mentions "spec", "requirements", or "feature spec".
Include trigger terms: "spec", "requirements", "feature spec", "user story", "acceptance criteria". The more specific the when-to-use, the better the agent's activation decision.
Markdown Body
The body contains the instructions the agent follows when the skill is activated. Typical sections:
| Section | Purpose |
|---|---|
| Instructions | Step-by-step process |
| When to Use | Refined activation criteria |
| Process Steps | Numbered workflow |
| Examples | Concrete input/output samples |
| Templates | Output format structures |
| References | Links to detailed docs |
Skill Directory Structure
Skills are stored as directories containing SKILL.md and optional supporting files:
.cursor/skills/spec-writer/
├── SKILL.md # Required: main instruction file
├── references/ # Optional: reference documents
│ ├── spec-template.md
│ └── component-checklist.md
├── scripts/ # Optional: automation scripts
│ └── validate-spec.sh
└── assets/ # Optional: templates, examples
└── example-spec.md
SKILL.md
The main file. Keep it under 5000 tokens (roughly 500 lines) for optimal loading. Use progressive disclosure: essential content in SKILL.md, details in references.
references/
Detailed documentation the agent reads when needed. Link from SKILL.md: "For the full template, see references/spec-template.md." Keep references one level deep—deeply nested references may be partially read.
scripts/
Executable helpers. Use when the skill involves validation, transformation, or automation that is more reliable as a script than as generated code. Document how to run them.
assets/
Templates, examples, and static resources. Use for content that doesn't change and benefits from being read as a file rather than inlined.
Skill Discovery Directories
Agents discover skills by scanning configured directories. A common priority order (often first match wins when skills have the same name) is:
.agents/skills/— Project-level (emerging standard).cursor/skills/— Project-level (Cursor)~/.cursor/skills/— User/global (Cursor).claude/skills/— Project-level (Claude Code compatibility).codex/skills/— Project-level (Codex compatibility).roo/— Project-level (Roo Code Memory Banks)
Project skills (.cursor/skills/, .agents/skills/) are shared with anyone using the repository. User skills (~/.cursor/skills/) are personal and available across all projects.
When the same skill name exists in multiple locations, the project-level path typically overrides the user-level path, allowing project-specific customization.
Progressive Loading
Skills use a three-phase loading model to balance discovery cost with activation depth:
Phase 1: Discovery (~100 tokens per skill)
The agent scans skill directories and reads only name and description from each SKILL.md. This lightweight pass builds a catalog. The agent uses descriptions to rank relevance for the current task.
Phase 2: Activation (<5000 tokens)
When the agent deems a skill relevant, it loads the full SKILL.md (and optionally referenced files). The token budget is typically under 5000 tokens to avoid crowding the context. Skills that exceed this may be truncated or load only partial content.
Phase 3: Execution
The agent follows the skill's instructions. It may read referenced files, run scripts, or apply templates. Execution continues until the task is complete or the agent determines the skill no longer applies.
Implication: Write concise SKILL.md files. Put extensive content in reference files. The agent will load references when the skill instructs it to.
Tutorial: Create a Spec-Writer Skill
This tutorial walks you through creating a complete "spec-writer" skill that produces SDD-compliant specifications.
Step 1: Create the Directory
mkdir -p .cursor/skills/spec-writer/references
Step 2: Write the YAML Frontmatter
Create .cursor/skills/spec-writer/SKILL.md:
---
name: spec-writer
description: Writes SDD-compliant specifications from user stories, feature descriptions, and product requirements. Use when creating specifications, writing requirements, converting product descriptions into structured specs, or when the user mentions "spec", "requirements", "feature spec", "user story", or "acceptance criteria".
version: 1.0.0
---
# Spec-Writer Skill
## When to Use
Apply this skill when the user wants to:
- Create a new feature specification
- Convert a user story or PRD into a structured spec
- Expand a vague feature description into a complete spec
- Add missing components to an incomplete spec
## Process
1. **Gather input**: Extract or request the feature description, user story, or requirements.
2. **Identify gaps**: Use [NEEDS CLARIFICATION: specific question] for any ambiguity.
3. **Follow the template**: Produce a spec with all 10 components (see references/spec-template.md).
4. **Validate**: Ensure each acceptance criterion is Given/When/Then testable.
## The 10 Components
Every specification MUST include:
| # | Component | Purpose |
|---|-----------|---------|
| 1 | Problem Statement | Why; who; pain; impact |
| 2 | User Journeys | Narrative scenarios |
| 3 | Functional Requirements | What the system must do |
| 4 | Non-Functional Requirements | Quality attributes |
| 5 | Acceptance Criteria | Testable conditions |
| 6 | Edge Cases | Boundaries, errors |
| 7 | Constraints | What NOT to do |
| 8 | Dependencies | Internal and external |
| 9 | Observability | Logs, metrics, alerts |
| 10 | Security Requirements | Auth, encryption, audit |
## Rules
- **Focus on WHAT, not HOW**: No implementation details, tech stack, or code structure.
- **Mark ambiguities**: Use [NEEDS CLARIFICATION: specific question] — never guess.
- **Testable criteria**: Every acceptance criterion must be Given/When/Then.
- **No premature detail**: Keep abstraction appropriate for the spec phase.
## Output Format
Use the structure in [references/spec-template.md](/appendices/spec-templates).
## Example
**Input**: "Users need to reset their password by email."
**Output**: A full specification with Problem (users locked out, support burden), User Journeys (successful reset, expired link, rate limited), Functional Requirements (request, validate token, set password, rate limit), Acceptance Criteria (testable), Edge Cases (expired, invalid, already used), Constraints (no email enumeration), Dependencies (email service, user store), Observability (logs, metrics), Security (token entropy, HTTPS).
Step 3: Create the Reference Template
Create .cursor/skills/spec-writer/references/spec-template.md:
# Feature [ID]: [Name]
## Problem
[1-3 sentences. Who experiences the problem? What is the pain? What is the impact?]
- **Who**: [User role or persona]
- **Pain**: [What they experience]
- **Impact**: [Consequence of not solving]
## User Journeys
### Journey 1: [Name]
[Narrative: 2-5 sentences from user perspective]
### Journey 2: [Name]
[Alternative or error path]
## Functional Requirements
### FR-1: [Capability Name]
[Precise description]
### FR-2: [Capability Name]
[Precise description]
## Non-Functional Requirements
### NFR-1: [Attribute] — [Measurable target]
[Description]
## Acceptance Criteria
- **AC-1**: Given [precondition], When [action], Then [expected result]
- **AC-2**: Given [precondition], When [action], Then [expected result]
## Edge Cases
- **EC-1**: [Boundary or error condition]
- **EC-2**: [Boundary or error condition]
## Constraints
- **C-1**: [What must NOT happen]
- **C-2**: [What must NOT happen]
## Dependencies
### Internal
- [Service/component]: [operations needed]
### External
- [System]: [integration required]
## Observability
### Logs
- [Event]: [fields to log]
### Metrics
- [metric_name]: [description]
### Alerts
- [Condition]: [action]
## Security Requirements
- **SEC-1**: [Auth, crypto, or audit requirement]
- **SEC-2**: [Auth, crypto, or audit requirement]
Step 4: Test the Skill
In Cursor, prompt:
"Create a specification for: Users need to export their data to CSV. Include all 10 components. Use the spec-writer skill."
Expected behavior: The agent loads the spec-writer skill and produces a complete, structured specification following the template.
Tutorial: Create a Code-Reviewer Skill
This tutorial creates a "code-reviewer" skill that reviews code against specifications.
Step 1: Create the Directory
mkdir -p .cursor/skills/code-reviewer/references
Step 2: Write the SKILL.md
Create .cursor/skills/code-reviewer/SKILL.md:
---
name: code-reviewer
description: Reviews code against specifications, constraints, and coding standards. Use when reviewing pull requests, examining code changes, validating implementation against specs, or when the user asks for a code review.
version: 1.0.0
---
# Code-Reviewer Skill
## When to Use
Apply this skill when the user wants to:
- Review code for spec compliance
- Validate implementation against a specification
- Check code against project constraints
- Perform a structured code review
## Process
1. **Load context**: Read the specification (if provided) and the code under review.
2. **Map requirements**: For each acceptance criterion, identify the implementing code.
3. **Check compliance**: Verify each AC is satisfied. Note gaps.
4. **Check constraints**: Verify no constraint violations.
5. **Check quality**: Assess readability, error handling, tests.
6. **Report**: Use the output format below.
## Review Dimensions
### Spec Compliance
- Every acceptance criterion has implementing code
- Edge cases are handled
- Constraints are respected
### Code Quality
- Logic is correct
- Error handling is comprehensive
- Functions are focused
- Naming is clear
### Security
- No obvious vulnerabilities (injection, XSS, etc.)
- Auth/authz used correctly
- Sensitive data handled properly
### Tests
- Acceptance criteria have test coverage
- Edge cases are tested
- Tests are meaningful (not just pass)
## Output Format
```markdown
# Code Review: [Feature/PR name]
## Spec Compliance
| AC | Status | Notes |
|----|--------|-------|
| AC-1 | ✅/❌ | [Brief note] |
| AC-2 | ✅/❌ | [Brief note] |
## Constraint Check
| Constraint | Status | Notes |
|------------|--------|-------|
| [Constraint] | ✅/❌ | [Brief note] |
## Findings
### Critical (must fix)
- [Finding]
### Suggestions (consider)
- [Finding]
### Nice to have
- [Finding]
## Summary
[2-3 sentence overall assessment]
Severity Levels
- Critical: Spec violation, constraint violation, security issue, broken logic
- Suggestion: Quality improvement, better error handling, clearer code
- Nice to have: Optional enhancement, style preference
### Step 3: Test the Skill
Provide a specification and code, then prompt:
> "Review this code against the specification. Use the code-reviewer skill. Provide the full review report."
**Expected behavior**: The agent produces a structured review with spec compliance table, constraint check, and findings by severity.
---
## Skill vs Rule: Decision Framework
When should you create a **Skill** vs a **Rule**?
### Create a Skill When:
- The task is **specialized** and not needed for every conversation
- The instructions are **substantial** (process, templates, examples)
- The capability is **reusable across projects**
- The agent should **activate on recognition** of the task type
- You want **progressive loading** (discovery first, full load on activation)
**Examples**: Spec-writing, code review, commit message generation, database schema analysis, API client generation.
### Create a Rule When:
- The guidance applies to **many or all** edits in a file type
- The content is **concise** (under 50 lines typical)
- It encodes **project-specific conventions**
- It should apply **whenever** certain files are open
- You want **always-on** or **file-triggered** activation
**Examples**: TypeScript error handling pattern, React component structure, API naming conventions, test file format.
### Create AGENTS.md Content When:
- The guidance is **project-wide** and **always relevant**
- It's **foundational** (architecture, stack, workflow)
- It doesn't fit the "task-specific" or "file-specific" model
**Examples**: "This project uses Express. All endpoints require auth. Tests go in __tests__."
### Decision Tree
Is it project-wide and always relevant? YES → AGENTS.md NO ↓
Is it file-type or session triggered? YES → Rule NO ↓
Is it a specialized task with substantial instructions? YES → Skill NO → Consider Rule or inline in prompt
---
## Installing Community Skills
Community skills can be installed via package managers or manual copy.
### Using npx (when available)
```bash
npx agent-skills install spec-writer
This fetches the skill from a registry and installs it to the appropriate directory.
Manual Installation
- Clone or download the skill repository
- Copy the skill directory to
.cursor/skills/(project) or~/.cursor/skills/(user) - Verify SKILL.md has correct frontmatter
Verifying Installation
List skills in Cursor: the skill should appear in the skill picker or be discoverable when you prompt for a task that matches its description.
Best Practices
1. Keep SKILL.md Under 5000 Tokens
Long skills consume context. Use progressive disclosure: essential instructions in SKILL.md, details in reference files.
2. Reference Files Instead of Inlining
Instead of:
## Template
[500 lines of template]
Use:
## Template
See [references/spec-template.md](/appendices/spec-templates).
The agent reads the file when needed. Saves tokens during discovery and activation.
3. Be Specific About When-to-Use
Vague: "Helps with specifications." Specific: "Writes SDD-compliant specifications. Use when creating specs, converting user stories, or when the user mentions 'spec', 'requirements', 'acceptance criteria'."
Specific descriptions improve activation accuracy.
4. Write in Third Person
The description is injected into the system prompt. Use third person:
- ✅ "Processes Excel files and generates reports"
- ❌ "I can help you process Excel files"
5. Include Trigger Terms
Add keywords the user might say: "spec", "requirements", "review", "commit message", "test generation". These help the agent match the skill to the request.
6. Provide Concrete Examples
Examples anchor the agent. Show input → output pairs. For workflows, show a complete example.
7. One Concern Per Skill
Don't combine spec-writing and code review in one skill. Split into focused skills. The agent can activate multiple skills when needed.
8. Version Your Skills
Use the version field. When you update a skill, increment the version. This helps track changes and debug activation issues.
9. Test Skills with Edge Cases
Verify your skill with:
- Minimal input (does it ask for more or fail gracefully?)
- Ambiguous input (does it use [NEEDS CLARIFICATION]?)
- Complex input (does it handle all components?)
- Wrong input (does it reject or correct?)
10. Document Skill Dependencies
If your skill assumes certain project structure (for example specs/[branch-name]/), document it. If it requires specific tools (for example npx), note them. Users should know prerequisites before installing.
Skill Debugging and Troubleshooting
Skill Not Activating
Symptoms: Agent doesn't use the skill when you expect it to.
Checks:
- Description: Does it include trigger terms the user might say?
- Location: Is the skill in a discovery directory? Check priority order.
- Name: Unique? No conflict with another skill?
- Format: Valid YAML frontmatter? No syntax errors?
Skill Activates but Produces Poor Output
Symptoms: Agent uses the skill but output doesn't follow instructions.
Checks:
- Instructions: Are they clear and unambiguous? Add examples.
- Token limit: Is the skill truncated? Move content to references.
- Conflicting context: Do rules or AGENTS.md contradict the skill?
- Examples: Are they representative? Add more diverse examples.
Skill Loads Slowly or Times Out
Symptoms: Delay when agent activates the skill.
Checks:
- Size: Is SKILL.md under 5000 tokens?
- References: Are referenced files large? Consider summarizing.
- Scripts: Do scripts run slowly? Optimize or document expected duration.
Skill Composition and Chaining
Skills can build on each other. A spec-writer skill's output can feed a plan-generator skill. Consider:
Sequential Chaining
User: "Write a spec for X, then create an implementation plan."
- Agent activates spec-writer, produces spec
- Agent activates plan-generator (or equivalent), uses spec as input
- Output: spec + plan
Conditional Chaining
User: "Review this code. If it passes, suggest improvements. If it fails, list fixes."
- Agent activates code-reviewer
- Based on findings, agent either suggests improvements or lists fixes
Shared References
Multiple skills can reference the same project documents (constitution, constraints). Ensure consistency: if the constitution changes, all skills that reference it stay aligned.
Try With AI
Prompt 1: Skill Discovery
"List the skills available in this project. For each, summarize the name and description. Which would you apply if I asked you to 'write a specification for user login'? Explain your reasoning."
Prompt 2: Skill Creation
"I need a skill for [describe task]. Create a SKILL.md with: (1) YAML frontmatter with name and description, (2) when-to-use section, (3) process steps, (4) output format or template. Keep it under 200 lines. What reference files would you add?"
Prompt 3: Skill vs Rule
"I want to enforce [describe convention or task]. Should this be a Skill, a Rule, or AGENTS.md content? Use the decision framework: project-wide? file-triggered? task-specific? Explain your reasoning and draft the appropriate artifact."
Prompt 4: Skill Improvement
"Review this skill: [paste SKILL.md]. Evaluate: (1) Is the description specific enough for discovery? (2) Is it under 5000 tokens? (3) Does it use progressive disclosure? (4) Are there concrete examples? Suggest specific improvements."
Practice Exercises
Exercise 1: Spec-Writer Skill Extension
Take the spec-writer skill from the tutorial. Add a references/component-checklist.md that lists a pre-output checklist: "Before finalizing the spec, verify: [ ] All 10 components present, [ ] No [NEEDS CLARIFICATION] unresolved, [ ] Every AC is Given/When/Then, [ ] Edge cases cover boundaries and errors." Update SKILL.md to reference this checklist in the process. Test with a new spec request.
Expected outcome: The agent uses the checklist before producing the spec, resulting in more complete output.
Exercise 2: Domain-Specific Skill
Create a skill for a domain you work in: e.g., "API design", "database migration", "E2E test generation". Include: frontmatter, when-to-use, process, and at least one reference file. Test it with a relevant prompt.
Expected outcome: A working skill that the agent activates and applies correctly for your domain.
Exercise 3: Skill Audit
Audit an existing skill (yours or from the community). Check: token estimate (use ~4 chars per token), description quality, progressive disclosure, examples. Write a one-page audit report with specific recommendations.
Expected outcome: An audit document that could guide skill improvement.
Key Takeaways
-
Skills are packaged, on-demand capabilities that extend AI agents. They are task-specific and reusable across projects.
-
Skills packaging conventions improve portability across Cursor, Claude Code, Codex, Gemini CLI, and VS Code, but practical adaptation is often required.
-
SKILL.md anatomy: YAML frontmatter (name, description required) + markdown body (instructions, when-to-use, process, examples).
-
Skill directory structure: SKILL.md + references/ + scripts/ + assets/. Use references for detailed content; keep SKILL.md under 5000 tokens.
-
Discovery order: .agents/skills/ → .cursor/skills/ → ~/.cursor/skills/ → .claude/skills/ → .codex/skills/.
-
Progressive loading: Discovery (name+description) → Activation (full SKILL.md) → Execution (follow instructions).
-
Skill vs Rule: Skills for task-specific, substantial, on-demand capabilities. Rules for file-scoped, concise, conditional conventions.
-
Best practices: Concise descriptions with trigger terms, third person, reference files over inlining, one concern per skill.
Chapter Quiz
-
What is a Skill, and how does it differ from a Rule and AGENTS.md in terms of loading and purpose?
-
What are the required fields in SKILL.md frontmatter? Why is the description especially critical?
-
Describe the skill directory structure. What goes in references/ vs scripts/ vs assets/?
-
List the skill discovery directories in priority order. What is the difference between project and user skills?
-
Explain progressive loading. What happens in Discovery, Activation, and Execution? Why does token count matter?
-
When should you create a Skill vs a Rule? Use the decision framework to explain.
-
What are three best practices for writing effective skills? Give a concrete example for each.
-
You want to add a skill that generates commit messages in your team's format. What would you include in the SKILL.md? What might go in a reference file?
Preserved Long-Form Material: reusable intelligence patterns
Pattern-library note: The restored examples below preserve useful teaching depth from the earlier manuscript. Their bookmark, chat, password-reset, or other sample domains are secondary exercises. TaskFlow audit export is the canonical running system, and the current definitions and policies earlier in this guide take precedence over tool-specific legacy wording.
Learning Objectives
By the end of this chapter, you will be able to:
- Define Reusable Intelligence (RI) and explain why every SDD project produces two outputs
- Distinguish and apply the five types of reusable intelligence: skills, subagents, ADRs, PHRs, and intelligence templates
- Design intelligence using the P+Q+P pattern: Persona, Questions, Principles
- Differentiate horizontal intelligence (cross-project) from vertical intelligence (domain-specific)
- Extract reusable intelligence from a completed feature through a hands-on tutorial
- Apply the intelligence maturity model: ad-hoc → documented → templated → automated
- Create a skill, ADR, and PHR from real project work
What Is Reusable Intelligence?
Reusable Intelligence (RI) is the capture of patterns, decisions, and effective prompts so they accelerate future work. In traditional development, knowledge lives in people's heads or scattered documentation. In SDD with AI, knowledge must be externalized so that both humans and AI can apply it consistently.
Every Spec-Driven Development project produces two outputs:
- The product code — The feature, the API, the UI. What the user sees and uses.
- The reusable intelligence — The skills, ADRs, PHRs, and templates that make the next project faster.
The second output is often overlooked. Teams ship code and move on. But the patterns that worked—the prompts that produced good results, the architectural decisions that paid off, the workflows that reduced rework—are lost. Reusable Intelligence is the practice of capturing and reusing those patterns.
The Compounding Effect
Project 1: Build feature A. Learn patterns. Ship code. (No RI capture)
Project 2: Build feature B. Relearn patterns. Ship code. (No RI capture)
Project 3: Build feature C. Relearn again. Ship code.
vs.
Project 1: Build feature A. Extract skills, ADRs, PHRs. Ship code + RI.
Project 2: Build feature B. Use RI from Project 1. Extract new RI. Ship code + RI.
Project 3: Build feature C. Use RI from 1 and 2. Extract new RI. Ship code + RI.
With RI capture, each project builds on the last. Without it, each project starts from zero.
Types of Reusable Intelligence
Five primary types of RI serve different purposes and scales.
1. Skills (SKILL.md)
Purpose: Encode 2–4 key decisions with human-guided execution.
When to use: Recurring workflows that benefit from structured guidance but don't need full autonomy.
Format: SKILL.md file with clear instructions, decision points, and examples.
Example: A "Create Cursor Rule" skill guides the user through creating a .cursor/rules file with the right structure. The human runs the skill; the AI follows the steps.
Location: agents/skills/ or $CODEX_HOME/skills/ (for cross-project reuse)
2. Subagents
Purpose: Package a reusable workflow whose supporting instructions and assets should load only when relevant.
When to use: Complex, multi-step workflows that can run with minimal human intervention.
Format: AGENTS.md entry or dedicated agent configuration with persona, capabilities, and constraints.
Example: A "Spec-to-Plan" subagent reads a spec and produces a full implementation plan. It makes many decisions (technology, data model, phases) autonomously.
Location: agents/subagents/ or referenced in AGENTS.md
3. Architectural Decision Records (ADRs)
Purpose: Capture why decisions were made.
When to use: Any significant architectural or design decision that future developers (or AI) need to understand.
Format: Markdown document with Context, Decision, Rationale, Consequences.
Example: "ADR 0002: Use WebSockets for real-time chat" — documents why WebSockets over Server-Sent Events or polling.
Location: memory/adr/
4. Prompt History Records (PHRs)
Purpose: Capture effective prompts that produced good results.
When to use: When a prompt consistently yields high-quality output and you want to reuse it.
Format: Markdown with the prompt, context, outcome, and when to use.
Example: "PHR-001: Generate OpenAPI from data model" — the exact prompt that produced a correct contract.
Location: memory/phr/ or memory/context/
5. Intelligence Templates
Purpose: Reusable specification and plan templates.
When to use: When features share structure (e.g., CRUD APIs, event-driven flows).
Format: Template files with placeholders and instructions.
Example: specs/templates/crud-api-spec-template.md — template for any CRUD feature with standard sections.
Location: specs/templates/, agents/templates/
The P+Q+P Pattern for Designing Intelligence
The P+Q+P pattern structures how you design any reusable intelligence artifact: skills, subagents, or agent instructions.
Persona: Who Is the Agent?
Define the agent's identity and expertise.
Bad: "You are helpful."
Good: "You are a backend architect specializing in REST APIs and PostgreSQL. You prefer simplicity over abstraction. You always consider security and performance."
Why it matters: Persona shapes tone, depth, and default assumptions. A "security specialist" agent will surface different concerns than a "rapid prototyping" agent.
Questions: What to Ask Before Acting
Define what the agent should clarify before proceeding.
Bad: (No questions — agent guesses)
Good:
- "What is the expected request volume?"
- "Is this endpoint authenticated?"
- "What error format does the client expect?"
Why it matters: Questions prevent wrong assumptions. They force the human (or upstream agent) to provide context that would otherwise be guessed incorrectly.
Principles: Rules for Execution
Define the rules the agent must follow.
Bad: "Write good code."
Good:
- "Validate all inputs at the boundary."
- "No business logic in controllers."
- "Every endpoint has an integration test."
Why it matters: Principles constrain output. They ensure consistency across sessions and prevent common mistakes.
P+Q+P in Practice
Example: API Design Skill
# API Design Skill
## Persona
You are an API architect who designs RESTful APIs for production systems.
You prioritize clarity, consistency, and backward compatibility.
## Questions (Ask Before Designing)
1. What is the primary consumer of this API? (web, mobile, internal service?)
2. What are the rate limits or scalability requirements?
3. Is pagination required? What are typical list sizes?
4. What error format does the client expect?
## Principles
1. Use nouns for resources, HTTP verbs for actions
2. Return 201 for creation, 204 for successful delete
3. Use consistent error format: { "error": { "code": "...", "message": "..." } }
4. Document all endpoints in OpenAPI 3.0
5. No breaking changes without versioning
Horizontal vs. Vertical Intelligence
Horizontal Intelligence
Horizontal intelligence applies across projects and domains. It is generic enough to be reused anywhere.
| Pattern | Applies To | Example |
|---|---|---|
| Testing | All projects | "Write unit tests with Arrange-Act-Assert" |
| Security | All projects | "Never log passwords; validate inputs" |
| API design | All REST APIs | "Use consistent error format" |
| Git workflow | All repos | "Commit messages: type(scope): description" |
| Spec structure | All SDD projects | "Spec must have AC for every FR" |
Location: Often in shared skill repositories, .cursor/rules that apply globally, or cross-project ADRs.
Vertical Intelligence
Vertical intelligence is domain-specific. It applies within a domain (fintech, healthcare, e-commerce) but not universally.
| Pattern | Domain | Example |
|---|---|---|
| PCI compliance | Fintech | "Never store raw card numbers" |
| HIPAA | Healthcare | "Audit all PHI access" |
| Cart flows | E-commerce | "Support guest checkout, merge on login" |
| Real-time chat | Collaboration | "Message ordering, delivery receipts" |
Location: Project-specific skills, domain ADRs, memory/ in domain projects.
When to Use Each
- Horizontal: Create once, reuse everywhere. Invest in quality; it pays off across many projects.
- Vertical: Create when starting a domain project. Refine as you build. Share within the domain team.
Intelligence Acceleration: How Skills Compound
Skills compound when they build on each other.
Level 1: Single Skill
You create a skill for "Write unit tests." Every time you need tests, you use it. Saves time.
Level 2: Skill Chain
You have:
- Skill A: "Generate spec from description"
- Skill B: "Generate plan from spec"
- Skill C: "Generate tasks from plan"
Using A → B → C creates a pipeline. Each skill feeds the next.
Level 3: Skill + ADR + PHR
You have:
- Skill: "Design REST endpoint"
- ADR: "Why we use this error format"
- PHR: "Prompt that generates correct OpenAPI from our conventions"
The skill tells you what to do. The ADR tells you why. The PHR gives you the exact prompt that works. Together, they produce consistent, high-quality output faster.
Level 4: Domain Stack
In a domain (e.g., fintech), you accumulate:
- Skills: PCI-safe validation, audit logging, idempotency
- ADRs: Why we use event sourcing, why we chose this payment provider
- PHRs: Prompts for compliance checks, reconciliation reports
- Templates: Spec template for payment flows, plan template for financial features
New features in the domain reuse the stack. Onboarding is faster. Consistency is higher.
Tutorial: Extract Reusable Intelligence from a Completed Feature
This tutorial walks you through extracting RI from a feature you've already built. We'll use "user registration" as the example.
Prerequisites
- A completed feature (spec, plan, implementation)
- Access to the project's memory/ and agents/ directories
Step 1: Identify Recurring Patterns
Review the feature end-to-end. Ask:
- What decisions did we make? (technology, structure, conventions)
- What prompts worked well? (exact prompts that produced good output)
- What would we do again? (patterns worth reusing)
- What would we do differently? (learnings for next time)
Example for user registration:
- Decisions: JWT for auth, bcrypt for passwords, email validation with regex + DNS check
- Prompts that worked: "Generate registration endpoint from this spec and contract"
- Patterns: Validation at boundary, error format, test structure
- Learnings: Should have added rate limiting earlier
Step 2: Create an ADR for the Architectural Decision
For each significant decision, create an ADR.
Example: memory/adr/0003-registration-auth-flow.md
# ADR 0003: User Registration and Authentication Flow
## Status
Accepted
## Context
We need user registration with secure password handling and session management.
Options: JWT vs session cookies, bcrypt vs Argon2, email verification timing.
## Decision
- JWT (RS256) for tokens: access 15 min, refresh 7 days
- bcrypt cost 12 for password hashing
- Email verification: send link, allow 24h to verify; user can log in with unverified email but with limited access
- Rate limiting: 5 failed attempts per IP per 15 min
## Rationale
- JWT: Stateless, works across services, team familiarity
- bcrypt: Battle-tested, cost 12 balances security and performance
- Email verification: Reduces spam; 24h window balances UX and security
- Rate limiting: Prevents brute force; 5 attempts is industry standard
## Consequences
- Must manage token refresh flow in client
- Must store refresh tokens (DB or Redis) for revocation
- Must implement rate limiting middleware
- Unverified users need "limited access" logic in authorization
Step 3: Create a Skill from the Pattern
Identify a workflow that recurs. Create a skill.
Example: agents/skills/user-registration-skill/SKILL.md
# User Registration Implementation Skill
## Persona
You are a backend developer implementing user registration for a production system.
You prioritize security, validation, and testability.
## Questions (Ask Before Implementing)
1. What fields are required? (email, password, name, etc.)
2. What validation rules? (password strength, email format)
3. Is email verification required? When?
4. What's the rate limiting policy?
5. What error format does the API use?
## Principles
1. Validate all inputs at the boundary (controller/service entry)
2. Hash passwords with bcrypt cost 12; never log or return passwords
3. Use parameterized queries; no SQL injection
4. Return 201 for success, 400 for validation errors, 409 for duplicate email
5. Write unit tests for validation, integration tests for full flow
6. Follow ADR 0003 for auth flow decisions
## Steps
1. Read spec and data model
2. Create User entity with required fields
3. Create migration
4. Implement RegistrationService with validation
5. Implement POST /register endpoint
6. Add rate limiting middleware
7. Write tests
8. Update API contract
Step 4: Save a PHR for the Most Effective Prompt
When a prompt produced excellent results, save it.
Example: memory/phr/phr-001-registration-endpoint.md
# PHR-001: Generate Registration Endpoint from Spec
## When to Use
When implementing a user registration endpoint and you have spec.md and contracts/register.yaml.
## Context Required
- spec.md (feature spec)
- contracts/register.yaml (API contract)
- data-model.md (User entity)
- memory/constitution.md (project conventions)
## Prompt
Implement the user registration endpoint per specs/001-user-registration/spec.md.
Requirements:
- Follow the contract in contracts/register.yaml exactly
- Use the User entity from data-model.md
- Apply validation: email format (RFC 5322), password min 12 chars, 1 upper, 1 lower, 1 digit, 1 special
- Hash password with bcrypt cost 12
- Return 201 with user (no password) on success
- Return 400 with field-level errors on validation failure
- Return 409 if email already exists
- Write unit test for validation, integration test for full flow
Reference memory/constitution.md for error format and coding standards.
## Outcome
- Produced correct endpoint matching contract
- Validation logic correct
- Tests passed on first run
- Error format consistent with project
## Variations
- For different validation rules: adjust the "Apply validation" line
- For different error format: reference project's api-conventions.md
Step 5: Update the Intelligence Maturity
Reflect on where your project sits:
| Level | State | Next Step |
|---|---|---|
| Ad-hoc | No capture | Document one ADR, one PHR |
| Documented | ADRs, PHRs exist | Create first skill |
| Templated | Skills, templates | Chain skills; create subagent |
| Automated | Subagents, pipelines | Refine; share across projects |
The Intelligence Maturity Model
Level 1: Ad-hoc
- No systematic capture
- Knowledge in people's heads
- Each project starts fresh
- High variability in output quality
Transition: Document one significant decision (ADR) and one effective prompt (PHR).
Level 2: Documented
- ADRs for key decisions
- PHRs for effective prompts
- Some templates (spec, plan)
- Still human-driven; AI uses docs as reference
Transition: Create first skill for a recurring workflow.
Level 3: Templated
- Skills for common workflows
- Templates for specs, plans, contracts
- Consistent structure across features
- AI follows templates; human guides
Transition: Chain skills; consider subagent for multi-step flows.
Level 4: Automated
- Subagents for complex flows
- Pipelines: specify → plan → tasks → implement
- Minimal human intervention for routine work
- Human focuses on review, exceptions, strategy
Transition: Refine based on feedback; share horizontal intelligence across projects.
Creating a Skill: Deep Dive
Skill Anatomy
A well-structured skill has:
- Title and description — What it does, when to use it
- Persona — Who the agent is (P+Q+P)
- Questions — What to ask before acting (P+Q+P)
- Principles — Rules for execution (P+Q+P)
- Steps — Ordered actions (optional but helpful)
- Examples — Input/output samples (optional)
Skill Template
# [Skill Name]
## Description
[One paragraph: what this skill does, when to use it]
## Persona
[Who the agent is; expertise; default stance]
## Questions (Ask Before Acting)
1. [Question 1]
2. [Question 2]
3. [Question 3]
## Principles
1. [Rule 1]
2. [Rule 2]
3. [Rule 3]
## Steps
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Examples
### Input
[Example input]
### Output
[Example output]
Skill vs. Subagent: When to Use Which
| Criterion | Skill | Subagent |
|---|---|---|
| Decisions | 2–4 | 5+ |
| Human involvement | High (human runs it) | Low (autonomous) |
| Complexity | Single workflow | Multi-step pipeline |
| Reuse scope | Often project-specific | Can be cross-project |
| Format | SKILL.md | AGENTS.md + config |
Creating an ADR: Deep Dive
ADR Template
# ADR [number]: [Title]
## Status
[Proposed | Accepted | Deprecated | Superseded by ADR-XXX]
## Context
[What is the issue? What forces are at play?]
## Decision
[What did we decide?]
## Rationale
[Why did we decide this?]
## Consequences
[What are the implications? Positive and negative.]
When to Write an ADR
- Technology choices (database, framework, auth)
- Architectural patterns (layering, event sourcing)
- API design decisions (REST vs GraphQL, error format)
- Process decisions (branching strategy, deployment)
- Security or compliance decisions
When NOT to Write an ADR
- Trivial choices ("we use 4 spaces for indentation")
- Temporary decisions
- Decisions that are fully documented elsewhere
Creating a PHR: Deep Dive
PHR Template
# PHR-[number]: [Short Title]
## When to Use
[Under what conditions does this prompt work well?]
## Context Required
[What files, specs, or info must be loaded?]
## Prompt
[The exact prompt—copy-paste ready]
## Outcome
[What did it produce? Quality? Any fixes needed?]
## Variations
[How to adapt for similar but different cases]
What Makes a Good PHR
- Specific: The prompt is exact, not vague
- Context-aware: Lists what must be loaded
- Reproducible: Someone else can get similar results
- Honest: Notes limitations and when it didn't work
Horizontal Intelligence: Cross-Project Skills
Some skills are valuable across all your projects. Consider creating a shared skills repository.
Example: Testing Skill (Horizontal)
# Unit Test Generation Skill
## Persona
You are a test engineer who writes clear, maintainable unit tests.
You use Arrange-Act-Assert. You mock external dependencies.
## Questions
1. What testing framework? (Jest, pytest, etc.)
2. What's the expected behavior? (from spec or docstring)
3. What are the edge cases?
4. What should be mocked?
## Principles
1. One assertion focus per test (or one logical unit)
2. Test behavior, not implementation
3. Descriptive test names: "should return 400 when email is invalid"
4. No flaky tests (no randomness, no time dependence unless tested)
5. Fast tests (no real DB, no real network)
This skill applies to any project. Put it in a shared location (e.g., $CODEX_HOME/skills/testing/).
Example: API Error Format (Horizontal)
# Consistent API Error Format
## Standard Format
{
"error": {
"code": "ERR_XXX",
"message": "Human-readable message",
"details": {} // optional, for validation errors
}
}
## HTTP Status Mapping
- 400: Validation error (ERR_VALIDATION)
- 401: Unauthorized (ERR_UNAUTHORIZED)
- 403: Forbidden (ERR_FORBIDDEN)
- 404: Not found (ERR_NOT_FOUND)
- 409: Conflict (ERR_CONFLICT)
- 500: Server error (ERR_INTERNAL)
This is a principle that can be referenced in any API project.
Vertical Intelligence: Domain-Specific Patterns
Example: Fintech — Payment Idempotency
# Payment Idempotency Skill
## Persona
You implement payment flows for a fintech application.
You prioritize correctness, auditability, and idempotency.
## Questions
1. What idempotency key does the client send? (header? body?)
2. What's the idempotency window? (24h? 7 days?)
3. What payment provider? (Stripe, Adyen, etc.)
4. What's the reconciliation process?
## Principles
1. Same idempotency key + same params = same result (no double charge)
2. Store idempotency key with result; return cached result on replay
3. Log all payment attempts (success and failure) for audit
4. Never expose raw card data; use tokens
5. Follow PCI DSS: no card data in logs, memory, or errors
Example: Healthcare — PHI Handling
# PHI Access Skill
## Persona
You implement features that touch Protected Health Information (PHI).
You prioritize HIPAA compliance and minimal access.
## Questions
1. What PHI is involved? (name, DOB, diagnosis, etc.)
2. Who needs access? (role-based?)
3. What's the audit requirement?
4. Is data at rest encrypted?
## Principles
1. Access only what's needed for the operation
2. Log all PHI access: who, when, what
3. No PHI in logs (mask or hash)
4. Use parameterized queries; no PHI in URLs
5. Session timeout for inactive users
Try With AI
Prompt 1: Extract ADR from Discussion
"We just decided to use WebSockets for real-time updates instead of polling. The reasons were: lower latency, less server load, better UX. Our alternative was Server-Sent Events. Help me write an ADR (memory/adr/000X-websockets.md) capturing this decision. Use the standard ADR format."
Prompt 2: Create Skill from Workflow
"I repeatedly do this workflow: (1) read a spec, (2) generate an OpenAPI contract, (3) implement the endpoint. Create a skill (SKILL.md) that guides an AI through this. Use the P+Q+P pattern. Include the questions I should answer before we start."
Prompt 3: Save Effective Prompt as PHR
"This prompt worked really well: [paste your prompt]. The output was [describe]. Create a PHR (memory/phr/phr-XXX.md) with: when to use, context required, the exact prompt, outcome, and one variation for a similar case."
Prompt 4: Intelligence Maturity Assessment
"Review my project's memory/ and agents/ directories. Assess where we are on the intelligence maturity model (ad-hoc, documented, templated, automated). List 3 concrete steps to move to the next level. Prioritize by impact."
Practice Exercises
Exercise 1: Extract RI from a Completed Feature
Choose a feature you've built (or use the user registration example). Extract: (1) one ADR for a significant decision, (2) one PHR for an effective prompt, (3) one skill for a recurring pattern. Write all three artifacts. Reflect: What was easy? What was hard? What would you do differently next time?
Expected outcome: Three RI artifacts (ADR, PHR, skill) plus a brief reflection.
Exercise 2: Design a Horizontal Skill
Create a skill that applies to any project. Examples: "Write integration test," "Design REST endpoint," "Create database migration." Use the P+Q+P pattern. Include at least 3 questions and 5 principles. Test it: Use the skill with AI on a small task. Did it improve output?
Expected outcome: A horizontal skill (SKILL.md) and a short test report.
Exercise 3: Intelligence Maturity Roadmap
For your current project (or a hypothetical one), create a 4-step roadmap to move from your current maturity level to "automated." For each step: (1) what you'll create, (2) who will use it, (3) how you'll measure success. Be specific.
Expected outcome: A one-page roadmap with 4 concrete steps.
Key Takeaways
-
Reusable Intelligence (RI) is the capture of patterns, decisions, and effective prompts so they accelerate future work. Every SDD project produces two outputs: product code and reusable intelligence.
-
Five types of RI: skills (reusable procedures), subagents (isolated delegated execution), ADRs (why), PHRs (effective prompts), intelligence templates (reusable structure).
-
P+Q+P pattern: Persona (who the agent is), Questions (what to ask before acting), Principles (rules for execution). Use it to design any RI artifact.
-
Horizontal vs. vertical: Horizontal intelligence applies across projects (testing, security, API design). Vertical intelligence is domain-specific (fintech, healthcare, e-commerce). Both compound over time.
-
Intelligence maturity model: Ad-hoc → documented (ADRs, PHRs) → templated (skills, templates) → automated (subagents, pipelines). Each level builds on the previous.
-
Extraction process: Identify patterns → create ADR for decisions → create skill for workflow → save PHR for effective prompts. Start with one of each; iterate.
Chapter Quiz
-
What are the two outputs of every SDD project? Why does the second one matter?
-
What is the difference between a skill and a subagent? When would you use each?
-
What does the P+Q+P pattern stand for? Give an example of each component for an "API design" skill.
-
What is horizontal intelligence? What is vertical intelligence? Give one example of each.
-
What are the four levels of the intelligence maturity model? What characterizes each?
-
What should an ADR contain? When should you write one vs. when should you skip it?
-
What makes a good PHR (Prompt History Record)? What sections should it have?
-
How do skills compound? Describe the progression from single skill to domain stack.
Sources and currency
Last technically verified: 2026-08-09
Commands, product support, and preview status can change. Verify the applicable version before adopting an example as policy.