Chapter 18: Building Custom Agents and Subagents
Learning Objectives
By the end of this chapter, you will be able to:
- Distinguish skills (2–4 decisions, human-guided) from subagents (5+ decisions, autonomous)
- Apply the P+Q+P pattern: Persona, Questions, Principles
- Design a subagent for specification writing
- Design a subagent for code review
- Design a subagent for test generation
- Understand multi-agent coordination and context passing
- Use slash commands and custom agent commands
- Build a complete SDD subagent: feature → questions → spec → plan → tasks
- Recognize the intelligence acceleration effect
- Decide when to promote a skill to a subagent
Skills vs Subagents: The Decision Boundary
Not every AI-assisted task requires the same level of autonomy. The distinction between skills and subagents hinges on decision complexity and human involvement.
Skills: 2–4 Decisions, Human-Guided
A skill handles tasks with a limited number of decision points. The human remains in the loop—guiding, approving, or correcting. The skill provides instructions; the human directs the flow.
Characteristics:
- Few branching decisions (2–4)
- Human validates or approves key outputs
- Task is well-defined with clear inputs and outputs
- Instructions fit in a single skill file
Examples: Generate a commit message from a diff. Format code to project style. Extract requirements from a user story into a template.
Subagents: 5+ Decisions, Autonomous
A subagent handles tasks with many decision points. It operates more autonomously—gathering information, making choices, and producing multi-step outputs. The human may provide the initial prompt and validate the final result, but the subagent drives the process.
Characteristics:
- Many branching decisions (5+)
- Agent gathers requirements, asks questions, iterates
- Task has multiple phases (spec → plan → implementation)
- Requires persona, question flow, and principles
Examples: Take a feature idea through spec → plan → task list. Perform a full code review with spec compliance, constraint check, and recommendations. Generate a complete test suite from specification and code.
The Boundary
| Factor | Skill | Subagent |
|---|---|---|
| Decisions | 2–4 | 5+ |
| Human role | In the loop | Validates at milestones |
| Phases | Single or few | Multiple |
| Autonomy | Low | High |
| Output | One artifact | Multiple artifacts |
| Questions | User provides | Agent asks |
When a skill's instructions grow complex, when the agent needs to ask many clarifying questions, or when the task spans multiple phases—consider promoting to a subagent.
Real-World Examples
Skill: "Generate a commit message from this diff." — 2 decisions: parse diff, format message. Human approves before commit.
Subagent: "Take this feature idea through spec, plan, and task list." — 10+ decisions: scope, users, flows, constraints, spec structure, plan phases, task ordering. Human validates at phase boundaries.
Skill: "Review this function for security issues." — 3 decisions: identify patterns, check against list, report. Single artifact.
Subagent: "Perform full PR review against spec and constraints." — 8+ decisions: load spec, map ACs, check constraints, assess tests, prioritize findings, format report. Multiple checks, structured output.
The P+Q+P Pattern: Persona + Questions + Principles
The P+Q+P pattern structures subagent design. It ensures the agent has a clear identity, gathers requirements before acting, and follows consistent rules.
Persona: Who the Agent Is
The persona defines the agent's expertise, role, and perspective. It shapes how the agent thinks and responds.
Elements:
- Role: What is the agent's job? (e.g., "Specification Engineer")
- Expertise: What does the agent know? (e.g., "SDD methodology, requirement extraction, acceptance criteria")
- Perspective: How does the agent approach problems? (e.g., "User-centric, testability-focused")
Example:
## Persona
You are a Specification Engineer with deep expertise in Spec-Driven Development.
You transform vague feature descriptions into structured, implementable specifications.
You think in terms of: user value, testability, edge cases, and constraints.
You never guess—you mark ambiguities with [NEEDS CLARIFICATION].
Questions: What the Agent Asks Before Acting
Questions are the requirements-gathering phase. The agent asks clarifying questions before producing output. This prevents wrong assumptions and ensures the specification or plan matches intent.
Types of questions:
- Scope: What's in? What's out?
- Behavior: How should X work when Y?
- Constraints: What must we never do?
- Dependencies: What does this integrate with?
- Quality: What are the success criteria?
Example:
## Questions to Ask
Before writing the specification, ask:
1. **Scope**: Is this the full feature or an MVP? What's explicitly out of scope?
2. **Users**: Who are the primary users? Any edge personas?
3. **Behavior**: For [key flow], what happens when [error case]?
4. **Constraints**: Are there performance, security, or compliance requirements?
5. **Dependencies**: What existing systems does this depend on?
6. **Success**: How will we know this is done? What metrics?
Principles: Rules the Agent Follows
Principles are the rules the agent follows while working. They encode methodology, constraints, and quality standards.
Example:
## Principles
1. **Focus on WHAT, not HOW**: No implementation details in specs.
2. **Testable criteria**: Every acceptance criterion is Given/When/Then.
3. **Mark ambiguity**: Use [NEEDS CLARIFICATION: question] — never guess.
4. **Complete structure**: All 10 components (Problem, User Journeys, FR, NFR, AC, Edge Cases, Constraints, Dependencies, Observability, Security).
5. **User-centric**: Start from user pain and value.
6. **Constraint-aware**: Check project constitution and constraints before finalizing.
Designing a Subagent for Specification Writing
A Specification Subagent takes a feature description and produces an SDD-compliant specification through a structured process.
Persona
You are a Specification Engineer. You specialize in transforming product ideas and
user stories into structured, implementable specifications. You understand SDD:
specifications are the source of truth; they must be complete, testable, and free of
implementation bias. You think in user journeys, acceptance criteria, and edge cases.
Questions
Before writing the spec, gather:
1. **Problem clarity**: Who experiences this? What's the pain? What's the impact of not solving it?
2. **Scope**: Full feature or MVP? What's explicitly out of scope?
3. **User flows**: What are the main success paths? What error paths matter?
4. **Constraints**: Performance? Security? Compliance? Integration limits?
5. **Dependencies**: What systems does this touch? Internal? External?
6. **Success metrics**: How do we measure "done"?
Principles
1. All 10 components present
2. [NEEDS CLARIFICATION] for any assumption
3. Given/When/Then for every AC
4. No implementation details
5. Edge cases explicit
6. Constraints explicit
Process
- Receive feature description
- Ask clarifying questions (from Questions section)
- Wait for user answers (or proceed with marked clarifications)
- Draft specification following 10-component structure
- Self-review: checklist, no unresolved [NEEDS CLARIFICATION]
- Output final spec
Designing a Subagent for Code Review
A Code Review Subagent validates code against specifications and constraints.
Persona
You are a Code Review Specialist. You validate implementations against specifications,
constraints, and coding standards. You are thorough but constructive. You distinguish
critical issues (must fix) from suggestions (consider) from nice-to-haves (optional).
You think in terms of: spec compliance, constraint violation, security, test coverage.
Questions
Before reviewing, confirm:
1. **Spec location**: Where is the specification? (If not provided, request it.)
2. **Scope**: Full review or specific focus (e.g., spec compliance only)?
3. **Constraints**: Which constraint documents apply?
4. **Context**: Any known issues or areas of concern?
Principles
1. Map every AC to implementing code
2. Check every constraint
3. Severity: Critical (must fix), Suggestion (consider), Nice to have (optional)
4. Be specific: cite file, line, and exact issue
5. Suggest fixes, don't just identify problems
6. Acknowledge what's done well
Process
- Load specification and code
- Map ACs to code
- Check constraints
- Assess quality, security, tests
- Produce structured report (Critical / Suggestion / Nice to have)
Designing a Subagent for Test Generation
A Test Generation Subagent produces tests from specifications and code.
Persona
You are a Test Engineer. You generate comprehensive test suites from specifications
and code. You prioritize: acceptance criteria coverage, edge cases, integration over
mocks. You follow TDD and Given/When/Then structure. You think in scenarios and
boundaries.
Questions
Before generating tests, confirm:
1. **Framework**: Jest? Vitest? Pytest? Other?
2. **Style**: Unit-only, integration, or mixed?
3. **Mocking**: Mock external APIs? Use real DB for integration?
4. **Coverage target**: Any specific coverage requirements?
Principles
1. Every AC has at least one test
2. Edge cases from spec are tested
3. Given/When/Then structure
4. Integration tests for critical paths (real DB where possible)
5. Meaningful assertions (not just "it doesn't throw")
6. Test names: "should [behavior] when [condition]"
Multi-Agent Coordination and Context Passing
When multiple agents (or subagent invocations) work on a task, they must pass context. The output of one becomes the input of the next.
Context Handoff Format
Use structured handoffs:
## Handoff: Specification → Implementation Plan
**From**: Specification Subagent
**To**: Architecture Subagent
**Artifacts**:
- Specification: specs/features/002-export.md
- Key decisions: [list any resolved clarifications]
- Constraints: specs/constraints/architecture.md
**Instructions for next phase**:
Create implementation plan. Satisfy all ACs. Pass Phase -1 gates.
What to Pass
| From | To | Pass |
|---|---|---|
| Spec Subagent | Architecture Subagent | Spec path, key decisions, constraints |
| Architecture Subagent | Coding Agent | Plan path, file order, tech choices |
| Coding Agent | Review Subagent | Code paths, spec path |
| Review Subagent | Coding Agent | Findings, prioritized fix list |
Avoiding Context Loss
- Reference by path: "See specs/features/001.md" rather than pasting full content
- Explicit artifacts: List what was produced and where
- Key decisions: Summarize non-obvious choices
- Constraints: Remind next agent which constraints apply
Slash Commands and Custom Agent Commands
Slash commands are shortcuts that invoke predefined prompts or workflows. They reduce typing and ensure consistent invocation.
Cursor
Cursor supports custom rules and slash commands. Commands can be configured to load specific context or invoke specific behaviors.
Claude Code
Claude Code uses .claude/commands/ for custom commands. Each command is a file with a prompt or script.
Example: .claude/commands/spec.md
# Spec Command
Run the Specification Subagent workflow:
1. Read the feature description from the user's message
2. Ask clarifying questions from the Questions section
3. After answers (or if user says "proceed"), generate the specification
4. Use the 10-component structure
5. Output to specs/features/[next-id]-[name].md
Custom Prompts
Custom prompts can be stored as files and invoked by name. The prompt file contains the full system + user prompt for the subagent.
Tutorial: Build a Complete SDD Subagent
This tutorial builds an SDD subagent that takes a feature description through the full pipeline: questions → spec → plan → tasks.
Step 1: Define the Subagent Configuration
Create .cursor/skills/sdd-subagent/SKILL.md (or equivalent config location):
---
name: sdd-subagent
description: Full SDD pipeline from feature idea to implementation plan and task list. Use when the user wants to take a feature from idea to ready-to-implement. Asks clarifying questions, generates spec, creates plan, produces tasks.
version: 1.0.0
---
# SDD Subagent
## Persona
You are an SDD Specialist. You guide features from idea to implementation-ready.
You combine the roles of Specification Engineer and Architecture Agent. You ask
questions before acting. You produce: specification, implementation plan, task list.
You follow the project constitution and constraints.
## Phase 1: Requirements Gathering
Before writing anything, ask these questions:
1. **Problem**: Who has this problem? What's the pain? Impact of not solving?
2. **Scope**: Full feature or MVP? What's out of scope?
3. **Users**: Primary users? Edge cases?
4. **Behavior**: Key flows? Error paths?
5. **Constraints**: Performance? Security? Dependencies?
6. **Success**: How do we measure done?
Present questions to the user. Wait for answers or "proceed with assumptions" (mark those [ASSUMED]).
## Phase 2: Specification
Using answers, produce a specification with all 10 components:
- Problem, User Journeys, FR, NFR, AC, Edge Cases, Constraints, Dependencies, Observability, Security
Use [NEEDS CLARIFICATION] for any remaining ambiguity.
Output to specs/features/[id]-[name].md
## Phase 3: Implementation Plan
From the spec, produce an implementation plan:
- Phase breakdown
- File creation order
- Technology choices
- Phase -1 gates (Simplicity, Anti-Abstraction, Integration-First)
- Constraint compliance check
Output to specs/features/[id]-[name]-plan.md
## Phase 4: Task List
From the plan, produce an ordered task list:
- Each task: description, files, acceptance
- Dependencies between tasks
- Estimated order of execution
Output to specs/features/[id]-[name]-tasks.md
## Principles
1. Ask before assuming
2. Spec before plan before tasks
3. Follow constitution and constraints
4. Mark [NEEDS CLARIFICATION] and [ASSUMED]
5. One artifact per phase, written to file
Step 2: Create Reference Files
Create references/constitution-summary.md with key constitutional principles.
Create references/plan-template.md with the implementation plan structure.
Step 3: Invoke the Subagent
Prompt:
"I want to add a feature: Users can export their data to CSV. Run the SDD subagent. Start with Phase 1—ask me the questions."
Expected: The agent asks the Phase 1 questions.
Step 4: Provide Answers and Continue
Answer the questions. Then:
"I've answered. Proceed with Phase 2."
Expected: The agent produces the specification.
Step 5: Complete Phases 3 and 4
"Proceed with Phase 3 and 4."
Expected: Implementation plan and task list.
What You Learned
- The subagent guides the user through phases
- Questions reduce wrong assumptions
- Each phase produces a file
- The full pipeline: idea → spec → plan → tasks
The Intelligence Acceleration Effect
Each skill and subagent you add compounds future productivity. Why?
-
Reuse: Once written, the skill/subagent applies to every matching task. The cost of creation is amortized.
-
Consistency: Output follows the same structure and quality. No reinventing the process each time.
-
Improvement: As you refine the skill/subagent, all future uses improve. One update benefits many tasks.
-
Specialization: The agent becomes better at specific tasks. A spec-writing subagent gets better at specs the more it's used and refined.
-
Composition: Skills and subagents can build on each other. A spec subagent's output feeds the plan subagent. The system becomes more capable as a whole.
Implication: Invest in skills and subagents for high-frequency tasks. The upfront cost pays off quickly.
When to Promote a Skill to a Subagent
Promote when:
| Signal | Action |
|---|---|
| Skill has 5+ decision points | Consider subagent |
| Agent needs to ask many questions | Add Questions phase; consider subagent |
| Task spans multiple phases | Subagent with phase structure |
| Human constantly corrects output | Add Questions; consider subagent |
| Skill file exceeds 500 lines | Split or promote to subagent |
| Task produces multiple artifacts | Subagent with handoff structure |
Don't promote when:
- Task is simple and well-defined
- 2–4 decisions suffice
- Single artifact output
- Human wants tight control (in the loop)
Try With AI
Prompt 1: P+Q+P Design
"Design a subagent for [describe task]. Use the P+Q+P pattern. Provide: (1) Persona (3-4 sentences), (2) Questions (5-7 questions the agent should ask before acting), (3) Principles (5-7 rules). Keep each section concise."
Prompt 2: Skill vs Subagent
"I have a skill that [describe what it does]. It currently has [N] decision points. Should this be a skill or a subagent? Use the 2–4 vs 5+ boundary. If subagent, what would you add (Persona, Questions, Principles)?"
Prompt 3: Context Handoff
"I'm designing a multi-agent flow: Spec Agent → Plan Agent → Coding Agent. What should each handoff include? Draft the handoff format for Spec → Plan and Plan → Coding. What could go wrong if we don't pass enough context?"
Prompt 4: Subagent Improvement
"Review this subagent design: [paste]. Evaluate: (1) Are the questions sufficient to avoid wrong assumptions? (2) Are the principles specific enough? (3) Is the phase structure clear? Suggest improvements."
Practice Exercises
Exercise 1: Specification Subagent
Create a Specification Subagent (as a skill or config). Include: Persona, Questions (at least 5), Principles, and a 4-step process. Test it with: "Users need to reset their password by email." Run through the full flow: questions → answers → spec. Evaluate: Did the questions help? Was the spec complete?
Expected outcome: A working subagent that produces better specs through structured questioning.
Exercise 2: Multi-Phase Handoff
Design the handoff from your Specification Subagent to an Implementation Plan agent. What must the handoff include? Create a template. Test: produce a spec, then use the handoff to invoke a plan agent. Does the plan agent have enough context?
Expected outcome: A handoff template that enables lossless context transfer.
Exercise 3: Promotion Decision
Take an existing skill (yours or from the tutorials). Count its decision points. List the phases it implicitly or explicitly has. Decide: keep as skill or promote to subagent? If promote, draft the Persona, Questions, and Principles. If keep, document why and what would trigger promotion.
Expected outcome: A decision record with clear rationale.
Key Takeaways
-
Skills handle 2–4 decisions with human guidance. Subagents handle 5+ decisions autonomously.
-
P+Q+P pattern: Persona (who the agent is), Questions (what it asks before acting), Principles (rules it follows).
-
Specification Subagent: Persona (Spec Engineer), Questions (problem, scope, users, behavior, constraints), Principles (10 components, [NEEDS CLARIFICATION], testable AC).
-
Code Review Subagent: Persona (Review Specialist), Questions (spec location, scope, constraints), Principles (map ACs, check constraints, severity levels).
-
Multi-agent coordination requires structured handoffs: artifact paths, key decisions, constraints. Reference by path to avoid context loss.
-
Intelligence acceleration: Each skill and subagent compounds productivity through reuse, consistency, and composition.
-
Promote skill to subagent when: 5+ decisions, many questions needed, multiple phases, multiple artifacts.
Subagent Output Quality and Validation
Subagents produce multiple artifacts. Ensuring quality requires validation at each phase.
Specification Validation
Before considering a spec complete, verify:
- All 10 components present
- No unresolved [NEEDS CLARIFICATION]
- Every AC is Given/When/Then testable
- Edge cases cover boundaries and errors
- Constraints are explicit
- Dependencies listed
Plan Validation
Before implementation, verify the plan:
- Passes Phase -1 gates (Simplicity, Anti-Abstraction, Integration-First)
- File creation order is logical (tests before implementation where TDD applies)
- Constraint compliance documented
- No speculative or "might need" features
Task List Validation
Before coding, verify tasks:
- Cover all plan phases
- Dependencies between tasks are correct
- Each task has clear acceptance
- Order is executable (no circular dependencies)
Automated Checks
Where possible, automate validation:
- Script to parse spec and check for 10 components
- Script to verify plan has Phase -1 section
- CI check that implementation matches spec (e.g., AC coverage in tests)
Scaling Subagents Across Teams
When multiple teams use subagents, consider:
Shared vs Team-Specific
- Shared subagents: Spec-writing, code review—same across teams. Store in org-level skill repo.
- Team-specific: Custom questions, domain-specific principles. Store in team repo.
Versioning
Subagents evolve. Use semantic versioning. Document breaking changes. Allow teams to pin to versions if needed.
Feedback Loops
Collect feedback: Did the subagent produce good output? Were the questions helpful? Use feedback to refine Persona, Questions, and Principles.
Subagent Prompt Engineering
The initial prompt to a subagent shapes its behavior. Best practices:
Be Explicit About Phase
Vague: "Add export to CSV." Better: "Add export to CSV. Run the SDD subagent. Start with Phase 1—ask your questions."
Provide Context
Minimal: "Write a spec for login." Better: "Write a spec for login. Our auth uses JWT. We have existing User and Session models. Constraints: no PII in logs, rate limit 5 req/min for auth endpoints."
Specify Output Location
Implicit: Agent chooses where to put the spec. Explicit: "Output the spec to specs/features/004-login.md."
Handle Partial Completion
If the subagent stops mid-flow: "Continue from where you left off. We're in Phase 3." Provide the last output if needed.
Appendix: Full SDD Subagent Template
Use this template when creating a new subagent:
---
name: [subagent-name]
description: [What it does]. Use when [trigger scenarios].
version: 1.0.0
---
# [Subagent Name]
## Persona
[3-5 sentences: role, expertise, perspective]
## Questions to Ask
1. [Question category]: [Specific question]
2. [Question category]: [Specific question]
...
## Principles
1. [Principle]
2. [Principle]
...
## Phase 1: [Name]
[Steps, output format]
## Phase 2: [Name]
[Steps, output format]
## Handoff Format
[What to pass to next phase or agent]
Chapter Quiz
-
What is the decision boundary between skills and subagents? Why does it matter?
-
Explain the P+Q+P pattern. What does each element contribute to subagent design?
-
For a Specification Subagent, what questions should it ask before writing the spec? List at least 5 and explain why each matters.
-
How do multi-agent handoffs work? What should be passed from Spec Agent to Plan Agent?
-
What is the "intelligence acceleration effect"? Give two concrete examples.
-
When should you promote a skill to a subagent? What signals indicate promotion is needed?
-
Design a Test Generation Subagent. What would the Persona, Questions, and Principles be?
-
You have a subagent that produces poor specs because it makes wrong assumptions. What would you add or change using the P+Q+P pattern?