prompt-engineering
Comprehensive prompt engineering for coding agents covering structured instruction design, few-shot prompting, chain-of-thought, decomposition, agent workflow patterns, and reliability techniques for multi-step pipelines.
What this skill does
# Prompt Engineering for Coding Agents
## Critical Importance
**Prompt engineering is the single highest-leverage skill for getting reliable output from coding agents.** A well-engineered prompt turns a coding agent from a frustrating guessing machine into a precise, predictable partner. Every prompt you write either compounds quality or compounds debt—there is no neutral. The techniques below are drawn from peer-reviewed research, production agent systems, and direct experience building multi-step coding workflows.
## Systematic Approach
** approach every prompt as an engineering artifact, not a casual instruction.** Treat prompts like API contracts: explicit inputs, defined outputs, documented constraints, and graceful failure modes. A prompt that works "most of the time" is a prompt that fails at the worst time.
## The Challenge
**The write prompts that produce reliable, correct code across multi-step agent workflows—even when individual step reliability is only 90%.** The "March of the Nines" (Karpathy) shows that a 10-step pipeline at 90% per-step reliability has only a 35% chance of succeeding end-to-end. Your prompts must be robust enough to close that gap through explicit planning, fallbacks, and constraint communication.
## When to Use This Skill
- Writing system prompts or task prompts for coding agents
- Designing multi-step agent workflows (spec → draft → test → refactor)
- Improving reliability of existing agent prompts
- Building few-shot examples for code generation
- Debugging why an agent produces inconsistent output
- Creating reusable prompt templates for teams
## Core Prompting Techniques
### 1. Structured Instruction Design
Good prompts have four explicit elements:
| Element | Purpose | Example |
|---------|---------|---------|
| **Role** | Sets expertise context | "You are a senior backend engineer with 10 years of Node.js experience" |
| **Task** | Defines the specific job | "Implement a rate limiter middleware using the sliding window algorithm" |
| **Context** | Provides relevant background | "This is for a REST API serving 10k req/s. Must be Redis-backed." |
| **Constraints** | Bounds the solution | "No external dependencies beyond ioredis. Must handle distributed instances." |
**Pattern:**
```
# Role
You are a [specific role] with [X years] of experience in [relevant domain].
# Task
[Specific, actionable instruction]
# Context
[Background information, existing code, architectural decisions]
# Constraints
- [Hard constraint 1]
- [Hard constraint 2]
- [Output format requirement]
```
### 2. Few-Shot Prompting
Provide concrete input/output examples to establish expected patterns. Research shows few-shot prompting dramatically improves consistency, especially for code style and conventions.
**Zero-shot vs Few-shot:**
```
Zero-shot: "Write a function that validates email addresses."
→ Unpredictable style, may not match project conventions.
Few-shot: "Write a function that validates email addresses, following this pattern:
// Example: validatePhoneNumber
export function validatePhoneNumber(input: string): Result<string, ValidationError> {
const trimmed = input.trim();
const pattern = /^\+?[\d\s-()]{7,}$/;
if (!pattern.test(trimmed)) {
return { ok: false, error: { field: 'phone', message: 'Invalid phone number' } };
}
return { ok: true, value: trimmed };
}"
→ Matches project style, returns same Result type, uses same error pattern.
```
**Best practices for few-shot with coding agents:**
- Use 1-3 examples from the actual project codebase
- Show the full pattern including types, error handling, and naming
- Match the exact import style and module structure
- Include edge case handling in examples
### 3. Chain-of-Thought (CoT) Prompting
Force explicit reasoning before action. Critical for debugging, refactoring, and architecture decisions.
**Pattern:**
```
Before writing any code:
1. Analyze the current implementation and identify all issues
2. List each issue with its severity and root cause
3. Propose a solution for each issue
4. Identify dependencies between fixes
5. Only then implement changes in the correct order
Format your analysis as:
## Analysis
[step-by-step reasoning]
## Plan
[ordered list of changes]
## Implementation
[code changes]
```
### 4. Decomposition Patterns
Break complex tasks into explicit sub-tasks. Two primary patterns:
**Self-Ask Pattern:**
```
Before solving this task, answer these sub-questions:
1. What are the input types and edge cases?
2. What existing code handles similar cases?
3. What error conditions need handling?
4. What tests would validate correctness?
5. What performance constraints apply?
Then synthesize your answers into the implementation.
```
**Step-Back Pattern:**
```
Before implementing, step back and consider:
- What is the broader architectural pattern this fits into?
- What are the common failure modes for this type of change?
- How will this scale or need to change in 6 months?
- What would a senior engineer review critically about this approach?
```
### 5. Agent Workflow Prompting
For autonomous or semi-autonomous coding agents, structure prompts around phases:
```
# Phase 1: Understand
Read the existing codebase. Identify:
- Current architecture and patterns
- Related code that will be affected
- Existing tests and their coverage
- Dependencies and integration points
# Phase 2: Plan
Create an explicit plan before writing code:
- List every file that needs to change
- Describe each change and why
- Identify the correct order of changes
- Flag any risky changes that need extra care
# Phase 3: Implement
Make changes one at a time:
- Each change should be independently verifiable
- Run relevant tests after each change
- Commit (or checkpoint) after each logical unit
# Phase 4: Verify
- Run the full test suite
- Check for type errors
- Verify edge case handling
- Review for security issues
# Phase 5: Simplify
Review all changes for:
- Unnecessary complexity
- Missed code reuse opportunities
- Better idioms or patterns
- Inconsistencies with the rest of the codebase
```
### 6. Reliability Techniques for Agent Pipelines
Addressing the "March of the Nines" problem:
| Technique | How to Apply | Example |
|-----------|-------------|---------|
| **Explicit Planning** | Require a plan before any code | "List all changes before implementing any" |
| **Verification Gates** | Insert checks between steps | "After each function, write a test that validates it" |
| **Fallback Instructions** | Define what to do on failure | "If the test fails, analyze the error before retrying" |
| **Output Constraints** | Define exact output format | "Return only valid TypeScript, no prose explanations" |
| **Self-Correction** | Prompt to review own output | "Review your code for these 5 common mistakes: [...]" |
| **Guardrails** | Set hard boundaries | "Never modify files outside src/features/auth/" |
### 7. Prompt Patterns for Specific Coding Tasks
#### Debugging
```
Analyze this error systematically:
## Error
[paste error message and stack trace]
## Context
[what were you doing, what changed recently]
## Steps
1. Identify the exact line and operation causing the error
2. Trace the data flow backward to find the root cause
3. Determine if this is a logic error, type error, or environmental issue
4. Propose the minimal fix
5. Explain why this fix is correct and what would break if wrong
```
#### Refactoring
```
Refactor this code following these constraints:
## Goal
[what the refactoring should achieve]
## Rules
- Preserve all existing behavior (tests must still pass)
- Make changes incrementally (each step should be commit-worthy)
- Prefer extracting functions over adding comments
- Follow the existing patterns in this codebase
## Anti-goals
- Do not add new features
- Do not change the public API
- Do not optimize prematurely
```
#### Feature Implementation
```
Implement [feature description]:
## Specification
[detailed requirements]
## ExistingRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.