Skill refresh

This commit is contained in:
movq
2025-10-28 12:28:48 -05:00
parent 7911d90995
commit 35d2069861
26 changed files with 3837 additions and 4143 deletions

View File

@@ -8,12 +8,7 @@
{
"name": "claude-code",
"source": "./claude-code",
"description": "Complete toolkit for Claude Code: plugins, slash commands, hooks, subagents, and memory management"
},
{
"name": "claude-skills",
"source": "./claude-skills-plugin",
"description": "Meta-skill for creating effective Agent Skills with best practices and templates"
"description": "Complete toolkit for Claude Code: plugins, skills, slash commands, hooks, subagents, and memory management"
}
]
}

View File

@@ -382,7 +382,7 @@ my-plugin/
### Skill Naming Conventions
**For Claude Code features:**
- `claude-code-[feature]` (e.g., claude-code-plugins)
- `claude-[feature]` (e.g., claude-plugins)
**For domain-specific:**
- `[domain]-[purpose]` (e.g., python-testing, api-documentation)
@@ -411,17 +411,17 @@ Update version in plugin.json when:
## Example: Adding a Skill
### Scenario: Add "claude-code-mcp" skill
### Scenario: Add "claude-mcp" skill
```bash
# 1. Navigate to plugin
cd claude-code/skills
# 2. Create skill
mkdir claude-code-mcp
mkdir claude-mcp
# 3. Create SKILL.md
cat > claude-code-mcp/SKILL.md << 'EOF'
cat > claude-mcp/SKILL.md << 'EOF'
---
name: Claude Code MCP Servers
description: Configure and troubleshoot Model Context Protocol servers for Claude Code. Use when setting up MCP servers, debugging connections, or integrating external tools.
@@ -435,7 +435,7 @@ EOF
# 4. Update plugin README
vim ../README.md
# Add claude-code-mcp to "What's Included"
# Add claude-mcp to "What's Included"
# 5. Bump version in plugin.json
vim ../.claude-plugin/plugin.json
@@ -468,7 +468,7 @@ vim ../.claude-plugin/plugin.json
## Getting Help
- **Skill creation guidance** - Use claude-skills plugin
- **Plugin structure questions** - Use claude-code-plugins skill
- **Plugin structure questions** - Use claude-plugins skill
- **Testing help** - See TESTING.md
- **Questions** - Open an issue

View File

@@ -8,11 +8,11 @@ A curated marketplace of Agent Skills and plugins for Claude Code and Claude.ai,
Complete toolkit for mastering Claude Code features.
**Includes 5 specialized skills:**
- **claude-code-plugins** - Create and structure plugins
- **claude-code-slash-commands** - Build custom commands
- **claude-code-hooks** - Set up event-driven automation
- **claude-code-subagents** - Refine and troubleshoot subagents
- **claude-code-memory** - Optimize CLAUDE.md files
- **claude-plugins** - Create and structure plugins
- **claude-commands** - Build custom commands
- **claude-hooks** - Set up event-driven automation
- **claude-subagents** - Refine and troubleshoot subagents
- **claude-memory** - Optimize CLAUDE.md files
[View Plugin Details](./claude-code/README.md)
@@ -85,11 +85,11 @@ Each plugin can be zipped and uploaded individually:
**Best for:** Claude Code users who want to master plugins, commands, hooks, subagents, and memory management.
**Skills included:**
1. `claude-code-plugins` - Plugin development
2. `claude-code-slash-commands` - Custom command creation
3. `claude-code-hooks` - Event-driven automation
4. `claude-code-subagents` - Subagent optimization
5. `claude-code-memory` - Memory file management
1. `claude-plugins` - Plugin development
2. `claude-commands` - Custom command creation
3. `claude-hooks` - Event-driven automation
4. `claude-subagents` - Subagent optimization
5. `claude-memory` - Memory file management
**Installation:**
```bash
@@ -149,23 +149,23 @@ claude-skills-marketplace/
```
# Plugin development
"Help me create a plugin for my team"
→ claude-code-plugins skill activates
→ claude-plugins skill activates
# Custom commands
"I want to create a slash command for code review"
→ claude-code-slash-commands skill activates
→ claude-commands skill activates
# Setting up automation
"How do I run tests automatically after file edits?"
→ claude-code-hooks skill activates
→ claude-hooks skill activates
# Subagent issues
"My security analyzer subagent isn't triggering"
→ claude-code-subagents skill activates
→ claude-subagents skill activates
# Memory optimization
"My CLAUDE.md file is too long and wastes tokens"
→ claude-code-memory skill activates
→ claude-memory skill activates
```
### Creating New Skills

View File

@@ -1,13 +1,14 @@
{
"name": "claude-code",
"description": "Comprehensive skills for mastering Claude Code features: plugins, slash commands, hooks, subagents, and memory management",
"version": "1.0.0",
"description": "Comprehensive skills for mastering Claude Code features: plugins, skills, slash commands, hooks, subagents, and memory management",
"version": "1.1.0",
"author": {
"name": "Claude Skills Contributors"
},
"keywords": [
"claude-code",
"plugins",
"skills",
"slash-commands",
"hooks",
"subagents",

View File

@@ -6,7 +6,7 @@ Comprehensive skills for mastering Claude Code features including plugins, slash
This plugin provides five specialized skills that help you work more effectively with Claude Code:
### 1. claude-code-plugins
### 1. claude-plugins
Create and structure Claude Code plugins with commands, agents, skills, hooks, and MCP servers.
**Use when:**
@@ -14,7 +14,7 @@ Create and structure Claude Code plugins with commands, agents, skills, hooks, a
- Setting up plugin structure
- Configuring plugin manifests
### 2. claude-code-slash-commands
### 2. claude-commands
Create custom slash commands with argument handling, bash execution, and file references.
**Use when:**
@@ -22,7 +22,7 @@ Create custom slash commands with argument handling, bash execution, and file re
- Automating workflows
- Creating project-specific commands
### 3. claude-code-hooks
### 3. claude-hooks
Configure event-driven hooks for automating workflows, validating code, and controlling tool execution.
**Use when:**
@@ -31,7 +31,7 @@ Configure event-driven hooks for automating workflows, validating code, and cont
- Injecting context
- Integrating external tools
### 4. claude-code-subagents
### 4. claude-subagents
Refine and troubleshoot Claude Code subagents by optimizing prompts, tool access, and delegation patterns.
**Use when:**
@@ -39,7 +39,7 @@ Refine and troubleshoot Claude Code subagents by optimizing prompts, tool access
- Debugging activation issues
- Optimizing performance
### 5. claude-code-memory
### 5. claude-memory
Optimize and troubleshoot Claude Code memory files (CLAUDE.md) for efficiency, token management, and team collaboration.
**Use when:**
@@ -75,11 +75,11 @@ Or install from local directory:
Once installed, these skills activate automatically when you work on related tasks:
- **Working on a plugin?** → claude-code-plugins skill activates
- **Creating slash commands?** → claude-code-slash-commands skill activates
- **Setting up hooks?** → claude-code-hooks skill activates
- **Refining a subagent?** → claude-code-subagents skill activates
- **Troubleshooting CLAUDE.md?** → claude-code-memory skill activates
- **Working on a plugin?** → claude-plugins skill activates
- **Creating slash commands?** → claude-commands skill activates
- **Setting up hooks?** → claude-hooks skill activates
- **Refining a subagent?** → claude-subagents skill activates
- **Troubleshooting CLAUDE.md?** → claude-memory skill activates
You can also explicitly reference skills:
```
@@ -90,7 +90,7 @@ You can also explicitly reference skills:
## Skills Details
### claude-code-plugins
### claude-plugins
**Covers:**
- Plugin manifest configuration (plugin.json)
@@ -98,9 +98,9 @@ You can also explicitly reference skills:
- Distribution and marketplace publishing
- Best practices and troubleshooting
[View Details](./skills/claude-code-plugins/SKILL.md)
[View Details](./skills/claude-plugins/SKILL.md)
### claude-code-slash-commands
### claude-commands
**Covers:**
- Command syntax and frontmatter options
@@ -109,9 +109,9 @@ You can also explicitly reference skills:
- File references with @ prefix
- Complete examples and patterns
[View Details](./skills/claude-code-slash-commands/SKILL.md)
[View Details](./skills/claude-commands/SKILL.md)
### claude-code-hooks
### claude-hooks
**Covers:**
- All hook types (SessionStart, PreToolUse, PostToolUse, etc.)
@@ -120,9 +120,9 @@ You can also explicitly reference skills:
- Environment variables
- Complete working examples
[View Details](./skills/claude-code-hooks/SKILL.md)
[View Details](./skills/claude-hooks/SKILL.md)
### claude-code-subagents
### claude-subagents
**Covers:**
- Common problems and solutions
@@ -132,9 +132,9 @@ You can also explicitly reference skills:
- Testing and validation
- Migration from ad-hoc prompts
[View Details](./skills/claude-code-subagents/SKILL.md)
[View Details](./skills/claude-subagents/SKILL.md)
### claude-code-memory
### claude-memory
**Covers:**
- Memory hierarchy (project/user/subfolder)
@@ -144,7 +144,7 @@ You can also explicitly reference skills:
- Troubleshooting loading issues
- Template examples
[View Details](./skills/claude-code-memory/SKILL.md)
[View Details](./skills/claude-memory/SKILL.md)
## Best Practices
@@ -176,18 +176,18 @@ Start with one skill at a time:
- Try explicit skill references in prompts
**Need help with specific features?**
- Memory issues → Use claude-code-memory skill
- Subagent problems → Use claude-code-subagents skill
- Hook debugging → Use claude-code-hooks skill
- Memory issues → Use claude-memory skill
- Subagent problems → Use claude-subagents skill
- Hook debugging → Use claude-hooks skill
## Version History
### 1.0.0 (Initial Release)
- claude-code-plugins skill
- claude-code-slash-commands skill
- claude-code-hooks skill
- claude-code-subagents skill
- claude-code-memory skill
- claude-plugins skill
- claude-slash-commands skill
- claude-hooks skill
- claude-subagents skill
- claude-memory skill
## Contributing

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,698 +0,0 @@
---
name: Slash Command Creator
description: Create custom slash commands for Claude Code with argument handling, bash execution, and file references. Use when building reusable prompts, automating workflows, or creating project-specific commands.
---
# Slash Command Development
## When to Use This Skill
Use this skill when:
- Creating custom slash commands for Claude Code
- Building reusable prompt templates
- Automating repetitive tasks with commands
- Setting up project-specific workflows
- Converting manual prompts to slash commands
Do NOT use this skill for:
- Creating full plugins (use claude-code-plugins skill)
- Setting up hooks (use claude-code-hooks skill)
- General Claude Code usage
## Quick Start: Creating a Command
### 1. Create Command File
```bash
# Project-specific command (shared with team)
mkdir -p .claude/commands
cat > .claude/commands/review.md << 'EOF'
---
description: Review code for common issues
---
Review the following code for:
- Bugs and logic errors
- Code style issues
- Performance problems
- Security vulnerabilities
$ARGUMENTS
EOF
```
**Usage**: `/review @src/main.js`
### 2. Personal Command (Your Use Only)
```bash
# Personal command (not shared)
mkdir -p ~/.claude/commands
cat > ~/.claude/commands/explain.md << 'EOF'
---
description: Explain code in detail
argument-hint: <file-path>
---
Provide a detailed explanation of: $ARGUMENTS
Include:
- What the code does
- How it works
- Key design decisions
- Potential improvements
EOF
```
**Usage**: `/explain @utils/parser.ts`
## Command Locations
### Project Commands (.claude/commands/)
**Location**: `.claude/commands/` in your project
**Scope**: Available to everyone working on the project
**Version Control**: Commit to git for team sharing
**Use For**: Project-specific workflows, team standards
### Personal Commands (~/.claude/commands/)
**Location**: `~/.claude/commands/`
**Scope**: Available in all your projects
**Version Control**: Not in git (user-specific)
**Use For**: Personal productivity, custom preferences
## Command Syntax
### Basic Structure
```markdown
---
description: Brief description for /help
---
Prompt content here
```
### Command Name
The filename (without `.md`) becomes the command:
```bash
# File: .claude/commands/test.md
# Command: /test
# File: .claude/commands/commit-push.md
# Command: /commit-push
```
## Frontmatter Options
### description
Shows in `/help` output:
```yaml
---
description: Generate unit tests for a function
---
```
### argument-hint
Shows expected arguments in autocomplete:
```yaml
---
description: Compare two files
argument-hint: <file1> <file2>
---
```
### allowed-tools
Specifies which tools the command can use:
```yaml
---
description: Review and commit changes
allowed-tools: Bash(git status:*), Bash(git add:*), Bash(git commit:*)
---
```
**Patterns**:
- `Bash(git status:*)` - Specific command with any args
- `Read(*)` - Tool with any args
- `*` - All tools allowed
### model
Override default model for this command:
```yaml
---
description: Simple task
model: claude-haiku-4
---
```
### disable-model-invocation
Prevent SlashCommand tool from calling this:
```yaml
---
description: Internal helper command
disable-model-invocation: true
---
```
## Argument Handling
### $ARGUMENTS - All Arguments
Captures everything passed to the command:
```markdown
---
description: Explain multiple files
---
Explain these files: $ARGUMENTS
```
**Usage**: `/explain @src/a.js @src/b.js @src/c.js`
**Result**: All three file paths captured
### Positional Arguments ($1, $2, $3...)
Individual arguments like shell scripts:
```markdown
---
description: Compare two approaches
argument-hint: <approach1> <approach2>
---
Compare approach "$1" versus "$2" and recommend which is better.
```
**Usage**: `/compare REST GraphQL`
**$1** = "REST"
**$2** = "GraphQL"
### Combining Arguments
```markdown
---
description: Test specific function
argument-hint: <file> <function-name>
---
In file $1, create comprehensive tests for the function: $2
$ARGUMENTS
```
## File References with @
### Single File
```markdown
---
description: Review a file
---
Review @$1 for code quality issues.
```
**Usage**: `/review src/auth.js`
Claude will read `src/auth.js` automatically
### Multiple Files
```markdown
---
description: Compare implementations
---
Compare the implementation approaches in:
$ARGUMENTS
Which approach is better and why?
```
**Usage**: `/compare @old/version.js @new/version.js`
### Inline File References
```markdown
Review @src/config.js and ensure it follows @docs/style-guide.md
```
The `@` prefix tells Claude to read those files before processing.
## Bash Execution with !
### Prefix Commands with !
Run bash before the slash command executes:
```markdown
---
description: Show git status and suggest next steps
allowed-tools: Bash(git status:*), Bash(git diff:*)
---
!git status
!git diff --stat
Based on the current git state, suggest what I should do next.
```
**Important**: Must include `allowed-tools` with Bash tool specification.
### Why Use ! Prefix?
Without `!`, bash commands are just text in the prompt.
With `!`, they execute and results are included in context.
```markdown
# This doesn't work (just text):
git status
What should I commit?
# This works (executes first):
---
allowed-tools: Bash(git status:*)
---
!git status
What should I commit?
```
## Namespacing with Directories
### Organize Related Commands
```
.claude/commands/
├── git/
│ ├── commit.md
│ ├── review.md
│ └── sync.md
└── test/
├── unit.md
└── integration.md
```
**Commands**: `/commit`, `/review`, `/sync`, `/unit`, `/integration`
**Note**: Directory structure is for organization only - it doesn't affect command names.
## Complete Examples
### 1. Security Review Command
```markdown
---
description: Comprehensive security review of code files
allowed-tools: Read(*), Grep(*), Bash(grep:*)
argument-hint: <files...>
---
Perform a security audit on: $ARGUMENTS
Check for:
1. SQL injection vulnerabilities
2. XSS vulnerabilities
3. Authentication/authorization issues
4. Hardcoded secrets or credentials
5. Unsafe deserialization
6. Path traversal vulnerabilities
7. Insecure cryptography
8. Information disclosure
For each issue found:
- Severity level (Critical/High/Medium/Low)
- Location (file:line)
- Explanation of the vulnerability
- Recommended fix with code example
```
**Usage**: `/security-review @src/auth.js @src/api.js`
### 2. Commit + Push Command
```markdown
---
description: Review changes, commit, and push to remote
allowed-tools: Bash(git:*)
---
!git status
!git diff
Review the changes above and:
1. Create an appropriate commit message
2. Commit the changes
3. Push to remote
Ask for confirmation before pushing.
```
**Usage**: `/commit-push`
### 3. Test Generator
```markdown
---
description: Generate comprehensive tests for a function
argument-hint: <file> <function-name>
model: claude-sonnet-4
---
For the function "$2" in @$1:
1. Analyze the function's behavior
2. Identify edge cases
3. Generate comprehensive unit tests including:
- Happy path tests
- Edge case tests
- Error condition tests
- Boundary value tests
Use the project's existing test framework and patterns.
```
**Usage**: `/test-gen src/parser.js parseQuery`
### 4. API Documentation
```markdown
---
description: Generate API documentation for endpoints
allowed-tools: Read(*), Grep(*)
---
Generate API documentation for: $ARGUMENTS
Include:
- Endpoint URL and method
- Request parameters (query, body, headers)
- Response format and status codes
- Example requests and responses
- Error conditions
- Authentication requirements
Format as OpenAPI/Swagger compatible YAML.
```
**Usage**: `/api-docs @routes/users.js @routes/posts.js`
### 5. Performance Analysis
```markdown
---
description: Analyze code for performance issues
argument-hint: <file>
---
Analyze @$1 for performance issues:
1. **Time Complexity**: Identify algorithms and their complexity
2. **Space Complexity**: Memory usage patterns
3. **Bottlenecks**: Potential performance problems
4. **Optimization Opportunities**: Specific improvements with examples
For each issue:
- Current implementation
- Why it's problematic
- Optimized version
- Performance impact estimate
```
**Usage**: `/perf @src/data-processor.js`
## Command Patterns
### Review Pattern
```markdown
---
description: Review X for Y
---
Review $ARGUMENTS for [specific criteria]
Include:
- [Aspect 1]
- [Aspect 2]
- [Aspect 3]
```
### Generate Pattern
```markdown
---
description: Generate X from Y
---
Generate [output type] for: $ARGUMENTS
Requirements:
- [Requirement 1]
- [Requirement 2]
```
### Compare Pattern
```markdown
---
description: Compare X and Y
argument-hint: <option1> <option2>
---
Compare "$1" versus "$2"
Analyze:
- [Comparison aspect 1]
- [Comparison aspect 2]
Recommendation: [Which is better and why]
```
### Workflow Pattern
```markdown
---
description: Execute multi-step workflow
allowed-tools: Bash(*), Read(*), Write(*)
---
Execute the following workflow:
1. [Step 1]
2. [Step 2]
3. [Step 3]
After each step, confirm before proceeding.
```
## Testing Commands
### 1. Check Command List
```bash
# See all available commands
/help
# Your command should appear in the list
```
### 2. Test Argument Handling
```bash
# Test with different argument patterns
/mycommand arg1
/mycommand arg1 arg2
/mycommand @file.js
/mycommand @file1.js @file2.js
```
### 3. Verify Bash Execution
If using `!` prefix, confirm commands execute:
```markdown
---
description: Test bash execution
allowed-tools: Bash(echo:*)
---
!echo "This should show before prompt processing"
Did the echo work?
```
## Best Practices
### 1. Clear Descriptions
```yaml
# Good
description: Generate unit tests for a specific function
# Bad
description: Testing
```
### 2. Explicit Arguments
```yaml
# Good
argument-hint: <file-path> <function-name>
# Bad (no hint)
argument-hint:
```
### 3. Specific Tool Permissions
```yaml
# Good - minimal permissions
allowed-tools: Bash(git status:*), Bash(git diff:*)
# Risky - too permissive
allowed-tools: *
```
### 4. Meaningful Names
```bash
# Good
/generate-tests
/review-security
/commit-and-push
# Bad
/gt
/rs
/cap
```
### 5. Self-Documenting Content
```markdown
Review code for:
1. Logic errors
2. Style issues
3. Performance problems
$ARGUMENTS
```
Better than:
```markdown
Review: $ARGUMENTS
```
## Troubleshooting
### Command Not Found
**Issue**: `/mycommand` says command not found
**Solutions**:
1. Check file is in `.claude/commands/` or `~/.claude/commands/`
2. Verify filename ends with `.md`
3. Restart Claude Code to refresh command list
### Arguments Not Working
**Issue**: `$ARGUMENTS` or `$1` showing literally
**Solutions**:
1. Ensure proper syntax: `$ARGUMENTS`, `$1`, `$2` (not `${ARGUMENTS}`)
2. Check for typos in variable names
3. Test with simple command first
### Bash Commands Not Executing
**Issue**: `!command` not running
**Solutions**:
1. Add `allowed-tools` to frontmatter
2. Include specific tool pattern: `Bash(git:*)`
3. Test with simple command: `!echo test`
### File References Not Loading
**Issue**: `@file.js` not including file content
**Solutions**:
1. Verify file path is correct (relative to project root)
2. Check file exists: `ls @file.js`
3. Ensure no typos in file path
## Security Considerations
### Limit Tool Access
Only grant necessary permissions:
```yaml
# Specific commands only
allowed-tools: Bash(git status:*), Bash(git log:*)
# Never use unless absolutely required
allowed-tools: *
```
### No Hardcoded Secrets
```markdown
# Bad - hardcoded API key
!curl -H "API-Key: sk-abc123..." api.example.com
# Good - use environment variables
!curl -H "API-Key: $MY_API_KEY" api.example.com
```
### Validate User Input
If using arguments in bash:
```markdown
# Risky - no validation
!rm -rf $1
# Better - validate first
Confirm you want to delete: $1
(Then use interactive confirmation before executing)
```
## Command Template
```markdown
---
description: [Clear, concise description of what this command does]
argument-hint: [Expected arguments format]
allowed-tools: [Specific tool patterns if needed]
---
[Command prompt template]
$ARGUMENTS
```
## Resources
- [Official Slash Commands Documentation](https://docs.claude.com/en/docs/claude-code/slash-commands)
- [Plugin Development](../claude-code-plugins/SKILL.md) - For packaging commands in plugins
- [Hooks](../claude-code-hooks/SKILL.md) - For event-based automation
---
**Remember**: Slash commands are for reusable prompts. Start with manual prompts, identify patterns you repeat, then codify them as commands.

View File

@@ -1,934 +0,0 @@
---
name: Claude Code Subagent Specialist
description: Refine and troubleshoot Claude Code subagents by optimizing prompts, tool access, descriptions, and performance. Use when improving existing subagents, debugging activation issues, or optimizing delegation patterns. NOT for initial creation - use /agents command first.
---
# Claude Code Subagent Refinement & Troubleshooting
## When to Use This Skill
Use this skill when:
- Refining existing subagent prompts for better performance
- Troubleshooting why a subagent isn't activating
- Optimizing tool access and permissions
- Improving subagent descriptions for better delegation
- Debugging context management issues
- Testing and validating subagent behavior
- Converting ad-hoc workflows to reusable subagents
Do NOT use this skill for:
- **Initial creation** - Use `/agents` command instead (it provides interactive UI)
- Creating slash commands (use claude-code-slash-commands skill)
- General Claude Code troubleshooting
**Important**: Always start with `/agents` to create subagents. Use this skill to refine them afterward.
## Quick Reference: Subagent Structure
```yaml
---
name: agent-name # Lowercase, kebab-case identifier
description: When to use # Triggers automatic delegation
tools: Tool1, Tool2 # Optional: omit to inherit all
model: sonnet # Optional: sonnet/opus/haiku/inherit
---
System prompt defining role, capabilities, and behavior.
Include specific instructions, constraints, and examples.
```
**File Locations**:
- Project: `.claude/agents/` (highest priority)
- User: `~/.claude/agents/` (shared across projects)
- Plugin: `agents/` in plugin directory
## Common Problems & Solutions
### Problem 1: Subagent Never Activates
**Symptoms**: Claude doesn't delegate to your subagent
**Diagnose**:
```yaml
# Check your description field
---
description: Helper agent # ❌ Too vague
---
```
**Fix - Make Description Specific**:
```yaml
# Before (vague)
---
description: Helps with security
---
# After (specific)
---
description: Analyze code for security vulnerabilities including SQL injection, XSS, authentication flaws, and hardcoded secrets. Use PROACTIVELY when reviewing code for security issues.
---
```
**Best Practices for Descriptions**:
- Include specific trigger words and scenarios
- Add "use PROACTIVELY" or "MUST BE USED" for automatic activation
- Mention the domain/context clearly
- List key capabilities or checks
### Problem 2: Subagent Has Wrong Tools
**Symptoms**: Subagent can't complete tasks or has too many permissions
**Diagnose**:
```bash
# Check current tool configuration
cat .claude/agents/my-agent.md | grep "tools:"
```
**Fix - Whitelist Specific Tools**:
```yaml
# Inherits all tools (may be too permissive)
---
name: security-analyzer
description: Security analysis
---
# Restricted to read-only tools (better)
---
name: security-analyzer
description: Security analysis
tools: Read, Grep, Glob
---
```
**Tool Access Strategies**:
**1. Inherit All (Default)**:
```yaml
# Omit 'tools' field entirely
---
name: general-helper
description: General assistance
---
```
Use when: Agent needs full flexibility
**2. Read-Only Access**:
```yaml
---
tools: Read, Grep, Glob, Bash(git log:*), Bash(git diff:*)
---
```
Use when: Analysis, review, documentation
**3. Specific Permissions**:
```yaml
---
tools: Read, Write, Edit, Bash(npm test:*)
---
```
Use when: Implementation with validation
**4. No File Access**:
```yaml
---
tools: WebFetch, WebSearch, Bash
---
```
Use when: Research, external data gathering
### Problem 3: Poor Quality Output
**Symptoms**: Subagent completes tasks but results are inconsistent or low-quality
**Diagnose**: Check system prompt specificity
**Fix - Enhance System Prompt**:
```markdown
# Before (vague)
---
name: code-reviewer
---
You review code for issues.
```
```markdown
# After (specific)
---
name: code-reviewer
---
You are a senior code reviewer specializing in production-ready code quality.
## Your Responsibilities
1. **Logic & Correctness**
- Verify algorithm correctness
- Check edge case handling
- Validate error conditions
2. **Code Quality**
- Ensure single responsibility principle
- Check for code duplication (DRY)
- Verify meaningful naming
3. **Security**
- Identify injection vulnerabilities
- Check authentication/authorization
- Flag hardcoded secrets
4. **Performance**
- Spot O(n²) or worse algorithms
- Identify unnecessary loops
- Check resource cleanup
## Output Format
For each issue found:
- **Severity**: Critical/High/Medium/Low
- **Location**: file:line
- **Issue**: Clear description
- **Fix**: Specific code example
## Constraints
- Only report actionable issues
- Provide code examples for fixes
- Focus on high-impact problems first
- No nitpicking style issues unless severe
```
**System Prompt Best Practices**:
- Define role and expertise level
- List specific responsibilities
- Include output format requirements
- Add examples of good/bad cases
- Specify constraints and boundaries
- Use headings for scannability
### Problem 4: Context Pollution
**Symptoms**: Main conversation gets cluttered with subagent details
**Understand**: Subagents have isolated context windows - only their final output returns
**Fix - Structure Output Properly**:
```markdown
# System prompt guidance
---
name: research-agent
---
Research [topic] and return ONLY:
1. Key findings (3-5 bullet points)
2. Relevant URLs
3. Recommendation
Do NOT include:
- Full article text
- Research methodology
- Intermediate thoughts
```
**Best Practices**:
- Explicitly tell subagent what to return
- Request summaries, not full details
- Have subagent filter before returning
- Use structured output formats
### Problem 5: Activation Too Broad/Narrow
**Symptoms**: Subagent activates for wrong tasks OR misses relevant tasks
**Diagnose - Test Trigger Scenarios**:
```markdown
# Test cases for a "security-analyzer" subagent
Should Activate:
- "Review this auth code for vulnerabilities"
- "Check if we're handling passwords securely"
- "Scan for SQL injection risks"
Should NOT Activate:
- "Write unit tests" (different concern)
- "Refactor this function" (not security-focused)
- "Add logging" (different task)
```
**Fix - Refine Description**:
```yaml
# Too narrow
---
description: Checks for SQL injection only
---
# Too broad
---
description: Helps with code
---
# Just right
---
description: Analyze code for security vulnerabilities including SQL injection, XSS, CSRF, authentication issues, and secrets exposure. Use when reviewing code for security concerns or compliance requirements.
---
```
### Problem 6: Model Selection Issues
**Symptoms**: Subagent too slow/expensive OR too simple for task
**Fix - Choose Right Model**:
```yaml
# Fast, simple tasks (formatting, linting)
---
model: haiku
---
# Complex reasoning (architecture, design)
---
model: opus
---
# Balanced (most cases)
---
model: sonnet
---
# Same as main conversation
---
model: inherit
---
```
**Model Selection Guide**:
| Model | Use For | Avoid For |
|-------|---------|-----------|
| haiku | Simple transforms, quick checks | Complex reasoning, creativity |
| sonnet | General tasks, balanced quality | When opus is specifically needed |
| opus | Complex architecture, creative work | Simple/repetitive tasks (cost) |
| inherit | Task complexity matches main thread | When you need different capability |
## Optimization Patterns
### Pattern 1: Role-Based Pipeline
Create specialized agents for each workflow stage:
```yaml
# 1. Spec Agent
---
name: product-spec-writer
description: Create detailed product specifications from user requirements
tools: Read, Write, WebSearch
model: opus
---
You convert user requirements into detailed product specs.
[Detailed prompt...]
```
```yaml
# 2. Architect Agent
---
name: solution-architect
description: Design system architecture from product specs
tools: Read, Write, Grep, Glob
model: opus
---
You design scalable system architectures.
[Detailed prompt...]
```
```yaml
# 3. Implementer Agent
---
name: code-implementer
description: Implement features from architectural designs
tools: Read, Write, Edit, Bash(npm test:*)
model: sonnet
---
You implement features following architectural guidelines.
[Detailed prompt...]
```
**Usage**: Chain with hooks or explicit handoffs
### Pattern 2: Domain Specialists
```yaml
# Frontend Specialist
---
name: frontend-specialist
description: React/TypeScript UI development and component design. Use PROACTIVELY for frontend work.
tools: Read, Write, Edit, Grep, Bash(npm:*)
---
You are a React/TypeScript expert specializing in modern frontend development.
## Tech Stack
- React 18+ with hooks
- TypeScript (strict mode)
- Tailwind CSS
- Component-driven architecture
## Principles
- Functional components only
- Custom hooks for logic reuse
- Accessibility (WCAG AA)
- Performance (lazy loading, memoization)
[More specific guidance...]
```
```yaml
# Backend Specialist
---
name: backend-specialist
description: Node.js/Express API development, database design, and server architecture. Use PROACTIVELY for backend work.
tools: Read, Write, Edit, Grep, Bash(npm:*), Bash(docker:*)
---
You are a Node.js backend expert.
[Similar detailed structure...]
```
### Pattern 3: Security-First Architecture
```yaml
# Security Analyzer (Read-Only)
---
name: security-analyzer
description: Analyze code for security vulnerabilities before allowing modifications. MUST BE USED before code changes in sensitive areas.
tools: Read, Grep, Glob, Bash(git diff:*)
---
You are a security analyst. Review code for vulnerabilities BEFORE changes are made.
## Security Checks
1. Authentication/Authorization
2. Input validation
3. SQL injection
4. XSS vulnerabilities
5. CSRF protection
6. Secrets management
## Output
Return ONLY:
- Security score (1-10)
- Critical issues (block changes)
- Warnings (allow with caution)
```
### Pattern 4: Test-Driven Subagent
```yaml
---
name: test-first-developer
description: Write comprehensive tests before implementing features. Use PROACTIVELY for TDD workflows.
tools: Read, Write, Bash(npm test:*)
model: sonnet
---
You are a TDD expert. For every feature request:
1. **Analyze Requirements**
- Extract testable behaviors
- Identify edge cases
2. **Write Tests FIRST**
- Unit tests for logic
- Integration tests for workflows
- Edge case coverage
3. **Run Tests** (they should fail)
```bash
npm test
```
4. **Implement ONLY Enough** to pass tests
5. **Refactor** while keeping tests green
## Test Structure
```javascript
describe('Feature', () => {
it('handles happy path', () => {})
it('handles edge case 1', () => {})
it('throws on invalid input', () => {})
})
```
Never implement before tests exist.
```
## Testing & Validation
### 1. Test Trigger Accuracy
Create test scenarios:
```markdown
# Test Plan for "api-developer" subagent
## Positive Tests (Should Activate)
1. "Create a REST endpoint for user authentication"
- Expected: Activates
- Actual: ___
2. "Add GraphQL mutation for updating profile"
- Expected: Activates
- Actual: ___
## Negative Tests (Should NOT Activate)
1. "Write unit tests for the API"
- Expected: Does not activate (testing concern)
- Actual: ___
2. "Review API security"
- Expected: Does not activate (security concern)
- Actual: ___
## Results
- Precision: X% (correct activations / total activations)
- Recall: Y% (correct activations / should activate)
```
### 2. Test Output Quality
```markdown
# Quality Checklist
Task: "Review auth.js for security issues"
Subagent Output Should Include:
- [ ] Specific vulnerabilities identified
- [ ] File:line locations
- [ ] Severity ratings
- [ ] Concrete fix suggestions
- [ ] Code examples for fixes
Should NOT Include:
- [ ] Generic advice
- [ ] Full file listings
- [ ] Unrelated issues
- [ ] Style nitpicks
```
### 3. Test Tool Access
```bash
# Verify tool restrictions work
# Give subagent a task requiring forbidden tool
# Example: Read-only subagent shouldn't be able to edit
# Test by asking it to "fix the security issue"
# Should fail or request permission
```
### 4. Performance Testing
```markdown
# Performance Metrics
Task: "Generate API documentation"
Metrics:
- Time to complete: ___
- Tokens used: ___
- Quality score (1-10): ___
- Required follow-ups: ___
Optimization targets:
- < 30 seconds for docs
- < 5000 tokens
- Quality >= 8
- 0 follow-ups needed
```
## Refinement Workflow
### Step 1: Baseline Performance
```bash
# Document current behavior
echo "Task: [Specific task]
Expected: [What should happen]
Actual: [What actually happens]
Issues: [Problems observed]
" > .claude/agents/refinement-notes.md
```
### Step 2: Identify Root Cause
Common causes:
- Description too vague → Won't activate
- Prompt lacks specificity → Poor output
- Wrong tools → Can't complete task
- Wrong model → Too slow/simple
- Output not filtered → Context pollution
### Step 3: Make Targeted Changes
**Only change ONE thing at a time**:
1. Update description OR
2. Refine prompt OR
3. Adjust tools OR
4. Change model
### Step 4: Test Changes
```bash
# Test with same scenarios
# Compare before/after results
# Document improvements
```
### Step 5: Iterate
Repeat until subagent meets quality bar.
## Best Practices Summary
### Description Writing
```yaml
# Template
description: [Action verb] [domain/task] [including specific capabilities]. Use [trigger condition]. PROACTIVELY when [scenario].
```
**Examples**:
```yaml
description: Analyze Python code for performance bottlenecks including O(n²) algorithms, memory leaks, and inefficient database queries. Use PROACTIVELY when optimizing Python applications.
description: Generate comprehensive API documentation from code including endpoints, parameters, responses, and examples. Use when documenting REST or GraphQL APIs.
description: Review frontend code for accessibility issues following WCAG 2.1 AA standards. MUST BE USED for all UI component changes.
```
### System Prompt Structure
```markdown
# Role Definition
You are a [role] specializing in [domain].
## Responsibilities
1. [Primary responsibility]
2. [Secondary responsibility]
3. [Additional responsibilities]
## Process
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Output Format
[Specific structure required]
## Examples
### Good Example
[Show what good looks like]
### Bad Example
[Show what to avoid]
## Constraints
- [Important limitation]
- [Another constraint]
```
### Tool Selection Strategy
```markdown
Decision Tree:
1. Does it need to modify files?
No → Read, Grep, Glob only
Yes → Continue
2. Does it need to run tests/builds?
No → Read, Write, Edit only
Yes → Add Bash(test:*), Bash(build:*)
3. Does it need external data?
Yes → Add WebFetch, WebSearch
No → Continue
4. Does it need git operations?
Yes → Add Bash(git:*) with specific commands
No → Done
```
### Model Selection
```markdown
Choose model based on:
1. Task complexity
- Simple transforms → haiku
- Standard coding → sonnet
- Complex reasoning → opus
2. Cost sensitivity
- High volume, simple → haiku
- Balanced → sonnet
- Quality critical → opus
3. Speed requirements
- Real-time needed → haiku
- Standard → sonnet
- Can wait → opus
Default: sonnet (best balance)
```
## Debugging Checklist
When subagent doesn't work as expected:
```markdown
- [ ] Description is specific and includes trigger words
- [ ] Description includes "PROACTIVELY" or "MUST BE USED" if needed
- [ ] System prompt defines role clearly
- [ ] System prompt includes process/steps
- [ ] System prompt specifies output format
- [ ] System prompt has examples
- [ ] Tools match required capabilities
- [ ] Tools follow least-privilege principle
- [ ] Model appropriate for task complexity
- [ ] File location correct (.claude/agents/)
- [ ] YAML frontmatter valid
- [ ] Name uses kebab-case
- [ ] Tested with positive/negative scenarios
```
## Common Anti-Patterns
### ❌ Anti-Pattern 1: Generic Description
```yaml
---
description: Helps with coding
---
```
**Why Bad**: Won't trigger reliably
**Fix**: Be specific about domain and triggers
### ❌ Anti-Pattern 2: No Process Defined
```markdown
You are a code reviewer. Review code.
```
**Why Bad**: Inconsistent results
**Fix**: Define step-by-step process
### ❌ Anti-Pattern 3: All Tools Granted
```yaml
---
# Omitting tools when only reads needed
---
```
**Why Bad**: Unnecessary permissions, security risk
**Fix**: Whitelist minimum required tools
### ❌ Anti-Pattern 4: Verbose System Prompt
```markdown
You are an expert developer with 20 years of experience who has worked on numerous projects across different industries... [3000 words]
```
**Why Bad**: Token waste, slower activation
**Fix**: Be concise, focus on process and format
### ❌ Anti-Pattern 5: No Output Structure
```markdown
Review the code and tell me about issues.
```
**Why Bad**: Inconsistent format, hard to parse
**Fix**: Define exact output format
## Advanced Techniques
### Technique 1: Chained Subagents
Use hooks or explicit handoffs:
```json
// .claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "echo 'Please use security-analyzer subagent to review this file' && exit 0"
}
]
}
]
}
}
```
### Technique 2: Context Injection
```yaml
---
name: context-aware-developer
---
Before starting any task:
1. Read PROJECT_CONTEXT.md
2. Review ARCHITECTURE.md
3. Check CODING_STANDARDS.md
Then proceed with development following documented patterns.
```
### Technique 3: Quality Gates
```yaml
---
name: pr-ready-checker
description: Verify code is PR-ready before submitting. MUST BE USED before creating pull requests.
tools: Read, Grep, Bash(npm test:*), Bash(npm run lint:*)
---
Verify PR readiness:
1. **Tests Pass**
```bash
npm test
```
All tests must pass.
2. **Linting Clean**
```bash
npm run lint
```
Zero warnings or errors.
3. **Coverage Adequate**
- New code > 80% covered
- Overall coverage not decreased
4. **Documentation Updated**
- README if public API changed
- Inline comments for complex logic
5. **No Debug Code**
- No console.log
- No debugger statements
- No commented code
Return: "PR Ready: Yes/No" + blockers list
```
### Technique 4: Iterative Refinement Prompt
```yaml
---
name: iterative-implementer
---
When implementation fails or produces errors:
1. **Analyze Failure**
- What was the error?
- Why did it happen?
- What was I trying to achieve?
2. **Adjust Approach**
- How should I do it differently?
- What did I learn?
3. **Re-implement**
- Apply new approach
- Test immediately
4. **Verify**
- Did it work?
- If not, repeat from step 1
Never give up after one failure. Iterate until success.
```
## Migration: Ad-Hoc to Subagent
### When to Migrate
Migrate repetitive prompts to subagents when:
- You've used the same prompt 3+ times
- Prompt has clear pattern/structure
- Task benefits from isolation
- Multiple team members need it
### Migration Process
**Step 1: Extract Pattern**
```markdown
# Repeated prompts you've used:
1. "Review auth.js for security issues including SQL injection, XSS, and auth flaws"
2. "Check payment.js for security vulnerabilities like injection and secrets"
3. "Analyze api.js for security problems including validation and auth"
# Common pattern:
Review [file] for security [vulnerability types]
```
**Step 2: Generalize**
```yaml
---
name: security-reviewer
description: Review code for security vulnerabilities including SQL injection, XSS, authentication flaws, and hardcoded secrets. Use PROACTIVELY for security reviews.
tools: Read, Grep, Glob
---
Review provided files for security vulnerabilities:
[Extract common structure from your prompts]
```
**Step 3: Test & Refine**
Test with previous use cases, refine until quality matches or exceeds manual prompts.
## Resources
- [Official Subagents Documentation](https://docs.claude.com/en/docs/claude-code/sub-agents)
- [Claude Code Plugins](../claude-code-plugins/SKILL.md) - For packaging subagents
- [Slash Commands](../claude-code-slash-commands/SKILL.md) - Alternative for simpler patterns
- [Hooks](../claude-code-hooks/SKILL.md) - For automating subagent workflows
---
**Remember**: Start with `/agents` command for creation. Use this skill for refinement. Iterate based on real usage. Test thoroughly. Document learnings.

View File

@@ -0,0 +1,399 @@
---
name: Slash Command Creator
description: Create custom slash commands for Claude Code with argument handling, bash execution, and file references. Use PROACTIVELY when building reusable prompts, automating workflows, creating project-specific commands, or when users mention "create a command", "reusable prompt", "/something", or "slash command". NOT for complex multi-file operations.
---
# Slash Command Development
## When to Use This Skill
Use this skill when:
- Creating custom slash commands for Claude Code
- Building reusable prompt templates
- Automating repetitive tasks with commands
- Setting up project-specific workflows
- Converting manual prompts to slash commands
Do NOT use this skill for:
- Creating full plugins (use claude-plugin skill)
- Setting up hooks (use claude-hooks skill)
- Complex multi-file operations (use subagents)
## Quick Start
### Create Command File
```bash
# Project-specific (team shared)
mkdir -p .claude/commands
cat > .claude/commands/review.md << 'EOF'
---
description: Review code for common issues
---
Review the following code for:
- Bugs and logic errors
- Code style issues
- Performance problems
- Security vulnerabilities
$ARGUMENTS
EOF
```
**Usage**: `/review @src/main.js`
## Command Locations
| Location | Scope | Version Control | Use For |
|----------|-------|-----------------|---------|
| `.claude/commands/` | Project (team) | In git | Team workflows, standards |
| `~/.claude/commands/` | User (personal) | Not in git | Personal productivity |
## Command Syntax
### Basic Structure
```markdown
---
description: Brief description for /help
---
Prompt content here
$ARGUMENTS
```
### Filename = Command Name
```bash
# File: .claude/commands/test.md
# Command: /test
# File: .claude/commands/commit-push.md
# Command: /commit-push
```
## Frontmatter Options
```yaml
---
description: Generate unit tests for a function # Shows in /help
argument-hint: <file-path> <function-name> # Autocomplete hint
allowed-tools: Read(*), Bash(git:*) # Tool permissions
model: claude-haiku-4 # Override default model
disable-model-invocation: true # Prevent auto-invocation
---
```
## Argument Handling
### $ARGUMENTS - All Arguments
```markdown
---
description: Explain multiple files
---
Explain these files: $ARGUMENTS
```
**Usage**: `/explain @src/a.js @src/b.js @src/c.js`
### Positional ($1, $2, $3...)
```markdown
---
description: Compare two approaches
argument-hint: <approach1> <approach2>
---
Compare approach "$1" versus "$2" and recommend which is better.
```
**Usage**: `/compare REST GraphQL`
### File References with @
```markdown
---
description: Review a file
---
Review @$1 for code quality issues.
```
**Usage**: `/review src/auth.js`
Claude reads `src/auth.js` automatically.
## Bash Execution with !
Prefix commands with `!` to execute before processing:
```markdown
---
description: Show git status and suggest next steps
allowed-tools: Bash(git status:*), Bash(git diff:*)
---
!git status
!git diff --stat
Based on the current git state, suggest what I should do next.
```
**Important**: Must include `allowed-tools` with Bash specifications.
## Complete Examples
### Security Review
```markdown
---
description: Comprehensive security review of code files
allowed-tools: Read(*), Grep(*)
argument-hint: <files...>
---
Perform a security audit on: $ARGUMENTS
Check for:
1. SQL injection vulnerabilities
2. XSS vulnerabilities
3. Authentication/authorization issues
4. Hardcoded secrets or credentials
5. Unsafe deserialization
6. Path traversal vulnerabilities
For each issue found:
- Severity level (Critical/High/Medium/Low)
- Location (file:line)
- Explanation of the vulnerability
- Recommended fix with code example
```
### Commit + Push
```markdown
---
description: Review changes, commit, and push to remote
allowed-tools: Bash(git:*)
---
!git status
!git diff
Review the changes above and:
1. Create an appropriate commit message
2. Commit the changes
3. Push to remote
Ask for confirmation before pushing.
```
### Test Generator
```markdown
---
description: Generate comprehensive tests for a function
argument-hint: <file> <function-name>
model: claude-sonnet-4
---
For the function "$2" in @$1:
1. Analyze the function's behavior
2. Identify edge cases
3. Generate comprehensive unit tests including:
- Happy path tests
- Edge case tests
- Error condition tests
- Boundary value tests
Use the project's existing test framework and patterns.
```
For more examples, see [examples.md](examples.md)
## Command Patterns
### Review Pattern
```markdown
---
description: Review X for Y
---
Review $ARGUMENTS for [specific criteria]
Include:
- [Aspect 1]
- [Aspect 2]
```
### Generate Pattern
```markdown
---
description: Generate X from Y
---
Generate [output type] for: $ARGUMENTS
Requirements:
- [Requirement 1]
- [Requirement 2]
```
### Compare Pattern
```markdown
---
description: Compare X and Y
argument-hint: <option1> <option2>
---
Compare "$1" versus "$2"
Analyze:
- [Comparison aspect 1]
- [Comparison aspect 2]
Recommendation: [Which is better and why]
```
## Testing Commands
```bash
# See all available commands
/help
# Test with different arguments
/mycommand arg1
/mycommand @file.js
/mycommand @file1.js @file2.js
```
## Best Practices
### 1. Clear Descriptions
```yaml
# Good
description: Generate unit tests for a specific function
# Bad
description: Testing
```
### 2. Explicit Arguments
```yaml
# Good
argument-hint: <file-path> <function-name>
# Bad (no hint)
```
### 3. Specific Tool Permissions
```yaml
# Good - minimal permissions
allowed-tools: Bash(git status:*), Bash(git diff:*)
# Risky - too permissive
allowed-tools: *
```
### 4. Meaningful Names
```bash
# Good
/generate-tests
/review-security
/commit-and-push
# Bad
/gt
/rs
/cap
```
### 5. Self-Documenting Content
```markdown
Review code for:
1. Logic errors
2. Style issues
3. Performance problems
$ARGUMENTS
```
## Troubleshooting
| Problem | Solution |
|---------|----------|
| Command not found | Check file is in `.claude/commands/`, ends with `.md` |
| Arguments not working | Use `$ARGUMENTS`, `$1`, `$2` (not `${ARGUMENTS}`) |
| Bash not executing | Add `allowed-tools` frontmatter with `Bash()` pattern |
| File references not loading | Verify file path, use `@` prefix |
## Security Considerations
### Limit Tool Access
```yaml
# Specific commands only
allowed-tools: Bash(git status:*), Bash(git log:*)
# Never use unless required
allowed-tools: *
```
### No Hardcoded Secrets
```markdown
# Bad - hardcoded API key
!curl -H "API-Key: sk-abc123..." api.example.com
# Good - use environment variables
!curl -H "API-Key: $MY_API_KEY" api.example.com
```
### Validate User Input
```markdown
# Risky - no validation
!rm -rf $1
# Better - validate first
Confirm you want to delete: $1
(Then use interactive confirmation)
```
## Command Template
```markdown
---
description: [Clear, concise description]
argument-hint: [Expected arguments]
allowed-tools: [Specific patterns if needed]
---
[Command prompt template]
$ARGUMENTS
```
## Resources
- [Complete Examples](examples.md) - Working command configurations
- [Advanced Patterns](patterns.md) - Complex workflows
- [Official Documentation](https://docs.claude.com/en/docs/claude-code/slash-commands)
- [Plugin Development](../claude-plugin/SKILL.md) - Packaging commands
---
**Remember**: Slash commands are for reusable prompts. Start with manual prompts, identify patterns you repeat, then codify them as commands.

View File

@@ -0,0 +1,404 @@
---
name: Claude Code Hooks
description: Configure event-driven hooks for Claude Code to automate workflows, validate code, inject context, and control tool execution. Use PROACTIVELY when setting up automation, enforcing standards, integrating external tools, or when users mention "automatically run", "on save", "event-driven", "workflow automation", or "enforce rules". NOT for one-time scripts.
---
# Claude Code Hooks
## When to Use This Skill
Use this skill when:
- Automating workflows with event-driven triggers
- Enforcing code standards or security policies
- Validating changes before/after tool execution
- Injecting context at session start
- Logging or monitoring tool usage
- Setting up team-wide automation
Do NOT use this skill for:
- Creating slash commands (use claude-command-expert skill)
- Building full plugins (use claude-plugin skill)
- One-time scripts (just run them directly)
## Quick Start
### 1. Hook Configuration File
```bash
# Project-wide (team shared)
.claude/settings.json
# User-specific (not shared)
.claude/settings.local.json
# Global (all projects)
~/.claude/settings.json
```
### 2. Simple Example - Log File Changes
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "echo \"$(date): Modified $TOOL_ARGS\" >> .claude/changes.log"
}
]
}
]
}
}
```
## Hook Types
| Event | When It Runs | Common Use |
|-------|--------------|-----------|
| SessionStart | Session begins | Inject project context |
| SessionEnd | Session ends | Cleanup, backups |
| PreToolUse | Before tool execution | Validation, permission checks |
| PostToolUse | After tool completes | Formatting, linting |
| UserPromptSubmit | User submits prompt | Logging, analytics |
| Notification | Claude sends notification | Desktop alerts |
| Stop | Agent finishes responding | Post-response processing |
## Core Concepts
### Matcher Patterns
```json
// Single tool
"matcher": "Write"
// Multiple tools (OR)
"matcher": "Write|Edit|Read"
// All tools
"matcher": "*"
// Git operations
"matcher": "Bash(git:*)"
```
### Exit Codes
```bash
# Success - Continue
exit 0
# Blocking Error - Stop operation
exit 2
# Non-Blocking Error - Continue
exit 1
```
### Environment Variables
```bash
$CLAUDE_PROJECT_DIR # Current project directory
$TOOL_NAME # Name of the tool being used
$TOOL_ARGS # Arguments passed to the tool
$HOOK_EVENT # Event type (PreToolUse, etc.)
```
## Common Use Cases
### Auto-Format on Save
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "cd $CLAUDE_PROJECT_DIR && npx prettier --write $TOOL_ARGS && exit 0"
}
]
}
]
}
}
```
### Security Validation
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if grep -qiE '(password|api[_-]?key|secret)' $TOOL_ARGS 2>/dev/null; then echo 'Error: Possible secret detected' >&2; exit 2; fi; exit 0",
"timeout": 30
}
]
}
]
}
}
```
### Test Before Commit
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "cd $CLAUDE_PROJECT_DIR && npm test -- --silent || (echo 'Tests failed' >&2; exit 2)",
"timeout": 120
}
]
}
]
}
}
```
For complete examples, see [examples.md](examples.md)
## Hook Configuration
### Basic Structure
```json
{
"type": "command",
"command": "your-command-here",
"timeout": 60 // Optional, default 60 seconds
}
```
### Multiple Hooks
Run several hooks in sequence:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $TOOL_ARGS"
},
{
"type": "command",
"command": "npx eslint --fix $TOOL_ARGS"
},
{
"type": "command",
"command": "git add $TOOL_ARGS"
}
]
}
]
}
}
```
### Conditional Execution
```json
{
"type": "command",
"command": "if [[ $TOOL_ARGS == *.js ]]; then npm run format $TOOL_ARGS; fi; exit 0"
}
```
## Settings File Hierarchy
**Load Order** (highest to lowest priority):
1. `.claude/settings.local.json` - Project, user-only (gitignored)
2. `.claude/settings.json` - Project, team-shared (in git)
3. `~/.claude/settings.json` - Global, user-only
**Use Cases**:
- **Global**: Personal preferences, universal logging
- **Project**: Team standards, project automation
- **Local**: Personal overrides, development experiments
## Testing Hooks
### Start Simple
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "echo 'Hook triggered for: $TOOL_ARGS' && exit 0"
}
]
}
]
}
}
```
### Test Exit Codes
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "echo 'This should block' >&2 && exit 2"
}
]
}
]
}
}
```
Try writing a file - should be blocked.
## Troubleshooting
| Problem | Solution |
|---------|----------|
| Hook not triggering | Check matcher pattern, restart Claude Code |
| Hook fails silently | Check exit codes (use 0 for success) |
| Command not found | Use full path: `/usr/local/bin/prettier` |
| Permission denied | `chmod +x .claude/hooks/script.sh` |
| Timeout | Increase timeout value or optimize command |
For detailed troubleshooting, see [troubleshooting.md](troubleshooting.md)
## Best Practices
### 1. Always Exit Explicitly
```bash
# Good
command && exit 0
# Bad
command
```
### 2. Use Timeouts
```json
{
"command": "npm test",
"timeout": 120 // Don't let tests run forever
}
```
### 3. Handle Errors Gracefully
```bash
if [ -f "$TOOL_ARGS" ]; then
process_file "$TOOL_ARGS"
else
echo "File not found" >&2
fi
exit 0 # Don't block on missing file
```
### 4. Use Scripts for Complex Logic
```json
// Bad - complex bash in JSON
{
"command": "if [ -f $TOOL_ARGS ]; then cat $TOOL_ARGS | grep pattern | wc -l; fi"
}
// Good - external script
{
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-file.sh $TOOL_ARGS"
}
```
### 5. Test Before Team Deployment
Test in `.claude/settings.local.json` before adding to `.claude/settings.json`.
## Security Considerations
### Validate Input
```bash
# Sanitize TOOL_ARGS
if [[ ! $TOOL_ARGS =~ ^[a-zA-Z0-9/_.-]+$ ]]; then
echo "Invalid file path" >&2
exit 2
fi
```
### Limit Permissions
```json
// Specific (good)
"matcher": "Write|Edit"
// Too broad (risky)
"matcher": "*"
```
### Avoid Destructive Commands
```bash
# Dangerous
rm -rf $TOOL_ARGS
# Safer
if [[ -f "$TOOL_ARGS" ]] && [[ "$TOOL_ARGS" != "/" ]]; then
rm "$TOOL_ARGS"
fi
```
## Resources
- [Complete Examples](examples.md) - Working hook configurations
- [Advanced Patterns](patterns.md) - Complex workflows
- [Troubleshooting Guide](troubleshooting.md) - Problem-solution reference
- [Official Documentation](https://docs.claude.com/en/docs/claude-code/hooks)
## Quick Reference Card
### Common Patterns
```json
// Format on save
"PostToolUse": [{"matcher": "Write|Edit", "hooks": [{"type": "command", "command": "prettier --write $TOOL_ARGS"}]}]
// Block secrets
"PreToolUse": [{"matcher": "Write", "hooks": [{"type": "command", "command": "grep -q 'secret' $TOOL_ARGS && exit 2 || exit 0"}]}]
// Log all activity
"PreToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "echo \"$TOOL_NAME: $TOOL_ARGS\" >> .claude/log && exit 0"}]}]
```
---
**Remember**: Hooks are powerful automation tools. Start simple, test thoroughly, use exit codes properly to control flow.

View File

@@ -0,0 +1,258 @@
# Complete Hook Examples
Working hook configurations for common scenarios.
## 1. Auto-Format on Save
Format files automatically after writing/editing:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "cd $CLAUDE_PROJECT_DIR && npx prettier --write $TOOL_ARGS && exit 0"
}
]
}
]
}
}
```
## 2. Security Validation
Block writes containing secrets:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if grep -qiE '(password|api[_-]?key|secret|sk-[a-zA-Z0-9]{48})' $TOOL_ARGS 2>/dev/null; then echo 'Error: Possible secret detected' >&2; exit 2; fi; exit 0",
"timeout": 30
}
]
}
]
}
}
```
## 3. Auto-Git on Changes
Automatically stage and commit changes:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "cd $CLAUDE_PROJECT_DIR && git add $TOOL_ARGS && git commit -m 'Auto-commit: Modified $TOOL_ARGS' && exit 0"
}
]
}
]
}
}
```
## 4. Test Before Commit
Run tests before allowing file writes:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "cd $CLAUDE_PROJECT_DIR && npm test -- --silent || (echo 'Tests failed, cannot save' >&2; exit 2)",
"timeout": 120
}
]
}
]
}
}
```
## 5. Inject Project Context
Load project info at session start:
```json
{
"hooks": {
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "cat << EOF\nProject: MyApp\nEnvironment: Production\nKey Files: src/config.js, .env.example\nCoding Standards: See CONTRIBUTING.md\nEOF"
}
]
}
]
}
}
```
## 6. Log All Activity
Track all tool usage:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "echo \"$(date '+%Y-%m-%d %H:%M:%S') - $TOOL_NAME - $TOOL_ARGS\" >> $CLAUDE_PROJECT_DIR/.claude/activity.log && exit 0"
}
]
}
]
}
}
```
## 7. Multiple Hooks Sequence
Format, lint, then stage:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "npx prettier --write $TOOL_ARGS"
},
{
"type": "command",
"command": "npx eslint --fix $TOOL_ARGS"
},
{
"type": "command",
"command": "git add $TOOL_ARGS"
}
]
}
]
}
}
```
## 8. Script-Based Hooks
Call external script for complex logic:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-write.sh $TOOL_ARGS",
"timeout": 60
}
]
}
]
}
}
```
**validate-write.sh**:
```bash
#!/bin/bash
file=$1
# Check file size
if [ -f "$file" ] && [ $(wc -c < "$file") -gt 1000000 ]; then
echo "Error: File too large" >&2
exit 2
fi
# Check for secrets
if grep -qiE '(password|api[_-]?key)' "$file" 2>/dev/null; then
echo "Error: Possible secret detected" >&2
exit 2
fi
exit 0
```
## 9. Conditional by File Type
Only format JavaScript files:
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "if [[ $TOOL_ARGS == *.js ]]; then npm run format $TOOL_ARGS; fi; exit 0"
}
]
}
]
}
}
```
## 10. Desktop Notifications
Alert when Claude needs attention:
```json
{
"hooks": {
"Notification": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"' && exit 0"
}
]
}
]
}
}
```
---
For advanced patterns, see [patterns.md](patterns.md)

View File

@@ -0,0 +1,254 @@
---
name: Claude Code Memory Specialist
description: Optimize and troubleshoot Claude Code memory files (CLAUDE.md) for efficiency, token management, and team collaboration. Use PROACTIVELY when memory isn't loading, context is bloated, optimizing existing memory files, or when users mention "CLAUDE.md", "memory file", or "project context". NOT for initial setup - use /init command first.
---
# Claude Code Memory Optimization & Troubleshooting
## When to Use This Skill
Use this skill when:
- Troubleshooting memory files that aren't loading
- Optimizing bloated CLAUDE.md files (>200 lines)
- Managing token consumption in project memory
- Setting up memory hierarchy (project/user/subfolder)
- Debugging why Claude isn't following instructions
- Organizing memory for team collaboration
Do NOT use this skill for:
- **Initial setup** - Use `/init` command instead
- Creating slash commands (use claude-command-expert skill)
- General Claude Code issues
**Important**: Always start with `/init` for initial project memory setup.
## Quick Reference: Memory Hierarchy
```
1. Enterprise Policy ~/.claude/enterprise/CLAUDE.md (highest priority)
2. Project Memory ./CLAUDE.md or ./.claude/CLAUDE.md
3. User Memory ~/.claude/CLAUDE.md
4. Subfolder Memory ./subfolder/CLAUDE.md
```
**Lookup Order**: Claude searches upward from current directory, loading all CLAUDE.md files found.
## Core Principles
### 1. Target Size: 100-200 Lines
**Why**: Each CLAUDE.md loaded consumes tokens in every conversation.
```markdown
# ❌ Bad (500+ lines)
Extensive documentation embedded inline
# ✓ Good (150 lines)
Core info + imports for details
```
### 2. Progressive Disclosure Pattern
```markdown
# CLAUDE.md (Core - always loaded)
Quick reference, critical rules, imports
# docs/architecture.md (Loaded on demand)
Detailed architecture information
# docs/style-guide.md (Loaded on demand)
Comprehensive coding standards
```
### 3. Use Specific, Emphatic Language
```markdown
# ❌ Weak
Use functional components
# ✓ Strong
IMPORTANT: ALL React components MUST be functional (no class components).
```
## Essential Structure
### Minimal Template (100 lines)
```markdown
# ProjectName
Brief description.
## Tech Stack
- Key technologies
- See @docs/tech-stack.md for details
## Common Commands
```bash
npm run dev # Start development
npm test # Run tests
```
## Conventions
- 2-space indentation
- ESLint + Prettier
- See @docs/style-guide.md
## IMPORTANT Rules
- YOU MUST run tests before commits
- Never commit secrets
- Update docs with code changes
```
For complete templates, see [templates.md](templates.md)
## Common Problems (Quick Fixes)
| Problem | Quick Fix |
|---------|-----------|
| Memory not loading | Check filename case: `CLAUDE.md` |
| Claude ignores rules | Add `IMPORTANT:` or `YOU MUST` |
| Too many tokens | Move details to @docs/ imports |
| Updates not working | Restart session or use `/memory` |
| Conflicting memories | Project wins over user (check hierarchy) |
For detailed troubleshooting, see [troubleshooting.md](troubleshooting.md)
## Optimization Quick Win
**Before (bloated)**:
```markdown
This project is a comprehensive platform built with React, Node.js, Express,
PostgreSQL... [extensive paragraph explaining everything]
```
**After (lean)**:
```markdown
Tech Stack: React + Node.js + PostgreSQL
See @docs/architecture.md for details
```
**Result**: 80% token reduction
For optimization patterns, see [patterns.md](patterns.md)
## File Locations
### Project (Team-Shared)
```bash
.claude/CLAUDE.md # Team standards (in git)
.claude/settings.json # Team configuration
```
### Personal (Not Shared)
```bash
.claude/CLAUDE.local.md # Personal overrides (gitignored)
~/.claude/CLAUDE.md # Global defaults
```
## Import Best Practices
### ✓ Do
```markdown
# CLAUDE.md
Quick reference content
For detailed architecture: @docs/architecture.md
For API reference: @docs/api-reference.md
```
### ❌ Don't
```markdown
# CLAUDE.md
@docs/a.md → @docs/b.md → @docs/c.md → @docs/d.md → @docs/e.md → @docs/f.md
# Max depth is 5, avoid deep chains
```
**Rules**:
- Max import depth: 5 levels
- No circular references
- Use relative paths for project files
- Keep import chains flat, not deep
## Quick Update Methods
### Method 1: # Shortcut (Fastest)
```bash
# Press # at input start
# Type your update
# Auto-adds to appropriate CLAUDE.md
```
### Method 2: /memory Command
```bash
/memory
# Opens memory management interface
```
### Method 3: Direct Edit
```bash
vim CLAUDE.md
# Then ask Claude to reload
```
## Emphasis Techniques
For critical rules:
```markdown
IMPORTANT: [Critical rule]
YOU MUST [mandatory action]
NEVER [forbidden action]
**Bold** for emphasis
ALL CAPS for maximum attention
```
## Testing Memory Effectiveness
### Quick Test
```markdown
# Add temporary marker to CLAUDE.md
**MEMORY TEST: If you see this, memory loaded correctly**
# Ask Claude: "What's the first line of your memory?"
# Should see marker, then remove it
```
## Team Setup Example
```bash
# .gitignore
.claude/CLAUDE.local.md # Personal only
.claude/settings.local.json # Personal settings
# .claude/CLAUDE.md (in git)
# Team Standards
@docs/architecture.md
@docs/conventions.md
IMPORTANT: All team members follow these standards.
## Git Workflow
1. Feature branch from develop
2. PR requires 2 approvals
3. Squash merge
## NEVER
- Commit directly to main
- Merge without tests passing
```
For team workflows, see [workflows.md](workflows.md)
## Resources
- [Memory File Templates](templates.md) - Ready-to-use CLAUDE.md templates
- [Troubleshooting Guide](troubleshooting.md) - Detailed problem-solution guide
- [Optimization Patterns](patterns.md) - Advanced token-saving techniques
- [Team Workflows](workflows.md) - Collaboration strategies
- [Official Documentation](https://docs.claude.com/en/docs/claude-code/memory)
---
**Remember**: Practice what we preach - keep memory lean (100-200 lines), be specific not vague, use imports for details, emphasize critical rules, test effectiveness.

View File

@@ -0,0 +1,557 @@
# Memory Optimization Patterns
Advanced techniques for token-efficient memory management.
## Pattern 1: Core + Imports Architecture
**Strategy**: Keep main CLAUDE.md minimal, import details on demand.
### Structure
```
project/
├── CLAUDE.md (100 lines - core)
├── docs/
│ ├── tech-stack.md
│ ├── architecture.md
│ ├── style-guide.md
│ └── api-reference.md
```
### CLAUDE.md (Core - Always Loaded)
```markdown
# MyProject
Quick reference for AI coding assistant.
## Tech Stack
- Backend: Node.js + Express + PostgreSQL
- Frontend: React + TypeScript + Tailwind
- Details: @docs/tech-stack.md
## Common Commands
```bash
npm run dev # Start dev server
npm test # Run tests
npm run build # Production build
```
## Coding Standards
- 2-space indentation
- ESLint + Prettier
- Full details: @docs/style-guide.md
## Architecture
- Microservices pattern
- See @docs/architecture.md
## IMPORTANT Rules
- YOU MUST run tests before commits
- Never commit secrets
- Update API docs with endpoint changes
```
**Token Cost**: ~400 tokens (loaded every conversation)
### docs/tech-stack.md (Detailed - Loaded on Demand)
```markdown
# Technology Stack
## Backend
- Node.js 20 LTS
- Express 4.18
- PostgreSQL 15
- Sequelize ORM
- Redis for caching
- JWT authentication
- bcrypt for passwords
[Extensive details, dependencies, versions, configuration...]
```
**Token Cost**: ~1500 tokens (loaded only when discussing tech stack)
### Benefits
- **Main memory stays lean**: 100 lines vs 500+
- **Details loaded contextually**: Only when needed
- **Easy to update**: Each doc has single focus
- **Team ownership**: Different people can own different docs
---
## Pattern 2: Subfolder Specialization
**Strategy**: Use subfolder memory for context-specific guidance.
### Directory Structure
```
myproject/
├── CLAUDE.md # Root - shared context
├── frontend/
│ ├── CLAUDE.md # Frontend-specific
│ └── src/
├── backend/
│ ├── CLAUDE.md # Backend-specific
│ └── src/
└── docs/
├── architecture.md
└── conventions.md
```
### Root CLAUDE.md
```markdown
# MyProject
Microservices e-commerce platform.
## Common Across All Areas
- Git workflow: feature branches + PRs
- Testing required before merge
- See @docs/architecture.md
## Subprojects
- `frontend/` - React app (see frontend/CLAUDE.md)
- `backend/` - API server (see backend/CLAUDE.md)
```
### frontend/CLAUDE.md (Loaded When Working in frontend/)
```markdown
# Frontend Context
- React 18 + TypeScript strict mode
- Component structure: Atomic Design
- Styling: Tailwind utility-first
- State: Redux Toolkit
## Component Patterns
@../docs/ui-patterns.md
## Testing
- Jest + React Testing Library
- Coverage > 80%
- Test user interactions, not implementation
```
### backend/CLAUDE.md (Loaded When Working in backend/)
```markdown
# Backend Context
- Express + TypeScript
- Database: PostgreSQL + Sequelize
- Auth: JWT + refresh tokens
- Caching: Redis
## API Patterns
@../docs/api-patterns.md
## Security
- All endpoints have rate limiting
- Input validation with Zod
- SQL injection protection via ORM
```
### When to Use
- Large monorepos
- Different tech stacks per area
- Team specialization (frontend/backend teams)
- Different conventions per module
---
## Pattern 3: User + Project Separation
**Strategy**: Personal preferences globally, project specifics locally.
### ~/.claude/CLAUDE.md (Personal - All Projects)
```markdown
# Personal Defaults
## Communication Style
- Explain decisions before acting
- Ask before destructive operations
- Show diffs for large changes
## Code Preferences
- Prefer functional programming
- Avoid premature optimization
- Comprehensive error handling
## Tools
- Git commit format: Conventional Commits
- Prefer `npm` over `yarn`
```
**Applies To**: Every project you work on
### ./CLAUDE.md (Project - Overrides Personal)
```markdown
# ProjectX
IMPORTANT: This legacy project uses OOP extensively (override FP preference).
Tech stack:
- Java Spring Boot
- MySQL
- jQuery (legacy frontend)
Common commands:
```bash
mvn clean install
mvn test
```
Conventions:
- CamelCase for classes
- snake_case for database
```
**Applies To**: Only this project, overrides personal preferences
### Benefits
- Consistent personal style across all projects
- Project-specific overrides when needed
- Easy onboarding to new projects
- Maintain personal workflow preferences
---
## Pattern 4: Team Collaboration
**Strategy**: Shared standards in git, personal overrides local.
### Setup
```bash
# Version control
.claude/CLAUDE.md # Team standards (in git)
.claude/settings.json # Team settings (in git)
# Local overrides
.claude/CLAUDE.local.md # Personal (gitignored)
.claude/settings.local.json # Personal (gitignored)
```
### .gitignore
```gitignore
# Personal overrides only
.claude/CLAUDE.local.md
.claude/settings.local.json
# Team files are tracked
# .claude/CLAUDE.md
# .claude/settings.json
```
### .claude/CLAUDE.md (Team - In Git)
```markdown
# Team Standards
IMPORTANT: All team members should follow these conventions.
## Git Workflow
1. Create feature branch: `feature/description`
2. PR to `develop` (not `main`)
3. 2 approvals required
4. Squash merge
## Code Review Checklist
- Tests pass locally
- Coverage > 80%
- No linter warnings
- Documentation updated
## Architecture Decisions
@docs/adr/ # Architecture Decision Records
## NEVER
- Commit directly to `main`
- Merge without tests passing
- Hardcode credentials
```
### .claude/CLAUDE.local.md (Personal - Gitignored)
```markdown
# My Personal Overrides
## Development Preferences
- Use Neovim for editing
- Prefer verbose logging during dev
- Run tests in watch mode
[Preferences that don't affect team]
```
### Benefits
- Consistent team standards
- Personal customization allowed
- Version-controlled team rules
- Built-in onboarding documentation
---
## Token Management Strategies
### Strategy 1: Measure Current Usage
```bash
# Estimate tokens (rough: chars ÷ 4)
wc -c CLAUDE.md | awk '{print $1/4}'
# Goal: < 5000 tokens (<20KB file)
# Count lines
wc -l CLAUDE.md
# Goal: 100-200 lines
# Find verbose sections (lines >100 chars)
grep -n "." CLAUDE.md | awk -F: 'length($2) > 100 {print NR": "$0}'
```
### Strategy 2: Lean Writing Techniques
#### Before (150 tokens)
```markdown
The application uses a microservices architecture where each service is
independently deployable and scalable. The services communicate via REST
APIs and message queues. This allows for better separation of concerns
and makes it easier to maintain and scale individual components.
```
#### After (30 tokens)
```markdown
Architecture: Microservices (REST + message queues)
- Independent deployment/scaling
- See @docs/architecture.md
```
**Reduction**: 80%
### Compression Techniques
1. **Bullet Points > Paragraphs**
- Lists are 50% more token-efficient
- Easier to scan
2. **Commands > Explanations**
- Show `npm test` instead of describing testing process
- Code is self-documenting
3. **Imports > Embedding**
- `@docs/api.md` costs 5 tokens
- Embedding API docs costs 2000 tokens
4. **Examples > Theory**
- One example worth 100 words
- Concrete beats abstract
### Strategy 3: Strategic Importing
```markdown
# Decision Tree
Is this info needed in 80%+ of sessions?
→ YES: Keep in CLAUDE.md
Is this info needed occasionally?
→ YES: Put in @docs/, reference from CLAUDE.md
Is this info needed rarely?
→ NO: Don't include, use web search or direct file read
```
### Example
```markdown
# CLAUDE.md (Always Loaded - ~400 tokens)
Core commands, key conventions, critical rules
# @docs/architecture.md (On Demand - ~1500 tokens)
Loaded only when discussing architecture
# @docs/api-reference.md (On Demand - ~2000 tokens)
Loaded only when working on APIs
# @docs/testing-guide.md (On Demand - ~800 tokens)
Loaded only when writing tests
# @docs/deployment.md (On Demand - ~600 tokens)
Loaded only when deploying
```
**Total**: 400 tokens/conversation instead of 5300 tokens
**Savings**: 92%
### Strategy 4: Regular Cleanup
Monthly review checklist:
```bash
# 1. Find outdated content
grep -i "deprecated\|old\|legacy\|TODO" CLAUDE.md
# 2. Check for redundant sections
# Look for repeated information
# 3. Identify candidates for @imports
# Sections >50 lines that aren't always needed
# 4. Verify all rules are current
# Test: does Claude follow each rule?
# 5. Measure improvement
# Before: X lines
# After: Y lines
# Reduction: Z%
```
---
## Advanced Patterns
### Dynamic Context Loading
```markdown
# CLAUDE.md
## Context Selection
When working on:
- **Frontend**: Read @frontend/CLAUDE.md
- **Backend**: Read @backend/CLAUDE.md
- **DevOps**: Read @docs/devops.md
- **Testing**: Read @docs/testing.md
- **Documentation**: Read @docs/writing-guide.md
Ask yourself: "What am I working on?" and load that context.
```
### Versioned Standards
```markdown
# CLAUDE.md
## Current Standards
API Version: v2
See @docs/api-v2.md
## Migration Guides
Upgrading from v1? See @docs/migration-v1-to-v2.md
## Deprecated
v1 API (deprecated, remove by Q1 2024)
Historical reference: @docs/api-v1-deprecated.md
```
### Role-Based Memory
```markdown
# CLAUDE.md
## Available Roles
You can act as different roles depending on the task:
- **Full-Stack Developer**: @docs/role-fullstack.md
- **Frontend Specialist**: @docs/role-frontend.md
- **Backend Specialist**: @docs/role-backend.md
- **DevOps Engineer**: @docs/role-devops.md
- **QA Engineer**: @docs/role-qa.md
Switch roles: "Act as [role name]"
```
### Conditional Instructions
```markdown
# CLAUDE.md
## Environment-Aware Behavior
### Development Environment
- Verbose logging OK
- Use local DB (localhost:5432)
- Mock external APIs
### Staging Environment
- Moderate logging
- Use staging DB
- Real external APIs (test keys)
### Production Environment
- Minimal logging
- Use RDS
- NEVER commit with console.log
- ALWAYS check deployment checklist
```
---
## Performance Optimization
### Before Optimization
```markdown
# CLAUDE.md (1000 lines, 4000 tokens)
[Everything embedded]
Average tokens per conversation: 4000
Cost per 1000 conversations: ~$80 (input tokens)
```
### After Optimization
```markdown
# CLAUDE.md (150 lines, 600 tokens)
[Core + imports]
# Imported when needed:
@docs/architecture.md (1500 tokens)
@docs/api.md (1200 tokens)
@docs/testing.md (800 tokens)
Average tokens per conversation: 600
+ Architecture discussions: +1500 (20% of conversations)
+ API work: +1200 (30% of conversations)
+ Testing: +800 (15% of conversations)
Weighted average: 600 + (1500×0.2) + (1200×0.3) + (800×0.15) = 1380 tokens
Cost per 1000 conversations: ~$27 (input tokens)
Savings: 66%
```
---
## Summary: Best Practices
1. **Target 100-200 lines** for main CLAUDE.md
2. **Use imports liberally** for detailed docs
3. **Write concisely**: bullets > paragraphs
4. **Be specific**: concrete > vague
5. **Emphasize critical rules**: IMPORTANT, YOU MUST, NEVER
6. **Organize by scope**: user vs project vs subfolder
7. **Measure regularly**: track token usage
8. **Clean monthly**: remove outdated content
9. **Test effectiveness**: verify Claude follows rules
10. **Version control team files**: track changes
**Goal**: Minimum tokens for maximum effectiveness.

View File

@@ -0,0 +1,406 @@
# Memory File Templates
Ready-to-use CLAUDE.md templates for different project types.
## Template 1: Minimal Project
For simple projects with straightforward requirements.
```markdown
# ProjectName
Brief description.
## Tech Stack
- Language/Framework
- Database
- Key libraries
## Common Commands
```bash
start-command
test-command
build-command
```
## Conventions
- Code style rule 1
- Code style rule 2
- Naming convention
## IMPORTANT
- Critical rule 1
- Critical rule 2
```
**Target Size**: ~50 lines
**Use For**: Small projects, prototypes, personal projects
---
## Template 2: Team Project
For collaborative projects with extensive documentation.
```markdown
# ProjectName
@docs/overview.md
## Quick Reference
### Tech Stack
@docs/tech-stack.md
### Common Commands
```bash
npm run dev
npm test
npm run build
```
### Coding Standards
- 2-space indentation
- ESLint + Prettier
- Full guide: @docs/style-guide.md
### Architecture
@docs/architecture.md
## IMPORTANT Team Rules
- YOU MUST create PR for all changes
- Tests must pass before merge
- Update docs with code changes
## Git Workflow
@docs/git-workflow.md
## NEVER
- Commit to main directly
- Merge without review
- Commit secrets
```
**Target Size**: ~100 lines
**Use For**: Team projects, open source, enterprise applications
---
## Template 3: Monorepo
For multi-package repositories.
```markdown
# MonorepoName
Multi-package repository.
## Structure
- `packages/frontend/` - React app → See frontend/CLAUDE.md
- `packages/backend/` - API server → See backend/CLAUDE.md
- `packages/shared/` - Common code
## Global Standards
- Node.js 20+
- pnpm workspaces
- Shared ESLint config
## Commands (from root)
```bash
pnpm install
pnpm test
pnpm run build
```
## Cross-Package
- Import from `@myapp/shared`
- See @docs/package-deps.md
## IMPORTANT
- Changes affecting multiple packages need full test suite
```
**Target Size**: ~80 lines
**Use For**: Monorepos, microservices, multi-tier applications
---
## Template 4: Personal Defaults
For ~/.claude/CLAUDE.md (applies to all your projects).
```markdown
# Personal Preferences
Applied to all my projects unless overridden.
## Communication
- Explain reasoning before acting
- Confirm before destructive ops
- Show diffs for large changes
## Code Style
- Functional programming preferred
- Descriptive variable names
- Comments for "why", not "what"
## Git
- Conventional Commits format
- Squash feature branches
## Testing
- Write tests alongside code
- Aim for 80%+ coverage
```
**Target Size**: ~50 lines
**Use For**: Personal global settings
---
## Template 5: Frontend Project
```markdown
# Frontend App
React/TypeScript application.
## Tech Stack
- React 18 + TypeScript
- Tailwind CSS
- State: Redux Toolkit
- Router: React Router v6
## Commands
```bash
npm run dev # Dev server (localhost:3000)
npm test # Jest + RTL
npm run build # Production build
npm run lint # ESLint
```
## Structure
- `src/components/` - React components
- `src/hooks/` - Custom hooks
- `src/store/` - Redux slices
- `src/utils/` - Helper functions
## Conventions
- Functional components only
- Custom hooks for logic reuse
- 2-space indentation
- Import order: external → internal → styles
## IMPORTANT
- All components need tests
- Accessibility: WCAG AA minimum
- No inline styles (use Tailwind)
```
**Target Size**: ~100 lines
**Use For**: React, Vue, Angular, or other SPA projects
---
## Template 6: Backend API
```markdown
# Backend API
Node.js/Express REST API.
## Tech Stack
- Express + TypeScript
- PostgreSQL + Sequelize
- Redis for caching
- JWT authentication
## Commands
```bash
npm run dev # Dev server (localhost:4000)
npm test # Jest
npm run migrate # Run migrations
npm run seed # Seed database
```
## Structure
- `src/routes/` - API endpoints
- `src/controllers/` - Business logic
- `src/models/` - Database models
- `src/middleware/` - Express middleware
- `src/utils/` - Helper functions
## Environment
- See `.env.example` for required vars
- Never commit `.env`
## IMPORTANT
- All endpoints need rate limiting
- Input validation required
- Error handling middleware
- Log security events
```
**Target Size**: ~110 lines
**Use For**: API servers, backend services
---
## Template 7: Python Project
```markdown
# Python Project
Python application using modern tooling.
## Tech Stack
- Python 3.11+
- uv for dependency management
- pytest for testing
- ruff for linting
## Commands
```bash
uv run python main.py # Run application
uv run pytest # Run tests
uv run ruff check . # Lint
```
## Structure
- `src/` - Application code
- `tests/` - Test files
- `pyproject.toml` - Project config
## Conventions
- Type hints required
- Docstrings for public APIs
- Follow PEP 8
- Max line length: 100
## IMPORTANT
- All functions need type hints
- Test coverage > 80%
- No bare `except:` clauses
```
**Target Size**: ~90 lines
**Use For**: Python applications, CLI tools, data science projects
---
## Customization Tips
### Adding Project-Specific Rules
```markdown
## IMPORTANT Project Rules
- YOU MUST [mandatory action]
- NEVER [forbidden action]
- ALWAYS [required practice]
```
### Adding Tech Stack Details
```markdown
## Tech Stack
- Backend: Node.js + Express
- Auth: JWT + refresh tokens
- ORM: Sequelize
- Validation: Zod
- Frontend: React + TypeScript
- State: Zustand
- Styling: Tailwind
- Forms: React Hook Form
```
### Adding Team Workflow
```markdown
## Git Workflow
1. Branch from `develop`
2. Name: `feature/description` or `fix/description`
3. PR requires 2 approvals
4. Squash merge to develop
5. Weekly releases to main
```
### Referencing External Docs
```markdown
## Documentation
- Architecture: @docs/architecture.md
- API Reference: @docs/api.md
- Contributing: @CONTRIBUTING.md
- Deployment: @docs/deployment.md
```
---
## Anti-Patterns to Avoid
### ❌ Too Verbose
```markdown
# Bad: 500 lines
This project is a comprehensive e-commerce platform that provides
users with the ability to browse products, add them to their cart,
and complete purchases securely. The architecture follows a microservices
pattern with separate services for user management, product catalog,
shopping cart, payment processing, and order fulfillment...
[400 more lines of detailed explanation]
```
### ✓ Concise with Imports
```markdown
# Good: 100 lines
E-commerce platform with microservices architecture.
Tech Stack: @docs/tech-stack.md
Architecture: @docs/architecture.md
Conventions: @docs/conventions.md
## Quick Start
```bash
npm run dev
```
```
### ❌ Vague Instructions
```markdown
# Bad
- Write clean code
- Follow best practices
- Be secure
```
### ✓ Specific Instructions
```markdown
# Good
IMPORTANT:
- All API endpoints MUST have rate limiting (100 req/min)
- Passwords MUST be hashed with bcrypt (min 10 rounds)
- Input validation MUST use Zod schemas
- SQL queries MUST use parameterized statements
```
---
## Quick Selection Guide
| Project Type | Template | Target Size |
|-------------|----------|-------------|
| Personal/Small | Minimal | ~50 lines |
| Team Project | Team | ~100 lines |
| Monorepo | Monorepo | ~80 lines |
| Frontend SPA | Frontend | ~100 lines |
| Backend API | Backend | ~110 lines |
| Python App | Python | ~90 lines |
| Global Settings | Personal Defaults | ~50 lines |
**General Rule**: Start with the appropriate template, customize for your needs, keep under 200 lines.

View File

@@ -0,0 +1,513 @@
# Memory Troubleshooting Guide
Detailed problem-solution reference for CLAUDE.md issues.
## Problem 1: Memory File Not Loading
**Symptoms**: Claude doesn't seem to remember project context, no awareness of CLAUDE.md contents.
### Diagnosis
```bash
# Check if file exists
ls -la CLAUDE.md
ls -la .claude/CLAUDE.md
ls -la ~/.claude/CLAUDE.md
# Check file permissions
ls -l CLAUDE.md
# Check current directory
pwd
```
### Common Causes & Solutions
#### Cause 1: Wrong Location
```bash
# ❌ Bad: Random location
/some/random/path/CLAUDE.md
# ✓ Good: Project root
./CLAUDE.md
# or
./.claude/CLAUDE.md
```
**Solution**: Move file to project root or `.claude/` directory.
#### Cause 2: Wrong Filename (Case-Sensitive!)
```bash
# ❌ Bad
claude.md
Claude.md
CLAUDE.MD
README.md
# ✓ Good
CLAUDE.md
```
**Solution**: Rename to exactly `CLAUDE.md` (all caps).
#### Cause 3: Syntax Errors in Imports
```markdown
# ❌ Bad: Broken import
@docs/nonexistent.md
# ✓ Good: Valid path
@docs/architecture.md
```
**Solution**: Verify all imported paths exist and are correct.
#### Cause 4: File Permissions
```bash
# Check permissions
ls -l CLAUDE.md
# If not readable, fix it
chmod 644 CLAUDE.md
```
### Verification Test
Add a temporary marker to CLAUDE.md:
```markdown
**MEMORY LOADED: This is a test marker**
```
Ask Claude: "What's the first line of your memory?"
If Claude sees the marker, memory is loading correctly.
Remove marker after test.
---
## Problem 2: Bloated Memory (Token Waste)
**Symptoms**: Context fills up quickly, slow responses, high costs, frequent compaction.
### Diagnosis
```bash
# Check file size
wc -l CLAUDE.md
# Goal: 100-200 lines max
# Count characters (rough token estimate: chars ÷ 4)
wc -c CLAUDE.md
# Goal: < 20KB
```
### Solution: Trim and Split
#### Before (Bloated - 500 lines)
```markdown
# Project Overview
This project is a comprehensive e-commerce platform built with React, Node.js,
Express, PostgreSQL, Redis, and Docker. The frontend uses React 18 with TypeScript
in strict mode, Tailwind CSS for styling, React Router for navigation, Redux Toolkit
for state management, and Axios for API calls. The backend uses Express.js with
TypeScript, Sequelize ORM for database access, JWT for authentication, bcrypt for
password hashing, and Redis for session management...
[400 more lines of verbose content]
```
#### After (Lean - 150 lines)
```markdown
# Tech Stack
- Frontend: React 18 + TypeScript + Tailwind
- Backend: Express + PostgreSQL + Redis
- Architecture: Microservices
- Details: @docs/tech-stack.md
## Common Commands
```bash
npm run dev # Local development
npm test # Run all tests
npm run build # Production build
```
## Key Conventions
- 2-space indentation
- Functional components only
- ESLint + Prettier
- 80% test coverage minimum
## IMPORTANT Rules
- YOU MUST run tests before committing
- Never commit .env files
- Always update API docs when adding endpoints
```
**Result**: 70% token reduction
### Compression Techniques
1. **Use Bullet Points, Not Paragraphs**
2. **Use Imports for Details**
3. **Show Commands, Not Explanations**
4. **Prefer Tables Over Text**
---
## Problem 3: Claude Not Following Instructions
**Symptoms**: Claude ignores rules in CLAUDE.md, doesn't follow conventions.
### Diagnosis
Check instruction specificity:
```markdown
# ❌ Too Vague (ignored)
- Write clean code
- Follow best practices
- Be careful with security
# ✓ Specific (followed)
- Use 2-space indentation (not tabs)
- All API endpoints must have rate limiting
- Hash passwords with bcrypt (min 10 rounds)
```
### Solution: Add Emphasis
#### Weak Instruction (Often Ignored)
```markdown
Use functional components in React.
Run tests before committing.
```
#### Strong Instruction (Followed)
```markdown
IMPORTANT: ALL React components MUST be functional (no class components).
YOU MUST run `npm test` and ensure all tests pass before any git commit.
```
### Emphasis Hierarchy
1. `ALL CAPS` - Maximum attention
2. `IMPORTANT:` - Critical rules
3. `YOU MUST` - Mandatory actions
4. `NEVER` - Forbidden actions
5. **Bold** - Standard emphasis
6. Regular text - General info
### Example: Strong Rules Section
```markdown
## IMPORTANT Project Rules
YOU MUST:
- Run full test suite before every commit
- Get 2 PR approvals before merging
- Update API documentation when adding endpoints
NEVER:
- Commit directly to main branch
- Merge code with failing tests
- Hardcode API keys or secrets
ALWAYS:
- Use environment variables for config
- Include error handling in all async functions
- Write tests for new features
```
---
## Problem 4: Memory Updates Not Reflected
**Symptoms**: Changes to CLAUDE.md don't take effect in current session.
### Solutions
#### Method 1: Quick Add (# Shortcut)
```bash
# At input prompt, press # first
# Type: Use snake_case for Python functions
# Claude auto-adds to appropriate CLAUDE.md
```
**Best For**: Quick single-line updates
#### Method 2: /memory Command
```bash
/memory
# Opens memory management interface
```
**Best For**: Reviewing and editing existing memory
#### Method 3: Direct Edit + Reload
```bash
# Edit the file
vim CLAUDE.md
# Then explicitly ask Claude
"Please re-read CLAUDE.md"
```
**Best For**: Major updates or reorganization
#### Method 4: Session Restart (Most Reliable)
```bash
# Close and reopen Claude Code
# Or Ctrl+C to exit CLI
```
**Best For**: When other methods don't work
---
## Problem 5: Too Many Memory Files
**Symptoms**: Conflicting instructions, unclear hierarchy, unexpected behavior.
### Diagnosis
```bash
# Find all CLAUDE.md files
find . -name "CLAUDE.md"
find ~ -name "CLAUDE.md"
# Check which directory you're in
pwd
```
### Understanding Priority
Higher priority wins on conflicts:
```
1. ~/.claude/enterprise/CLAUDE.md # Organization policy (highest)
2. ./CLAUDE.md # Current project
3. ~/.claude/CLAUDE.md # Your personal defaults
4. ./subfolder/CLAUDE.md # Subfolder overrides
```
### Solution: Organize Properly
#### Global Personal (~/.claude/CLAUDE.md)
```markdown
# Personal Defaults
## Communication Style
- Explain decisions before acting
- Ask before destructive operations
## Code Preferences
- Prefer functional programming
- Avoid premature optimization
```
**Use For**: Universal personal preferences
#### Project Root (./CLAUDE.md)
```markdown
# MyProject
@docs/tech-stack.md
@docs/conventions.md
IMPORTANT: This project uses OOP (override personal FP preference).
Tech Stack: Java + Spring Boot
```
**Use For**: Project-specific standards (overrides personal)
#### Subfolder (./frontend/CLAUDE.md)
```markdown
# Frontend Context
- React 18 + TypeScript
- Component structure: Atomic Design
- See @../docs/ui-patterns.md
```
**Use For**: Directory-specific context (loaded when in that directory)
---
## Problem 6: Import Loops or Errors
**Symptoms**: "Import depth exceeded", circular import error, or infinite loading.
### Import Rules
```markdown
# ❌ Bad: Too Deep
CLAUDE.md
@docs/a.md (depth 1)
@docs/b.md (depth 2)
@docs/c.md (depth 3)
@docs/d.md (depth 4)
@docs/e.md (depth 5)
@docs/f.md (depth 6 - FAILS!)
# ✓ Good: Flat Structure
CLAUDE.md
@docs/architecture.md
@docs/conventions.md
@docs/testing.md
@docs/deployment.md
# ❌ Bad: Circular Import
CLAUDE.md → @docs/a.md → @docs/b.md → @docs/a.md (LOOP!)
# ✓ Good: No Circles
CLAUDE.md → @docs/a.md → @docs/c.md
@docs/b.md → @docs/c.md
```
### Solution: Restructure Imports
**Before (Deep Chain)**:
```markdown
# CLAUDE.md
@docs/main.md
# docs/main.md
@project/overview.md
# project/overview.md
@details/architecture.md
# details/architecture.md
[content]
```
**After (Flat)**:
```markdown
# CLAUDE.md
@docs/overview.md
@docs/architecture.md
@docs/conventions.md
```
### Best Practices
- **Max depth**: 5 levels
- **No circular references**
- **Prefer flat over deep**
- **Use relative paths** for project files: `@docs/file.md`
- **Use absolute paths** for global files: `@~/.claude/shared.md`
---
## Problem 7: Conflicting Team Instructions
**Symptoms**: Different team members get different behavior from Claude.
### Diagnosis
```bash
# Check for local overrides
ls .claude/CLAUDE.local.md
ls .claude/settings.local.json
# Check git-tracked files
git ls-files | grep -i claude
```
### Solution: Proper Separation
#### Team-Shared (.claude/CLAUDE.md - in git)
```markdown
# Team Standards
IMPORTANT: All team members follow these conventions.
## Git Workflow
1. Branch from `develop`
2. PR requires 2 approvals
3. Squash merge
## Coding Standards
@docs/style-guide.md
## NEVER
- Commit directly to main
- Merge without tests
```
#### Personal (.claude/CLAUDE.local.md - gitignored)
```markdown
# My Personal Preferences
[Individual customizations that don't affect team]
```
#### .gitignore Setup
```gitignore
# Personal files (not shared)
.claude/CLAUDE.local.md
.claude/settings.local.json
```
---
## Quick Reference: Diagnostic Checklist
When memory isn't working, check:
```markdown
- [ ] File named exactly "CLAUDE.md" (case-sensitive)
- [ ] File in project root or .claude/ directory
- [ ] File has read permissions (chmod 644)
- [ ] Valid markdown syntax
- [ ] Imports use correct paths
- [ ] No circular import loops
- [ ] Import depth ≤ 5 levels
- [ ] File size < 20KB (~200 lines)
- [ ] Instructions are specific, not vague
- [ ] Used emphasis for critical rules
- [ ] No syntax errors in code blocks
- [ ] Tried session restart
- [ ] Verified loading with test marker
```
---
## Getting Help
If problems persist:
1. **Verify File Loading**: Add test marker, ask Claude to read it
2. **Check Hierarchy**: Understand which files are being loaded
3. **Review Syntax**: Ensure valid markdown and imports
4. **Simplify First**: Start with minimal CLAUDE.md, add back gradually
5. **Restart Session**: Most reliable way to reload changes
For further assistance, see [Official Documentation](https://docs.claude.com/en/docs/claude-code/memory).

View File

@@ -0,0 +1,624 @@
# Team Collaboration Workflows
Strategies for using CLAUDE.md in team environments.
## Workflow 1: Onboarding New Developer
### Goal
Get new team members productive immediately using CLAUDE.md as primary documentation.
### Setup
```bash
# Project repository structure
myproject/
├── .claude/
│ └── CLAUDE.md # Team standards
├── docs/
│ ├── architecture.md
│ ├── conventions.md
│ └── getting-started.md
└── README.md
```
### Process
#### Step 1: Clone Repository
```bash
git clone repo
cd myproject
```
#### Step 2: Claude Reads Memory Automatically
New developer opens Claude Code - memory loads automatically.
#### Step 3: Ask Claude for Orientation
```
New Dev: "What's this project about?"
Claude (using CLAUDE.md): "This is an e-commerce platform using:
- Tech Stack: React + Node.js + PostgreSQL
- Architecture: Microservices pattern
- Key directories: src/api, src/components, src/services
- Start with: npm install && npm run dev
- See docs/getting-started.md for detailed setup"
```
#### Step 4: Productive Immediately
New developer can:
- Ask Claude about any convention
- Get help with setup issues
- Understand architecture decisions
- Follow team standards automatically
### Benefits
- **Zero onboarding docs to read**: Claude explains everything
- **Consistent answers**: Same info for all team members
- **Always up to date**: Update CLAUDE.md, everyone gets it
- **Interactive learning**: Ask questions, get context-aware answers
---
## Workflow 2: Updating Team Standards
### Goal
Change team conventions and have all developers adopt them immediately.
### Scenario
Team decides to switch from npm to pnpm.
### Process
#### Step 1: Update CLAUDE.md
```bash
# Edit .claude/CLAUDE.md
sed -i 's/npm run/pnpm run/g' .claude/CLAUDE.md
sed -i 's/npm test/pnpm test/g' .claude/CLAUDE.md
sed -i 's/npm install/pnpm install/g' .claude/CLAUDE.md
```
Update commands section:
```markdown
## Common Commands
```bash
pnpm run dev # Start development server
pnpm test # Run test suite
pnpm run build # Production build
```
IMPORTANT: This project uses pnpm, not npm.
```
#### Step 2: Commit Change
```bash
git add .claude/CLAUDE.md
git commit -m "docs: switch package manager from npm to pnpm"
git push
```
#### Step 3: Team Pulls Update
```bash
# Each developer
git pull
```
#### Step 4: Claude Uses New Standard
Next time anyone asks Claude to run a command, it uses pnpm automatically.
### Benefits
- **Immediate adoption**: No need to notify team
- **No context switching**: Claude reminds developers
- **Version controlled**: Track convention changes
- **Rollback if needed**: Git history
---
## Workflow 3: Feature-Specific Context
### Goal
Provide context for specific feature areas without bloating root memory.
### Structure
```
project/
├── CLAUDE.md # Root context
├── features/
│ ├── auth/
│ │ ├── CLAUDE.md # Auth-specific context
│ │ └── src/
│ ├── payments/
│ │ ├── CLAUDE.md # Payment-specific context
│ │ └── src/
│ └── notifications/
│ ├── CLAUDE.md # Notification-specific context
│ └── src/
```
### Root CLAUDE.md
```markdown
# MyProject
## Feature Areas
Each feature has specific context:
- `features/auth/` - Authentication (see auth/CLAUDE.md)
- `features/payments/` - Payment processing (see payments/CLAUDE.md)
- `features/notifications/` - Notification system (see notifications/CLAUDE.md)
When working in a feature directory, Claude loads that context automatically.
```
### features/auth/CLAUDE.md
```markdown
# Authentication Feature
## Implementation
- JWT + refresh tokens
- Token lifetime: 15min access, 7d refresh
- Password requirements: min 12 chars, bcrypt rounds: 12
## Key Files
- `src/auth.service.ts` - Core auth logic
- `src/jwt.util.ts` - Token generation/validation
- `src/password.util.ts` - Password hashing
## IMPORTANT Security Rules
- Passwords MUST be hashed with bcrypt (min 12 rounds)
- Tokens MUST have expiration
- MFA required for admin accounts
- Log all authentication failures
## Testing
- Unit tests: `tests/auth.test.ts`
- Integration: `tests/auth.integration.test.ts`
- All auth changes need security review
```
### Usage
```bash
# Developer working on auth feature
cd features/auth
# Claude now has both root context + auth-specific context
# Can answer auth-specific questions with full context
```
### Benefits
- **Contextual memory**: Right info at right time
- **No bloat**: Root memory stays lean
- **Feature ownership**: Each team owns their feature docs
- **Isolated changes**: Update feature context independently
---
## Workflow 4: Architecture Decision Records (ADR)
### Goal
Document why decisions were made and have Claude reference them.
### Structure
```
project/
├── .claude/
│ └── CLAUDE.md
└── docs/
└── adr/
├── 001-use-postgresql.md
├── 002-microservices-architecture.md
├── 003-graphql-over-rest.md
└── template.md
```
### CLAUDE.md Reference
```markdown
# MyProject
## Architecture Decisions
All architectural decisions are documented in ADRs.
See @docs/adr/ for all decisions.
When making architectural changes:
1. Propose via ADR
2. Get team review
3. Update CLAUDE.md if needed
```
### ADR Format (docs/adr/003-graphql-over-rest.md)
```markdown
# 3. Use GraphQL Instead of REST
Date: 2024-01-15
Status: Accepted
## Context
Need API design pattern for new features.
## Decision
Use GraphQL for new APIs, maintain REST for legacy.
## Consequences
**Positive:**
- Flexible queries
- Reduced over-fetching
- Strong typing
**Negative:**
- Learning curve
- More complex caching
## Implementation
See @docs/graphql-guide.md
```
### Usage
Developer asks Claude: "Why do we use GraphQL?"
Claude references ADR and explains the decision context.
### Benefits
- **Historical context**: Understand past decisions
- **Onboarding**: New devs understand "why"
- **Consistency**: Reference when making new decisions
- **Change tracking**: Git history of decisions
---
## Workflow 5: Code Review Automation
### Goal
Use CLAUDE.md to establish review standards, have Claude enforce them.
### .claude/CLAUDE.md
```markdown
# MyProject
## Code Review Checklist
Before approving PRs, verify:
### Functionality
- [ ] Tests pass locally
- [ ] New features have tests
- [ ] Coverage > 80%
### Code Quality
- [ ] Follows style guide
- [ ] No linter warnings
- [ ] Functions < 50 lines
- [ ] Clear variable names
### Security
- [ ] No hardcoded secrets
- [ ] Input validation present
- [ ] SQL uses parameterized queries
- [ ] Auth checks on protected routes
### Documentation
- [ ] API changes documented
- [ ] Complex logic has comments
- [ ] README updated if needed
## NEVER Approve PRs With
- Failing tests
- Linter errors
- Hardcoded credentials
- console.log statements
```
### Usage in Review
```
Reviewer: "Review this PR: #123"
Claude (reads PR, checks against CLAUDE.md):
"Reviewing PR #123 against team standards:
✓ Tests pass
✓ Coverage maintained (85%)
✗ Found console.log in auth.ts:42
✗ Missing input validation in user.controller.ts:67
✗ API changes not documented
Recommendation: Request changes before approval.
Specific issues:
1. auth.ts:42 - Remove console.log (violates standards)
2. user.controller.ts:67 - Add Zod validation for email field
3. Missing: Update API.md with new /users/profile endpoint
```
### Benefits
- **Consistent reviews**: Same standards for all reviewers
- **Automated checks**: Claude catches issues
- **Teaching tool**: Shows reviewers what to look for
- **Living standards**: Update CLAUDE.md as standards evolve
---
## Workflow 6: Multi-Repository Consistency
### Goal
Maintain consistent standards across multiple repositories.
### Setup
```
~/.claude/CLAUDE.md # Personal + org standards
org-repo-1/
└── .claude/
└── CLAUDE.md # Repo-specific (imports personal)
org-repo-2/
└── .claude/
└── CLAUDE.md # Repo-specific (imports personal)
```
### ~/.claude/CLAUDE.md (Shared Across All Repos)
```markdown
# Organization Standards
Applied to all our repositories.
## Git Workflow
- Branch from main
- Squash merge PRs
- Conventional commits
## Code Quality
- Tests required
- Linting enforced
- 80% coverage minimum
## Security
- No hardcoded secrets
- Input validation required
- Security review for auth changes
## Documentation
@~/docs/org-standards.md
```
### org-repo-1/.claude/CLAUDE.md
```markdown
# Repo 1
Frontend React application.
## Repo-Specific
- React 18 + TypeScript
- Tailwind for styling
- Jest + RTL for testing
## Tech Stack
@docs/tech-stack.md
All organization standards apply (see ~/.claude/CLAUDE.md)
```
### Benefits
- **DRY**: Don't repeat org standards in each repo
- **Consistency**: Same standards everywhere
- **Easy updates**: Change once, applies to all
- **Repo specifics**: Each repo adds its unique context
---
## Workflow 7: Gradual Migration
### Goal
Migrate existing documentation to CLAUDE.md progressively.
### Phase 1: Start Small (Week 1)
```markdown
# CLAUDE.md (50 lines)
## Common Commands
```bash
npm run dev
npm test
npm run build
```
## Key Conventions
- 2-space indentation
- ESLint + Prettier
```
### Phase 2: Add Core Info (Week 2-3)
```markdown
# CLAUDE.md (100 lines)
[Previous content]
## Tech Stack
- Backend: Node.js + Express
- Frontend: React + TypeScript
- Database: PostgreSQL
## Architecture
@docs/architecture.md
## IMPORTANT Rules
- Tests required before merge
- No commits to main
```
### Phase 3: Import Existing Docs (Week 4)
```markdown
# CLAUDE.md (150 lines)
[Previous content]
## Detailed Documentation
- Architecture: @docs/architecture.md
- API Reference: @docs/api.md
- Style Guide: @docs/style-guide.md
- Testing: @docs/testing-guide.md
```
### Phase 4: Optimize (Ongoing)
- Move inline content to imports
- Compress verbose sections
- Test with team
- Gather feedback
- Iterate
### Benefits
- **Low risk**: Start small, grow gradually
- **Learn as you go**: Discover what works
- **Team adoption**: Give team time to adjust
- **Continuous improvement**: Iterate based on usage
---
## Workflow 8: Cross-Team Collaboration
### Goal
Enable multiple teams to work on shared codebase with team-specific context.
### Structure
```
monorepo/
├── .claude/
│ └── CLAUDE.md # Shared standards
├── packages/
│ ├── frontend/
│ │ └── .claude/
│ │ └── CLAUDE.md # Frontend team context
│ └── backend/
│ └── .claude/
│ └── CLAUDE.md # Backend team context
```
### Root .claude/CLAUDE.md (Shared)
```markdown
# Monorepo Standards
## Shared Across All Teams
- pnpm workspaces
- Conventional commits
- Test coverage > 80%
- Code review required
## Team-Specific Context
- Frontend: packages/frontend/CLAUDE.md
- Backend: packages/backend/CLAUDE.md
When in a package directory, team-specific context loads automatically.
```
### packages/frontend/.claude/CLAUDE.md
```markdown
# Frontend Team Context
**Team**: Frontend (React specialists)
## Our Stack
- React 18 + TypeScript
- Tailwind + shadcn/ui
- Zustand for state
- React Query for data
## Our Conventions
- Atomic design pattern
- Mobile-first responsive
- Dark mode support required
## Our PR Process
- 2 frontend developers must approve
- Accessibility check required
- Browser testing checklist
## Contact
- Lead: @alice
- Questions: #frontend-team
```
### packages/backend/.claude/CLAUDE.md
```markdown
# Backend Team Context
**Team**: Backend (API specialists)
## Our Stack
- Node.js + Express + TypeScript
- PostgreSQL + Prisma
- Redis caching
- JWT authentication
## Our Conventions
- RESTful API design
- OpenAPI documentation
- Rate limiting all endpoints
## Our PR Process
- 2 backend developers must approve
- Security review for auth changes
- Load testing for perf-critical paths
## Contact
- Lead: @bob
- Questions: #backend-team
```
### Benefits
- **Team autonomy**: Each team defines their standards
- **Shared foundations**: Common org-wide rules
- **Context switching**: Right context automatically
- **Cross-team awareness**: See other team's standards
---
## Summary: Team Success Patterns
1. **Start Simple**: Begin with 50-100 lines, grow organically
2. **Version Control**: Track changes, review updates
3. **Team Buy-In**: Get feedback, iterate together
4. **Clear Ownership**: Assign responsibility for updates
5. **Regular Reviews**: Monthly check for outdated content
6. **Measure Impact**: Track onboarding time, review consistency
7. **Document Decisions**: Use ADRs for architecture
8. **Progressive Disclosure**: Core in CLAUDE.md, details in imports
9. **Feature Contexts**: Use subfolders for feature-specific guidance
10. **Cross-Repo Standards**: Share common standards across projects
**Goal**: Make CLAUDE.md the single source of truth for team development practices.

View File

@@ -1,6 +1,6 @@
---
name: Claude Code Plugin Developer
description: Create and structure Claude Code plugins with commands, agents, skills, hooks, and MCP servers. Use when building plugins for Claude Code, setting up plugin structure, or configuring plugin manifests.
description: Create and structure Claude Code plugins with commands, agents, skills, hooks, and MCP servers. Use PROACTIVELY when building plugins for Claude Code, setting up plugin structure, configuring plugin manifests, or when users mention "create a plugin", "package for distribution", or "plugin marketplace". NOT for creating individual components in isolation.
---
# Claude Code Plugin Development
@@ -186,66 +186,7 @@ Create `.mcp.json` for external tools:
## Complete Plugin Example
### File Structure
```
weather-plugin/
├── .claude-plugin/
│ └── plugin.json
├── commands/
│ └── weather.md
├── agents/
│ └── forecast-analyst.md
├── skills/
│ └── weather-api/
│ └── SKILL.md
└── README.md
```
### plugin.json
```json
{
"name": "weather-plugin",
"description": "Weather forecasting and analysis tools",
"version": "1.0.0",
"author": {
"name": "Weather Team"
}
}
```
### commands/weather.md
```markdown
---
description: Get current weather for a location
argument-hint: <location>
---
Get the current weather conditions for: $ARGUMENTS
Include:
- Temperature
- Conditions
- Humidity
- Wind speed
```
### agents/forecast-analyst.md
```markdown
---
description: Analyzes weather patterns and forecasts
tools: [WebFetch, Read]
---
You are a weather analysis specialist. When asked about weather:
1. Gather current conditions
2. Analyze patterns
3. Provide forecast insights
4. Suggest appropriate actions
```
See [examples.md](examples.md) for full working plugin examples including weather-plugin, git-tools, and api-plugin.
## Distribution & Installation
@@ -459,56 +400,14 @@ allowed-tools: Read(src/**), Grep(src/**)
## Plugin Template
Use this as a starting point:
```bash
#!/bin/bash
# create-plugin.sh <plugin-name>
PLUGIN_NAME=$1
mkdir -p "$PLUGIN_NAME"/{.claude-plugin,commands,agents,skills,hooks}
cat > "$PLUGIN_NAME/.claude-plugin/plugin.json" << EOF
{
"name": "$PLUGIN_NAME",
"description": "TODO: Add description",
"version": "0.1.0",
"author": {
"name": "TODO: Add author"
}
}
EOF
cat > "$PLUGIN_NAME/README.md" << EOF
# $PLUGIN_NAME
TODO: Add plugin description
## Installation
\`\`\`
/plugin install $PLUGIN_NAME@marketplace
\`\`\`
## Features
TODO: List features
## Usage
TODO: Add usage examples
EOF
echo "Plugin structure created in $PLUGIN_NAME/"
```
See [templates.md](templates.md) for ready-to-use templates and the create-plugin.sh script.
## Resources
- [Official Plugin Documentation](https://docs.claude.com/en/docs/claude-code/plugins)
- [Slash Commands Guide](../claude-code-slash-commands/SKILL.md)
- [Hooks Guide](../claude-code-hooks/SKILL.md)
- [Agent Skills Guide](../claude-skills/SKILL.md)
- [Slash Commands Guide](../claude-command-expert/SKILL.md)
- [Hooks Guide](../claude-hooks/SKILL.md)
- [Agent Skills Guide](../claude-skill/SKILL.md)
## Quick Reference

View File

@@ -1,6 +1,6 @@
---
name: Skill Creator
description: Guide for creating effective Claude Agent Skills with best practices, structure guidelines, and progressive disclosure principles. Use when building new skills or improving existing ones.
description: Guide for creating effective Claude Agent Skills with best practices, structure guidelines, and progressive disclosure principles. Use PROACTIVELY when creating new skills, refining existing skills, debugging why skills don't trigger, optimizing SKILL.md files for token efficiency, or when users mention "create a skill", "skill not working", or "skill.md". NOT for using existing skills.
---
# Skill Creation Best Practices

View File

@@ -0,0 +1,362 @@
---
name: Claude Code Subagent Specialist
description: Refine and troubleshoot Claude Code subagents by optimizing prompts, tool access, descriptions, and performance. Use PROACTIVELY when improving existing subagents, debugging activation issues, optimizing delegation patterns, or when users mention "subagent not working", "agent won't trigger", or "refine agent". NOT for initial creation - use /agents command first.
---
# Claude Code Subagent Refinement & Troubleshooting
## When to Use This Skill
Use this skill when:
- Refining existing subagent prompts for better performance
- Troubleshooting why a subagent isn't activating
- Optimizing tool access and permissions
- Improving subagent descriptions for better delegation
- Debugging context management issues
- Converting ad-hoc workflows to reusable subagents
Do NOT use this skill for:
- **Initial creation** - Use `/agents` command instead (interactive UI)
- Creating slash commands (use claude-command-expert skill)
- General Claude Code troubleshooting
**Important**: Always start with `/agents` to create subagents. Use this skill to refine them afterward.
## Quick Reference: Subagent Structure
```yaml
---
name: agent-name # Lowercase, kebab-case
description: When to use # Triggers automatic delegation
tools: Tool1, Tool2 # Optional: omit to inherit all
model: sonnet # Optional: sonnet/opus/haiku/inherit
---
System prompt defining role, capabilities, and behavior.
```
**Locations**:
- Project: `.claude/agents/` (highest priority)
- User: `~/.claude/agents/` (shared across projects)
- Plugin: `agents/` in plugin directory
## Common Problems (Quick Solutions)
### Problem 1: Subagent Never Activates
**Diagnosis**: Check description specificity
```yaml
# ❌ Too vague (ignored)
---
description: Helper agent
---
# ✓ Specific (works)
---
description: Analyze code for security vulnerabilities including SQL injection, XSS, authentication flaws, and hardcoded secrets. Use PROACTIVELY when reviewing code for security issues.
---
```
**Fix**: Make description specific with trigger words + "PROACTIVELY" or "MUST BE USED"
### Problem 2: Wrong Tool Access
**Diagnosis**: Check tool configuration
```yaml
# ❌ Too permissive
---
name: security-analyzer
# (inherits all tools)
---
# ✓ Restricted to needs
---
name: security-analyzer
tools: Read, Grep, Glob
---
```
**Tool Access Strategies**:
- **Inherit All**: Omit `tools` field (full flexibility)
- **Read-Only**: `tools: Read, Grep, Glob` (analysis/review)
- **Specific**: `tools: Read, Write, Edit, Bash(npm test:*)` (implementation)
- **No Files**: `tools: WebFetch, WebSearch` (research only)
### Problem 3: Poor Output Quality
**Diagnosis**: System prompt needs structure
```markdown
# ❌ Vague
You review code for issues.
# ✓ Structured
You are a senior code reviewer specializing in production-ready code quality.
## Your Responsibilities
1. **Logic & Correctness**: Verify algorithms, edge cases
2. **Code Quality**: SRP, DRY, meaningful naming
3. **Security**: Injection vulnerabilities, auth checks
4. **Performance**: O(n²) algorithms, resource cleanup
## Output Format
For each issue:
- **Severity**: Critical/High/Medium/Low
- **Location**: file:line
- **Issue**: Clear description
- **Fix**: Specific code example
## Constraints
- Only actionable issues
- Focus on high-impact problems
```
For detailed system prompt patterns, see [patterns.md](patterns.md)
## Description Best Practices
### Template
```yaml
description: [Action verb] [domain/task] [including capabilities]. Use [trigger]. PROACTIVELY when [scenario].
```
### Examples
**✓ Good**:
```yaml
description: Analyze Python code for performance bottlenecks including O(n²) algorithms, memory leaks, and inefficient database queries. Use PROACTIVELY when optimizing Python applications.
description: Generate comprehensive API documentation from code including endpoints, parameters, responses, and examples. Use when documenting REST or GraphQL APIs.
description: Review frontend code for accessibility issues following WCAG 2.1 AA standards. MUST BE USED for all UI component changes.
```
**❌ Avoid**:
```yaml
description: Helps with coding
description: Python utilities
description: Security checker
```
## Model Selection Guide
| Model | Use For | Avoid For |
|-------|---------|-----------|
| haiku | Simple transforms, quick checks | Complex reasoning, creativity |
| sonnet | General tasks, balanced quality | When opus needed |
| opus | Complex architecture, creative work | Simple/repetitive (costly) |
| inherit | Task matches main thread | Need different capability |
**Default**: sonnet (best balance)
## Testing Subagents
### Test Plan Template
```markdown
# Positive Tests (Should Activate)
1. "Create REST endpoint for user auth"
Expected: Activates
Actual: ___
2. "Add GraphQL mutation for profile"
Expected: Activates
Actual: ___
# Negative Tests (Should NOT Activate)
1. "Write unit tests for API"
Expected: Does not activate (testing concern)
Actual: ___
2. "Review API security"
Expected: Does not activate (security concern)
Actual: ___
## Results
- Precision: X% (correct activations / total activations)
- Recall: Y% (correct activations / should activate)
```
For complete testing strategies, see [testing.md](testing.md)
## System Prompt Structure
```markdown
# Role Definition
You are a [role] specializing in [domain].
## Responsibilities
1. [Primary responsibility]
2. [Secondary responsibility]
3. [Additional responsibilities]
## Process
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Output Format
[Specific structure required]
## Examples
### Good Example
[Show what good looks like]
### Bad Example
[Show what to avoid]
## Constraints
- [Important limitation]
- [Another constraint]
```
## Optimization Patterns
### Pattern 1: Role-Based Pipeline
Specialized agents for each workflow stage:
```yaml
# Spec Agent (opus)
---
name: product-spec-writer
description: Create detailed product specifications from user requirements
tools: Read, Write, WebSearch
model: opus
---
# Architect Agent (opus)
---
name: solution-architect
description: Design system architecture from product specs
tools: Read, Write, Grep, Glob
model: opus
---
# Implementer Agent (sonnet)
---
name: code-implementer
description: Implement features from architectural designs
tools: Read, Write, Edit, Bash(npm test:*)
model: sonnet
---
```
### Pattern 2: Domain Specialists
```yaml
# Frontend Specialist
---
name: frontend-specialist
description: React/TypeScript UI development and component design. Use PROACTIVELY for frontend work.
tools: Read, Write, Edit, Grep, Bash(npm:*)
---
You are a React/TypeScript expert specializing in modern frontend development.
## Tech Stack
- React 18+ with hooks
- TypeScript (strict mode)
- Tailwind CSS
- Component-driven architecture
## Principles
- Functional components only
- Custom hooks for logic reuse
- Accessibility (WCAG AA)
- Performance (lazy loading, memoization)
```
For more patterns, see [patterns.md](patterns.md)
## Debugging Checklist
When subagent doesn't work as expected:
```markdown
- [ ] Description is specific and includes trigger words
- [ ] Description includes "PROACTIVELY" or "MUST BE USED" if needed
- [ ] System prompt defines role clearly
- [ ] System prompt includes process/steps
- [ ] System prompt specifies output format
- [ ] System prompt has examples
- [ ] Tools match required capabilities
- [ ] Tools follow least-privilege principle
- [ ] Model appropriate for task complexity
- [ ] File location correct (.claude/agents/)
- [ ] YAML frontmatter valid
- [ ] Name uses kebab-case
- [ ] Tested with positive/negative scenarios
```
## Common Anti-Patterns
### ❌ Generic Description
```yaml
description: Helps with coding
```
**Fix**: Be specific about domain and triggers
### ❌ No Process Defined
```markdown
You are a code reviewer. Review code.
```
**Fix**: Define step-by-step process
### ❌ All Tools Granted
```yaml
# Omitting tools when only reads needed
```
**Fix**: Whitelist minimum required tools
### ❌ Verbose Prompt
```markdown
You are an expert developer with 20 years of experience... [3000 words]
```
**Fix**: Be concise, focus on process and format
## Migration: Ad-Hoc to Subagent
### When to Migrate
- Used same prompt 3+ times
- Prompt has clear pattern/structure
- Task benefits from isolation
- Multiple team members need it
### Process
**Step 1: Extract Pattern**
```markdown
# Repeated prompts:
1. "Review auth.js for security issues"
2. "Check payment.js for vulnerabilities"
3. "Analyze api.js for security problems"
# Common pattern: Review [file] for security [types]
```
**Step 2: Generalize**
```yaml
---
name: security-reviewer
description: Review code for security vulnerabilities including SQL injection, XSS, authentication flaws, and hardcoded secrets. Use PROACTIVELY for security reviews.
tools: Read, Grep, Glob
---
```
**Step 3: Test & Refine**
Test with previous use cases, refine until quality matches manual prompts.
## Resources
- [Optimization Patterns](patterns.md) - Advanced subagent patterns
- [Testing Strategies](testing.md) - Comprehensive testing guide
- [System Prompt Templates](templates.md) - Ready-to-use prompts
- [Official Documentation](https://docs.claude.com/en/docs/claude-code/sub-agents)
---
**Remember**: Start with `/agents` for creation. Use this skill for refinement. Iterate based on real usage. Test thoroughly.

View File

@@ -1,15 +0,0 @@
{
"name": "claude-skills",
"description": "Meta-skill for creating effective Agent Skills with best practices, templates, and progressive disclosure principles",
"version": "1.0.0",
"author": {
"name": "Claude Skills Contributors"
},
"keywords": [
"agent-skills",
"skill-creation",
"best-practices",
"templates",
"progressive-disclosure"
]
}

View File

@@ -1,250 +0,0 @@
# Claude Skills Plugin
Meta-skill for creating effective Agent Skills with best practices, structure guidelines, and progressive disclosure principles.
## What's Included
The **claude-skills** skill provides comprehensive guidance for building high-quality Agent Skills that work efficiently with Claude Code and Claude.ai.
### claude-skills (Skill Creator)
A comprehensive guide covering:
- **Progressive disclosure** - Three-layer architecture (metadata → instructions → resources)
- **Trigger optimization** - Writing descriptions that activate at the right time
- **Token efficiency** - Strategic file splitting and on-demand loading
- **Development workflow** - Iterative approach to skill creation
- **Security considerations** - Best practices for safe skill creation and usage
**Includes:**
- `SKILL.md` - Complete best practices guide
- `examples.md` - Working examples across different domains
- `templates.md` - Ready-to-use templates for common skill types
- `checklist.md` - Quality assurance checklist
- `README.md` - Skill-specific overview
## When to Use This Skill
Use this skill when:
- Creating a new Agent Skill from scratch
- Improving or refactoring an existing skill
- Debugging why a skill isn't triggering correctly
- Understanding skill architecture and design patterns
- Optimizing skill structure for token efficiency
## Installation
### For Claude Code
Install from marketplace:
```bash
/plugin install claude-skills@claude-skills-marketplace
```
Or install from local directory:
```bash
/plugin install /path/to/Skills/claude-skills-plugin@local
```
### For Claude.ai
1. Zip this plugin directory
2. Go to Settings > Capabilities > Upload skill
3. Upload the zip file
4. Enable the plugin
## Usage
Once installed, the skill activates automatically when you work on skill-related tasks:
```
"Help me create a skill for Python testing"
"Why isn't my skill triggering?"
"How do I optimize my skill for token usage?"
"Review my skill structure"
```
## Key Concepts
### Progressive Disclosure
Skills use a three-layer architecture:
**Layer 1: Metadata (Always Loaded)**
- YAML frontmatter with `name` and `description`
- ~100 tokens per skill
- Used for trigger detection
**Layer 2: Instructions (Triggered)**
- Main SKILL.md content
- Procedural guidance and workflows
- Loaded when skill is relevant
**Layer 3: Resources (On-Demand)**
- Additional files, scripts, reference materials
- Loaded only when explicitly needed
- Maximizes token efficiency
### Writing Effective Descriptions
The description field determines when your skill triggers:
**Good Descriptions:**
```yaml
description: Create and analyze Excel spreadsheets with formulas, formatting, and pivot tables. Use when working with .xlsx files, data analysis, or generating reports.
```
**Poor Descriptions:**
```yaml
description: Helps with coding tasks
```
### Skill Structure
Every skill MUST have:
```yaml
---
name: Your Skill Name (max 64 chars)
description: Clear description with use cases (max 1024 chars)
---
# Skill content
```
## What You'll Learn
### From SKILL.md
- When to use progressive disclosure
- How to write effective descriptions
- Structuring content for scannability
- Token optimization techniques
- Development workflow best practices
- Security considerations
### From examples.md
- Python testing with pytest
- REST API integration patterns
- Technical documentation writing
- Real-world skill structures
### From templates.md
- Code framework skill template
- Workflow/process skill template
- Reference/lookup skill template
- Tool/utility skill template
### From checklist.md
- Metadata requirements
- Content quality checks
- Trigger testing scenarios
- Security review items
## Quick Start
### Creating Your First Skill
1. Ask Claude: "Help me create a skill for [your topic]"
2. Claude will guide you through:
- Choosing the right template
- Writing an effective description
- Structuring content efficiently
- Adding concrete examples
### Improving an Existing Skill
1. Ask Claude: "Review my skill at [path]"
2. Claude will analyze:
- Trigger accuracy
- Structure optimization
- Content clarity
- Best practices alignment
## Best Practices Summary
**DO:**
- Keep SKILL.md focused and concise
- Use clear, scannable hierarchies
- Include concrete, working examples
- Reference additional files explicitly
- Start simple, expand based on need
**DON'T:**
- Create vague descriptions
- Add unnecessary complexity upfront
- Hardcode sensitive data
- Skip testing trigger scenarios
## Development Workflow
1. **Start with Evaluation** - Work with Claude on tasks, identify patterns
2. **Iterate Collaboratively** - Let Claude help structure the skill
3. **Test Triggering** - Verify activation with target scenarios
4. **Start Simple** - Begin minimal, expand based on actual needs
## Skills Checklist
Before finalizing a skill:
- [ ] Name ≤ 64 characters
- [ ] Description ≤ 1024 characters and specific
- [ ] Description includes trigger scenarios
- [ ] SKILL.md has valid YAML frontmatter
- [ ] "When to Use This Skill" section present
- [ ] At least one concrete example included
- [ ] No sensitive information hardcoded
- [ ] File references are accurate
- [ ] Tested triggering with target scenarios
- [ ] Tested NOT triggering with unrelated scenarios
## Common Patterns
### Code Development Skills
```yaml
---
name: [Framework] Development Guide
description: Build [framework] applications following [patterns]. Use when building [type] with [requirements].
---
```
### Workflow Skills
```yaml
---
name: [Task] Workflow
description: Execute [task] following [methodology]. Use when [scenario].
---
```
### Reference Skills
```yaml
---
name: [Topic] Reference
description: Quick reference for [domain]. Use when looking up [specific aspects].
---
```
## Resources
- [Official Documentation](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview)
- [Engineering Blog](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills)
- [Using Skills Guide](https://support.claude.com/en/articles/12512180-using-skills-in-claude)
## Version History
### 1.0.0 (Initial Release)
- Complete best practices guide (SKILL.md)
- Working examples across domains (examples.md)
- Ready-to-use templates (templates.md)
- Quality assurance checklist (checklist.md)
## Contributing
Found an issue or have improvements? See the main marketplace [CONTRIBUTING.md](../CONTRIBUTING.md).
## License
See main marketplace repository for license information.
---
**Remember**: The best skills emerge from real usage patterns. Start simple, iterate based on actual needs, and prioritize clarity over comprehensiveness.