claude-best-practice
Health Warn
- No license Γ’β¬β Repository has no license file
- Description Γ’β¬β Repository has a description
- Active repo Γ’β¬β Last push 0 days ago
- Low visibility Γ’β¬β Only 5 GitHub stars
Code Fail
- rm -rf Γ’β¬β Recursive force deletion command in .claude/settings.json
Permissions Pass
- Permissions Γ’β¬β No dangerous permissions requested
No AI report is available for this listing yet.
π€ Claude Code β Best Practices & Advanced Patterns The most comprehensive, production-ready guide to mastering Claude Code From vibe coding β agentic engineering β autonomous AI development teams
π€ Claude Code β Best Practices & Advanced Patterns
The most comprehensive, production-ready guide to mastering Claude Code
From vibe coding β agentic engineering β autonomous AI development teams
Built for engineers who treat Claude Code as infrastructure, not a toy.
π Table of Contents
- Why This Guide Exists
- What is Claude Code?
- Architecture Overview
- Quick Start
- Core Concepts
- Advanced Patterns
- Development Workflows
- Orchestration Patterns
- Tips & Tricks (190+)
- CLAUDE.md Mastery
- Model Selection Strategy
- Session Management
- Debugging Claude Code
- Performance Optimization
- Security Best Practices
- Team & Enterprise Usage
- Directory Structure
- Contributing
π― Why This Guide Exists
Most Claude Code guides cover the basics. This one doesn't stop there.
After thousands of hours of real-world usage across solo projects, startup teams, and enterprise codebases, this repository captures:
- What actually works β not what looks good in demos
- Anti-patterns to avoid β hard-won lessons from production failures
- Advanced architectural patterns β agent teams, automated pipelines, cross-model routing
- Copy-paste ready configs β
.claude/settings.json, hooks, commands, skills - Full development methodologies β end-to-end workflows from idea to deployment
Whether you're a solo developer building side projects or an engineering team shipping at scale, this guide gives you the mental models and practical tools to unlock Claude Code's full potential.
π§ What is Claude Code?
Claude Code is Anthropic's official AI-powered CLI and IDE extension that brings Claude directly into your development workflow. Unlike chat-based AI tools, Claude Code:
- Reads and edits your actual files β not copy-pasted snippets
- Runs shell commands β tests, builds, linters, git operations
- Manages multi-file changes β across entire codebases
- Supports agentic workflows β autonomous multi-step task execution
- Integrates with external tools β via MCP (Model Context Protocol)
- Scales to teams β with shared configs, hooks, and agent definitions
Claude Code vs Other AI Tools
| Feature | Claude Code | GitHub Copilot | Cursor | ChatGPT |
|---|---|---|---|---|
| Full codebase access | β | β | β | β |
| Shell command execution | β | β | Limited | β |
| Agentic task execution | β | β | Limited | β |
| Subagent orchestration | β | β | β | β |
| MCP tool integrations | β | β | β | β |
| Custom hooks | β | β | β | β |
| CLAUDE.md project context | β | β | β | β |
| Cross-model routing | β | β | β | β |
| Scheduled/automated tasks | β | β | β | β |
ποΈ Architecture Overview
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLAUDE CODE SYSTEM β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β USER INPUT β
β β β
β βΌ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β CLAUDE ORCHESTRATOR β β
β β β’ Reads CLAUDE.md (project context) β β
β β β’ Applies settings.json (permissions/model/style) β β
β β β’ Fires pre-tool hooks β β
β β β’ Routes to subagents / invokes tools β β
β ββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββΌβββββββββββββββββββββββββββββββββββββ β
β βΌ βΌ βΌ βΌ β
β ββββββββ ββββββββ ββββββββββ ββββββββββ β
β β Read β β Edit β β Bash β β MCP β β
β β File β β File β β Shell β β Tools β β
β ββββββββ ββββββββ ββββββββββ ββββββββββ β
β β
β SUBAGENTS (isolated context windows) β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β Explore β β Planner β β Coder β β Reviewer β β
β β Agent β β Agent β β Agent β β Agent β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β
β HOOKS (event-driven automation) β
β PreToolUse β PostToolUse β Stop β SubagentStop β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Quick Start
Installation
# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code
# Or use the VS Code / JetBrains extension
# Or access via claude.ai/code
Your First Session
# Navigate to your project
cd my-project
# Start Claude Code
claude
# Or start with a specific task
claude "explain the architecture of this codebase"
# Enable plan mode for complex tasks
claude --plan "refactor the authentication system"
Essential First Setup
# Initialize CLAUDE.md for your project
claude /init
# Check settings
claude /config
# View available commands
claude /help
π Core Concepts
1. Context Management
Context is the most critical resource in Claude Code. Mismanaging it is the #1 cause of degraded output quality.
The Context Budget
Claude Code operates within a token context window. Think of it like RAM β finite, precious, and easy to exhaust.
Context Window
βββ System prompt (CLAUDE.md + settings) ~5-10%
βββ Conversation history grows with each turn
βββ File contents (read files) can be large
βββ Tool outputs (bash, search results) often very large
βββ Available for response shrinks as above grows
Context Health Rules
Rule 1: The 30% Rule
Keep your context utilization below 30-40%. Above this threshold, Claude starts "forgetting" earlier context and output quality degrades.
0% ββββββββββββββββββββββ 30% ββββββββββββ 60% ββββ 80% ββ 100%
IDEAL ZONE WARNING DANGER CRITICAL
Rule 2: Rewind Don't Correct
When Claude makes a mistake mid-task, don't keep piling on corrections. The corrections consume context AND confuse the model. Instead:
- Press
ESCto interrupt - Use
/rewindto go back to the last clean state - Re-issue the instruction with more specificity
Rule 3: Fresh Sessions for Fresh Tasks
# Wrong: Continuing from a long session for an unrelated task
# (you're now paying the cost of all that prior context)
# Right: New task = new session
claude /clear
claude "new task here"
# Or use /compact to summarize and continue
claude /compact "focus on the auth refactor"
Rule 4: Strategic /compact
Use /compact with a specific hint so Claude summarizes what matters:
# Bad (no hint β Claude guesses what to keep)
/compact
# Good (Claude knows what to preserve)
/compact "we're mid-way through the database migration, keep all schema decisions"
Context-Aware File Reading
Don't read files you don't need. Be surgical:
# Instead of asking Claude to read the whole codebase, guide it:
"Read only src/auth/middleware.ts and tell me what token validation logic exists"
# Not:
"Read the codebase and tell me about auth"
2. Plan Mode
Plan Mode is Claude Code's most powerful feature for complex, multi-step tasks. It separates thinking from acting, preventing premature execution.
When to Use Plan Mode
| Task Type | Plan Mode? |
|---|---|
| Simple bug fix (1-2 files) | Optional |
| Feature spanning 3+ files | Yes |
| Refactoring/architecture changes | Yes |
| Database migrations | Yes, always |
| Security-sensitive changes | Yes, always |
| Anything you can't easily undo | Yes |
How to Enter Plan Mode
# Via CLI flag
claude --plan "migrate the users table to add OAuth columns"
# Via slash command mid-session
/plan
# Via keyboard shortcut
Shift + Tab # toggle plan/execute mode
Effective Plan Mode Usage
GOOD PLAN WORKFLOW:
1. Enter plan mode
2. State the goal + constraints
3. Review the plan Claude proposes
4. Ask questions / push back on decisions
5. Refine until you're confident
6. Exit plan mode β execute
BAD PLAN WORKFLOW:
1. Skip plan mode
2. Ask Claude to "just do it"
3. Get halfway through, realize the approach was wrong
4. Spend 3x as long cleaning up
Plan Mode Prompting
# Template for complex tasks
I need to [GOAL].
Constraints:
- [constraint 1]
- [constraint 2]
Do NOT touch:
- [file/system to leave alone]
Before executing, give me a step-by-step plan including:
1. Which files will be modified
2. What tests need to run
3. Any risks or irreversible steps
3. Subagents
Subagents are isolated Claude instances with their own context windows. They're the key to handling complex tasks without exhausting your main context.
Why Subagents?
WITHOUT SUBAGENTS:
Main Context: [task 1 history] [task 2 history] [task 3 history]
βββββββββββββββββββββββββββββββββββββββββββββββββ
Context fills up β quality degrades
WITH SUBAGENTS:
Main Context: [orchestration logic only] β stays clean
Subagent 1: [task 1 isolated]
Subagent 2: [task 2 isolated]
Subagent 3: [task 3 isolated]
Each starts fresh β quality stays high
Spawning Subagents
// In a slash command or skill:
Agent({
description: "Analyze authentication vulnerabilities",
subagent_type: "general-purpose",
prompt: `
Review src/auth/ for security vulnerabilities.
Check for: SQL injection, JWT mishandling, session fixation.
Report findings with file paths and line numbers.
Do NOT modify any files β research only.
`
})
Subagent Types
| Type | Best For |
|---|---|
general-purpose |
Research, analysis, multi-step tasks |
Explore |
Fast read-only code search (keyword/pattern lookup) |
Plan |
Architecture design, implementation planning |
claude |
Catch-all for complex tasks needing full capabilities |
Subagent Patterns
Pattern 1: Research β Execute
Subagent 1: Research the codebase, find all auth-related files
Main: Review findings, decide on approach
Subagent 2: Execute the changes based on the research
Pattern 2: Parallel Workers
Subagents 1-3 (parallel): Each handles one module
Main: Collect results, integrate
Pattern 3: Specialist Chain
Architect subagent β designs the solution
Coder subagent β implements it
Reviewer subagent β checks the implementation
Tester subagent β writes and runs tests
Subagent Communication Best Practices
# Good subagent prompt structure:
## Context
[What the overall task is]
## Your Specific Job
[Exactly what THIS subagent should do]
## What NOT To Do
[Boundaries β files to leave alone, operations to skip]
## Output Format
[Exactly what to return so the orchestrator can use it]
4. Commands
Commands are slash commands (/command-name) that trigger predefined workflows. They're the equivalent of keyboard macros for your development process.
Creating a Command
Commands live in .claude/commands/. Each .md file becomes a /command-name.
<!-- .claude/commands/ship.md -->
# Ship Feature
Prepare and ship the current feature branch.
## Steps
1. Run tests: `npm test`
2. Run linter: `npm run lint`
3. Check for TODO/FIXME comments
4. Generate a changelog entry
5. Create a PR with description
Command Categories
Development Commands
/plan β enter structured planning mode
/ship β run checks and create PR
/review β self-review before submitting
/debug β systematic debugging workflow
/refactor β safe refactoring checklist
Analysis Commands
/audit β security audit of changed files
/perf β performance analysis
/complexity β flag overly complex functions
/dead-code β find unused code
Documentation Commands
/docs β generate documentation
/readme β update README
/changelog β generate changelog from git log
Parameterized Commands
<!-- .claude/commands/test-feature.md -->
# Test Feature: $ARGUMENTS
Run comprehensive tests for: $ARGUMENTS
1. Find all test files related to "$ARGUMENTS"
2. Run them with coverage
3. Report any failures with suggested fixes
# Usage:
/test-feature authentication
/test-feature payment-processing
Dynamic Commands with Shell Output
<!-- .claude/commands/context-check.md -->
Current git status:
!`git status`
Recent changes:
!`git diff --stat HEAD~3`
Now review these changes and suggest what to test next.
The ! prefix runs the shell command and injects its output into the prompt.
5. Skills
Skills are reusable, composable task templates with progressive disclosure. They're more powerful than commands because they support structured context loading.
Skill vs Command
| Command | Skill | |
|---|---|---|
| Trigger | /command-name |
Auto-detected by description |
| Complexity | Simple workflows | Complex, multi-file patterns |
| Context | Inline only | Can reference external docs |
| Composition | Limited | Highly composable |
| Discovery | Manual | AI-matched to task |
Skill Structure
.claude/skills/
βββ deploy/
βββ SKILL.md # Main skill definition
βββ references/
βββ rollback.md # Referenced if rollback needed
βββ monitoring.md # Referenced if monitoring needed
βββ checklist.md # Referenced for verification
<!-- .claude/skills/deploy/SKILL.md -->
---
name: production-deploy
description: Use when deploying to production, releasing a version, or shipping to users. Handles pre-deploy checks, deployment, and post-deploy verification.
---
# Production Deployment Skill
## Pre-Deploy Checklist
- [ ] All tests passing: `npm test`
- [ ] No linting errors: `npm run lint`
- [ ] Environment variables verified
- [ ] Database migrations ready
## Deploy
```bash
npm run build
npm run deploy:prod
Post-Deploy Verification
See @references/monitoring.md for health check procedures.
If deploy fails, see @references/rollback.md.
#### Writing Effective Skill Descriptions
The `description:` field is critical β it's how Claude decides when to invoke the skill automatically.
```markdown
# BAD β too vague
description: Helps with deployment
# BAD β describes what it does, not when to use it
description: Runs build, tests, and deploys to production
# GOOD β describes triggering conditions
description: Use when the user wants to deploy, release, ship to production,
push a new version, or go live. Also triggers for rollback
requests and deployment troubleshooting.
Progressive Disclosure Pattern
Keep the main SKILL.md concise. Use @references/ for depth:
# Main skill β stays under 50 lines
Core workflow here.
For advanced rollback procedures: @references/rollback.md
For monitoring setup: @references/monitoring.md
For multi-region deploys: @references/multi-region.md
Claude only reads referenced files when actually needed, preserving context.
6. Hooks
Hooks are shell commands that Claude Code executes automatically at specific lifecycle events. They're the most powerful way to enforce consistent behavior.
Hook Events
| Event | When It Fires | Common Uses |
|---|---|---|
PreToolUse |
Before any tool call | Validation, logging, rate limiting |
PostToolUse |
After any tool call | Audit logging, notifications |
Stop |
When Claude finishes a turn | Summaries, notifications, cleanup |
SubagentStop |
When a subagent finishes | Collect results, log output |
Notification |
On system notifications | Alert routing |
Hook Configuration
// .claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo '[HOOK] Bash command: ' && cat"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/post-edit.sh"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/session-summary.sh"
}
]
}
]
}
}
Real Hook Examples
Auto-run tests after file edits:
#!/bin/bash
# ~/.claude/hooks/post-edit.sh
# Runs relevant tests after Claude edits a file
FILE=$(echo "$CLAUDE_TOOL_INPUT" | jq -r '.file_path // empty')
if [[ "$FILE" == *.ts || "$FILE" == *.tsx ]]; then
echo "Running tests for $FILE..."
npx jest --findRelatedTests "$FILE" --passWithNoTests 2>&1 | tail -20
fi
Block dangerous git operations:
#!/bin/bash
# ~/.claude/hooks/pre-bash.sh
COMMAND=$(echo "$CLAUDE_TOOL_INPUT" | jq -r '.command // empty')
# Block force push to main
if echo "$COMMAND" | grep -q "git push.*--force.*main\|git push.*main.*--force"; then
echo "BLOCKED: Force push to main is not allowed"
exit 2 # exit 2 = block the tool call
fi
# Block rm -rf
if echo "$COMMAND" | grep -qE "rm\s+-rf\s+/"; then
echo "BLOCKED: Dangerous rm -rf command"
exit 2
fi
Slack notification on task completion:
#!/bin/bash
# ~/.claude/hooks/notify-slack.sh
WEBHOOK_URL="$SLACK_WEBHOOK_URL"
MESSAGE="Claude Code task completed in $(pwd)"
curl -s -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" \
"$WEBHOOK_URL"
Auto-format after edit:
#!/bin/bash
# ~/.claude/hooks/post-edit-format.sh
FILE=$(echo "$CLAUDE_TOOL_INPUT" | jq -r '.file_path // empty')
case "$FILE" in
*.ts|*.tsx|*.js|*.jsx)
npx prettier --write "$FILE" 2>/dev/null
;;
*.py)
black "$FILE" 2>/dev/null
;;
*.go)
gofmt -w "$FILE" 2>/dev/null
;;
esac
Hook Exit Codes
exit 0 β Success, continue normally
exit 1 β Warning/error, but continue
exit 2 β BLOCK the tool call entirely (PreToolUse only)
7. MCP Servers
MCP (Model Context Protocol) servers extend Claude Code with external tool capabilities β databases, APIs, cloud services, and more.
Built-in MCP Integrations
// .claude/settings.json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "${DATABASE_URL}"]
},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
}
}
}
Popular MCP Servers
| Server | What It Enables |
|---|---|
@mcp/server-github |
PR/issue management, code search |
@mcp/server-postgres |
Direct database queries |
@mcp/server-filesystem |
Expanded file system access |
@mcp/server-brave-search |
Web search during tasks |
@mcp/server-slack |
Send Slack messages from Claude |
@mcp/server-linear |
Ticket management |
@mcp/server-sentry |
Error monitoring integration |
@mcp/server-datadog |
Metrics and logs |
Building a Custom MCP Server
// custom-mcp-server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "my-internal-tools",
version: "1.0.0"
}, {
capabilities: { tools: {} }
});
// Register a tool
server.setRequestHandler("tools/list", async () => ({
tools: [{
name: "get_deployment_status",
description: "Check deployment status for a service",
inputSchema: {
type: "object",
properties: {
service: { type: "string", description: "Service name" }
},
required: ["service"]
}
}]
}));
server.setRequestHandler("tools/call", async (request) => {
if (request.params.name === "get_deployment_status") {
const { service } = request.params.arguments;
// Your internal API call here
const status = await getDeploymentStatus(service);
return { content: [{ type: "text", text: JSON.stringify(status) }] };
}
});
const transport = new StdioServerTransport();
await server.connect(transport);
8. Memory System
Claude Code's memory system lets it retain information across sessions, building up project-specific knowledge over time.
Memory Types
| Type | What to Store | Lifespan |
|---|---|---|
user |
Developer preferences, expertise level | Long-term |
feedback |
What worked/didn't, style preferences | Long-term |
project |
Goals, deadlines, architecture decisions | Medium-term |
reference |
External system locations, credentials | Long-term |
Memory File Structure
~/.claude/projects/<project-slug>/memory/
βββ MEMORY.md β Index (always loaded)
βββ user_profile.md β Who the developer is
βββ feedback_*.md β Style and approach preferences
βββ project_*.md β Current project context
βββ reference_*.md β Where things live
Memory Best Practices
# Good memory content (non-obvious facts)
- user prefers explicit error messages over silent failures
- this project uses pessimistic locking for the inventory system
- the CI pipeline takes 12 minutes β don't wait for it before continuing
# Bad memory content (obvious from code)
- project uses React (visible in package.json)
- uses TypeScript (visible in tsconfig.json)
- has a users table (visible in schema)
Triggering Memory Saves
"Remember that I prefer Jest over Vitest for this project"
"Save this: the payment service uses idempotency keys, always check before retrying"
"Note that the staging DB has stale data after 3pm β refresh with dump script"
9. Settings & Permissions
The settings.json file is the control plane for Claude Code's behavior. Master it.
Settings Hierarchy
~/.claude/settings.json β Global (all projects)
~/.claude/settings.local.json β Global local overrides
.claude/settings.json β Project (committed to git)
.claude/settings.local.json β Project local (gitignored)
Later files override earlier ones. Use project settings for team-shared config, local settings for personal preferences.
Full Settings Reference
{
// Model selection
"model": "claude-opus-4-7", // for planning
// or
"model": "claude-sonnet-4-6", // for coding (faster/cheaper)
// Output style
"outputStyle": "explanatory", // verbose explanations
// or
"outputStyle": "concise", // brief responses
// Permission mode
"permissionMode": "auto", // no prompts (careful!)
// or
"permissionMode": "default", // prompt for risky ops
// or
"permissionMode": "strict", // prompt for everything
// Allowed tools (bypass permission prompts)
"allowedTools": [
"Read",
"Bash(git status)",
"Bash(git diff*)",
"Bash(npm test*)",
"Bash(npm run lint*)"
],
// Blocked tools
"blockedTools": [
"Bash(rm -rf*)",
"Bash(git push --force*)"
],
// Environment variables passed to Claude
"env": {
"NODE_ENV": "development"
},
// MCP server configurations
"mcpServers": { ... },
// Hooks
"hooks": { ... }
}
Smart Permission Strategies
// For read-only analysis sessions
{
"allowedTools": ["Read", "Bash(find*)", "Bash(grep*)", "Bash(cat*)", "Bash(ls*)"],
"blockedTools": ["Edit", "Write", "Bash(git commit*)", "Bash(npm*)", "Bash(rm*)"]
}
// For test-driven development
{
"allowedTools": [
"Read", "Edit", "Write",
"Bash(npm test*)", "Bash(npx jest*)", "Bash(npm run*)"
]
}
// For deployment scripts
{
"allowedTools": ["Read", "Bash(*)"],
"blockedTools": ["Bash(rm -rf*)", "Bash(git push --force*)"]
}
β‘ Advanced Patterns
Multi-Agent Teams
Run multiple Claude Code instances in parallel using tmux + git worktrees for maximum throughput.
# Setup: create worktrees for parallel development
git worktree add ../feature-auth -b feature/auth
git worktree add ../feature-payments -b feature/payments
git worktree add ../feature-notifications -b feature/notifications
# Launch agents in parallel tmux panes
tmux new-session -d -s claude-team
tmux split-window -h
tmux split-window -v
# Pane 1: Auth agent
tmux send-keys -t 0 "cd ../feature-auth && claude 'implement OAuth2 login'" Enter
# Pane 2: Payments agent
tmux send-keys -t 1 "cd ../feature-payments && claude 'implement Stripe checkout'" Enter
# Pane 3: Notifications agent
tmux send-keys -t 2 "cd ../feature-notifications && claude 'implement email notifications'" Enter
For detailed patterns, see advanced/multi-agent-teams.md.
Cross-Model Routing
Route different tasks to the right model for cost/quality optimization.
// .claude/settings.json β model per task type
{
"profiles": {
"planning": {
"model": "claude-opus-4-7",
"outputStyle": "explanatory"
},
"coding": {
"model": "claude-sonnet-4-6",
"outputStyle": "concise"
},
"review": {
"model": "claude-opus-4-7",
"outputStyle": "explanatory"
}
}
}
Use /model claude-opus-4-7 when you need deep reasoning, /model claude-sonnet-4-6 for fast coding tasks.
For routing to external models (DeepSeek, Gemini, Ollama), see advanced/cross-model-routing.md.
Automated Pipelines
Use Claude Code's scheduling capabilities to create automated development workflows.
# Daily code quality check
claude schedule "every day at 9am: run /audit and post results to #eng-alerts Slack channel"
# Weekly dependency updates
claude schedule "every monday: check for outdated npm packages and create a PR with safe updates"
# Pre-commit pipeline
# In .git/hooks/pre-commit:
claude --non-interactive "review staged changes for security vulnerabilities, output PASS or FAIL"
For full pipeline patterns, see advanced/automated-pipelines.md.
Security Patterns
Claude Code has broad filesystem and shell access. Lock it down properly.
// Principle of least privilege
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/security-check.sh"
}]
}]
},
"blockedTools": [
"Bash(curl * | bash*)",
"Bash(wget * | sh*)",
"Bash(eval*)",
"Bash(rm -rf /*)"
]
}
For full security hardening guide, see advanced/security-patterns.md.
Enterprise Patterns
Scaling Claude Code across engineering teams requires governance and standardization.
enterprise-setup/
βββ .claude/
β βββ settings.json # Team-wide permissions
β βββ commands/ # Shared slash commands
β βββ skills/ # Shared skill library
βββ onboarding/
β βββ CLAUDE.md.template # New project template
β βββ setup.sh # Auto-setup script
βββ governance/
βββ approved-mcps.json # Vetted MCP servers
βββ security-policy.json # Security constraints
For full enterprise deployment guide, see advanced/enterprise-patterns.md.
π Development Workflows
Boris Cherny Creator Workflow
Boris Cherny (Claude Code creator at Anthropic) runs 5 local + 5β10 cloud sessions simultaneously using git worktrees. His single most impactful tip:
"Enable verification loops. Testing improves final output quality by 2β3x."
See development-workflows/boris-creator-workflow.md for his full workflow including model selection, voice coding, /loop automation, and the --bare startup flag.
Verification Loops β The #1 Quality Multiplier
Set up PostToolUse hooks so tests run automatically after every file edit. Claude sees the results and self-corrects before you see it.
// .claude/settings.json
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{"type": "command", "command": ".claude/hooks/verification-loop.sh"}]
}]
}
}
See development-workflows/verification-loop.md for the full implementation.
Real-World Team Patterns
Production workflows from teams that have shipped with Claude Code:
| Team/Workflow | Stars | Core Pattern |
|---|---|---|
| Superpowers | 188kβ | Brainstorm β Worktree β Plan β Subagent Impl β Review β Merge |
| BMAD Method | Community | Brief β PRD β Architecture β Epics β Sprint β TDD β Retro |
| gstack | 95kβ | 14-stage: Spec β Plan β Code β Self-Review β QA β Security β Deploy β Metrics |
| Spec Kit | 97kβ | Constitution β Specify β Clarify β Plan β Tasks β Implement β Verify-Spec |
| Debugging War Room | Field-tested | Incident β Triage β Investigate β Fix β Verify β Post-mortem |
Full details: development-workflows/real-world-teams.md
Babysit PRs β Automated PR Management
# Run every 5 minutes: check PRs, fix CI failures, address review comments, merge when ready
/loop 5m /babysit-prs
See development-workflows/babysit-prs.md for the full command definition and safety guards.
Batch Migrations
Distribute large code migrations (50-200+ files) across parallel worktree agents:
# Split 100 files into 5 batches, run 5 agents in parallel
./scripts/batch-migrate.sh "convert from CommonJS require() to ESM import syntax"
See development-workflows/batch-migration.md for the full script.
The RIPE Workflow (Research β Iterate β Polish β Execute)
Best for features with unknown territory.
Phase 1: RESEARCH
ββ Subagent: explore codebase, find relevant patterns
ββ Ask questions, gather requirements
Phase 2: ITERATE (Plan Mode)
ββ Draft implementation plan
ββ Review with stakeholders
ββ Refine until confident
Phase 3: POLISH
ββ Implement with frequent test runs
ββ Review diffs at each step
Phase 4: EXECUTE
ββ Run full test suite
ββ Create PR with full context
ββ Deploy
See development-workflows/ripe-workflow.md for full details.
The TDD Spiral
/tdd <feature> triggers:
1. Write failing test
2. Implement minimum to pass
3. Refactor
4. Repeat until feature complete
5. Final review
6. Ship
See development-workflows/tdd-spiral.md.
The Spec-First Method
1. /spec "describe the feature in plain English"
2. Claude generates: user stories, acceptance criteria, edge cases
3. Review and approve spec
4. /implement-spec β Claude codes to the spec
5. /verify-spec β Claude checks implementation against spec
See development-workflows/spec-first.md.
The Worktree Sprint
For teams shipping features in parallel:
# Sprint setup
git worktree add ../sprint-auth -b sprint/auth
git worktree add ../sprint-api -b sprint/api
git worktree add ../sprint-frontend -b sprint/frontend
# Assign agents
claude -p ../sprint-auth /sprint "auth feature"
claude -p ../sprint-api /sprint "API endpoints"
claude -p ../sprint-frontend /sprint "frontend components"
# Merge sprint
git merge sprint/auth sprint/api sprint/frontend
See development-workflows/worktree-sprint.md.
π Orchestration Patterns
Research β Plan β Execute β Review β Ship
The gold-standard 5-phase workflow for any significant feature.
ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ
β RESEARCH βββββΆβ PLAN βββββΆβ EXECUTE βββββΆβ REVIEW βββββΆβ SHIP β
ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ
Explore Plan mode Implement Self-review PR + deploy
codebase + approval + tests + security + notify
Command β Agent β Skill Flow
User types: /feature "add dark mode"
β
βΌ
Command: feature.md
Reads context, spawns agents
β
ββββββββ΄βββββββ
βΌ βΌ
Research Agent Planning Agent
(explores repo) (designs approach)
β β
ββββββββ¬βββββββ
βΌ
Coding Agent
(implements)
β
βΌ
Review Agent
(verifies)
β
βΌ
Ship Command
(PR + deploy)
See orchestration-workflow/ for all patterns.
π§ From the Creators β Boris & Thariq Tips
Boris Cherny (Claude Code creator) and Thariq (Anthropic Claude Code team) shared 70+ specific, production-tested tips. The top 10 most impactful:
- Verification loops β auto-run tests after every edit (Boris: "2β3x quality improvement")
- Rewind over correct β jump back before the mistake, don't pile corrections (Thariq)
- CLAUDE.md = living document β update it after every mistake (Boris)
- Plan mode first β always, for non-trivial tasks (Boris)
- Session-per-phase β research / planning / execution in separate sessions (Thariq)
- Commit slash commands β encode any repeated workflow (Boris)
- Subagents for research β keep main context clean (Thariq)
- Model for the task β Opus for decisions, Sonnet for grinding (Boris)
- Skill Gotchas section β encode every real failure into the skill (Thariq)
- Compact with hints β
/compact "keep: X, drop: Y"not just/compact(Thariq)
Context rot β Thariq's key insight: quality degrades around 300β400k tokens even before the window is full. "Just because you haven't run out of context doesn't mean you shouldn't start a new session."
Full 70-tip list: tips/boris-and-thariq-tips.md
Thariq's 9 skill types framework: best-practice/11-thariq-skill-types.md
Context rot prevention guide: best-practice/12-context-rot.md
π‘ Tips & Tricks (190+)
Prompting
- State the WHY, not just the WHAT β "Refactor this for readability because new engineers are struggling to understand it" beats "Refactor this"
- Give negative constraints β "Don't use any libraries, this needs to be zero-dependency"
- Set the bar explicitly β "This code will be reviewed by a senior engineer, make it production quality"
- Reference existing patterns β "Follow the same pattern as
src/auth/middleware.ts" - Use role priming β "You are a security engineer reviewing this for vulnerabilities"
- Specify output format β "Output a bulleted list of changes, each with file:line reference"
- Batch related questions β Ask everything about a topic in one message instead of follow-ups
- Use numbered lists for multi-step instructions β Claude follows numbered steps more reliably
- Explicitly say what NOT to change β "Don't touch the tests, only modify the implementation"
- Ask for a plan before execution β "Before making any changes, tell me your plan"
Context Management
- Read only what you need β "Read just the function signature, not the whole file"
- Use
/compactbefore switching topics β Compress history when changing focus - Start fresh for unrelated tasks β Don't drag prior context into new problems
- Name your sessions β
/rename sprint-authfor easy/resume - Rewind don't apologize β Hit ESC and rewind instead of asking Claude to undo mistakes
- Monitor context bar β Keep below 40%, watch for yellow/red warnings
- Limit tool outputs β
| head -50after bash commands to avoid context bloat - Summarize long files before editing β "Summarize auth.ts, then tell me what to change"
- Use subagents for research β Keep exploration context isolated
- Clear after major milestones β
/clearbetween logical phases of work
Planning
- Plan at the right granularity β Not too abstract, not too detailed
- Include rollback steps β "How do we undo this if it breaks?"
- List affected files upfront β Know the blast radius before starting
- Identify irreversible steps β Flag database migrations, schema changes
- Break into vertical slices β Ship a thin but complete feature, not horizontal layers
- Review the plan out loud β Read it back in your own words before approving
- Ask "what could go wrong?" β Get Claude to identify failure modes
- Separate design from implementation β Don't let planning and coding mix
- Set checkpoints β "After each step, show me the diff before continuing"
- Plan tests alongside code β Not as an afterthought
Session Management
- Use
/renameimmediately for important sessions /resumeto restore context after a break- Don't exceed 200 messages per session β quality degrades
- Use
/modelto switch mid-session β Opus for hard decisions, Sonnet for grinding - Screenshot terminal state before long operations
- Keep a parallel notepad β Copy key decisions from session to notes
/fastmode for routine tasks β Faster output, same quality for simple work- Break long sessions with
/compactβ Every 50-60 messages - Fresh sessions for separate concerns β Auth work β UI work β infra work
- Use multiple terminal panes β Different sessions for different layers
Debugging
- Share the actual error, not a description β Paste the stack trace
- Include context around the error β What did you change? What were you doing?
- Ask for hypothesis list first β "List 5 possible causes before fixing"
- Binary search with Claude β "What's the simplest thing we could test to narrow this down?"
- Use rubber duck mode β "I'm going to explain my understanding, tell me where I'm wrong"
- Ask for regression tests β "Write a test that would have caught this bug"
- Check assumptions explicitly β "What assumptions is this code making about input?"
- Compare to working version β "Here's the working code and broken code, what changed?"
- Use
/debugcommand for systematic investigation - Ask about edge cases β "What inputs would make this fail?"
Code Quality
- Ask for code review before and after β Get critique, not just implementation
- Request explicit tradeoffs β "What are the pros and cons of this approach?"
- Ask about alternatives β "Show me 3 ways to do this and recommend one"
- Request complexity analysis β "What's the time/space complexity?"
- Check for security issues explicitly β "Are there any injection or auth vulnerabilities?"
- Ask about observability β "What would be hard to debug about this in production?"
- Request idiomatic style β "Is this idiomatic Go/Python/TypeScript?"
- Ask about testability β "How would I write a unit test for this?"
- Check for error handling gaps β "What errors aren't being handled?"
- Ask about scalability β "What breaks when this gets 100x traffic?"
Subagents
- Give subagents complete context β They don't see the main conversation
- Define clear output formats β So orchestrator can parse results
- Set explicit boundaries β "Read-only, do not modify files"
- Parallelize independent work β Research and analysis can run simultaneously
- Keep subagent prompts focused β One job per agent
- Return structured data β JSON output is easier to process than prose
- Use Explore subagent for search β Faster and cheaper than general-purpose
- Chain specialist agents β Architect β Coder β Reviewer β Tester
- Debrief in main context β Synthesize subagent results yourself
- Don't nest subagents deeply β Max 2-3 levels of nesting
Hooks
- Start with logging hooks β Before automation, log what's happening
- Use
exit 2sparingly β Only block when truly necessary - Test hooks independently β Run hook scripts manually before wiring up
- Keep hooks idempotent β Safe to run multiple times
- Use hooks for policy, not logic β Complex logic belongs in commands/skills
- Log hook execution β Hard to debug otherwise
- Rate limit expensive hooks β Add cooldowns to avoid runaway costs
- Scope hooks to project β Use
.claude/settings.jsonnot global settings - Test exit codes β Verify your hook returns the right codes
- Document hook purpose β Future you will thank you
CLAUDE.md
- Keep it under 200 lines β Longer files get ignored
- Put most important rules first β Top of file gets most attention
- Use
<important if="...">tags β Conditional instructions reduce noise - Update it as patterns evolve β Stale CLAUDE.md is worse than none
- Split into rules/ directory β For monorepos with different contexts
- Test instructions work β Ask Claude what rules apply to verify loading
- Prefer imperative style β "Always use TypeScript strict mode" not "TypeScript strict mode is preferred"
- Include architecture decisions β Why things are the way they are
- List banned patterns explicitly β "Never use any-type casts"
- Include test commands β Exact commands to run tests, lint, build
MCP & Integrations
- Start with official MCP servers β Before building custom ones
- Scope MCP permissions carefully β Least privilege principle
- Use environment variables for secrets β Never hardcode in settings.json
- Test MCP servers independently β Before wiring into Claude Code
- Document custom MCP tools β Others won't know what they do
- Version pin MCP packages β Avoid unexpected breaking changes
- Monitor MCP token usage β Some servers can inflate context quickly
- Use MCP for stable integrations β Flaky APIs make bad MCP servers
Advanced
- Use thinking mode for hard problems β Enable extended thinking for architecture decisions
- Combine fast mode + subagents β Fast responses + isolated context = efficient throughput
- Build a personal command library β Invest in reusable commands upfront
- Version control your
.claude/directory β Share improvements with your team - Write skills for your domain β Generic skills are fine, domain-specific are better
- Profile before optimizing β Know what's actually slow before addressing it
- Use UltraReview for critical PRs β Multi-agent review catches more issues
- Scheduled tasks for routine work β Dependency updates, audit checks, reports
- Treat CLAUDE.md as living documentation β Update it when patterns change
- Build a team command playbook β Standard commands everyone uses
- Retrospect on Claude sessions β What prompting patterns worked? Document them.
- Invest in onboarding templates β New team members should be productive day 1
Model Selection
- Opus for architecture decisions β Don't cheap out on design
- Sonnet for implementation grind β Fast and capable for well-defined work
- Haiku for simple lookups β Symbol search, format checks
- Upgrade mid-session when stuck β
/model opuswhen Sonnet is struggling - Factor in cost β Opus is ~5x more expensive than Sonnet per token
- Use fast mode for iterations β Speed matters when you're iterating
- Match model to stakes β Production security review = Opus, test rename = Sonnet
- Don't over-specify the model β Let the task guide you, not habit
Mindset
- You're the architect, Claude is the builder β Own the design decisions
- Invest 10 minutes in context setup β Saves an hour of back-and-forth
- Treat bad output as a prompt problem β Rephrase before giving up
- Document what works β Build a personal playbook
- Pair Claude with your expertise β It's amplification, not replacement
π CLAUDE.md Mastery
CLAUDE.md is the foundation of every good Claude Code setup. Here's a production-ready template:
# Project: [Your Project Name]
## Overview
[2-3 sentences describing what this project does]
## Architecture
- **Frontend**: [tech stack]
- **Backend**: [tech stack]
- **Database**: [type + ORM]
- **Auth**: [approach]
- **Deploy**: [platform]
## Development Setup
```bash
npm install
npm run dev
Testing
npm test # unit tests
npm run test:e2e # end-to-end tests
npm run test:coverage # with coverage
Code Standards
- TypeScript strict mode always
- No
anytypes β useunknownand narrow - All async functions return explicit types
- ESLint + Prettier enforced by CI
Patterns to Follow
- Auth: see
src/auth/middleware.tsfor the pattern - API routes: see
src/api/users.tsfor the pattern - Database queries: see
src/db/users.tsfor the pattern
NEVER
- Never commit secrets or API keys
- Never skip TypeScript types with
// @ts-ignore - Never merge with failing tests
- Never edit migrations after they've been applied
Important Files
src/config.tsβ all configurationsrc/types/index.tsβ global type definitionsprisma/schema.prismaβ database schema
---
## π€ Model Selection Strategy
Task Complexity Γ Risk = Model Choice
LOW RISK HIGH RISK
ββββββββββββββββββ¬βββββββββββββββββ
SIMPLE TASK β Haiku β Sonnet β
ββββββββββββββββββΌβββββββββββββββββ€
COMPLEX TASK β Sonnet β Opus β
ββββββββββββββββββ΄βββββββββββββββββ
Examples:
β’ Find a symbol in code β Haiku
β’ Implement a CRUD endpoint β Sonnet
β’ Design auth architecture β Opus
β’ Write a unit test β Sonnet
β’ Review PR for security issues β Opus
β’ Fix a typo in README β Haiku
---
## π Security Best Practices
### Protecting Secrets
```bash
# .gitignore β always include
.claude/settings.local.json
.env
.env.*
# Use environment variables in settings.json
{
"env": {
"API_KEY": "${MY_API_KEY}" # reads from shell env
}
}
Least Privilege Configuration
// For a frontend-only project
{
"allowedTools": ["Read", "Edit", "Write", "Bash(npm*)"],
"blockedTools": ["Bash(rm*)", "Bash(curl*)", "Bash(wget*)"]
}
Audit Logging Hook
#!/bin/bash
# Log all Claude tool calls to audit file
echo "$(date) TOOL=$CLAUDE_TOOL_NAME INPUT=$(echo $CLAUDE_TOOL_INPUT | jq -c .)" \
>> ~/.claude/audit.log
π₯ Team & Enterprise Usage
Shared Configuration
team-repo/
βββ .claude/
βββ settings.json # committed β shared rules
βββ commands/ # committed β shared workflows
βββ skills/ # committed β shared skills
# Each developer has locally:
.claude/settings.local.json # personal preferences, gitignored
Onboarding Template
#!/bin/bash
# scripts/claude-setup.sh
echo "Setting up Claude Code for this project..."
# Install required MCP servers
npx -y @modelcontextprotocol/server-github > /dev/null 2>&1
npx -y @modelcontextprotocol/server-postgres > /dev/null 2>&1
# Copy hooks
mkdir -p ~/.claude/hooks
cp .claude/hooks-templates/* ~/.claude/hooks/
chmod +x ~/.claude/hooks/*
echo "β Claude Code ready. Run 'claude /help' to get started."
π Directory Structure
claude-best-practice/
βββ README.md β You are here
βββ .claude/
β βββ settings.json β Example project settings
β βββ commands/ β Reusable slash commands
β β βββ plan.md
β β βββ ship.md
β β βββ review.md
β β βββ debug.md
β β βββ audit.md
β β βββ ...
β βββ agents/ β Subagent definitions
β β βββ architect.md
β β βββ reviewer.md
β β βββ ...
β βββ skills/ β Skill templates
β βββ deploy/
β βββ test/
β βββ ...
βββ best-practice/ β Deep-dive guides
β βββ 01-context-management.md
β βββ 02-plan-mode.md
β βββ 03-subagents.md
β βββ 04-commands.md
β βββ 05-skills.md
β βββ 06-hooks.md
β βββ 07-mcp-servers.md
β βββ 08-memory-system.md
β βββ 09-settings.md
β βββ 10-claudemd-guide.md
βββ advanced/ β Advanced patterns
β βββ multi-agent-teams.md
β βββ cross-model-routing.md
β βββ automated-pipelines.md
β βββ security-patterns.md
β βββ enterprise-patterns.md
βββ implementation/ β Working code examples
β βββ hooks/ β Copy-paste hook scripts
β βββ mcp/ β MCP server examples
β βββ workflows/ β Workflow automation
βββ orchestration-workflow/ β Architecture patterns
β βββ research-plan-execute.md
β βββ tdd-workflow.md
β βββ spec-first.md
β βββ command-agent-skill-flow.md
βββ development-workflows/ β Full methodologies
β βββ ripe-workflow.md
β βββ tdd-spiral.md
β βββ spec-first.md
β βββ worktree-sprint.md
β βββ solo-vs-team.md
βββ tips/ β Curated tip collections
β βββ prompting-tips.md
β βββ context-tips.md
β βββ session-tips.md
β βββ debugging-tips.md
β βββ advanced-tips.md
βββ reports/ β Deep-dive reports
βββ memory-deep-dive.md
βββ hooks-deep-dive.md
βββ mcp-ecosystem.md
βββ agent-teams-report.md
π€ Contributing
This repository is a living document. Contributions welcome.
- Fork the repo
- Create a branch:
git checkout -b add/my-pattern - Add your content following the existing structure
- Submit a PR with a description of what you're adding and why it's useful
What to contribute:
- Real-world workflows that worked on production projects
- Hook scripts that solved actual problems
- Advanced patterns not covered here
- Corrections to outdated information
π License
MIT License β use freely, attribution appreciated.
If this helped you ship faster, give it a β
Made with experience, not just prompts.
Reviews (0)
Sign in to leave a review.
Leave a reviewNo results found