
Best Practices
- 480 installs
- 1.1k repo stars
- Updated May 5, 2026
- skillcreatorai/ai-agent-skills
Best Practices is an agent skill authoring guide that teaches proven patterns for prompts, tool use, guardrails, and progressive disclosure so coding assistants behave reliably across repos.
About
Best Practices is a skill from skillcreatorai/ai-agent-skills for authoring or refining agent skills with proven patterns around prompts, tool use, guardrails, and progressive disclosure. It helps developers structure SKILL.md files, triggers, allowed tools, and disclosure levels so assistants stay predictable across repositories and tasks. Reach for it when creating a new skill, hardening an existing one, or reviewing why an agent over-invokes tools or ignores boundaries. The focus is meta-engineering of agent behavior rather than application feature code.
- Skill authoring conventions
- Tool invocation guardrails
- Progressive disclosure patterns
- Cross-repo reliability tips
- Prompt structure templates
Best Practices by the numbers
- 480 all-time installs (skills.sh)
- +11 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #1,813 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/skillcreatorai/ai-agent-skills --skill best-practicesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 480 |
|---|---|
| repo stars | ★ 1.1k |
| Last updated | May 5, 2026 |
| Repository | skillcreatorai/ai-agent-skills ↗ |
How do you write reliable agent skills?
Author or refine agent skills using proven patterns for prompts, tool use, guardrails, and progressive disclosure so assistants behave reliably across repos and tasks.
Who is it for?
Developers authoring or auditing agent skills who need consistent prompt, tool-use, and disclosure patterns.
Skip if: Application feature implementation where no new agent skill or prompt contract is being defined.
When should I use this skill?
User is creating, editing, or reviewing agent skills, triggers, allowed-tools lists, or assistant guardrails.
What you get
Refined SKILL.md manifests, trigger definitions, tool guardrails, and progressive disclosure sections.
- refined skill manifests
- guardrail specifications
- disclosure outlines
Files
Best Practices — Prompt Transformer
Transform prompts by adding what Claude needs to succeed.
Start Here
Based on user's request:
User provides a prompt to transform: → Ask using AskUserQuestion:
- Question: "How should I improve this prompt?"
- Header: "Mode"
- Options:
1. Transform directly — "I'll apply best practices and output an improved version" 2. Build context first — "I'll gather codebase context and intent analysis first"
User asks to learn/understand: → Show the 5 Transformation Principles section
User asks for examples: → Link to references/before-after-examples.md
User asks to evaluate a prompt: → Use the Success Criteria eval rubric at the end of this document
---
If "Transform directly"
Apply the 5 principles below and output the improved prompt immediately.
If "Build context first"
Launch 3 parallel agents to gather context:
Run these agents IN PARALLEL using the Task tool:
- Task task-intent-analyzer("[user's prompt]")
- Task best-practices-referencer("[user's prompt]")
- Task codebase-context-builder("[user's prompt]")What Each Agent Returns
| Agent | Mission | Returns |
|---|---|---|
| task-intent-analyzer | Understand what user is trying to do | Task type, gaps, edge cases, transformation guidance |
| best-practices-referencer | Find relevant patterns from references/ | Matching examples, anti-patterns to avoid, transformation rules |
| codebase-context-builder | Explore THIS codebase | Specific file paths, similar implementations, conventions |
After Agents Return
1. Synthesize findings — Combine intent + best practices + codebase context 2. Apply matching patterns — Use examples from best-practices-referencer as templates 3. Ground in codebase — Add specific file paths from codebase-context-builder 4. Transform the prompt — Apply the 5 principles with all gathered context 5. Output — Show improved prompt with before/after comparison
Agent Definitions
The agents are defined in agents/:
agents/task-intent-analyzer.md— Analyzes intent, gaps, and edge casesagents/best-practices-referencer.md— Finds relevant examples and patterns from references/agents/codebase-context-builder.md— Explores codebase for files and conventions
---
Transformation Workflow
When transforming (after mode selection):
1. Identify what's missing — Check against the 5 principles below 2. Add missing elements — Verification, context, constraints, phases, rich content 3. Output the improved prompt — In a code block, ready to copy-paste 4. Show what changed — Brief comparison of before/after
---
The 5 Transformation Principles
Apply these in order of priority:
1. Add Verification (Highest Priority)
The single highest-leverage improvement. Claude performs dramatically better when it can verify its own work.
| Missing | Add |
|---|---|
| No success criteria | Test cases with expected inputs/outputs |
| UI changes | "take screenshot and compare to design" |
| Bug fixes | "write a failing test, then fix it" |
| Build issues | "verify the build succeeds after fixing" |
| Refactoring | "run the test suite after each change" |
| No root cause enforcement | "address root cause, don't suppress error" |
| No verification report | "summarize what you ran and what passed" |
BEFORE: "implement email validation"
AFTER: "write a validateEmail function. test cases: user@example.com → true,
invalid → false, user@.com → false. run the tests after implementing"BEFORE: "fix the API error"
AFTER: "the /api/orders endpoint returns 500 for large orders. check
OrderService.ts for the error. address the root cause, don't suppress
the error. after fixing, run the test suite and summarize what passed
and what you verified."2. Provide Specific Context
Replace vague references with precise locations and details.
| Vague | Specific |
|---|---|
| "the code" | src/auth/login.ts |
| "the bug" | "users report X happens when Y" |
| "the API" | "the /api/users endpoint in routes.ts" |
| "that function" | processPayment() on line 142 |
Four ways to add context:
| Strategy | Example |
|---|---|
| Scope the task | "write a test for foo.py covering the edge case where user is logged out. avoid mocks." |
| Point to sources | "look through ExecutionFactory's git history and summarize how its API evolved" |
| Reference patterns | "look at HotDogWidget.php and follow that pattern for the calendar widget" |
| Describe symptoms | "users report login fails after session timeout. check src/auth/, especially token refresh" |
Respect Project CLAUDE.md:
If the project has a CLAUDE.md, the transformed prompt should:
- Not contradict project conventions
- Reference project-specific patterns when relevant
- Note any project constraints that apply
BEFORE: "add a new API endpoint"
AFTER: "add a GET /api/products endpoint. check CLAUDE.md for API conventions
in this project. follow the pattern in routes/users.ts. run the API
tests after implementing."BEFORE: "fix the login bug"
AFTER: "users report login fails after session timeout. check the auth flow
in src/auth/, especially token refresh. write a failing test that
reproduces the issue, then fix it"3. Add Constraints
Tell Claude what NOT to do. Prevents over-engineering and unwanted changes.
| Constraint Type | Examples |
|---|---|
| Dependencies | "no new libraries", "only use existing deps" |
| Testing | "avoid mocks", "use real database in tests" |
| Scope | "don't refactor unrelated code", "only touch auth module" |
| Approach | "address root cause, don't suppress error", "keep backward compat" |
| Patterns | "follow existing codebase conventions", "match the style in utils.ts" |
BEFORE: "add a calendar widget"
AFTER: "implement a calendar widget with month selection and year pagination.
follow the pattern in HotDogWidget.php. build from scratch without
libraries other than the ones already used in the codebase"4. Structure Complex Tasks in Phases
For larger tasks, separate exploration from implementation.
The 4-Phase Pattern:
Phase 1: EXPLORE
"read src/auth/ and understand how we handle sessions and login.
also look at how we manage environment variables for secrets."
Phase 2: PLAN
"I want to add Google OAuth. What files need to change?
What's the session flow? Create a plan."
Phase 3: IMPLEMENT
"implement the OAuth flow from your plan. write tests for the
callback handler, run the test suite and fix any failures."
Phase 4: COMMIT
"commit with a descriptive message and open a PR"When to use phases:
- Uncertain about the approach
- Change modifies multiple files
- Unfamiliar with the code being modified
Skip phases when:
- Could describe the diff in one sentence
- Fixing a typo, adding a log line, renaming a variable
BEFORE: "add OAuth"
AFTER: "read src/auth/ and understand current session handling. create a plan
for adding OAuth. then implement following the plan. write tests and
verify they pass"5. Include Rich Content
Provide supporting materials that Claude can use directly.
| Content Type | How to Provide |
|---|---|
| Files | Use @filename to reference files |
| Images | Paste screenshots directly |
| Errors | Paste actual error messages, not descriptions |
| Logs | Pipe with `cat error.log \ |
| URLs | Link to relevant documentation |
BEFORE: "make the dashboard look better"
AFTER: "[paste screenshot] implement this design for the dashboard.
take a screenshot of the result and compare it to the original.
list any differences and fix them. ensure responsive behavior
at 768px and 1024px breakpoints"BEFORE: "the build is failing"
AFTER: "the build fails with this error: [paste actual error]. fix it
and verify the build succeeds. address the root cause, don't
suppress the error"---
Output Format
When transforming a prompt, output:
**Original:** [their prompt]
**Improved:**[transformed prompt in code block]
**Added:**
- [what was missing and added]
- [another improvement]
- [etc.]---
Quick Transformation Examples
Bug Fix
BEFORE: "fix the login bug"
AFTER: "users report login fails after session timeout. check the auth flow
in src/auth/, especially token refresh. write a failing test that reproduces
the issue, then fix it. verify by running the auth test suite."
ADDED: symptom, location, verification (failing test), success criteriaFeature Implementation
BEFORE: "add a search feature"
AFTER: "implement search for the products page. look at how filtering works
in ProductList.tsx for the pattern. search should filter by name and category.
add tests for: empty query returns all, partial match works, no results shows
message. no external search libraries."
ADDED: location, reference pattern, specific behavior, test cases, constraintRefactoring
BEFORE: "make the code better"
AFTER: "refactor utils.js to use ES2024 features while maintaining the same
behavior. specifically: convert callbacks to async/await, use optional
chaining, add proper TypeScript types. run the existing test suite after
each change to ensure nothing breaks."
ADDED: specific changes, constraint (same behavior), verification after each stepTesting
BEFORE: "add tests for foo.py"
AFTER: "write tests for foo.py covering the edge case where the user is
logged out. avoid mocks. use the existing test patterns in tests/. test
cases: logged_out_user returns 401, expired_session redirects to login,
invalid_token raises AuthError."
ADDED: specific edge case, constraint (no mocks), pattern reference, test casesDebugging
BEFORE: "the API is slow"
AFTER: "the /api/orders endpoint takes 3+ seconds. profile the database
queries in OrderService.ts. look for N+1 queries or missing indexes.
fix the performance issue and verify response time is under 500ms."
ADDED: specific endpoint, location, what to look for, measurable success criteriaUI Changes
BEFORE: "fix the button styling"
AFTER: "[paste screenshot of design] update the primary button to match this
design. check Button.tsx and the theme in tailwind.config.js. take a
screenshot after changes and compare to the design. list any differences."
ADDED: design reference, file locations, visual verificationExploration
BEFORE: "how does auth work?"
AFTER: "read src/auth/ and explain how authentication works in this codebase.
cover: how sessions are created, how tokens are refreshed, where secrets
are stored. summarize in a markdown doc."
ADDED: specific files, specific questions to answer, output formatMigration
BEFORE: "upgrade to React 18"
AFTER: "migrate from React 17 to React 18. first, read the migration guide
at [URL]. then identify all components using deprecated APIs. update one
component at a time, running tests after each. don't change unrelated code."
ADDED: phased approach, reference docs, incremental verification, scope constraintWith Verification Report
BEFORE: "fix the API error"
AFTER: "the /api/orders endpoint returns 500 for large orders. check
OrderService.ts for the error. address the root cause, don't suppress
the error. after fixing, run the test suite and summarize what passed
and what you verified."
ADDED: symptom, location, root cause enforcement, verification report---
Transformation Checklist
Before outputting, verify the improved prompt has:
- [ ] Verification — How to know it worked (tests, screenshot, output)
- [ ] Location — Specific files, functions, or areas
- [ ] Constraints — What NOT to do
- [ ] Single task — Not compound (split if needed)
- [ ] Phases — If complex, structured as explore → plan → implement
- [ ] Root cause — For bugs: "address root cause, don't suppress"
- [ ] CLAUDE.md — Respect project conventions if they exist
---
Quick Prompt Quality Check
Rate the prompt against these dimensions:
| Dimension | 0 (Missing) | 1 (Partial) | 2 (Complete) |
|---|---|---|---|
| Verification | None | "test it" | Specific test cases + report |
| Location | "the code" | "auth module" | src/auth/login.ts:42 |
| Constraints | None | Implied | "avoid X, no Y, root cause only" |
| Scope | Vague | Partial | Single clear task |
Quick assessment:
- 0-3: Needs significant work
- 4-5: Needs some improvements
- 6-8: Good, minor tweaks
---
Fallback: If Still Too Vague
If user chose "Transform directly" but the prompt lacks enough context, ask one natural question:
"What would Claude need to know to do this well?"
Don't interrogate — one question is enough. Transform with what you learn.
---
Common Anti-Patterns to Fix
| Anti-Pattern | Problem | Fix |
|---|---|---|
| "fix the bug" | No symptom, no location | Add what users report + where to look |
| "add tests" | No scope, no cases | Specify edge cases + test patterns |
| "make it better" | No criteria for "better" | Define specific improvements |
| "implement X" | No verification | Add test cases or success criteria |
| "update the code" | No constraints | Add what to preserve, what to avoid |
---
Success Criteria — Prompt Quality Eval
A well-transformed prompt passes these checks:
Principle 1: Verification ✅
| Check | Pass | Fail |
|---|---|---|
| Has success criteria | "run tests", "screenshot matches" | Nothing |
| Measurable outcome | "response < 500ms" | "make it faster" |
| Self-verifiable | Claude can check its own work | Requires human judgment |
| Root cause enforced | "don't suppress error" | Silent about approach |
Principle 2: Specificity ✅
| Check | Pass | Fail |
|---|---|---|
| File locations | src/auth/login.ts | "the auth code" |
| Function/class names | processPayment() | "that function" |
| Line numbers (if relevant) | :42 | "somewhere in there" |
| CLAUDE.md respected | "check project conventions" | Ignores project rules |
Principle 3: Constraints ✅
| Check | Pass | Fail |
|---|---|---|
| What NOT to do | "avoid mocks", "no new deps" | Open-ended |
| Scope boundaries | "only touch auth module" | Unlimited scope |
| Pattern to follow | "match UserService.ts style" | No reference |
Principle 4: Structure ✅
| Check | Pass | Fail |
|---|---|---|
| Single task | One clear objective | Multiple goals |
| Phased (if complex) | "explore → plan → implement" | Jump straight to code |
| Appropriate depth | Matches task complexity | Over/under-specified |
Principle 5: Rich Content ✅
| Check | Pass | Fail |
|---|---|---|
| Actual errors | Pasted error message | "it's broken" |
| Screenshots (UI) | Image attached | "the button looks wrong" |
| File references | @filename or path | "that file" |
Overall Quality Score
| Score | Meaning | Principles Passed |
|---|---|---|
| ⭐⭐⭐⭐⭐ | Excellent | All 5 |
| ⭐⭐⭐⭐ | Good | 4 of 5 |
| ⭐⭐⭐ | Acceptable | 3 of 5 |
| ⭐⭐ | Needs work | 2 of 5 |
| ⭐ | Poor | 1 or 0 |
Target: Every transformed prompt should score ⭐⭐⭐⭐ or ⭐⭐⭐⭐⭐
---
Reference Files
For more examples and patterns:
- 50+ Examples: See references/before-after-examples.md
- Prompt Templates: See references/prompt-patterns.md
- Task Workflows: See references/common-workflows.md
- What to Avoid: See references/anti-patterns.md
- Official Guide: See references/best-practices-guide.md
---
Sources
- Best Practices for Claude Code — Official documentation
- Claude Code Skills — Skill authoring guide
- Anthropic Prompt Engineering — General prompting patterns
- Dicklesworthstone meta_skill — "THE EXACT PROMPT" pattern
Note: The current year is 2026. Use this when searching for recent documentation and patterns.
You are a best practices research expert specializing in prompt transformation patterns. Your mission is to find the most relevant examples, patterns, and anti-patterns from the skill's reference files that apply to a specific prompt, enabling high-quality transformation.
Core Responsibilities
1. Reference File Search
Search these files in the references/ folder:
| File | Contains | Search For |
|---|---|---|
before-after-examples.md | 50+ transformation examples by category | Examples matching task type and domain |
prompt-patterns.md | Reusable templates for common scenarios | Templates that can be adapted |
common-workflows.md | Task-specific workflow structures | Multi-step patterns for complex tasks |
anti-patterns.md | What to avoid and why | Mistakes common for this task type |
best-practices-guide.md | Official Claude Code documentation | Verification strategies, context tips |
2. Pattern Matching
Match the prompt to relevant patterns across multiple dimensions:
By Task Type:
| Type | Best Examples | Key Patterns | Common Anti-Patterns |
|---|---|---|---|
| Bug Fix | Debug examples, error handling | Symptom → location → test → fix | "fix the bug" (no symptom) |
| Feature | Feature impl examples | Pattern reference → scope → tests | "add X" (no constraints) |
| Refactor | Restructuring examples | Preserve behavior → incremental → verify | "make better" (no criteria) |
| Testing | Test writing examples | Edge cases → patterns → coverage | "add tests" (no cases) |
| Performance | Optimization examples | Profile → identify → fix → measure | "make faster" (no target) |
By Domain:
| Domain | Relevant Patterns | Key Verification |
|---|---|---|
| Auth | Session, token, permission patterns | Security tests, penetration testing |
| UI | Component, styling, responsive patterns | Visual regression, screenshot comparison |
| API | Endpoint, validation, error patterns | Integration tests, contract testing |
| Database | Query, migration, integrity patterns | Data integrity checks, rollback plans |
| DevOps | Pipeline, deployment, monitoring patterns | Smoke tests, health checks |
3. The 5 Transformation Principles
Know which principles apply most strongly:
| Principle | Applies When | How to Apply |
|---|---|---|
| 1. Add Verification | ALWAYS | Tests, screenshots, CLI output, success criteria |
| 2. Provide Context | Location vague | Specific files, functions, line numbers |
| 3. Add Constraints | Open-ended task | "avoid X", "no new deps", "keep backward compat" |
| 4. Structure in Phases | Complex task | Explore → Plan → Implement → Verify |
| 5. Include Rich Content | Debug/UI tasks | Error logs, screenshots, @file references |
4. Anti-Pattern Recognition
Identify patterns to AVOID in the transformation:
Universal Anti-Patterns:
- Over-specifying (too many constraints = confusion)
- Under-specifying (too vague = wrong direction)
- Compound tasks (multiple goals = scattered results)
- Missing verification (no way to check success)
Task-Specific Anti-Patterns:
| Task Type | Anti-Pattern | Why It's Bad |
|---|---|---|
| Bug Fix | "fix the bug" | No symptom = guessing |
| Feature | "add feature like X" | Unclear what "like" means |
| Refactor | "clean up the code" | No criteria for "clean" |
| Testing | "add tests" | No coverage target or cases |
| Performance | "make it faster" | No baseline or target |
Research Methodology
Phase 1: Classify the Task
1. Identify primary task type from signal words 2. Identify domain (auth, UI, API, etc.) 3. Note complexity level (simple, medium, complex)
Phase 2: Search Examples
1. Read before-after-examples.md 2. Find 2-3 examples matching task type 3. Find 1-2 examples matching domain if different 4. Extract the transformation pattern used
Phase 3: Check Anti-Patterns
1. Read anti-patterns.md 2. Identify anti-patterns relevant to this task type 3. Note what the prompt might be doing wrong 4. Find the corrective pattern
Phase 4: Extract Principles
1. Determine which of the 5 principles apply most 2. Note the order of application for this task type 3. Find specific guidance from best-practices-guide.md
Phase 5: Build Template
1. Combine examples into a transformation template 2. List specific elements to add 3. Note what to avoid 4. Suggest verification approach
Output Format
## Best Practices for: "[original prompt]"
### Classification
- **Task Type**: [Bug fix / Feature / Refactor / etc.]
- **Domain**: [Auth / UI / API / Database / etc.]
- **Complexity**: [Simple / Medium / Complex]
### Matching Examples
**Example 1** (from `before-after-examples.md`):BEFORE: "[similar vague prompt]"
AFTER: "[transformed version with all improvements]"
ADDED: [list of what was added] WHY: [why each addition matters]
**Example 2** (from `[source file]`):BEFORE: "[another similar prompt]"
AFTER: "[transformed version]"
ADDED: [list of what was added]
### Transformation Principles to Apply
**In this order:**
1. **[Principle Name]** (Priority: Critical)
- Apply by: [specific guidance for this prompt]
- Example: "[specific wording to add]"
2. **[Principle Name]** (Priority: Important)
- Apply by: [specific guidance]
- Example: "[specific wording]"
3. **[Principle Name]** (Priority: Recommended)
- Apply by: [specific guidance]
### Anti-Patterns to Avoid
**❌ Don't:**
- [Anti-pattern 1]: [Why it's bad for this task]
- [Anti-pattern 2]: [Why it's bad]
**✅ Instead:**
- [Corrective pattern 1]
- [Corrective pattern 2]
### Official Guidance
From `best-practices-guide.md`:
> "[Relevant quote from official docs]"
**Key recommendations for this task type:**
- [Specific recommendation 1]
- [Specific recommendation 2]
### Verification Strategy
For [task type], verify success by:
- [Primary verification method]
- [Secondary verification method]
**Specific commands/tests:**[example verification command or test case]
### Transformation Template
Based on these patterns, transform the prompt by adding:
[Original prompt essence]
[Add symptom/context]: "[specific wording]" [Add location]: "[specific wording]" [Add verification]: "[specific wording]" [Add constraints]: "[specific wording]"
### Sources Referenced
- `before-after-examples.md`: Examples 1, 2
- `anti-patterns.md`: [relevant section]
- `best-practices-guide.md`: [relevant section]Quality Standards
- Quote actual examples: Copy real examples from references, don't paraphrase
- Be specific to THIS prompt: Generic advice is useless
- Cite sources: Every pattern should reference its source file
- Prioritize: Most important patterns first
- Provide templates: Give copy-paste ready transformation guidance
Important Considerations
- Match task type precisely: Bug fix patterns don't apply to features
- Consider domain nuances: Auth tasks have different needs than UI tasks
- Layer patterns: Apply multiple principles, not just one
- Reference existing examples: The best transformation follows proven patterns
- Keep the skill evolving: If no matching example exists, note this gap
Your research should give the transformation engine everything it needs to improve this specific prompt using proven patterns from the reference files.
Note: The current year is 2026. Use this when referencing recent patterns or documentation.
You are a codebase exploration expert. Your mission is to gather specific, actionable context from THIS codebase that will transform a vague prompt into a precise, grounded one. You make prompts specific to the actual code, not generic advice.
Core Responsibilities
1. Relevant Files & Locations
Find the exact files, functions, and lines involved:
| What to Find | How to Find It | Why It Matters |
|---|---|---|
| Entry points | Glob for routes, controllers, handlers | Where changes likely start |
| Core logic | Grep for domain keywords | Where the work happens |
| Tests | Find matching test files | How to verify changes |
| Config | package.json, tsconfig, CLAUDE.md | Constraints and conventions |
| Types/Interfaces | Grep for type definitions | Contracts to maintain |
2. Similar Implementations
Find code that does something similar:
Pattern Recognition:
- If adding a feature → Find existing features with similar structure
- If fixing a bug → Find how similar bugs were fixed
- If refactoring → Find well-structured code to emulate
- If testing → Find existing test patterns
Why This Matters:
- "Follow the pattern in UserService.ts" is better than "implement a service"
- "Match the error handling in ErrorBoundary.tsx" is better than "handle errors"
3. Tech Stack Context
Understand the frameworks, libraries, and conventions:
| Category | What to Discover | Where to Look |
|---|---|---|
| Framework | Next.js, Rails, Express, etc. | package.json, Gemfile |
| UI Library | React, Vue, Tailwind, etc. | Dependencies, components/ |
| Testing | Jest, Vitest, RSpec, Pytest | Test config files |
| Database | Postgres, MongoDB, Prisma | Config, migrations |
| Validation | Zod, Yup, class-validator | Imports, schemas |
| Auth | Clerk, NextAuth, custom | Auth-related files |
4. Constraints to Surface
Identify what the prompt MUST respect:
From CLAUDE.md:
- Coding conventions
- Forbidden patterns
- Required approaches
- Testing requirements
From Codebase:
- Existing patterns that should be followed
- Dependencies that shouldn't be added
- Architectural decisions in place
From Tests:
- What's already covered
- Test patterns to follow
- Required coverage levels
Exploration Methodology
Phase 1: Understand the Request
1. Parse the prompt for domain keywords (auth, payment, user, etc.) 2. Identify the task type (bug, feature, refactor, etc.) 3. Note any files or areas explicitly mentioned
Phase 2: Broad Discovery
1. Check CLAUDE.md first — project-specific instructions 2. Check README.md — architecture overview 3. Check package.json/Gemfile — dependencies and scripts 4. Glob for relevant directories — find where domain code lives
Phase 3: Deep Exploration
1. Search by domain keywords — find all related code 2. Find test files — understand testing patterns 3. Find similar implementations — code to reference 4. Check imports/dependencies — understand the tech stack
Phase 4: Constraint Discovery
1. Read conventions from CLAUDE.md 2. Identify patterns that should be followed 3. Find anti-patterns that exist (to avoid making them worse) 4. Note dependencies that shouldn't be added
Phase 5: Synthesize Context
1. Prioritize findings — most relevant first 2. Create specific references — exact file paths, line numbers 3. Formulate suggestions — what to add to the prompt 4. Note constraints — what the prompt should include
Search Strategies
By Task Type
Bug Fix:
1. Search for error messages or symptoms mentioned
2. Find related error handling code
3. Locate tests that should catch this
4. Find similar bug fixes in git historyFeature:
1. Find similar features already implemented
2. Locate the module/directory where this belongs
3. Find existing patterns (services, components, etc.)
4. Check for feature flags or configuration patternsRefactor:
1. Find the code to refactor
2. Find all places that depend on it
3. Find tests that cover it
4. Find better-structured examples to emulateTesting:
1. Find existing test files for the module
2. Identify test patterns used (factories, mocks, etc.)
3. Find coverage configuration
4. Locate test utilities and helpersBy Domain
Auth/Security:
- Check
/auth,/security,middleware/ - Find session handling, token management
- Look for permission checks, role definitions
UI/Frontend:
- Check
/components,/pages,/views - Find similar components
- Look for styling patterns (CSS modules, Tailwind)
API/Backend:
- Check
/api,/routes,/controllers - Find validation patterns
- Look for error response formats
Database:
- Check
/models,/schema,/migrations - Find query patterns
- Look for transaction handling
Output Format
## Codebase Context for: "[original prompt]"
### Project Overview
- **Framework**: [e.g., Next.js 14 with App Router]
- **Language**: [e.g., TypeScript 5.3]
- **Key Libraries**: [e.g., Prisma, Zod, Tailwind]
- **Testing**: [e.g., Vitest with React Testing Library]
### CLAUDE.md Findings
[If exists, extract relevant conventions:]
- [Convention 1]
- [Convention 2]
- [Any forbidden patterns]
### Relevant Files
**Primary files (most likely to change):**
- `src/path/to/main.ts` — [what it does, why relevant]
- `src/path/to/related.ts:42` — [specific function/class]
**Test files:**
- `tests/path/to/main.test.ts` — [existing test coverage]
- `tests/helpers/testUtils.ts` — [test utilities to use]
**Config files:**
- `src/config/relevant.ts` — [relevant configuration]
### Similar Implementations
**Best example to follow:**
- **File**: `src/features/SimilarFeature.ts`
- **Pattern**: [describe the pattern]
- **Key insight**: [what to copy/follow]
- **Why it's relevant**: [connection to the task]
**Secondary example:**
- **File**: `src/features/AnotherExample.ts`
- **Pattern**: [describe]
### Tech Stack Details
| Category | Technology | Relevant For |
|----------|------------|--------------|
| [Category] | [Tech] | [How it relates to task] |
| [Category] | [Tech] | [How it relates to task] |
### Constraints Discovered
**MUST follow:**
- [Constraint from CLAUDE.md or codebase]
- [Pattern that should be followed]
**AVOID:**
- [Anti-pattern found in codebase]
- [Dependency that shouldn't be added]
**CONVENTION:**
- [Naming convention]
- [File organization pattern]
- [Code style requirement]
### Test Patterns
**Existing test structure:**tests/ ├── unit/ # [description] ├── integration/ # [description] └── helpers/ # [available test utilities]
**Test patterns to follow:**
- [How similar tests are structured]
- [Mock/stub patterns used]
- [Assertion patterns]
### Suggested Additions to Prompt
Add these specific references to ground the prompt:
- "check `src/specific/path/` for existing patterns"
- "follow the approach in `SpecificFile.ts`"
- "use the existing `helperFunction` utility"
- "maintain compatibility with `DependentModule.ts`"
- "run `npm test -- specific.test.ts` to verify"
### Verification Commands
Based on this codebase:Run relevant tests
[specific test command]
Type check
[type check command]
Lint
[lint command]
Quality Standards
- Be specific:
src/auth/login.ts:42not "the auth module" - Be actionable: Patterns to follow, not just observations
- Be grounded: Every suggestion backed by actual code found
- Be concise: Only include what improves the prompt
- Be prioritized: Most relevant files/patterns first
Important Considerations
- CLAUDE.md is authoritative: If it exists, respect its conventions
- Let the codebase guide: Don't suggest patterns that don't exist here
- Find the best examples: Point to well-structured code, not legacy
- Consider dependencies: Changes might affect other parts
- Note testing gaps: If tests are missing, that's relevant context
- Respect architecture: Don't suggest changes that violate existing structure
Your context should transform a vague prompt into one that references THIS codebase specifically, with exact file paths, proven patterns, and clear constraints.
Note: The current year is 2026. Use this when referencing recent patterns or documentation.
You are a task analysis expert specializing in understanding developer intent. Your mission is to deeply understand what a prompt is really asking for, identify what's missing, and surface considerations that would make the task clearer and more actionable.
Core Responsibilities
1. Task Type Classification
Classify the prompt into one of these categories with confidence level:
| Type | Signal Words | What's Needed |
|---|---|---|
| Bug Fix | fix, broken, error, crash, not working, fails | Symptom, reproduction steps, expected vs actual |
| Feature | add, implement, create, build, new | Scope, constraints, similar patterns to follow |
| Refactor | refactor, clean up, improve, restructure | Goals, invariants to preserve, test coverage |
| Testing | test, coverage, spec, verify | What to test, edge cases, test patterns |
| Exploration | understand, how does, why, explain | Questions to answer, depth needed |
| Documentation | document, explain, readme, comments | Audience, format, what to cover |
| Performance | slow, optimize, faster, latency | Metrics, target, profiling approach |
| Security | vulnerability, auth, permission, secure | Threat model, attack vectors, compliance |
| Migration | upgrade, migrate, convert, port | Source, target, compatibility requirements |
| DevOps | deploy, CI, pipeline, infrastructure | Environment, rollback plan, monitoring |
Confidence Levels:
- High (>80%): Single clear signal, unambiguous intent
- Medium (50-80%): Mixed signals or common pattern
- Low (<50%): Vague, multiple interpretations possible
2. Missing Elements Detection
Check the prompt against these essential elements:
| Element | Question | If Missing |
|---|---|---|
| Verification | How will success be measured? | No tests, screenshots, or success criteria specified |
| Location | Where in the codebase? | No file paths, modules, or areas mentioned |
| Symptom | What's actually happening? (bugs) | No description of user-facing problem |
| Expected | What should happen instead? (bugs) | No definition of correct behavior |
| Scope | What's in/out of scope? | Unclear boundaries, might expand |
| Constraints | What should NOT be done? | No mention of approaches to avoid |
| Context | Any prior attempts or background? | No history or context provided |
| Urgency | How critical is this? | No indication of priority |
3. Ambiguity Detection
Identify where the prompt could be interpreted multiple ways:
Common Ambiguities:
- Scope ambiguity: "improve the auth" — entire auth system or specific flow?
- Approach ambiguity: "add caching" — Redis, in-memory, CDN, or browser?
- Success ambiguity: "make it faster" — how fast is fast enough?
- Actor ambiguity: "user can't login" — which user? all users? specific conditions?
4. Edge Cases & Considerations
Think through what could go wrong or be forgotten:
By Task Type:
| Type | Common Edge Cases |
|---|---|
| Bug Fix | Race conditions, null states, network failures, concurrent users |
| Feature | Mobile/desktop, permissions, internationalization, accessibility |
| Refactor | Breaking changes, backward compatibility, dependent code |
| Testing | Async operations, error states, boundary conditions, mocking |
| Performance | Cold start, cache invalidation, memory leaks, connection pooling |
| Security | Input validation, session handling, rate limiting, audit logging |
Analysis Methodology
Phase 1: Parse & Extract
1. Identify every piece of information explicitly provided 2. Note the exact words used (signals for classification) 3. Extract any file paths, function names, or technical terms 4. Identify any implicit assumptions
Phase 2: Classify & Assess
1. Determine primary task type from signal words 2. Check for secondary task types (e.g., "fix bug and add tests") 3. Assess confidence level based on clarity 4. Note if classification is uncertain
Phase 3: Gap Analysis
1. Check each essential element against what's provided 2. For each gap, specify what information is needed 3. Prioritize gaps by impact on transformation quality 4. Distinguish critical gaps from nice-to-haves
Phase 4: Ambiguity & Edge Cases
1. List all possible interpretations 2. Surface edge cases specific to this task type 3. Consider dependencies and downstream effects 4. Think about failure modes
Phase 5: Synthesize Guidance
1. Prioritize what the transformed prompt needs most 2. Formulate specific questions to fill gaps 3. Suggest verification approaches for this task type 4. Recommend constraints based on common mistakes
Output Format
## Task Intent Analysis: "[original prompt]"
### Classification
- **Primary type**: [Bug fix / Feature / Refactor / Testing / etc.]
- **Secondary type**: [If applicable, e.g., "also involves testing"]
- **Confidence**: [High / Medium / Low] — [brief reasoning]
- **Domain**: [Auth / UI / API / Database / DevOps / etc.]
### Signal Words Detected
- "[word]" → suggests [interpretation]
- "[word]" → suggests [interpretation]
### What's Provided ✅
- **[Element]**: [What was explicitly given]
- **[Element]**: [What was explicitly given]
### What's Missing ❌
**Critical Gaps** (must address):
1. **[Element]**: [What's needed and why it matters]
2. **[Element]**: [What's needed and why it matters]
**Important Gaps** (should address):
3. **[Element]**: [What's needed]
4. **[Element]**: [What's needed]
**Nice-to-Have**:
5. **[Element]**: [Would improve but not required]
### Ambiguities Detected
**Ambiguity 1: [Name]**
- Interpretation A: [one way to read it]
- Interpretation B: [another way to read it]
- **Impact**: [what goes wrong if we guess wrong]
**Ambiguity 2: [Name]**
- Interpretation A: [one way]
- Interpretation B: [another way]
### Edge Cases to Consider
- **[Edge case]**: [Why it matters for this task]
- **[Edge case]**: [Why it matters for this task]
- **[Edge case]**: [Why it matters for this task]
### Transformation Guidance
**Priority 1** (Critical):
Add: [Most important missing element with specific wording suggestion]
**Priority 2** (Important):
Add: [Second most important element]
**Priority 3** (Recommended):
Add: [Third element]
**Suggested Verification Approach**:
For this task type, verify success by: [specific approach]
**Suggested Constraints**:
Based on common mistakes with [task type], add: [constraints]
### Interview Questions (if needed)
If gathering context interactively, ask:
1. "[Specific question to resolve critical gap]"
Options: [Option A] / [Option B] / [Option C] / Other
2. "[Specific question to resolve ambiguity]"
Options: [Option A] / [Option B] / OtherQuality Standards
- Be precise: "Missing verification" → "No test cases, expected output, or success criteria"
- Be actionable: Don't just identify gaps — suggest what to add
- Be prioritized: Critical gaps first, nice-to-haves last
- Be realistic: Focus on gaps that matter for THIS specific task
- Be specific to task type: Bug fixes need different things than features
Important Considerations
- Don't over-analyze simple prompts: "fix typo in README" doesn't need edge case analysis
- Match depth to complexity: More ambiguous prompts need deeper analysis
- Consider the user's expertise: Technical terms might indicate they know what they want
- Watch for XY problems: Sometimes the stated task isn't the real goal
- Surface assumptions: Make implicit assumptions explicit
Your analysis should make it immediately obvious what the transformed prompt needs to include, prioritized by importance.
Prompt Anti-Patterns to Avoid
This document catalogs common prompt mistakes and how to fix them. When transforming prompts, actively look for and correct these anti-patterns.
Table of Contents
1. Vagueness Anti-Patterns 2. Missing Context Anti-Patterns 3. Verification Anti-Patterns 4. Scope Anti-Patterns 5. Instruction Anti-Patterns 6. Session Anti-Patterns
---
Vagueness Anti-Patterns
Anti-Pattern: The Generic Request
BAD:
fix the bugWHY IT FAILS: No information about what bug, where it is, what symptoms, or how to verify it's fixed.
GOOD:
users report login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it.---
Anti-Pattern: The Ambiguous Improvement
BAD:
make the code betterWHY IT FAILS: "Better" is subjective. Better performance? Readability? Type safety? Fewer lines?
GOOD:
refactor utils.js to use ES2024 features while maintaining the same behavior. specifically: convert callbacks to async/await, use optional chaining. run the test suite after each change.---
Anti-Pattern: The Undefined Problem
BAD:
something's wrong with the APIWHY IT FAILS: No error message, no endpoint, no reproduction steps.
GOOD:
the GET /api/users endpoint returns 500 with this error: [paste error]. I can reproduce by calling the endpoint without an auth header. check src/api/users.ts line 45 where the request is handled.---
Anti-Pattern: The Wishful Feature
BAD:
add a nice login pageWHY IT FAILS: "Nice" is undefined. No design reference, no requirements, no patterns to follow.
GOOD:
create a login page with email and password fields. follow the form patterns in @src/components/SignupForm.tsx. include: validation feedback, remember me checkbox, forgot password link. test at 320px and 1024px widths.---
Anti-Pattern: The Partial Error
BAD:
getting an errorWHY IT FAILS: Which error? What file? What line? What action triggered it?
GOOD:
getting "TypeError: Cannot read property 'map' of undefined" at src/components/UserList.tsx:45 when loading the users page without being logged in. check the data fetching and add proper null handling.---
Missing Context Anti-Patterns
Anti-Pattern: The Locationless Request
BAD:
update the validation logicWHY IT FAILS: Validation is everywhere. Which validation? Which file? Which form?
GOOD:
update the email validation in @src/utils/validators.ts to also check for common disposable email domains. the domain list is in @src/config/blocked-domains.json.---
Anti-Pattern: The Pattern-Free Feature
BAD:
add a new componentWHY IT FAILS: No reference to existing patterns, no example of similar components.
GOOD:
add a ProductCard component following the patterns in @src/components/UserCard.tsx. include: image, title, price, and "Add to cart" button. use the same CSS modules approach.---
Anti-Pattern: The Orphan Request
BAD:
implement user authenticationWHY IT FAILS: No context about existing auth, no framework info, no session strategy preference.
GOOD:
read src/auth/ to understand current session handling. add Google OAuth following the existing patterns. use the session strategy already in place. test the complete flow from login to protected page access.---
Anti-Pattern: The Technology Vacuum
BAD:
add a databaseWHY IT FAILS: Which database? What schema? What connection library? What patterns?
GOOD:
add PostgreSQL using the existing Prisma setup. create a new Product model with: id, name, price, description, createdAt. follow the User model in @prisma/schema.prisma for patterns. add a migration and seed some test data.---
Anti-Pattern: The Assumed Knowledge
BAD:
do the same thing for productsWHY IT FAILS: Assumes Claude remembers what was done and where.
GOOD:
create a ProductRepository following the same pattern as UserRepository in @src/repositories/UserRepository.ts. include methods for: findAll, findById, create, update, delete. use the same database connection approach.---
Verification Anti-Patterns
Anti-Pattern: The Trust-and-Ship
BAD:
implement email validationWHY IT FAILS: No way to verify correctness. Plausible-looking code might not handle edge cases.
GOOD:
implement validateEmail function. test cases: [email protected] → true, invalid → false, [email protected] → false, empty string → false. run the tests after implementing.---
Anti-Pattern: The Visual Guess
BAD:
make the dashboard look goodWHY IT FAILS: No design reference to compare against.
GOOD:
[paste screenshot] implement this design. take a screenshot of the result and compare to the original. list differences and fix them.---
Anti-Pattern: The Symptom Suppression
BAD:
make the error go awayWHY IT FAILS: Encourages suppressing errors rather than fixing root causes.
GOOD:
the build fails with this error: [paste error]. fix the root cause, don't suppress the error with @ts-ignore. run the build to verify it succeeds.---
Anti-Pattern: The Unchecked Refactor
BAD:
refactor the utilitiesWHY IT FAILS: Refactoring without verification often introduces regressions.
GOOD:
refactor utils.js to use modern JavaScript features. maintain the same behavior. run the existing test suite after each change to ensure nothing breaks. add tests for any untested functions before refactoring them.---
Anti-Pattern: The Deployment Prayer
BAD:
should be ready to deployWHY IT FAILS: No verification steps. "Should be" isn't certainty.
GOOD:
verify the changes are ready for deployment:
1. run the full test suite
2. run the linter
3. run the type checker
4. build for production
5. test the build locally
list any issues found.---
Scope Anti-Patterns
Anti-Pattern: The Kitchen Sink
BAD:
fix the login bug, also update the styling, and add some tests, and maybe refactor the auth moduleWHY IT FAILS: Too many unrelated tasks mixed together. Context gets polluted.
GOOD: Split into separate prompts, use /clear between: 1. "fix the login bug in src/auth/. write a failing test first, then fix it." 2. (new session) "update the login page styling to match this mockup: [paste]" 3. (new session) "add tests for the auth module covering: login, logout, token refresh"
---
Anti-Pattern: The Infinite Scope
BAD:
add tests for everythingWHY IT FAILS: Unscoped. Will read hundreds of files filling context.
GOOD:
add tests for @src/services/PaymentService.ts covering:
- calculateTotal with various inputs
- validateCard (valid/expired/invalid)
- processPayment (success/failure)
target 80% coverage for this file.---
Anti-Pattern: The Implied Requirements
BAD:
add user managementWHY IT FAILS: What does "user management" include? List users? Edit? Delete? Roles?
GOOD:
add user management to the admin panel:
- list users with pagination (20 per page)
- view user details
- edit user email and role
- soft-delete user (no hard delete)
follow the admin patterns in @src/admin/ProductManagement.tsx---
Anti-Pattern: The Unbounded Investigation
BAD:
figure out why the app is slowWHY IT FAILS: Could lead to reading the entire codebase.
GOOD:
the product listing page takes 5+ seconds to load. profile using Chrome DevTools:
1. identify the slowest network requests
2. check for blocking resources
3. look for long JavaScript execution
report the top 3 bottlenecks with suggested fixes.---
Anti-Pattern: The Feature Creep
BAD:
add a search feature with autocomplete and fuzzy matching and recent searches and trending suggestionsWHY IT FAILS: Combines multiple features. Should be phased.
GOOD: Start with MVP:
add basic search to the products page:
- text input with search button
- filter products by name (case-insensitive contains)
- show "no results" when empty
follow the existing input patterns in @src/components/forms/Then iterate in follow-up prompts.
---
Instruction Anti-Patterns
Anti-Pattern: The Dictation
BAD:
open src/utils.js, go to line 45, change the if statement to check for null, then save the file, then open tests/utils.test.js and add a testWHY IT FAILS: Micromanaging Claude instead of delegating.
GOOD:
update the getUserById function in src/utils.js to handle null user IDs gracefully. add a test for the null case. run the tests after.---
Anti-Pattern: The Contradictory Instructions
BAD:
add comprehensive tests but keep it simple and quickWHY IT FAILS: Contradictory. Comprehensive takes time. Quick isn't comprehensive.
GOOD: Choose one:
- "add tests covering the critical paths: login, checkout, account creation"
- "add comprehensive tests for the payment module including all edge cases"
---
Anti-Pattern: The Unsaid Constraint
BAD:
add a date picker(User actually wanted no external dependencies, but didn't say so)
WHY IT FAILS: Claude might add a library when user wanted vanilla implementation.
GOOD:
add a date picker to the form. build from scratch without external libraries. use only the utilities already in the codebase. follow the existing form input patterns.---
Anti-Pattern: The Vague Rejection
BAD:
that's not quite rightWHY IT FAILS: No specific feedback about what's wrong or what's expected.
GOOD:
the date format should be MM/DD/YYYY not YYYY-MM-DD. also the validation should reject dates in the past. update the function and its tests.---
Anti-Pattern: The Suppressed Error
BAD:
add a try/catch to stop the errorWHY IT FAILS: Encourages hiding problems instead of fixing them.
GOOD:
the function throws when receiving null. add proper null validation at the start of the function. if null, return a sensible default or throw a descriptive error. add a test for the null case.---
Session Anti-Patterns
Anti-Pattern: The Eternal Session
BAD: Working on multiple unrelated tasks without clearing:
> fix the login bug
[work happens]
> also add the search feature
[more work]
> and refactor the utilities
[context is now full of three unrelated things]WHY IT FAILS: Context fills with irrelevant information from previous tasks.
GOOD:
> fix the login bug...
[work completes]
> /clear
> add the search feature...---
Anti-Pattern: The Correction Spiral
BAD:
> do X
> no, I meant Y
> that's not right either, try Z
> still wrong, maybe A?
> let me explain again...WHY IT FAILS: Context polluted with failed approaches. Claude gets confused.
GOOD: After 2 failed corrections, /clear and write a better initial prompt:
> /clear
> implement [clear description with specific requirements and verification]. follow patterns in @[similar code].---
Anti-Pattern: The Overstuffed CLAUDE.md
BAD: A 2000-line CLAUDE.md with every possible instruction.
WHY IT FAILS: Claude ignores important rules lost in the noise.
GOOD: Keep CLAUDE.md concise:
- Commands Claude can't guess
- Style rules that differ from defaults
- Critical project-specific conventions
Move details to linked documents or skills.
---
Anti-Pattern: The Context Hog
BAD:
read all the files in src/ and then tell me about the architectureWHY IT FAILS: Reads entire codebase into context, leaving no room for actual work.
GOOD:
read the main entry point and top-level directories to understand the architecture. don't read every file - just enough to explain the main patterns.Or use subagents:
use a subagent to investigate the codebase architecture and report a summary.---
Anti-Pattern: The Lost History
BAD:
do what we discussed earlierWHY IT FAILS: After compaction, earlier discussion might be summarized or lost.
GOOD: Be explicit about what was decided:
implement the user notification system using WebSocket as we decided. the spec is in @NOTIFICATIONS_SPEC.md. start with the backend WebSocket handler.Or use ledger files to track state across sessions.
---
Summary: Quick Fix Reference
| Anti-Pattern | Quick Fix |
|---|---|
| Generic request | Add symptom + location + verification |
| Ambiguous improvement | Specify exact changes |
| Locationless request | Add file paths with @ |
| Pattern-free feature | Reference similar existing code |
| Trust-and-ship | Add test cases with expected outputs |
| Visual guess | Paste screenshot for comparison |
| Kitchen sink | Split tasks, /clear between |
| Infinite scope | Bound to specific files/functions |
| Dictation | Delegate outcome, not steps |
| Vague rejection | Specify what's wrong and expected |
| Eternal session | /clear between unrelated tasks |
| Correction spiral | After 2 fails, /clear + better prompt |
Before/After Prompt Transformation Examples
This document contains 50+ examples of prompt transformations organized by category. Each example shows the original suboptimal prompt and the optimized version following Claude Code best practices.
Table of Contents
1. Verification & Testing 2. Bug Fixes & Debugging 3. Feature Implementation 4. Refactoring 5. UI & Frontend 6. API & Backend 7. Database 8. Testing 9. Documentation 10. Code Review 11. DevOps & CI/CD 12. Security 13. Performance 14. Git & Version Control
---
Verification & Testing
Example 1: Email Validation
BEFORE:
implement a function that validates email addressesAFTER:
write a validateEmail function. test cases:
- [email protected] → true
- invalid → false
- [email protected] → false
- user@domain → false
- @domain.com → false
run the tests after implementingWhy it's better: Provides specific test cases with expected outputs, giving Claude verification criteria.
---
Example 2: Password Strength Checker
BEFORE:
create a password strength validatorAFTER:
create a checkPasswordStrength function that returns 'weak', 'medium', or 'strong'. test cases:
- "abc" → weak (too short)
- "password123" → weak (common pattern)
- "MyP@ssw0rd!" → strong (mixed case, numbers, symbols, 10+ chars)
- "abcdefghij" → medium (long but no variety)
run tests after implementing. place in src/utils/validation.ts following existing util patterns.---
Example 3: Date Parsing
BEFORE:
write a date parserAFTER:
write a parseDate function in src/utils/dates.ts that handles multiple formats. test cases:
- "2024-01-15" → Date object for Jan 15, 2024
- "01/15/2024" → Date object for Jan 15, 2024
- "January 15, 2024" → Date object for Jan 15, 2024
- "invalid" → null
- "" → null
follow the existing utility function patterns in @src/utils/. run tests after implementing.---
Bug Fixes & Debugging
Example 4: Generic Bug Report
BEFORE:
fix the login bugAFTER:
users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it. verify by running the auth test suite.Why it's better: Describes the symptom, points to specific location, requests a failing test first.
---
Example 5: Build Failure
BEFORE:
the build is failingAFTER:
the build fails with this error:
[paste actual error message here]
fix it and verify the build succeeds. address the root cause, don't suppress the error. run `npm run build` after fixing to confirm.---
Example 6: Undefined Error
BEFORE:
getting undefined errorAFTER:
getting "Cannot read property 'user' of undefined" error on line 45 of src/components/Dashboard.tsx when loading the dashboard without being logged in. check the auth context provider and add proper null handling. write a test for the unauthenticated state, then fix it.---
Example 7: Race Condition
BEFORE:
there's a race condition somewhereAFTER:
users intermittently see stale data after updating their profile. I suspect a race condition between the optimistic update and the API response in src/hooks/useProfile.ts. add console logs to trace the update flow, identify the race condition, then fix it. add a test that simulates the race condition by delaying the API response.---
Example 8: Memory Leak
BEFORE:
fix the memory leakAFTER:
the app's memory usage grows over time when navigating between pages. I suspect event listeners aren't being cleaned up. check src/components/ for useEffect hooks that add listeners without cleanup. profile the heap in Chrome DevTools to identify the leak source. fix any missing cleanup functions and verify memory stays stable during navigation.---
Feature Implementation
Example 9: Calendar Widget
BEFORE:
add a calendar widgetAFTER:
look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase. add tests for month selection and pagination.Why it's better: References existing patterns, specifies exact functionality, sets constraints.
---
Example 10: Search Feature
BEFORE:
add search functionalityAFTER:
add a search feature to the products page following the existing search pattern in @src/components/UserSearch.tsx. requirements:
- debounce input by 300ms
- show loading spinner during search
- display "no results" when empty
- highlight matching text in results
add tests for debouncing and empty states. place component in src/components/ProductSearch.tsx.---
Example 11: Pagination
BEFORE:
add pagination to the listAFTER:
add cursor-based pagination to the /api/products endpoint and ProductList component. follow the existing pagination pattern in @src/api/users.ts and @src/components/UserList.tsx. requirements:
- 20 items per page
- "Load more" button (not page numbers)
- preserve scroll position when loading more
- handle loading and error states
add API tests and component tests. verify by loading the products page and clicking "Load more" multiple times.---
Example 12: Dark Mode
BEFORE:
add dark modeAFTER:
add dark mode toggle to the settings page. implementation:
1. read src/styles/ to understand current theming approach
2. add CSS variables for dark theme colors in src/styles/themes.css
3. create a ThemeContext in src/context/ThemeContext.tsx
4. add toggle switch to Settings.tsx
5. persist preference in localStorage
6. respect system preference as default
follow existing context patterns in @src/context/AuthContext.tsx. test the toggle persists across page reloads.---
Example 13: File Upload
BEFORE:
implement file uploadAFTER:
implement file upload for user avatars in the profile settings. requirements:
- accept only jpg, png, webp under 5MB
- show preview before upload
- display progress bar during upload
- handle errors gracefully with user-friendly messages
follow the existing form patterns in @src/components/ProfileForm.tsx. backend endpoint is POST /api/upload. add tests for file validation and error handling. verify by uploading various file types and sizes.---
Refactoring
Example 14: Generic Refactor
BEFORE:
make the code betterAFTER:
refactor utils.js to use ES2024 features while maintaining the same behavior. specifically:
- convert callbacks to async/await
- use optional chaining where applicable
- add proper TypeScript types
run the existing test suite after each change to ensure nothing breaks.---
Example 15: Extract Component
BEFORE:
refactor this componentAFTER:
the UserDashboard component in @src/components/UserDashboard.tsx is 500+ lines. extract these sections into separate components:
- UserStats (lines 45-120)
- RecentActivity (lines 150-250)
- QuickActions (lines 280-350)
keep the parent component as the layout orchestrator. ensure props are typed correctly. run the existing tests after each extraction to ensure nothing breaks.---
Example 16: Remove Duplication
BEFORE:
DRY up this codeAFTER:
src/api/users.ts and src/api/products.ts have duplicate error handling logic (lines 20-45 in each). extract a shared handleApiError function to src/api/utils.ts. requirements:
- handle 401, 403, 404, 500 errors
- return typed error objects
- log errors to our logging service
update both files to use the shared function. run the API tests after to verify behavior is unchanged.---
Example 17: Modernize Patterns
BEFORE:
update the old codeAFTER:
modernize src/legacy/OrderProcessor.js:
- convert from class to functional approach with hooks
- replace var with const/let
- convert promises to async/await
- add TypeScript types (rename to .ts)
- update imports from CommonJS to ES modules
make one change at a time, running tests after each to catch regressions. the existing tests are in tests/legacy/OrderProcessor.test.js (update to .ts as well).---
UI & Frontend
Example 18: UI Improvements
BEFORE:
make the dashboard look betterAFTER:
[paste screenshot of target design]
implement this design for the dashboard. focus on:
- card layout with shadows
- proper spacing (use existing spacing variables from @src/styles/variables.css)
- responsive grid (2 columns on tablet, 1 on mobile)
take a screenshot of the result and compare it to the original design. list differences and fix them.Why it's better: Includes visual reference, specifies responsive requirements, asks for verification.
---
Example 19: Form Styling
BEFORE:
style the formAFTER:
[paste screenshot of design mockup]
style the registration form to match this mockup. requirements:
- input fields: 48px height, 8px border-radius, 1px border
- labels: 14px, 500 weight, above inputs
- error states: red border, error message below
- submit button: full width, primary color from theme
use existing CSS variables from @src/styles/. verify all states: empty, filled, error, disabled. test at 320px, 768px, and 1024px widths.---
Example 20: Animation
BEFORE:
add animationsAFTER:
add subtle entrance animations to the card grid on the home page. requirements:
- cards fade in and slide up 20px
- stagger delay: 50ms between each card
- duration: 300ms with ease-out
- use CSS animations, not JavaScript
- respect prefers-reduced-motion
follow the existing animation patterns in @src/styles/animations.css. test with reduced motion enabled in browser settings.---
Example 21: Accessibility
BEFORE:
make it accessibleAFTER:
audit the navigation component in @src/components/Nav.tsx for accessibility. check and fix:
- keyboard navigation (Tab, Enter, Escape)
- ARIA labels for icon-only buttons
- focus indicators visible on all interactive elements
- screen reader announcements for menu open/close
- color contrast meets WCAG AA
test with keyboard-only navigation and VoiceOver. run `npm run test:a11y` after fixes.---
API & Backend
Example 22: Generic API Question
BEFORE:
why does ExecutionFactory have such a weird api?AFTER:
look through ExecutionFactory's git history and summarize how its api came to be. specifically:
- when was it created and by whom?
- what were the major changes and why?
- are there any related issues or PRs that explain design decisions?Why it's better: Points to sources (git history), asks for specific investigation.
---
Example 23: New Endpoint
BEFORE:
add an API endpointAFTER:
add a GET /api/products/:id endpoint following the pattern in @src/api/users.ts. requirements:
- return 404 if product not found
- include related category data (JOIN)
- cache response for 5 minutes
- add rate limiting (100 req/min)
- validate :id is a valid UUID
add tests for success, not found, invalid id, and rate limiting. document in the API docs.---
Example 24: Authentication
BEFORE:
add authAFTER:
read src/auth/ to understand current session handling, then add Google OAuth. implementation plan:
1. add Google OAuth credentials to .env.example
2. create callback handler in src/auth/google.ts
3. update session to store OAuth tokens
4. add "Sign in with Google" button to login page
5. handle account linking for existing users
follow the existing auth patterns. write tests for the callback handler including error cases. document the setup steps in README.---
Example 25: Webhooks
BEFORE:
implement webhooksAFTER:
add a webhook system for order status updates. requirements:
- POST /api/webhooks/register endpoint to register URLs
- validate webhook URLs are HTTPS
- sign payloads with HMAC-SHA256
- retry failed deliveries 3 times with exponential backoff
- log all delivery attempts
follow the event pattern in @src/events/. store registrations in the webhooks table (create migration). add tests for registration validation, signature verification, and retry logic.---
Database
Example 26: Migration
BEFORE:
add a new columnAFTER:
add an 'archived_at' nullable timestamp column to the products table. steps:
1. create migration in db/migrations/
2. update Product model in src/models/Product.ts
3. update ProductRepository to filter out archived by default
4. add 'includeArchived' option to list queries
follow the migration pattern in @db/migrations/20240101_add_user_status.sql. run migration locally and verify with a query. add test for archive filtering.---
Example 27: Query Optimization
BEFORE:
the query is slowAFTER:
the getOrdersWithProducts query in src/repositories/OrderRepository.ts takes 3+ seconds for users with many orders. current query is on line 45. profile the query with EXPLAIN ANALYZE:
- identify missing indexes
- check for N+1 queries
- consider pagination
add any needed indexes via migration. target: under 100ms for 1000 orders. run the performance test in tests/performance/orders.test.ts before and after.---
Example 28: Seeding
BEFORE:
add test dataAFTER:
create a database seed script in db/seeds/development.ts that creates:
- 10 users with varied roles (2 admin, 3 manager, 5 regular)
- 50 products across 5 categories
- 100 orders with realistic date distribution over past 90 days
- proper relationships between entities
use Faker.js for realistic data. follow the seed pattern in @db/seeds/categories.ts. add npm script "db:seed" to package.json. verify by running seed and checking counts.---
Testing
Example 29: Generic Test Request
BEFORE:
add tests for foo.pyAFTER:
write a test for foo.py covering the edge case where the user is logged out. avoid mocks. test cases:
- logged_out_user returns 401
- expired_session redirects to login
- invalid_token raises AuthError
follow the test patterns in @tests/auth/. run the new tests after implementing.Why it's better: Specifies exact edge case, provides test cases, states constraints (no mocks).
---
Example 30: Integration Tests
BEFORE:
add integration testsAFTER:
add integration tests for the order checkout flow in tests/integration/checkout.test.ts. test the complete flow:
1. add items to cart
2. apply discount code
3. enter shipping info
4. process payment (use test Stripe key)
5. verify order created in database
6. verify confirmation email sent (mock email service only)
cover error cases: invalid card, out of stock, expired discount. use the test database setup in @tests/setup.ts.---
Example 31: Snapshot Tests
BEFORE:
add snapshot testsAFTER:
add snapshot tests for the ProductCard component covering these variants:
- default state
- on sale (with discount badge)
- out of stock (with overlay)
- loading state
place in tests/components/ProductCard.snapshot.test.tsx. use the existing snapshot config in @jest.config.js. run and commit the initial snapshots.---
Documentation
Example 32: API Docs
BEFORE:
document the APIAFTER:
add OpenAPI/Swagger documentation for the products API endpoints. include:
- GET /api/products (list with pagination params)
- GET /api/products/:id (single product)
- POST /api/products (create, admin only)
- PUT /api/products/:id (update)
- DELETE /api/products/:id (soft delete)
document request/response schemas, auth requirements, and error responses. follow the format in @docs/api/users.yaml. validate the spec with `npm run docs:validate`.---
Example 33: README
BEFORE:
update the readmeAFTER:
update README.md with the new authentication flow. add:
- environment variables needed (.env.example reference)
- setup steps for Google OAuth credentials
- how to run locally with OAuth disabled (for development)
- troubleshooting section for common auth errors
keep existing sections intact. follow the documentation style of existing README sections.---
Code Review
Example 34: Generic Review
BEFORE:
review my codeAFTER:
review the changes in @src/services/PaymentService.ts for:
- security issues (especially around handling card data)
- error handling completeness
- edge cases not covered
- consistency with existing service patterns in @src/services/
- test coverage gaps
provide specific line references for any issues found.---
Example 35: PR Review
BEFORE:
review this PRAFTER:
review PR #123 for the new notification system. focus on:
- does the implementation match the spec in @docs/specs/notifications.md?
- are there race conditions in the real-time updates?
- is the database schema migration reversible?
- are error states handled in the UI?
- is test coverage sufficient for the critical paths?
provide actionable feedback with code suggestions where applicable.---
DevOps & CI/CD
Example 36: CI Setup
BEFORE:
set up CIAFTER:
add GitHub Actions workflow for CI in .github/workflows/ci.yml. the workflow should:
- run on push to main and all PRs
- install dependencies with npm ci
- run linting (npm run lint)
- run type checking (npm run typecheck)
- run tests with coverage (npm run test:coverage)
- fail if coverage drops below 80%
- cache node_modules between runs
follow the workflow pattern in @.github/workflows/deploy.yml for caching strategy.---
Example 37: Docker
BEFORE:
dockerize the appAFTER:
create Dockerfile and docker-compose.yml for local development. requirements:
- multi-stage build for smaller production image
- node:20-alpine base
- separate services for app, postgres, redis
- mount source code for hot reloading in dev
- health checks for all services
- .dockerignore to exclude node_modules, .git
follow the patterns in @infrastructure/docker/ if present. document docker commands in README. verify with `docker-compose up` and test the app works.---
Security
Example 38: Security Audit
BEFORE:
check for security issuesAFTER:
audit the user input handling in @src/api/ for security vulnerabilities:
- SQL injection in raw queries
- XSS in rendered user content
- CSRF protection on state-changing endpoints
- authentication bypass possibilities
- sensitive data in logs or error messages
- hardcoded secrets or credentials
provide specific file:line references for each issue with remediation steps. prioritize by severity.---
Example 39: Input Validation
BEFORE:
add validationAFTER:
add input validation to the user registration endpoint in src/api/users.ts. validate:
- email: valid format, not already registered
- password: min 8 chars, at least 1 number and 1 special char
- username: 3-20 chars, alphanumeric and underscores only, not taken
return specific error messages for each validation failure. use the validation patterns in @src/utils/validators.ts. add tests for each validation rule including edge cases.---
Performance
Example 40: Performance Investigation
BEFORE:
the page is slowAFTER:
the product listing page takes 5+ seconds to load. investigate:
1. run Lighthouse audit and report scores
2. check network waterfall for blocking requests
3. profile React components for unnecessary re-renders
4. check API response times in Network tab
5. identify the top 3 performance bottlenecks
then create an action plan with estimated impact for each fix. start with the highest-impact fix.---
Example 41: Bundle Optimization
BEFORE:
reduce bundle sizeAFTER:
analyze and reduce the JavaScript bundle size. steps:
1. run `npm run build` and report current bundle sizes
2. use webpack-bundle-analyzer to identify large dependencies
3. implement code splitting for routes
4. lazy load heavy components (charts, editors)
5. check for duplicate dependencies
target: main bundle under 200KB gzipped. document changes and new bundle sizes.---
Git & Version Control
Example 42: Commit History
BEFORE:
look at the git historyAFTER:
trace the evolution of the payment processing module. check git history for:
- when was src/payments/ first created?
- what were the major refactors and why (check commit messages and linked PRs)?
- who are the main contributors?
- are there any reverted changes that might explain current quirks?
summarize the key decisions and their rationale.---
Example 43: Merge Conflict
BEFORE:
fix the merge conflictAFTER:
resolve the merge conflict in src/components/Header.tsx between feature/new-nav and main. context:
- feature/new-nav adds a mobile menu
- main updated the logo and added a search bar
- we want both changes
resolve to keep both features working together. run `npm run test` and `npm run typecheck` after resolving to verify nothing broke.---
Example 44: Branch Cleanup
BEFORE:
clean up branchesAFTER:
identify branches that can be deleted:
- list branches merged into main more than 30 days ago
- list branches with no commits in 60+ days
- exclude branches matching: release/*, hotfix/*, main, develop
show the list for review before deleting. after approval, delete the remote branches with `git push origin --delete`.---
Complex Multi-Step Examples
Example 45: Full Feature Implementation
BEFORE:
add user notificationsAFTER:
implement a user notification system. phase this work:
PHASE 1 - Explore:
- read existing user-related code in src/users/ and src/components/
- check if we have any notification patterns already
- identify where notifications should integrate
PHASE 2 - Plan:
- design the notification data model
- plan the API endpoints needed
- sketch the UI components
- write the plan to NOTIFICATIONS_PLAN.md for review
PHASE 3 - Implement (after plan approval):
- create database migration for notifications table
- add API endpoints (list, mark read, delete)
- create NotificationBell component for header
- create NotificationList dropdown
- add real-time updates with WebSocket
- write tests for each component
PHASE 4 - Verify:
- run all tests
- manually test the full flow
- check mobile responsiveness
- verify WebSocket reconnection handling---
Example 46: Legacy System Migration
BEFORE:
migrate from the old systemAFTER:
migrate OrderProcessor from the legacy PHP system to our Node.js backend.
STEP 1 - Understand:
- read legacy/OrderProcessor.php and document its behavior
- identify all inputs, outputs, and side effects
- note any business logic that isn't obvious from code
- list all database tables it touches
STEP 2 - Plan:
- map PHP functions to TypeScript equivalents
- design the new data models
- identify what can be simplified vs must be preserved exactly
- create migration plan document
STEP 3 - Implement:
- create new OrderProcessor in src/services/
- write comprehensive tests based on legacy behavior
- implement each method, running tests after each
- add logging to match legacy log format
STEP 4 - Validate:
- run both systems in parallel with same inputs
- compare outputs for 100 test orders
- document any differences and justify or fix them---
Example 47: Debugging Session
BEFORE:
users can't checkoutAFTER:
users report "checkout failed" error intermittently. investigate:
1. GATHER INFO:
- check error logs in CloudWatch for checkout-related errors
- identify error patterns (time of day, user segments, browsers)
- get sample user IDs who experienced the issue
2. REPRODUCE:
- set up local environment to match production
- attempt to reproduce with sample user data
- add detailed logging to checkout flow if needed
3. IDENTIFY ROOT CAUSE:
- trace the checkout flow for a failing case
- identify where it diverges from success path
- determine if it's frontend, backend, or third-party issue
4. FIX:
- write a test that reproduces the failure
- implement the fix
- verify the test passes
- check for similar issues elsewhere in codebase
5. VERIFY:
- deploy to staging
- test with previously failing scenarios
- monitor error rates after production deploy---
Example 48: API Versioning
BEFORE:
version the APIAFTER:
implement API versioning for our REST endpoints.
REQUIREMENTS:
- support v1 (current) and v2 (new) simultaneously
- v1 endpoints remain unchanged for 6 months
- v2 endpoints use new response format
- deprecation warnings in v1 responses
IMPLEMENTATION:
1. read current API structure in src/api/
2. create src/api/v1/ and src/api/v2/ directories
3. move current handlers to v1/
4. create v2/ handlers with new format
5. update router to handle /api/v1/* and /api/v2/*
6. add deprecation headers to v1 responses
7. update API docs for both versions
TESTING:
- ensure all existing tests pass for v1
- add tests for v2 endpoints
- test version routing
- verify deprecation headers present
Follow the existing routing patterns in @src/router.ts.---
Example 49: Performance Critical Fix
BEFORE:
make the search fasterAFTER:
the product search takes 8+ seconds for queries with common terms. optimize:
PROFILE FIRST:
1. run EXPLAIN ANALYZE on the search query
2. identify slow operations (full table scan, missing index, etc.)
3. check query plan for the WHERE clause and JOINs
OPTIMIZE:
- add appropriate indexes (document which ones and why)
- consider full-text search index for product names/descriptions
- implement search result caching (5 minute TTL)
- add pagination if not present (100 results max)
VERIFY:
- run EXPLAIN ANALYZE again, compare before/after
- measure response times for common queries
- target: under 200ms for 95th percentile
- load test with 100 concurrent searches
Document the changes and performance improvements in a PR description.---
Example 50: Complete Testing Suite
BEFORE:
add tests for the payment moduleAFTER:
create comprehensive tests for src/services/PaymentService.ts
UNIT TESTS (tests/unit/PaymentService.test.ts):
- calculateTotal with various inputs (items, discounts, tax)
- validateCard (valid cards, expired, invalid number)
- formatCurrency (different locales)
INTEGRATION TESTS (tests/integration/payment.test.ts):
- full checkout flow with test Stripe API
- refund processing
- webhook handling for payment events
- idempotency for duplicate requests
EDGE CASES:
- zero amount orders
- maximum order value
- currency conversion
- partial refunds
- network timeout handling
- invalid API responses
MOCKING STRATEGY:
- mock Stripe only for unit tests
- use Stripe test mode for integration
- mock database for unit, real DB for integration
Run each test file as you create it. Target 90%+ coverage for the payment module.Best Practices for Claude Code
Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.
Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.
This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.
But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.
This guide covers patterns that have proven effective across Anthropic's internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see How Claude Code works.
***
Most best practices are based on one constraint: Claude's context window fills up fast, and performance degrades as it fills.
Claude's context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.
This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start "forgetting" earlier instructions or making more mistakes. The context window is the most important resource to manage. For detailed strategies on reducing token usage, see Reduce token usage.
***
Give Claude a way to verify its work
Tip: Include tests, screenshots, or expected outputs so Claude can check itself. This is the single highest-leverage thing you can do.
Claude performs dramatically better when it can verify its own work, like run tests, compare screenshots, and validate outputs.
Without clear success criteria, it might produce something that looks right but actually doesn't work. You become the only feedback loop, and every mistake requires your attention.
| Strategy | Before | After |
|---|---|---|
| Provide verification criteria | "implement a function that validates email addresses" | "write a validateEmail function. example test cases: user@example.com is true, invalid is false, user@.com is false. run the tests after implementing" |
| Verify UI changes visually | "make the dashboard look better" | "[paste screenshot] implement this design. take a screenshot of the result and compare it to the original. list differences and fix them" |
| Address root causes, not symptoms | "the build is failing" | "the build fails with this error: [paste error]. fix it and verify the build succeeds. address the root cause, don't suppress the error" |
UI changes can be verified using the Claude in Chrome extension. It opens a browser, tests the UI, and iterates until the code works.
Your verification can also be a test suite, a linter, or a Bash command that checks output. Invest in making your verification rock-solid.
***
Explore first, then plan, then code
Tip: Separate research and planning from implementation to avoid solving the wrong problem.
Letting Claude jump straight to coding can produce code that solves the wrong problem. Use Plan Mode to separate exploration from execution.
The recommended workflow has four phases:
Step 1: Explore
Enter Plan Mode. Claude reads files and answers questions without making changes.
read /src/auth and understand how we handle sessions and login.
also look at how we manage environment variables for secrets.Step 2: Plan
Ask Claude to create a detailed implementation plan.
I want to add Google OAuth. What files need to change?
What's the session flow? Create a plan.Step 3: Implement
Switch back to Normal Mode and let Claude code, verifying against its plan.
implement the OAuth flow from your plan. write tests for the
callback handler, run the test suite and fix any failures.Step 4: Commit
Ask Claude to commit with a descriptive message and create a PR.
commit with a descriptive message and open a PRNote: Plan Mode is useful, but also adds overhead. For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly. Planning is most useful when you're uncertain about the approach, when the change modifies multiple files, or when you're unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.
***
Provide specific context in your prompts
Tip: The more precise your instructions, the fewer corrections you'll need.
Claude can infer intent, but it can't read your mind. Reference specific files, mention constraints, and point to example patterns.
| Strategy | Before | After |
|---|---|---|
| Scope the task. Specify which file, what scenario, and testing preferences. | "add tests for foo.py" | "write a test for foo.py covering the edge case where the user is logged out. avoid mocks." |
| Point to sources. Direct Claude to the source that can answer a question. | "why does ExecutionFactory have such a weird api?" | "look through ExecutionFactory's git history and summarize how its api came to be" |
| Reference existing patterns. Point Claude to patterns in your codebase. | "add a calendar widget" | "look at how existing widgets are implemented on the home page to understand the patterns. HotDogWidget.php is a good example. follow the pattern to implement a new calendar widget that lets the user select a month and paginate forwards/backwards to pick a year. build from scratch without libraries other than the ones already used in the codebase." |
| Describe the symptom. Provide the symptom, the likely location, and what "fixed" looks like. | "fix the login bug" | "users report that login fails after session timeout. check the auth flow in src/auth/, especially token refresh. write a failing test that reproduces the issue, then fix it" |
Vague prompts can be useful when you're exploring and can afford to course-correct. A prompt like "what would you improve in this file?" can surface things you wouldn't have thought to ask about.
Provide rich content
Tip: Use @ to reference files, paste screenshots/images, or pipe data directly.You can provide rich data to Claude in several ways:
- Reference files with `@` instead of describing where code lives. Claude reads the file before responding.
- Paste images directly. Copy/paste or drag and drop images into the prompt.
- Give URLs for documentation and API references. Use
/permissionsto allowlist frequently-used domains. - Pipe in data by running
cat error.log | claudeto send file contents directly. - Let Claude fetch what it needs. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.
***
Configure your environment
A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see Extend Claude Code.
Write an effective CLAUDE.md
Tip: Run /init to generate a starter CLAUDE.md file based on your current project structure, then refine over time.CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can't infer from code alone.
The /init command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.
There's no required format for CLAUDE.md files, but keep it short and human-readable. For example:
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')
# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performanceCLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use skills instead. Claude loads them on demand without bloating every conversation.
Keep it concise. For each line, ask: "Would removing this cause Claude to make mistakes?" If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!
| ✅ Include | ❌ Exclude |
|---|---|
| Bash commands Claude can't guess | Anything Claude can figure out by reading code |
| Code style rules that differ from defaults | Standard language conventions Claude already knows |
| Testing instructions and preferred test runners | Detailed API documentation (link to docs instead) |
| Repository etiquette (branch naming, PR conventions) | Information that changes frequently |
| Architectural decisions specific to your project | Long explanations or tutorials |
| Developer environment quirks (required env vars) | File-by-file descriptions of the codebase |
| Common gotchas or non-obvious behaviors | Self-evident practices like "write clean code" |
If Claude keeps doing something you don't want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts.
You can tune instructions by adding emphasis (e.g., "IMPORTANT" or "YOU MUST") to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.
CLAUDE.md files can import additional files using @path/to/import syntax:
See @README.md for project overview and @package.json for available npm commands.
# Additional Instructions
- Git workflow: @docs/git-instructions.md
- Personal overrides: @~/.claude/my-project-instructions.mdYou can place CLAUDE.md files in several locations:
- Home folder (`~/.claude/CLAUDE.md`): Applies to all Claude sessions
- Project root (`./CLAUDE.md`): Check into git to share with your team, or name it
CLAUDE.local.mdand.gitignoreit - Parent directories: Useful for monorepos where both
root/CLAUDE.mdandroot/foo/CLAUDE.mdare pulled in automatically - Child directories: Claude pulls in child CLAUDE.md files on demand when working with files in those directories
Configure permissions
Tip: Use/permissionsto allowlist safe commands or/sandboxfor OS-level isolation. This reduces interruptions while keeping you in control.
By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you're not really reviewing anymore, you're just clicking through. There are two ways to reduce these interruptions:
- Permission allowlists: Permit specific tools you know are safe (like
npm run lintorgit commit) - Sandboxing: Enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries
Alternatively, use --dangerously-skip-permissions to bypass all permission checks for contained workflows like fixing lint errors or generating boilerplate.
Warning: Letting Claude run arbitrary commands can result in data loss, system corruption, or data exfiltration via prompt injection. Only use --dangerously-skip-permissions in a sandbox without internet access.Read more about configuring permissions and enabling sandboxing.
Use CLI tools
Tip: Tell Claude Code to use CLI tools likegh,aws,gcloud, andsentry-cliwhen interacting with external services.
CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the gh CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without gh, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.
Claude is also effective at learning CLI tools it doesn't already know. Try prompts like Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.
Connect MCP servers
Tip: Run claude mcp add to connect external tools like Notion, Figma, or your database.With MCP servers, you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.
Set up hooks
Tip: Use hooks for actions that must happen every time with zero exceptions.
Hooks run scripts automatically at specific points in Claude's workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.
Claude can write hooks for you. Try prompts like "Write a hook that runs eslint after every file edit" or "Write a hook that blocks writes to the migrations folder." Run /hooks for interactive configuration, or edit .claude/settings.json directly.
Create skills
Tip: CreateSKILL.mdfiles in.claude/skills/to give Claude domain knowledge and reusable workflows.
Skills extend Claude's knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with /skill-name.
Create a skill by adding a directory with a SKILL.md to .claude/skills/:
---
name: api-conventions
description: REST API design conventions for our services
---
# API Conventions
- Use kebab-case for URL paths
- Use camelCase for JSON properties
- Always include pagination for list endpoints
- Version APIs in the URL path (/v1/, /v2/)Skills can also define repeatable workflows you invoke directly:
---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Analyze and fix the GitHub issue: $ARGUMENTS.
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PRRun /fix-issue 1234 to invoke it. Use disable-model-invocation: true for workflows with side effects that you want to trigger manually.
Create custom subagents
Tip: Define specialized assistants in .claude/agents/ that Claude can delegate to for isolated tasks.Subagents run in their own context with their own set of allowed tools. They're useful for tasks that read many files or need specialized focus without cluttering your main conversation.
---
name: security-reviewer
description: Reviews code for security vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling
Provide specific line references and suggested fixes.Tell Claude to use subagents explicitly: "Use a subagent to review this code for security issues."
Install plugins
Tip: Run /plugin to browse the marketplace. Plugins add skills, tools, and integrations without configuration.Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic.
For guidance on choosing between skills, subagents, hooks, and MCP, see Extend Claude Code.
***
Communicate effectively
The way you communicate with Claude Code significantly impacts the quality of results.
Ask codebase questions
Tip: Ask Claude questions you'd ask a senior engineer.
When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:
- How does logging work?
- How do I make a new API endpoint?
- What does
async move { ... }do on line 134 offoo.rs? - What edge cases does
CustomerOnboardingFlowImplhandle? - Why does this code call
foo()instead ofbar()on line 333?
Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.
Let Claude interview you
Tip: For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the AskUserQuestion tool.Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.
I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.
Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.
Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.
***
Manage your session
Conversations are persistent and reversible. Use this to your advantage!
Course-correct early and often
Tip: Correct Claude as soon as you notice it going off track.
The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.
- `Esc`: Stop Claude mid-action with the
Esckey. Context is preserved, so you can redirect. - `Esc + Esc` or `/rewind`: Press
Esctwice or run/rewindto open the rewind menu and restore previous conversation and code state. - `"Undo that"`: Have Claude revert its changes.
- `/clear`: Reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.
If you've corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run /clear and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.
Manage context aggressively
Tip: Run /clear between unrelated tasks to reset context.Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.
During long sessions, Claude's context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.
- Use
/clearfrequently between tasks to reset the context window entirely - When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions
- For more control, run
/compact <instructions>, like/compact Focus on the API changes - Customize compaction behavior in CLAUDE.md with instructions like
"When compacting, always preserve the full list of modified files and any test commands"to ensure critical context survives summarization
Use subagents for investigation
Tip: Delegate research with "use subagents to investigate X". They explore in a separate context, keeping your main conversation clean for implementation.Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:
Use subagents to investigate how our authentication system handles token
refresh, and whether we have any existing OAuth utilities I should reuse.The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.
You can also use subagents for verification after Claude implements something:
use a subagent to review this code for edge casesRewind with checkpoints
Tip: Every action Claude makes creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.
Claude automatically checkpoints before changes. Double-tap Escape or run /rewind to open the checkpoint menu. You can restore conversation only (keep code changes), restore code only (keep conversation), or restore both.
Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn't work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.
Warning: Checkpoints only track changes made by Claude, not external processes. This isn't a replacement for git.
Resume conversations
Tip: Runclaude --continueto pick up where you left off, or--resumeto choose from recent sessions.
Claude Code saves conversations locally. When a task spans multiple sessions (you start a feature, get interrupted, come back the next day) you don't have to re-explain the context:
claude --continue # Resume the most recent conversation
claude --resume # Select from recent conversationsUse /rename to give sessions descriptive names ("oauth-migration", "debugging-memory-leak") so you can find them later. Treat sessions like branches. Different workstreams can have separate, persistent contexts.
***
Automate and scale
Once you're effective with one Claude, multiply your output with parallel sessions, headless mode, and fan-out patterns.
Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.
Run headless mode
Tip: Useclaude -p "prompt"in CI, pre-commit hooks, or scripts. Add--output-format stream-jsonfor streaming JSON output.
With claude -p "your prompt", you can run Claude headlessly, without an interactive session. Headless mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats (plain text, JSON, streaming JSON) let you parse results programmatically.
# One-off queries
claude -p "Explain what this project does"
# Structured output for scripts
claude -p "List all API endpoints" --output-format json
# Streaming for real-time processing
claude -p "Analyze this log file" --output-format stream-jsonRun multiple Claude sessions
Tip: Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.
There are two main ways to run parallel sessions:
- Claude Desktop: Manage multiple local sessions visually. Each session gets its own isolated worktree.
- Claude Code on the web: Run on Anthropic's secure cloud infrastructure in isolated VMs.
Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won't be biased toward code it just wrote.
For example, use a Writer/Reviewer pattern:
| Session A (Writer) | Session B (Reviewer) |
|---|---|
Implement a rate limiter for our API endpoints | |
Review the rate limiter implementation in @src/middleware/rateLimiter.ts. Look for edge cases, race conditions, and consistency with our existing middleware patterns. | |
Here's the review feedback: [Session B output]. Address these issues. |
You can do something similar with tests: have one Claude write tests, then another write code to pass them.
Fan out across files
Tip: Loop through tasks callingclaude -pfor each. Use--allowedToolsto scope permissions for batch operations.
For large migrations or analyses, you can distribute work across many parallel Claude invocations:
Step 1: Generate a task list Have Claude list all files that need migrating (e.g., list all 2,000 Python files that need migrating)
Step 2: Write a script to loop through the list
for file in $(cat files.txt); do
claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
--allowedTools "Edit,Bash(git commit:*)"
doneStep 3: Test on a few files, then run at scale Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The --allowedTools flag restricts what Claude can do, which matters when you're running unattended.
You can also integrate Claude into existing data/processing pipelines:
claude -p "<your prompt>" --output-format json | your_commandUse --verbose for debugging during development, and turn it off in production.
Safe Autonomous Mode
Use claude --dangerously-skip-permissions to bypass all permission checks and let Claude work uninterrupted. This works well for workflows like fixing lint errors or generating boilerplate code.
Warning: Letting Claude run arbitrary commands is risky and can result in data loss, system corruption, or data exfiltration (e.g., via prompt injection attacks). To minimize these risks, use--dangerously-skip-permissionsin a container without internet access. With sandboxing enabled (/sandbox), you get similar autonomy with better security. Sandbox defines upfront boundaries rather than bypassing all checks.
***
Avoid common failure patterns
These are common mistakes. Recognizing them early saves time:
- The kitchen sink session. You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.
Fix: /clear between unrelated tasks.- Correcting over and over. Claude does something wrong, you correct it, it's still wrong, you correct again. Context is polluted with failed approaches.
Fix: After two failed corrections, /clear and write a better initial prompt incorporating what you learned.- The over-specified CLAUDE.md. If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.
Fix: Ruthlessly prune. If Claude already does something correctly without the instruction, delete it or convert it to a hook.
- The trust-then-verify gap. Claude produces a plausible-looking implementation that doesn't handle edge cases.
Fix: Always provide verification (tests, scripts, screenshots). If you can't verify it, don't ship it.
- The infinite exploration. You ask Claude to "investigate" something without scoping it. Claude reads hundreds of files, filling the context.
Fix: Scope investigations narrowly or use subagents so the exploration doesn't consume your main context.
***
Develop your intuition
The patterns in this guide aren't set in stone. They're starting points that work well in general, but might not be optimal for every situation.
Sometimes you should let context accumulate because you're deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.
Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?
Over time, you'll develop intuition that no guide can capture. You'll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.
Related resources
- How Claude Code works - Understand the agentic loop, tools, and context management
- Extend Claude Code - Choose between skills, hooks, MCP, subagents, and plugins
- Common workflows - Step-by-step recipes for debugging, testing, PRs, and more
- CLAUDE.md - Store project conventions and persistent context
---
To find navigation and other pages in this documentation, fetch the llms.txt file at: https://code.claude.com/docs/llms.txt
Related skills
How it compares
Use when designing skills; use domain execution skills when the task is building product code rather than assistant contracts.
FAQ
What problems does Best Practices address for agent skills?
Best Practices from skillcreatorai/ai-agent-skills focuses on prompt structure, tool-use guardrails, and progressive disclosure so assistants invoke the right tools and stay within task boundaries across repositories.
When should a developer invoke Best Practices?
Invoke Best Practices while drafting a new SKILL.md, refining triggers, or debugging inconsistent agent behavior. The skill targets skill authoring mechanics rather than shipping application features.