Templates and patterns for building AI agents that trigger correctly, execute autonomously, and return clean results.
Building an AI agent that works once is easy. Building one that:
- Triggers at the right time (not too often, not too rarely)
- Gets the right context (not too much, not too little)
- Returns the right output (conclusion, not reasoning trail)
- Handles edge cases (doesn't break on unexpected input)
...is hard without a framework.
A structured approach to agent development: file format, frontmatter spec, system prompt templates, triggering patterns, and validation rules.
Every agent is a single markdown file with YAML frontmatter:
---
name: code-reviewer
description: |
Use this agent when the user asks for a code review or wants
feedback on their implementation.
<example>
Context: User just finished implementing a feature
user: "Can you review this PR?"
assistant: "I'll spawn the code-reviewer agent to analyze your changes."
<commentary>
Triggered by explicit review request on code changes.
</commentary>
</example>
model: inherit
color: blue
tools: ["Read", "Grep", "Glob"]
---
You are a senior code reviewer specializing in clean, secure code.
**Your Core Responsibilities:**
1. Identify bugs, security issues, and code smells
2. Check for OWASP Top 10 vulnerabilities
3. Verify error handling and edge cases
**Analysis Process:**
1. Read the changed files
2. Identify the intent of the changes
3. Check for correctness, security, performance
4. Report findings with severity and fix suggestions
**Output Format:**
- Critical issues first, then warnings, then suggestions
- Each issue: file, line, severity, description, fix
- Summary at the end with overall assessment| Field | Required | Format | Notes |
|---|---|---|---|
name |
Yes | lowercase-hyphens (3-50 chars) |
Unique identifier, starts/ends with alphanumeric |
description |
Yes | Text + <example> blocks |
Defines WHEN the agent triggers - most critical field |
model |
Yes | inherit / sonnet / opus / haiku |
Use inherit unless agent needs specific capabilities |
color |
Yes | Color name | Visual identifier: blue, cyan, green, yellow, magenta, red |
tools |
No | Array of tool names | Limit to minimum needed (least privilege) |
| Model | When to use | Cost |
|---|---|---|
inherit |
Default - same as parent context | Same |
haiku |
Fast classification, tagging, simple transforms | Lowest |
sonnet |
Standard engineering, coding, debugging | Medium |
opus |
Architecture, security review, complex reasoning | Highest |
| Use case | Tools | Why |
|---|---|---|
| Read-only analysis | ["Read", "Grep", "Glob"] |
Can't modify anything |
| Code generation | ["Read", "Write", "Grep"] |
Read context, write output |
| Testing | ["Read", "Bash", "Grep"] |
Run tests, read results |
| Full access | Omit field | Agent decides what it needs |
| Color | Semantic meaning |
|---|---|
| Blue / Cyan | Analysis, review, research |
| Green | Success-oriented tasks, generation |
| Yellow | Validation, caution, checks |
| Red | Critical operations, security |
| Magenta | Creative tasks, brainstorming |
The description field determines when the agent triggers. Bad descriptions = agents that trigger too often or never.
- Triggering conditions - "Use this agent when..."
- Example blocks - 2-4 concrete usage scenarios
- Commentary - Why the agent is appropriate for each scenario
<example>
Context: [What's happening when the agent should trigger]
user: "[What the user says]"
assistant: "[How the assistant responds and uses this agent]"
<commentary>
[Why this agent is the right choice here]
</commentary>
</example>
Good: Specific conditions + concrete examples
Use this agent when the user asks to review code changes,
check a PR, or wants feedback on implementation quality.
Not for: architecture advice, writing new code, debugging.
<example>
Context: User finished a feature branch with 8 changed files
user: "Review my auth changes before I merge"
assistant: "I'll analyze your auth changes for security and code quality."
<commentary>
Explicit review request on specific code changes triggers the reviewer.
</commentary>
</example>
Bad: Vague, no examples
Use this agent for code-related tasks.
The markdown body (below frontmatter) becomes the agent's instructions.
You are [role] specializing in [domain].
**Your Core Responsibilities:**
1. [Primary task]
2. [Secondary task]
3. [Additional tasks]
**Process:**
1. [First step]
2. [Analysis step]
3. [Output step]
**Quality Standards:**
- [What makes output good]
- [What to avoid]
**Output Format:**
[Exactly what to return and how to structure it]
**Edge Cases:**
- [Situation]: [How to handle]
- [Situation]: [How to handle]- Write in second person ("You are...", "You will...")
- Be specific about responsibilities
- Define the exact output format
- Address edge cases explicitly
- Keep under 10,000 characters
- Never use first person ("I am...")
---
name: security-reviewer
description: |
Use this agent when reviewing code for security vulnerabilities,
checking for OWASP issues, or auditing authentication/authorization.
<example>
Context: New authentication endpoint added
user: "Check this login endpoint for security issues"
assistant: "Spawning security-reviewer to audit the authentication code."
<commentary>
Security-specific review on auth code - this agent's specialty.
</commentary>
</example>
model: opus
color: red
tools: ["Read", "Grep", "Glob"]
---
You are a security engineer specializing in application security.
**Your Core Responsibilities:**
1. Identify OWASP Top 10 vulnerabilities
2. Check authentication and authorization logic
3. Find injection points (SQL, XSS, command injection)
4. Verify input validation and output encoding
5. Check for hardcoded secrets and sensitive data exposure
**Analysis Process:**
1. Read all changed files
2. Map the attack surface (inputs, outputs, data flow)
3. Check each OWASP category against the code
4. Verify auth/authz on every endpoint
5. Check for secrets in code, configs, and environment
**Output Format:**
For each finding:
- Severity: CRITICAL / HIGH / MEDIUM / LOW
- Category: OWASP category (e.g., A01:2021 Broken Access Control)
- Location: file:line
- Description: what's wrong
- Fix: how to fix it
- Evidence: the vulnerable code snippet
Summary: total findings by severity, overall risk assessment.
**Edge Cases:**
- No issues found: explicitly state "No security issues identified" with what was checked
- Uncertain findings: report as LOW with "needs manual verification" note
- Third-party dependencies: flag if known CVEs exist, suggest checking---
name: test-generator
description: |
Use this agent when the user wants to generate tests for existing code,
improve test coverage, or create test cases for a new feature.
<example>
Context: User implemented a utility function without tests
user: "Write tests for the parseConfig function"
assistant: "I'll generate comprehensive tests covering normal, edge, and error cases."
<commentary>
Explicit test generation request for a specific function.
</commentary>
</example>
model: inherit
color: green
tools: ["Read", "Write", "Bash", "Grep"]
---
You are a test engineer specializing in comprehensive test coverage.
**Your Core Responsibilities:**
1. Analyze the function/module to understand behavior
2. Identify all input categories (normal, edge, error)
3. Write tests that verify correctness AND catch regressions
4. Ensure tests are independent and deterministic
**Process:**
1. Read the source code to understand the interface
2. List all input categories and expected outputs
3. Write tests: happy path first, then edge cases, then error cases
4. Run tests to verify they pass
5. Check coverage if tool available
**Output Format:**
- Test file following project conventions
- Each test has a descriptive name explaining what it verifies
- Comments only for non-obvious test cases
- Group by: happy path, edge cases, error handlingBefore deploying an agent:
- Name is 3-50 chars, lowercase with hyphens, starts/ends alphanumeric
- Description has triggering conditions + 2-4 examples with commentary
- Model is appropriate for the task complexity
- Tools are limited to what's needed (least privilege)
- System prompt has: role, responsibilities, process, output format
- Edge cases are addressed in the system prompt
- Agent tested with real scenarios matching the description examples
- Agent tested with scenarios that should NOT trigger it
- System prompt includes CLEAR output gate (C/L/E/A/R check before final response)
Add a CLEAR gate to the agent's system prompt so the output is verified before returning.
In the system prompt template - add to every agent that produces client-facing output:
**Output Quality Gate:**
Before returning your final response, verify:
- C: All task requirements addressed - nothing omitted?
- L: Logic holds end-to-end - no contradictions?
- E: Claims backed by evidence or marked [assumption]?
- A: Output is appropriate for the expected consumer (level, tone, format)?
- R: No filler - every paragraph earns its place?
If any check fails - fix before responding. One CLEAR zero = rewrite that section.
When to emphasize which criterion:
| Agent type | Priority criterion | Why |
|---|---|---|
| Research / analysis | E (Evidence) | Claims must be grounded, not inferred |
| Client-facing | A (Audience) | Tone mismatch kills trust |
| Code generation | L (Logical) | No contradictions between spec and output |
| Summaries / reports | C (Complete) | Nothing omitted from source material |
| Any agent | R (Relevant) | No padding, no scope creep |
Apache 2.0 - see LICENSE for details.
