From 7911d9099576bdf5ed977ddbd4cc20e4583cc9e9 Mon Sep 17 00:00:00 2001 From: movq Date: Fri, 17 Oct 2025 11:17:09 -0500 Subject: [PATCH] feat: Convert to Claude Code plugin marketplace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Transform repository into a plugin marketplace structure with two plugins: - claude-code plugin: Complete toolkit with 5 skills * claude-code-plugins * claude-code-slash-commands * claude-code-hooks * claude-code-subagents * claude-code-memory - claude-skills plugin: Meta-skill for creating Agent Skills * Comprehensive best practices guide * Templates and examples * Progressive disclosure patterns Infrastructure: - Add marketplace.json manifest - Create plugin.json for each plugin - Update documentation for marketplace structure - Add contribution and testing guides Installation: - /plugin install claude-code@claude-skills - /plugin install claude-skills@claude-skills πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .claude-plugin/marketplace.json | 19 + .gitignore | 57 + CONTRIBUTING.md | 484 ++++++++ README.md | 363 ++++++ TESTING.md | 446 +++++++ claude-code/.claude-plugin/plugin.json | 17 + claude-code/README.md | 202 ++++ claude-code/skills/claude-code-hooks/SKILL.md | 1049 +++++++++++++++++ .../skills/claude-code-memory/SKILL.md | 1032 ++++++++++++++++ .../skills/claude-code-plugins/SKILL.md | 546 +++++++++ .../claude-code-slash-commands/SKILL.md | 698 +++++++++++ .../skills/claude-code-subagents/SKILL.md | 934 +++++++++++++++ .../.claude-plugin/plugin.json | 15 + claude-skills-plugin/README.md | 250 ++++ .../skills/claude-skills}/README.md | 0 .../skills/claude-skills}/SKILL.md | 0 .../skills/claude-skills}/checklist.md | 0 .../skills/claude-skills}/examples.md | 0 .../skills/claude-skills}/templates.md | 0 19 files changed, 6112 insertions(+) create mode 100644 .claude-plugin/marketplace.json create mode 100644 CONTRIBUTING.md create mode 100644 README.md create mode 100644 TESTING.md create mode 100644 claude-code/.claude-plugin/plugin.json create mode 100644 claude-code/README.md create mode 100644 claude-code/skills/claude-code-hooks/SKILL.md create mode 100644 claude-code/skills/claude-code-memory/SKILL.md create mode 100644 claude-code/skills/claude-code-plugins/SKILL.md create mode 100644 claude-code/skills/claude-code-slash-commands/SKILL.md create mode 100644 claude-code/skills/claude-code-subagents/SKILL.md create mode 100644 claude-skills-plugin/.claude-plugin/plugin.json create mode 100644 claude-skills-plugin/README.md rename {claude-skills => claude-skills-plugin/skills/claude-skills}/README.md (100%) rename {claude-skills => claude-skills-plugin/skills/claude-skills}/SKILL.md (100%) rename {claude-skills => claude-skills-plugin/skills/claude-skills}/checklist.md (100%) rename {claude-skills => claude-skills-plugin/skills/claude-skills}/examples.md (100%) rename {claude-skills => claude-skills-plugin/skills/claude-skills}/templates.md (100%) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..9f08e11 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,19 @@ +{ + "name": "claude-skills-marketplace", + "owner": { + "name": "Claude Skills Contributors" + }, + "description": "A curated collection of Agent Skills and plugins for Claude Code and Claude.ai", + "plugins": [ + { + "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" + } + ] +} diff --git a/.gitignore b/.gitignore index d6b130c..6b34773 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,58 @@ +# Claude Code local settings .claude/settings.local.json + +# macOS +.DS_Store +.AppleDouble +.LSOverride + +# Temporary files +*.tmp +*.swp +*.swo +*~ +.*.sw? + +# Test artifacts +tmp/ +temp/ +test-output/ + +# Compressed skill packages +*.zip +*.tar.gz + +# IDE +.vscode/ +.idea/ +*.sublime-* + +# Python (if testing skills) +__pycache__/ +*.py[cod] +*$py.class +.pytest_cache/ +.coverage +htmlcov/ +.venv/ +venv/ +ENV/ + +# Node (if testing skills) +node_modules/ +npm-debug.log +yarn-error.log +.npm/ + +# Build outputs +dist/ +build/ +*.egg-info/ + +# Sensitive data +*.key +*.pem +*.cert +secrets/ +.env +.env.local diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..afe3100 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,484 @@ +# Contributing to Claude Skills Marketplace + +Thank you for contributing! This guide helps you add plugins, skills, and improvements to the marketplace. + +## Types of Contributions + +1. **Add skills to existing plugins** - Extend claude-code or claude-skills +2. **Create new plugins** - Package related skills together +3. **Improve existing skills** - Refine content, fix bugs, add examples +4. **Update documentation** - Improve guides and READMEs + +## Before You Start + +1. **Use the claude-skills plugin** - Get guidance on skill creation +2. **Review existing plugins** - Check claude-code and claude-skills-plugin +3. **Test thoroughly** - See [TESTING.md](./TESTING.md) + +## Adding a Skill to an Existing Plugin + +### Option 1: Add to claude-code Plugin + +Add Claude Code-specific skills (features, tools, workflows): + +```bash +# 1. Create skill directory +cd claude-code/skills +mkdir my-claude-code-skill + +# 2. Create SKILL.md +cat > my-claude-code-skill/SKILL.md << 'EOF' +--- +name: My Claude Code Feature +description: [Specific description with trigger scenarios] +--- + +# Content here +EOF + +# 3. Update plugin README +vim claude-code/README.md +# Add your skill to the "What's Included" section +``` + +**Best for:** +- Claude Code features (like our existing 5 skills) +- Development workflows +- Tool integrations + +### Option 2: Add to claude-skills Plugin + +Add skill-creation guidance (templates, patterns, best practices): + +```bash +# 1. Create skill directory +cd claude-skills-plugin/skills +mkdir my-skill-pattern + +# 2. Create SKILL.md +# Follow claude-skills format (see existing skill) + +# 3. Update plugin README +``` + +**Best for:** +- New skill templates +- Skill-creation patterns +- Meta-guidance on skills + +## Creating a New Plugin + +For a collection of related skills that don't fit existing plugins: + +### 1. Create Plugin Structure + +```bash +# Create plugin directory +mkdir my-plugin + +# Create required directories +mkdir -p my-plugin/.claude-plugin +mkdir -p my-plugin/skills + +# Optional: commands, agents, hooks +mkdir -p my-plugin/commands +mkdir -p my-plugin/agents +mkdir -p my-plugin/hooks +``` + +### 2. Create plugin.json + +```bash +cat > my-plugin/.claude-plugin/plugin.json << 'EOF' +{ + "name": "my-plugin", + "description": "Clear description of plugin purpose", + "version": "1.0.0", + "author": { + "name": "Your Name", + "email": "you@example.com" + }, + "keywords": [ + "keyword1", + "keyword2" + ] +} +EOF +``` + +**Required fields:** +- `name` - Lowercase, kebab-case identifier +- `description` - Clear, concise purpose +- `version` - Semantic versioning (1.0.0) +- `author.name` - Creator name + +**Optional fields:** +- `author.email` - Contact email +- `author.url` - Website or profile +- `repository` - Git repository info +- `license` - License identifier +- `keywords` - Search/discovery terms + +### 3. Add Skills to Plugin + +```bash +# Create skill directory +mkdir my-plugin/skills/my-skill + +# Create SKILL.md with frontmatter +cat > my-plugin/skills/my-skill/SKILL.md << 'EOF' +--- +name: Skill Name +description: [Specific description] +--- + +# Skill content +EOF +``` + +### 4. Create Plugin README + +```bash +cat > my-plugin/README.md << 'EOF' +# My Plugin + +Brief description. + +## What's Included + +List of skills/features + +## Installation + +```bash +/plugin install my-plugin@claude-skills +``` + +## Usage + +Examples of how to use + +[More sections...] +EOF +``` + +### 5. Update Marketplace Manifest + +```bash +# Edit .claude-plugin/marketplace.json +vim .claude-plugin/marketplace.json +``` + +Add your plugin: +```json +{ + "plugins": [ + { + "name": "my-plugin", + "source": "./my-plugin", + "description": "Brief plugin description" + } + ] +} +``` + +### 6. Test Plugin Installation + +```bash +# Test local installation +/plugin install /path/to/Skills/my-plugin@local + +# Verify skills load +# Try triggering scenarios +``` + +## Skill Creation Guidelines + +### Required: SKILL.md Structure + +```yaml +--- +name: Skill Name (max 64 chars) +description: Specific description with triggers (max 1024 chars) +--- + +# Skill Name + +## When to Use This Skill + +Use this skill when: +- [Primary scenario] +- [Secondary scenario] + +Do NOT use this skill for: +- [Confusion case] + +## Quick Start + +[Minimal example] + +## Core Workflows + +[Step-by-step guides] + +## Examples + +[Concrete examples] +``` + +### Writing Effective Descriptions + +**Template:** +``` +[Action] [domain/task] [with/for] [capabilities]. +Use when [trigger scenario]. +[Optional: PROACTIVELY/MUST BE USED if needed] +``` + +**Good Examples:** +```yaml +# Specific, clear triggers +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. + +# Domain-specific +description: Optimize and troubleshoot Claude Code memory files (CLAUDE.md) for efficiency, token management, and team collaboration. Use when memory isn't loading, context is bloated, or organizing memory hierarchy. +``` + +**Bad Examples:** +```yaml +# Too vague +description: Helps with development + +# No triggers +description: Python tools and utilities +``` + +### Progressive Disclosure + +**Layer 1: Metadata (100 tokens)** +- Skill name and description in frontmatter +- Triggers skill selection + +**Layer 2: SKILL.md (2000-5000 tokens)** +- Core workflows and common examples +- Loaded when skill activates + +**Layer 3: Additional Files (on-demand)** +- Detailed docs in separate .md files +- Scripts, templates, references +- Loaded only when needed + +### Content Best Practices + +**DO:** +- Be specific, not vague +- Use bullet points, not paragraphs +- Include concrete, working examples +- Provide step-by-step workflows +- Add troubleshooting sections +- Test trigger scenarios + +**DON'T:** +- Include sensitive data (API keys, credentials) +- Use generic advice ("write good code") +- Create novel-length content +- Duplicate information +- Skip testing + +## Quality Checklist + +Before submitting: + +### Metadata +- [ ] Name ≀ 64 characters +- [ ] Description ≀ 1024 characters +- [ ] Description includes specific triggers +- [ ] YAML frontmatter is valid + +### Content +- [ ] "When to Use This Skill" section present +- [ ] At least one concrete example +- [ ] Examples are runnable/testable +- [ ] File references are accurate +- [ ] No sensitive data hardcoded + +### Testing +- [ ] Skill triggers on target scenarios +- [ ] Doesn't trigger on unrelated scenarios +- [ ] Examples work as documented +- [ ] No conflicts with existing skills + +### Documentation +- [ ] Plugin README updated +- [ ] Marketplace manifest updated (if new plugin) +- [ ] Clear installation instructions +- [ ] Usage examples provided + +## Testing Your Contribution + +See [TESTING.md](./TESTING.md) for: +- Trigger accuracy testing +- Content quality validation +- Token efficiency measurement +- Team collaboration testing + +Quick test: +```bash +# 1. Install locally +/plugin install /path/to/your-plugin@local + +# 2. Test trigger scenarios +# Ask questions that should trigger the skill + +# 3. Test exclusion scenarios +# Ask questions that should NOT trigger + +# 4. Verify quality +# Review Claude's responses for accuracy +``` + +## Submission Process + +### For Small Changes (Skills to Existing Plugins) + +1. Create skill in appropriate plugin +2. Update plugin README +3. Test locally +4. Submit PR with: + - Skill files + - Updated README + - Test results + +### For New Plugins + +1. Create complete plugin structure +2. Update marketplace.json +3. Create plugin README +4. Test installation and usage +5. Submit PR with: + - Full plugin directory + - Updated marketplace.json + - Documentation + - Test results + +## Common Patterns + +### Plugin Organization + +``` +my-plugin/ +β”œβ”€β”€ .claude-plugin/ +β”‚ └── plugin.json +β”œβ”€β”€ skills/ # Related skills grouped together +β”‚ β”œβ”€β”€ skill-1/ +β”‚ β”œβ”€β”€ skill-2/ +β”‚ └── skill-3/ +β”œβ”€β”€ commands/ # Optional: slash commands +β”œβ”€β”€ agents/ # Optional: subagent configs +β”œβ”€β”€ hooks/ # Optional: automation hooks +└── README.md +``` + +### Skill Naming Conventions + +**For Claude Code features:** +- `claude-code-[feature]` (e.g., claude-code-plugins) + +**For domain-specific:** +- `[domain]-[purpose]` (e.g., python-testing, api-documentation) + +**For meta/general:** +- `[category]-[action]` (e.g., skill-creator, code-reviewer) + +### Version Bumping + +Follow semantic versioning: + +```json +{ + "version": "1.2.3" +} +``` + +- **Major (1.x.x)**: Breaking changes +- **Minor (x.2.x)**: New features, backward compatible +- **Patch (x.x.3)**: Bug fixes + +Update version in plugin.json when: +- Adding new skills β†’ Minor +- Changing skill structure β†’ Major +- Fixing bugs β†’ Patch + +## Example: Adding a Skill + +### Scenario: Add "claude-code-mcp" skill + +```bash +# 1. Navigate to plugin +cd claude-code/skills + +# 2. Create skill +mkdir claude-code-mcp + +# 3. Create SKILL.md +cat > claude-code-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. +--- + +# Claude Code MCP Server Management + +## When to Use This Skill +[Content here...] +EOF + +# 4. Update plugin README +vim ../README.md +# Add claude-code-mcp to "What's Included" + +# 5. Bump version in plugin.json +vim ../.claude-plugin/plugin.json +# Change: "version": "1.0.0" β†’ "1.1.0" + +# 6. Test +/plugin install /path/to/Skills/claude-code@local +# Test trigger scenarios + +# 7. Submit PR +``` + +## Security Considerations + +### Never Include + +- API keys, tokens, or credentials +- Personal identifying information +- Proprietary code without permission +- Hardcoded paths to user-specific locations +- Malicious scripts or commands + +### Always Review + +- External dependencies (trusted sources only) +- File system access patterns +- Network requests +- Bash commands in examples + +## Getting Help + +- **Skill creation guidance** - Use claude-skills plugin +- **Plugin structure questions** - Use claude-code-plugins skill +- **Testing help** - See TESTING.md +- **Questions** - Open an issue + +## Resources + +- [Agent Skills Documentation](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview) +- [Plugin Documentation](https://docs.claude.com/en/docs/claude-code/plugins) +- [claude-skills Plugin](./claude-skills-plugin/README.md) +- [claude-code Plugin](./claude-code/README.md) + +--- + +**Thank you for contributing!** Your skills help the entire Claude community work more effectively. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3281389 --- /dev/null +++ b/README.md @@ -0,0 +1,363 @@ +# Claude Skills Marketplace + +A curated marketplace of Agent Skills and plugins for Claude Code and Claude.ai, designed to extend Claude's capabilities with specialized knowledge and workflows. + +## What's in This Marketplace + +### πŸ”§ claude-code Plugin +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 + +[View Plugin Details](./claude-code/README.md) + +### πŸ“š claude-skills Plugin +Meta-skill for creating effective Agent Skills. + +**Comprehensive guide covering:** +- Progressive disclosure architecture +- Trigger optimization techniques +- Token efficiency strategies +- Development workflows +- Templates and examples + +[View Plugin Details](./claude-skills-plugin/README.md) + +## Quick Start + +### For Claude Code + +Install individual plugins from this marketplace: + +```bash +# Install Claude Code plugin +/plugin install claude-code@local --path /path/to/Skills + +# Install Claude Skills plugin +/plugin install claude-skills@local --path /path/to/Skills +``` + +Or configure the marketplace in your settings: + +```json +// ~/.claude/settings.json or .claude/settings.json +{ + "plugin-marketplaces": { + "claude-skills": { + "url": "file:///path/to/Skills" + } + } +} +``` + +Then install from the marketplace: + +```bash +/plugin install claude-code@claude-skills +/plugin install claude-skills@claude-skills +``` + +### For Claude.ai + +Each plugin can be zipped and uploaded individually: + +1. Zip a plugin directory (e.g., `claude-code/`) +2. Go to Settings > Capabilities > Upload skill +3. Upload the zip file +4. Enable the plugin + +## Available Plugins + +| Plugin | Version | Skills | Description | +|--------|---------|--------|-------------| +| [claude-code](./claude-code/) | 1.0.0 | 5 | Complete Claude Code toolkit | +| [claude-skills](./claude-skills-plugin/) | 1.0.0 | 1 | Skill creation meta-guide | + +## Plugin Details + +### claude-code + +**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 + +**Installation:** +```bash +/plugin install claude-code@claude-skills +``` + +### claude-skills + +**Best for:** Anyone creating Agent Skills for Claude Code or Claude.ai. + +**What it teaches:** +- How to structure skills effectively +- Writing descriptions that trigger correctly +- Optimizing for token efficiency +- Progressive disclosure patterns +- Testing and validation + +**Installation:** +```bash +/plugin install claude-skills@claude-skills +``` + +## How This Marketplace Works + +### Marketplace Structure + +``` +claude-skills-marketplace/ +β”œβ”€β”€ .claude-plugin/ +β”‚ └── marketplace.json # Marketplace manifest +β”œβ”€β”€ claude-code/ # Plugin 1 +β”‚ β”œβ”€β”€ .claude-plugin/ +β”‚ β”‚ └── plugin.json +β”‚ β”œβ”€β”€ skills/ # 5 Claude Code skills +β”‚ └── README.md +β”œβ”€β”€ claude-skills-plugin/ # Plugin 2 +β”‚ β”œβ”€β”€ .claude-plugin/ +β”‚ β”‚ └── plugin.json +β”‚ β”œβ”€β”€ skills/ # Skill creation guide +β”‚ └── README.md +β”œβ”€β”€ README.md # This file +β”œβ”€β”€ CONTRIBUTING.md # How to add plugins/skills +└── TESTING.md # Validation guide +``` + +### Plugin Installation Flow + +1. **Marketplace Configuration** - Add marketplace to settings +2. **Discovery** - Claude Code reads marketplace.json +3. **Installation** - `/plugin install [plugin-name]@[marketplace-name]` +4. **Activation** - Skills load automatically based on context + +## Usage Examples + +### Working with Claude Code Features + +``` +# Plugin development +"Help me create a plugin for my team" +β†’ claude-code-plugins skill activates + +# Custom commands +"I want to create a slash command for code review" +β†’ claude-code-slash-commands skill activates + +# Setting up automation +"How do I run tests automatically after file edits?" +β†’ claude-code-hooks skill activates + +# Subagent issues +"My security analyzer subagent isn't triggering" +β†’ claude-code-subagents skill activates + +# Memory optimization +"My CLAUDE.md file is too long and wastes tokens" +β†’ claude-code-memory skill activates +``` + +### Creating New Skills + +``` +"I want to create a skill for React testing" +β†’ claude-skills skill activates +β†’ Guides you through templates and best practices +``` + +## Team Setup + +Share this marketplace with your team: + +### Option 1: Git Repository (Recommended) + +```bash +# Team members clone the repo +git clone https://your-repo/claude-skills-marketplace.git + +# Add to Claude Code settings +# .claude/settings.json (committed to repo) +{ + "plugin-marketplaces": { + "team-skills": { + "url": "file:///path/to/claude-skills-marketplace" + } + }, + "plugins": [ + "claude-code@team-skills", + "claude-skills@team-skills" + ] +} +``` + +Benefits: +- Version control for skills +- Team consistency +- Easy updates via `git pull` + +### Option 2: Network Share + +```json +{ + "plugin-marketplaces": { + "team-skills": { + "url": "file://network-share/claude-skills" + } + } +} +``` + +### Option 3: Individual Installation + +Team members install plugins locally: + +```bash +/plugin install /local/path/to/claude-code@local +/plugin install /local/path/to/claude-skills@local +``` + +## Best Practices + +### For Plugin Users + +1. **Start with claude-skills** if you're creating skills +2. **Install claude-code** if you use Claude Code regularly +3. **Keep plugins updated** - Check for new versions +4. **Test in local settings** before team-wide deployment + +### For Skill Creators + +1. Follow [CONTRIBUTING.md](./CONTRIBUTING.md) guidelines +2. Test skills thoroughly (see [TESTING.md](./TESTING.md)) +3. Use progressive disclosure (keep main content lean) +4. Include concrete examples +5. Write specific trigger descriptions + +### For Teams + +1. **Share marketplace via git** for version control +2. **Document custom workflows** in team CLAUDE.md +3. **Create team-specific plugins** for your stack +4. **Regular reviews** of skill effectiveness + +## Customization + +### Adding Your Own Plugins + +1. Create plugin directory with structure: +``` +your-plugin/ +β”œβ”€β”€ .claude-plugin/ +β”‚ └── plugin.json +β”œβ”€β”€ skills/ +β”‚ └── your-skill/ +β”‚ └── SKILL.md +└── README.md +``` + +2. Update marketplace.json: +```json +{ + "plugins": [ + { + "name": "your-plugin", + "source": "./your-plugin", + "description": "Your plugin description" + } + ] +} +``` + +3. See [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed guidelines + +### Creating Custom Skills + +Use the **claude-skills** plugin to guide you: + +``` +"Help me create a skill for [your domain]" +``` + +## Troubleshooting + +### Plugins Not Installing + +**Check marketplace configuration:** +```bash +# Verify marketplace.json exists +cat .claude-plugin/marketplace.json + +# Check file paths are correct +ls claude-code/.claude-plugin/plugin.json +ls claude-skills-plugin/.claude-plugin/plugin.json +``` + +### Skills Not Triggering + +**Verify installation:** +```bash +/plugin list +# Should show: claude-code, claude-skills +``` + +**Check descriptions:** Skills may not match your use case +- Read plugin READMEs for trigger scenarios +- Try explicit skill references in prompts + +### Updates Not Applying + +**Reload plugins:** +```bash +# Restart Claude Code session +# Or reinstall plugin +/plugin uninstall claude-code +/plugin install claude-code@claude-skills +``` + +## Contributing + +We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for: +- Adding new skills +- Improving existing skills +- Creating new plugins +- Documentation improvements +- Bug reports + +## Resources + +### Official Documentation +- [Agent Skills Overview](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview) +- [Claude Code Plugins](https://docs.claude.com/en/docs/claude-code/plugins) +- [Sub-agents](https://docs.claude.com/en/docs/claude-code/sub-agents) +- [Memory Management](https://docs.claude.com/en/docs/claude-code/memory) + +### Community +- [Engineering Blog: Agent Skills](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills) +- [Engineering Blog: Claude Code Best Practices](https://www.anthropic.com/engineering/claude-code-best-practices) + +## Version History + +### 1.0.0 (Initial Release) +- claude-code plugin (5 skills) +- claude-skills plugin (meta-skill) +- Marketplace infrastructure +- Documentation and guides + +## License + +Individual plugins may have their own licenses. Check each plugin directory for details. + +--- + +**Get Started**: Install the plugins, explore the skills, and level up your Claude Code workflow! diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 0000000..29124b5 --- /dev/null +++ b/TESTING.md @@ -0,0 +1,446 @@ +# Testing and Validating Skills + +This guide helps you validate skills before adding them to the repository or using them in production. + +## Quick Validation Checklist + +Run through this checklist before submitting a skill: + +``` +Metadata +[ ] SKILL.md exists +[ ] YAML frontmatter is valid +[ ] Name ≀ 64 characters +[ ] Description ≀ 1024 characters +[ ] Description includes trigger scenarios + +Content Quality +[ ] "When to Use This Skill" section present +[ ] At least one concrete example +[ ] Examples are runnable/testable +[ ] File references are accurate +[ ] No sensitive data hardcoded + +Triggering Tests +[ ] Triggers on target scenarios +[ ] Doesn't trigger on unrelated scenarios +[ ] No conflicts with similar skills + +Security +[ ] No credentials or API keys +[ ] No personal information +[ ] Safe file system access only +[ ] External dependencies verified +``` + +## Detailed Testing Process + +### 1. Metadata Validation + +#### Test YAML Parsing + +Try parsing the frontmatter: + +```bash +# Extract and validate YAML +head -n 10 SKILL.md | grep -A 3 "^---$" +``` + +Verify: +- YAML is valid (no syntax errors) +- Both `name` and `description` are present +- Values are within character limits + +#### Character Limits + +```bash +# Count characters in name (must be ≀ 64) +grep "^name:" SKILL.md | sed 's/name: //' | wc -c + +# Count characters in description (must be ≀ 1024) +grep "^description:" SKILL.md | sed 's/description: //' | wc -c +``` + +### 2. Content Quality Testing + +#### Check Required Sections + +```bash +# Verify "When to Use This Skill" section exists +grep -i "when to use" SKILL.md + +# Verify examples exist +grep -i "example" SKILL.md +``` + +#### Test File References + +If skill references other files, verify they exist: + +```bash +# Find markdown links +grep -o '\[.*\]([^)]*\.md)' SKILL.md + +# Check if referenced files exist +# (manually verify each one) +``` + +#### Validate Examples + +For each example in the skill: +1. Try running the code/commands +2. Verify output matches expectations +3. Check for edge cases +4. Ensure examples are complete (no placeholders) + +### 3. Trigger Testing + +This is the most important validation step. + +#### Create Test Scenarios + +**Positive Tests (SHOULD trigger)** + +Create a list of scenarios where the skill should activate: + +```markdown +Test Scenario 1: [Describe task that should trigger] +Expected: Skill activates +Actual: [Test result] + +Test Scenario 2: [Another trigger case] +Expected: Skill activates +Actual: [Test result] +``` + +**Negative Tests (SHOULD NOT trigger)** + +Create scenarios where the skill should NOT activate: + +```markdown +Test Scenario 3: [Similar but different task] +Expected: Skill does NOT activate +Actual: [Test result] + +Test Scenario 4: [Unrelated task] +Expected: Skill does NOT activate +Actual: [Test result] +``` + +#### Example Testing Session + +For a "Python Testing with pytest" skill: + +**Should Trigger:** +- "Help me write tests for my Python function" +- "How do I use pytest fixtures?" +- "Create unit tests for this class" + +**Should NOT Trigger:** +- "Help me test my JavaScript code" (different language) +- "Debug my pytest installation" (installation, not testing) +- "Explain what unit testing is" (concept, not implementation) + +#### Run Tests with Claude + +1. Load the skill +2. Ask Claude each test question +3. Observe if skill triggers (check response for skill context) +4. Document results + +### 4. Token Efficiency Testing + +#### Measure Content Size + +```bash +# Count tokens (approximate: words Γ— 1.3) +wc -w SKILL.md + +# Or use a proper token counter +# (tokens β‰ˆ characters Γ· 4 for rough estimate) +wc -c SKILL.md +``` + +#### Evaluate Split Points + +Ask yourself: +- Is content loaded only when needed? +- Could mutually exclusive sections be split? +- Are examples concise but complete? +- Is reference material in separate files? + +Target sizes: +- **SKILL.md**: Under 3000 tokens (core workflows) +- **Additional files**: Load only when referenced +- **Total metadata**: ~100 tokens + +### 5. Security Validation + +#### Automated Checks + +```bash +# Check for potential secrets +grep -iE "(password|api[_-]?key|secret|token|credential)" SKILL.md + +# Check for hardcoded paths +grep -E "(/Users/|/home/|C:\\\\)" SKILL.md + +# Check for sensitive file extensions +grep -E "\.(key|pem|cert|p12|pfx)( |$)" SKILL.md +``` + +#### Manual Review + +Review each file for: +- [ ] No credentials in examples +- [ ] No personal information +- [ ] File paths are generic/relative +- [ ] Network access is documented +- [ ] External dependencies are from trusted sources +- [ ] Scripts don't make unsafe system changes + +### 6. Cross-Skill Conflict Testing + +If you have multiple skills installed: + +1. **Similar domain overlap**: Test that specific skills trigger (not generic ones) +2. **Keyword conflicts**: Check if multiple skills trigger on same query +3. **Description clarity**: Ensure each skill's domain is distinct + +Example conflicts to avoid: +- "Python Helper" (too generic) vs "Python Testing with pytest" (specific) +- Both trigger on "Help with Python" β†’ Fix by making descriptions more specific + +## Testing Workflows + +### Quick Test (5 minutes) + +For minor updates or simple skills: + +1. βœ“ Validate metadata (YAML, character limits) +2. βœ“ Check one example works +3. βœ“ Test one positive trigger +4. βœ“ Test one negative trigger +5. βœ“ Scan for secrets + +### Standard Test (15 minutes) + +For new skills or significant changes: + +1. βœ“ Complete metadata validation +2. βœ“ Test all examples +3. βœ“ Run 3-5 trigger tests (positive + negative) +4. βœ“ Check token efficiency +5. βœ“ Full security review +6. βœ“ Verify file references + +### Comprehensive Test (30+ minutes) + +For complex skills or pre-release: + +1. βœ“ All standard tests +2. βœ“ Test with different Claude models +3. βœ“ Test conflict scenarios with other skills +4. βœ“ Have someone else try the skill +5. βœ“ Test edge cases in examples +6. βœ“ Review progressive disclosure strategy +7. βœ“ Load test (simulate typical usage) + +## Common Issues and Fixes + +### Skill Doesn't Trigger + +**Symptoms**: Claude doesn't load skill context when expected + +**Diagnose**: +1. Description too vague? +2. Description missing trigger keywords? +3. Name too generic? + +**Fix**: +```yaml +# Before +description: Python development helpers + +# After +description: Create Python projects using Hatch and Hatchling for dependency management. Use when initializing new Python packages or configuring build systems. +``` + +### Skill Triggers Too Often + +**Symptoms**: Skill loads for unrelated queries + +**Diagnose**: +1. Description too broad? +2. Keywords too common? + +**Fix**: +```yaml +# Add specificity and exclusions +description: Debug Swift applications using LLDB for crashes, memory issues, and runtime errors. Use when investigating Swift bugs or analyzing app behavior. NOT for general Swift coding or learning. +``` + +### Examples Don't Work + +**Symptoms**: Users can't reproduce examples + +**Diagnose**: +1. Missing prerequisites? +2. Placeholders not explained? +3. Environment-specific code? + +**Fix**: +- Add prerequisites section +- Make examples self-contained +- Use generic paths and values + +### High Token Usage + +**Symptoms**: Skill loads too much content + +**Diagnose**: +1. Too much in SKILL.md? +2. No progressive disclosure? +3. Verbose examples? + +**Fix**: +- Split reference material to separate files +- Link to external resources +- Condense examples +- Move advanced content to on-demand files + +## Automated Testing (Advanced) + +For repositories with many skills, consider automation: + +### Validate All Skills + +```bash +#!/bin/bash +# validate-skills.sh + +for skill_dir in */; do + if [ -f "$skill_dir/SKILL.md" ]; then + echo "Validating $skill_dir..." + + # Check frontmatter exists + if ! grep -q "^---$" "$skill_dir/SKILL.md"; then + echo "❌ Missing YAML frontmatter" + fi + + # Check name length + name=$(grep "^name:" "$skill_dir/SKILL.md" | sed 's/name: //') + if [ ${#name} -gt 64 ]; then + echo "❌ Name too long: ${#name} chars" + fi + + # Check for secrets + if grep -qiE "(password|api[_-]?key|secret)" "$skill_dir/SKILL.md"; then + echo "⚠️ Potential secrets found" + fi + + echo "βœ“ $skill_dir validated" + fi +done +``` + +### CI/CD Integration + +Add to GitHub Actions or similar: + +```yaml +name: Validate Skills +on: [push, pull_request] + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Run validation + run: | + chmod +x validate-skills.sh + ./validate-skills.sh +``` + +## Documentation Testing + +Ensure documentation is accurate: + +1. **Links work**: All markdown links resolve +2. **Paths are correct**: File references are accurate +3. **Examples are current**: Code samples match latest versions +4. **Formatting is consistent**: Markdown renders correctly + +```bash +# Check for broken internal links +grep -r '\[.*\](.*\.md)' . | while read line; do + # Extract and verify file exists + # (implementation left as exercise) +done +``` + +## User Acceptance Testing + +The ultimate test is real usage: + +1. **Give skill to others**: Have colleagues test it +2. **Monitor usage**: See when it triggers in practice +3. **Gather feedback**: Ask users about clarity and usefulness +4. **Iterate**: Refine based on real-world usage + +## Testing Checklist Template + +Copy this for each skill you test: + +```markdown +# Testing Report: [Skill Name] + +Date: [YYYY-MM-DD] +Tester: [Name] + +## Metadata +- [ ] YAML valid +- [ ] Name ≀ 64 chars +- [ ] Description ≀ 1024 chars +- [ ] Trigger scenarios in description + +## Content +- [ ] "When to Use" section present +- [ ] Examples runnable +- [ ] File references accurate +- [ ] No secrets + +## Triggering +Positive tests: +1. [Scenario] - Result: [ ] Pass [ ] Fail +2. [Scenario] - Result: [ ] Pass [ ] Fail + +Negative tests: +1. [Scenario] - Result: [ ] Pass [ ] Fail +2. [Scenario] - Result: [ ] Pass [ ] Fail + +## Security +- [ ] No credentials +- [ ] No personal data +- [ ] Safe file access +- [ ] Dependencies verified + +## Overall +- [ ] Ready for production +- [ ] Needs revision +- [ ] Rejected + +Notes: +[Any additional observations] +``` + +## Resources + +- [claude-skills/SKILL.md](./claude-skills/SKILL.md) - Best practices guide +- [claude-skills/checklist.md](./claude-skills/checklist.md) - Quality checklist +- [CONTRIBUTING.md](./CONTRIBUTING.md) - Contribution guidelines + +--- + +**Remember**: Testing isn't just about finding bugsβ€”it's about ensuring your skill provides real value and triggers at the right time. diff --git a/claude-code/.claude-plugin/plugin.json b/claude-code/.claude-plugin/plugin.json new file mode 100644 index 0000000..cdf085e --- /dev/null +++ b/claude-code/.claude-plugin/plugin.json @@ -0,0 +1,17 @@ +{ + "name": "claude-code", + "description": "Comprehensive skills for mastering Claude Code features: plugins, slash commands, hooks, subagents, and memory management", + "version": "1.0.0", + "author": { + "name": "Claude Skills Contributors" + }, + "keywords": [ + "claude-code", + "plugins", + "slash-commands", + "hooks", + "subagents", + "memory", + "productivity" + ] +} diff --git a/claude-code/README.md b/claude-code/README.md new file mode 100644 index 0000000..5b60028 --- /dev/null +++ b/claude-code/README.md @@ -0,0 +1,202 @@ +# Claude Code Plugin + +Comprehensive skills for mastering Claude Code features including plugins, slash commands, hooks, subagents, and memory management. + +## What's Included + +This plugin provides five specialized skills that help you work more effectively with Claude Code: + +### 1. claude-code-plugins +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 +- Configuring plugin manifests + +### 2. claude-code-slash-commands +Create custom slash commands with argument handling, bash execution, and file references. + +**Use when:** +- Building reusable prompts +- Automating workflows +- Creating project-specific commands + +### 3. claude-code-hooks +Configure event-driven hooks for automating workflows, validating code, and controlling tool execution. + +**Use when:** +- Setting up automation +- Enforcing standards +- Injecting context +- Integrating external tools + +### 4. claude-code-subagents +Refine and troubleshoot Claude Code subagents by optimizing prompts, tool access, and delegation patterns. + +**Use when:** +- Improving existing subagents (NOT initial creation - use `/agents` command) +- Debugging activation issues +- Optimizing performance + +### 5. claude-code-memory +Optimize and troubleshoot Claude Code memory files (CLAUDE.md) for efficiency, token management, and team collaboration. + +**Use when:** +- Memory isn't loading +- Context is bloated +- Organizing memory hierarchy +- Setting up team collaboration (NOT initial setup - use `/init` command) + +## Installation + +### For Claude Code + +Install from marketplace: + +```bash +/plugin install claude-code@claude-skills-marketplace +``` + +Or install from local directory: + +```bash +/plugin install /path/to/Skills/claude-code@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, 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 + +You can also explicitly reference skills: +``` +"Help me optimize my CLAUDE.md file" +"My subagent isn't triggering correctly" +"How do I create a hook that runs after file writes?" +``` + +## Skills Details + +### claude-code-plugins + +**Covers:** +- Plugin manifest configuration (plugin.json) +- Component setup (commands/agents/skills/hooks) +- Distribution and marketplace publishing +- Best practices and troubleshooting + +[View Details](./skills/claude-code-plugins/SKILL.md) + +### claude-code-slash-commands + +**Covers:** +- Command syntax and frontmatter options +- Argument patterns ($ARGUMENTS, $1, $2...) +- Bash integration with ! prefix +- File references with @ prefix +- Complete examples and patterns + +[View Details](./skills/claude-code-slash-commands/SKILL.md) + +### claude-code-hooks + +**Covers:** +- All hook types (SessionStart, PreToolUse, PostToolUse, etc.) +- Matcher patterns for tool filtering +- Exit codes and control flow +- Environment variables +- Complete working examples + +[View Details](./skills/claude-code-hooks/SKILL.md) + +### claude-code-subagents + +**Covers:** +- Common problems and solutions +- System prompt optimization +- Tool access strategies +- Model selection guide +- Testing and validation +- Migration from ad-hoc prompts + +[View Details](./skills/claude-code-subagents/SKILL.md) + +### claude-code-memory + +**Covers:** +- Memory hierarchy (project/user/subfolder) +- Token management and optimization +- Import system (@path/to/file) +- Team collaboration patterns +- Troubleshooting loading issues +- Template examples + +[View Details](./skills/claude-code-memory/SKILL.md) + +## Best Practices + +### Initial Setup +1. Use built-in commands first: + - `/init` for memory setup + - `/agents` for subagent creation +2. Use these skills to refine and optimize afterward + +### Progressive Learning +Start with one skill at a time: +1. Begin with **memory** - establish good context management +2. Add **slash commands** for common workflows +3. Implement **hooks** for automation +4. Create **subagents** for specialized tasks +5. Package everything in **plugins** for reusability + +### Team Collaboration +- Share this plugin with your team for consistent workflows +- Use memory files for team standards +- Create project-specific slash commands +- Document subagent usage patterns + +## Troubleshooting + +**Skills not activating?** +- Verify plugin is installed: `/plugin list` +- Check descriptions match your use case +- 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 + +## 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 + +## Contributing + +Found an issue or have improvements? See the main marketplace [CONTRIBUTING.md](../CONTRIBUTING.md). + +## License + +See main marketplace repository for license information. + +--- + +**Remember**: These skills are for refinement and troubleshooting. Use Claude Code's built-in commands (`/init`, `/agents`, `/memory`) for initial setup, then use these skills to optimize. diff --git a/claude-code/skills/claude-code-hooks/SKILL.md b/claude-code/skills/claude-code-hooks/SKILL.md new file mode 100644 index 0000000..591fabb --- /dev/null +++ b/claude-code/skills/claude-code-hooks/SKILL.md @@ -0,0 +1,1049 @@ +--- +name: Claude Code Hooks +description: Configure event-driven hooks for Claude Code to automate workflows, validate code, inject context, and control tool execution. Use when setting up automation, enforcing standards, or integrating external tools with Claude Code. +--- + +# 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 +- Controlling MCP tool permissions +- Setting up team-wide automation + +Do NOT use this skill for: +- Creating slash commands (use claude-code-slash-commands skill) +- Building full plugins (use claude-code-plugins skill) +- One-time scripts (just run them directly) + +## Quick Start: Creating a Hook + +### 1. Basic Hook Configuration + +Create or edit settings 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" + } + ] + } + ] + } +} +``` + +**Result**: Every file write/edit gets logged with timestamp. + +## Hook Types + +### SessionStart + +Runs when a session begins (before any interaction): + +```json +{ + "hooks": { + "SessionStart": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "echo 'Project: MyApp | Env: production' > .claude/context.txt" + } + ] + } + ] + } +} +``` + +**Use For**: Injecting project context, loading environment info + +### SessionEnd + +Runs when a session ends: + +```json +{ + "hooks": { + "SessionEnd": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "git add . && git stash save 'Claude session backup'" + } + ] + } + ] + } +} +``` + +**Use For**: Cleanup, backups, state preservation + +### PreToolUse + +Runs after Claude creates tool parameters but before execution: + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "echo 'About to write: $TOOL_ARGS' && exit 0" + } + ] + } + ] + } +} +``` + +**Use For**: Validation, permission checks, preprocessing + +### PostToolUse + +Runs immediately after tool completes successfully: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit", + "hooks": [ + { + "type": "command", + "command": "npx prettier --write $TOOL_ARGS" + } + ] + } + ] + } +} +``` + +**Use For**: Formatting, linting, post-processing + +### UserPromptSubmit + +Runs when user submits a prompt (before Claude processes it): + +```json +{ + "hooks": { + "UserPromptSubmit": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "date >> .claude/prompt-log.txt && exit 0" + } + ] + } + ] + } +} +``` + +**Use For**: Logging, analytics, context injection + +### Notification + +Runs when Claude sends notifications (permission requests, idle waiting): + +```json +{ + "hooks": { + "Notification": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'" + } + ] + } + ] + } +} +``` + +**Use For**: Desktop notifications, alerts + +### Stop / SubagentStop + +Runs when agents finish responding: + +```json +{ + "hooks": { + "Stop": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "echo 'Response complete' >> .claude/activity.log && exit 0" + } + ] + } + ] + } +} +``` + +**Use For**: Post-response processing, logging + +### PreCompact + +Runs before context compaction: + +```json +{ + "hooks": { + "PreCompact": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "echo 'Compacting context...' && exit 0" + } + ] + } + ] + } +} +``` + +**Use For**: Logging, saving state before compaction + +## Matcher Patterns + +### Tool Name Matching + +```json +// Single tool +"matcher": "Write" + +// Multiple tools (OR) +"matcher": "Write|Edit|Read" + +// All tools +"matcher": "*" + +// Regex patterns supported +"matcher": "Bash.*|Git.*" +``` + +### Common Patterns + +```json +// File operations +"matcher": "Write|Edit|Delete" + +// Read operations +"matcher": "Read|Grep|Glob" + +// Git operations +"matcher": "Bash(git:*)" + +// All Bash commands +"matcher": "Bash" +``` + +## Hook Configuration + +### Basic Structure + +```json +{ + "type": "command", + "command": "your-command-here", + "timeout": 60 +} +``` + +### Command Field + +Use bash commands with environment variables: + +```json +{ + "type": "command", + "command": "cd $CLAUDE_PROJECT_DIR && npm test" +} +``` + +### Timeout Field + +Optional execution limit in seconds (default: 60): + +```json +{ + "type": "command", + "command": "long-running-task", + "timeout": 300 // 5 minutes +} +``` + +## Exit Codes & Control Flow + +### Exit Code 0 - Success (Continue) + +```bash +# Hook succeeds, stdout shown to user (most events) +echo "Success message" +exit 0 +``` + +### Exit Code 2 - Blocking Error + +```bash +# Hook blocks operation, stderr sent to Claude +echo "Error: Cannot proceed" >&2 +exit 2 +``` + +**Use For**: Validation failures, permission denials + +### Other Exit Codes - Non-Blocking Error + +```bash +# Hook fails but operation continues +echo "Warning: Hook failed" >&2 +exit 1 +``` + +## Environment Variables + +### Available 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, PostToolUse, etc.) +``` + +### Example Usage + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "cd $CLAUDE_PROJECT_DIR && git add $TOOL_ARGS" + } + ] + } + ] + } +} +``` + +## Complete Examples + +### 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)' $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. 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" + } + ] + } + ] + } +} +``` + +### 5. 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 + } + ] + } + ] + } +} +``` + +### 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. Enforce File Permissions + +Ensure proper permissions on sensitive files: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "if [[ $TOOL_ARGS == *\".env\"* ]]; then chmod 600 $TOOL_ARGS; fi; exit 0" + } + ] + } + ] + } +} +``` + +### 8. Notify on Long Sessions + +Alert when session ends: + +```json +{ + "hooks": { + "SessionEnd": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "osascript -e 'display notification \"Session ended\" with title \"Claude Code\"' && exit 0" + } + ] + } + ] + } +} +``` + +## Advanced Patterns + +### Multiple Hooks per Event + +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" + } + ] + } + ] + } +} +``` + +Hooks run in order; if one fails, subsequent hooks may not run. + +### Conditional Execution + +Use bash conditionals: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "if [[ $TOOL_ARGS == *.js ]]; then npm run format $TOOL_ARGS; fi; exit 0" + } + ] + } + ] + } +} +``` + +### Script-Based Hooks + +Call external scripts 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 +``` + +### JSON Output for Advanced Control + +Return structured data (advanced): + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "echo '{\"continue\": true, \"decision\": \"allow\"}'" + } + ] + } + ] + } +} +``` + +## Settings File Hierarchy + +### Load Order (Highest to Lowest Priority) + +1. `.claude/settings.local.json` - Project-specific, user-only (gitignored) +2. `.claude/settings.json` - Project-specific, team-shared (in git) +3. `~/.claude/settings.json` - Global, user-only + +### Use Cases + +**Global (~/.claude/settings.json)**: +- Personal preferences +- Universal logging +- Desktop notifications + +**Project (.claude/settings.json)**: +- Team standards +- Project-specific automation +- Shared workflows + +**Local (.claude/settings.local.json)**: +- Personal overrides +- Development experiments +- User-specific credentials + +## Testing Hooks + +### 1. Start Simple + +Test with basic echo: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "echo 'Hook triggered for: $TOOL_ARGS' && exit 0" + } + ] + } + ] + } +} +``` + +### 2. Verify Environment Variables + +```json +{ + "hooks": { + "SessionStart": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "echo \"Project: $CLAUDE_PROJECT_DIR\" && exit 0" + } + ] + } + ] + } +} +``` + +### 3. 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. + +### 4. Check Timeout + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "sleep 5 && echo 'Done'", + "timeout": 3 + } + ] + } + ] + } +} +``` + +Should timeout after 3 seconds. + +## Common Use Cases + +### Code Quality Enforcement + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit", + "hooks": [ + { + "type": "command", + "command": "npx prettier --write $TOOL_ARGS && npx eslint --fix $TOOL_ARGS && exit 0" + } + ] + } + ] + } +} +``` + +### Security Scanning + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "if grep -qE '(sk-[a-zA-Z0-9]{48}|ghp_[a-zA-Z0-9]{36})' $TOOL_ARGS 2>/dev/null; then echo 'API key detected!' >&2; exit 2; fi; exit 0" + } + ] + } + ] + } +} +``` + +### Automatic Documentation + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "if [[ $TOOL_ARGS == *.js ]]; then npx jsdoc2md $TOOL_ARGS >> API.md; fi; exit 0" + } + ] + } + ] + } +} +``` + +### Change Tracking + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": "echo \"$(date): $TOOL_NAME $TOOL_ARGS\" >> .claude/audit.log && exit 0" + } + ] + } + ] + } +} +``` + +## Troubleshooting + +### Hook Not Triggering + +**Issue**: Hook doesn't run when expected + +**Solutions**: +1. Check matcher pattern matches tool name +2. Verify settings file location and syntax (valid JSON) +3. Restart Claude Code to reload settings +4. Test with simple echo command first + +### Hook Fails Silently + +**Issue**: Hook runs but doesn't work as expected + +**Solutions**: +1. Check exit codes (0 for success) +2. Verify command syntax in terminal first +3. Check timeout isn't too short +4. Look at stderr output + +### Command Not Found + +**Issue**: Hook says command not found + +**Solutions**: +1. Use full path to command: `/usr/local/bin/prettier` +2. Check command is in PATH +3. Test command in terminal first + +### Permission Denied + +**Issue**: Hook can't execute script + +**Solutions**: +```bash +chmod +x .claude/hooks/script.sh +``` + +## Best Practices + +### 1. Always Exit with Code + +```bash +# Good - explicit exit +command && exit 0 + +# Bad - implicit exit might vary +command +``` + +### 2. Use Timeouts for Long Operations + +```json +{ + "type": "command", + "command": "npm test", + "timeout": 120 // Don't let tests run forever +} +``` + +### 3. Handle Errors Gracefully + +```bash +# Check if file exists before processing +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 + +Don't put complex bash in JSON: + +```json +// Bad +{ + "command": "if [ -f $TOOL_ARGS ]; then cat $TOOL_ARGS | grep pattern | wc -l; fi && exit 0" +} + +// Good +{ + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/check-file.sh $TOOL_ARGS" +} +``` + +### 5. Test Before Deploying + +Test in `.claude/settings.local.json` before adding to `.claude/settings.json`. + +### 6. Document Your Hooks + +Add comments in settings: + +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit", + "hooks": [ + { + "type": "command", + "command": "npx prettier --write $TOOL_ARGS", + "_comment": "Auto-format all JS/TS files on save" + } + ] + } + ] + } +} +``` + +(Note: JSON doesn't officially support comments, but Claude Code ignores `_comment` fields) + +## Security Considerations + +### Validate Input + +```bash +# Sanitize TOOL_ARGS before use +if [[ ! $TOOL_ARGS =~ ^[a-zA-Z0-9/_.-]+$ ]]; then + echo "Invalid file path" >&2 + exit 2 +fi +``` + +### Limit Permissions + +Don't use `*` matcher unless necessary: + +```json +// Specific +"matcher": "Write|Edit" + +// Too broad +"matcher": "*" +``` + +### Avoid Destructive Commands + +```bash +# Dangerous +rm -rf $TOOL_ARGS + +# Better - add safety checks +if [[ -f "$TOOL_ARGS" ]] && [[ "$TOOL_ARGS" != "/" ]]; then + rm "$TOOL_ARGS" +fi +``` + +### Use Local Settings for Sensitive Operations + +Keep potentially dangerous hooks in `.claude/settings.local.json` (not shared). + +## Resources + +- [Official Hooks Documentation](https://docs.claude.com/en/docs/claude-code/hooks) +- [Slash Commands](../claude-code-slash-commands/SKILL.md) - For command-based automation +- [Plugin Development](../claude-code-plugins/SKILL.md) - For packaging hooks in plugins + +--- + +**Remember**: Hooks are powerful automation tools. Start with simple, safe operations. Test thoroughly before deploying to teams. Use exit codes properly to control flow. diff --git a/claude-code/skills/claude-code-memory/SKILL.md b/claude-code/skills/claude-code-memory/SKILL.md new file mode 100644 index 0000000..c7ab3af --- /dev/null +++ b/claude-code/skills/claude-code-memory/SKILL.md @@ -0,0 +1,1032 @@ +--- +name: Claude Code Memory Specialist +description: Optimize and troubleshoot Claude Code memory files (CLAUDE.md) for efficiency, token management, and team collaboration. Use when memory isn't loading, context is bloated, or optimizing existing memory files. 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 +- Managing token consumption +- Setting up memory hierarchy (project/user/subfolder) +- Creating additional memory files and imports +- Debugging why Claude isn't following instructions +- Organizing memory for team collaboration +- Converting verbose documentation to efficient memory + +Do NOT use this skill for: +- **Initial setup** - Use `/init` command instead +- Creating slash commands (use claude-code-slash-commands skill) +- General Claude Code issues + +**Important**: Always start with `/init` for initial project memory setup. Use this skill to refine and troubleshoot afterward. + +## 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 (loaded when in subfolder) +``` + +**Lookup Order**: Claude recursively searches upward from current directory, loading all CLAUDE.md files found. + +## Common Problems & Solutions + +### Problem 1: Memory File Not Loading + +**Symptoms**: Claude doesn't seem to remember project context + +**Diagnose**: +```bash +# Check if memory file exists +ls -la CLAUDE.md +ls -la .claude/CLAUDE.md +ls -la ~/.claude/CLAUDE.md + +# Check file permissions +ls -l CLAUDE.md +``` + +**Common Causes**: + +1. **Wrong Location** +```bash +# ❌ Bad: Random location +/some/random/path/CLAUDE.md + +# βœ“ Good: Project root +./CLAUDE.md +# or +./.claude/CLAUDE.md +``` + +2. **Wrong Filename** (Case-sensitive!) +```bash +# ❌ Bad +claude.md +Claude.md +CLAUDE.MD + +# βœ“ Good +CLAUDE.md +``` + +3. **Syntax Errors in Imports** +```markdown +# ❌ Bad: Broken import +@docs/nonexistent.md + +# βœ“ Good: Valid path +@docs/architecture.md +``` + +**Fix - Verify Loading**: +```markdown +# Add to top of CLAUDE.md temporarily +**MEMORY LOADED: Project memory is active** + +# Ask Claude: "What's at the top of your memory?" +# Should see the marker +``` + +### Problem 2: Bloated Memory (Token Waste) + +**Symptoms**: Context fills up quickly, slow responses, high costs + +**Diagnose**: +```bash +# Check memory file size +wc -l CLAUDE.md +# Goal: 100-200 lines max + +# Count total tokens (rough estimate: chars Γ· 4) +wc -c CLAUDE.md +``` + +**Fix - Trim and Split**: + +```markdown +# Before (Bloated - 500 lines) +# 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. We follow a microservices architecture with... + +[400 more lines of verbose content] +``` + +```markdown +# After (Lean - 150 lines) +# Tech Stack + +- Frontend: React 18 + TypeScript + Tailwind +- Backend: Express + PostgreSQL + Redis +- Architecture: Microservices pattern +- See @docs/architecture.md for details + +# Coding Standards + +- 2-space indentation +- Functional components only +- ESLint + Prettier +- 80% test coverage minimum + +# Common Commands + +```bash +npm run dev # Local development +npm test # Run all tests +npm run build # Production build +``` + +# Key Files + +- `src/api/`: REST endpoints +- `src/components/`: React components +- See @docs/file-structure.md + +# IMPORTANT Project Rules + +- YOU MUST run tests before committing +- Never commit .env files +- Always update API docs when adding endpoints +``` + +**Best Practices**: +- **100-200 lines max** for main CLAUDE.md +- Use **bullet points**, not paragraphs +- Be **specific**, not verbose +- **Import** detailed docs instead of embedding + +### Problem 3: Claude Not Following Instructions + +**Symptoms**: Claude ignores rules in CLAUDE.md + +**Diagnose**: +```markdown +# Check instruction specificity + +# ❌ Too vague +- Write clean code +- Follow best practices +- Be careful with security + +# βœ“ Specific +- Use 2-space indentation (not tabs) +- All API endpoints must have rate limiting +- Hash passwords with bcrypt (min 10 rounds) +``` + +**Fix - Add Emphasis**: + +```markdown +# Before (Weak) +Use functional components in React. + +# After (Strong) +IMPORTANT: ALL React components MUST be functional (no class components). + +# Before (Ignored) +Run tests before committing. + +# After (Enforced) +YOU MUST run `npm test` and ensure all tests pass before any git commit. +``` + +**Emphasis Techniques**: +- `IMPORTANT:` for critical rules +- `YOU MUST` for mandatory actions +- `NEVER` for forbidden actions +- **Bold** for emphasis +- ALL CAPS for maximum attention + +### Problem 4: Memory Updates Not Reflected + +**Symptoms**: Changes to CLAUDE.md don't take effect + +**Fix**: + +**Method 1: Quick Add** +```bash +# Press # at input start +# Type: Use snake_case for Python functions +# Claude auto-adds to appropriate CLAUDE.md +``` + +**Method 2: Manual Edit** +```bash +# Use /memory command +/memory + +# Or edit directly +vim CLAUDE.md + +# Then explicitly ask Claude to reload +"Please re-read CLAUDE.md" +``` + +**Method 3: Session Restart** +```bash +# Most reliable: restart session +# Ctrl+C or close/reopen Claude Code +``` + +### Problem 5: Too Many Memory Files + +**Symptoms**: Conflicting instructions, unclear hierarchy + +**Diagnose**: +```bash +# Find all CLAUDE.md files +find . -name "CLAUDE.md" +find ~ -name "CLAUDE.md" +``` + +**Understand Priority**: +``` +Higher Priority (wins on conflict) +↓ +1. ~/.claude/enterprise/CLAUDE.md # Organization policy +2. ./CLAUDE.md # Current project +3. ~/.claude/CLAUDE.md # Your personal defaults +4. ./subfolder/CLAUDE.md # Subfolder overrides +↓ +Lower Priority +``` + +**Fix - Organize Properly**: + +```markdown +# ~/.claude/CLAUDE.md (Personal defaults for ALL projects) +# General Preferences + +- Prefer functional programming +- Explain complex code +- Ask before destructive operations + +# ./CLAUDE.md (Project-specific, overrides above) +# MyProject Specifics + +@docs/tech-stack.md +@docs/conventions.md + +IMPORTANT: This project uses OOP (override personal FP preference). + +# ./frontend/CLAUDE.md (Frontend-specific) +# Frontend Guidelines + +- React + TypeScript +- Component-driven development +- See @../docs/ui-patterns.md +``` + +### Problem 6: Import Loops or Errors + +**Symptoms**: "Import depth exceeded" or circular imports + +**Fix - Import Rules**: + +```markdown +# ❌ Bad: Too deep +CLAUDE.md + β†’ @docs/a.md + β†’ @docs/b.md + β†’ @docs/c.md + β†’ @docs/d.md + β†’ @docs/e.md + β†’ @docs/f.md (FAILS - max depth 5) + +# βœ“ 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 +``` + +**Import Best Practices**: +- Max depth: 5 levels +- No circular references +- Use relative paths for project files +- Use absolute paths for user/global files + +## Optimization Patterns + +### Pattern 1: Core + Imports Architecture + +```markdown +# CLAUDE.md (Core - 100 lines) +# 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 + +--- + +# docs/tech-stack.md (Detailed - loaded on demand) +[Full tech stack details, dependencies, versions...] + +# docs/style-guide.md (Detailed) +[Comprehensive coding standards...] + +# docs/architecture.md (Detailed) +[System architecture diagrams, patterns...] +``` + +**Benefits**: +- Main memory stays lean +- Details loaded only when needed +- Easy to update specific areas +- Team can own different docs + +### Pattern 2: Subfolder Specialization + +```markdown +# Project Structure +myproject/ +β”œβ”€β”€ CLAUDE.md # Project-wide context +β”œβ”€β”€ frontend/ +β”‚ β”œβ”€β”€ CLAUDE.md # Frontend-specific +β”‚ └── src/ +β”œβ”€β”€ backend/ +β”‚ β”œβ”€β”€ CLAUDE.md # Backend-specific +β”‚ └── src/ +└── docs/ + β”œβ”€β”€ architecture.md + └── conventions.md + +# ./CLAUDE.md (Root) +# MyProject + +Microservices e-commerce platform. + +Common across all areas: +- Git workflow: feature branches + PRs +- Testing required before merge +- See @docs/architecture.md + +# ./frontend/CLAUDE.md (Loaded when in frontend/) +# Frontend Context + +- React 18 + TypeScript strict mode +- Component structure: Atomic Design +- Styling: Tailwind utility-first +- State: Redux Toolkit + +## Component Patterns +@../docs/ui-patterns.md + +# ./backend/CLAUDE.md (Loaded when in backend/) +# Backend Context + +- Express + TypeScript +- Database: PostgreSQL + Sequelize +- Auth: JWT + refresh tokens +- Caching: Redis + +## API Patterns +@../docs/api-patterns.md +``` + +**When to Use**: +- Large monorepos +- Different tech stacks per area +- Team specialization (frontend/backend teams) +- Different conventions per module + +### Pattern 3: User + Project Separation + +```markdown +# ~/.claude/CLAUDE.md (Personal preferences - ALL projects) +# 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` + +# ./CLAUDE.md (Project overrides personal defaults) +# 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 +``` + +**Benefits**: +- Consistent personal style across projects +- Project-specific overrides when needed +- Easy onboarding to new projects + +### Pattern 4: Team Collaboration + +```markdown +# .claude/CLAUDE.md (Team-shared, in git) +# 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 + +## Tech Stack +@docs/tech-stack.md + +## NEVER +- Commit directly to `main` +- Merge without tests passing +- Hardcode credentials + +# .claude/CLAUDE.local.md (Personal, gitignored) +# My Personal Overrides + +[Your personal preferences that don't affect team] +``` + +**Team Setup**: +```gitignore +# .gitignore +.claude/CLAUDE.local.md # Personal only +.claude/settings.local.json # Personal settings +``` + +**Benefits**: +- Consistent team standards +- Personal customization allowed +- Version control for team rules +- Onboarding documentation + +## Token Management Strategies + +### Strategy 1: Measure Current Usage + +```bash +# Estimate tokens in memory +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 +grep -n "." CLAUDE.md | awk -F: 'length($2) > 100 {print NR": "$0}' +``` + +### Strategy 2: Lean Writing + +```markdown +# Before (150 tokens) +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) +Architecture: Microservices (REST + message queues) +- Independent deployment/scaling +- See @docs/architecture.md +``` + +**Compression Techniques**: +- Bullet points > paragraphs +- Commands > explanations +- Imports > embedding +- Examples > theory + +### Strategy 3: Strategic Importing + +```markdown +# CLAUDE.md - Always Loaded (100 lines = ~400 tokens) +Common commands, key conventions, critical rules + +# @docs/ - Loaded On Demand +architecture.md # Loaded when discussing architecture +api-reference.md # Loaded when working on APIs +testing-guide.md # Loaded when writing tests +deployment.md # Loaded when deploying +``` + +**Import Decision Tree**: +``` +Need info for 80%+ of sessions? + β†’ Put in CLAUDE.md + +Need info occasionally? + β†’ Put in @docs/, reference from CLAUDE.md + +Need info rarely? + β†’ Don't include, use web search or direct file read +``` + +### Strategy 4: Regular Cleanup + +```bash +# Monthly review checklist +# 1. Remove outdated info +grep -i "deprecated\|old\|legacy\|TODO" CLAUDE.md + +# 2. Merge redundant sections +# 3. Move details to @docs/ +# 4. Update changed conventions +# 5. Test: does Claude follow all rules? +``` + +## Testing Memory Effectiveness + +### Test 1: Loading Verification + +```markdown +# Add temporary marker +**MEMORY TEST: If you see this, memory loaded correctly** + +# Ask Claude +"What's the first line of your project memory?" + +# Should respond with marker +# Remove marker after verification +``` + +### Test 2: Instruction Adherence + +```markdown +# Test Plan + +Rule: "Use 2-space indentation" +Test: Ask Claude to write a function +Expected: 2-space indentation +Actual: ___ + +Rule: "Run tests before commit" +Test: Ask Claude to commit changes +Expected: Runs npm test first +Actual: ___ + +Rule: "Never commit .env files" +Test: Ask to add .env to commit +Expected: Refuses or warns +Actual: ___ +``` + +### Test 3: Token Efficiency + +```markdown +# Baseline +Current tokens: ___ (measure file size Γ· 4) +Session context usage: ___ (check /usage) + +# After optimization +New tokens: ___ +Reduction: ___ +Improvement: ___% + +# Quality check +Does Claude still follow all rules? Yes/No +Response quality maintained? Yes/No +``` + +### Test 4: Team Consistency + +```markdown +# Cross-developer test + +Developer A asks: "What's our git workflow?" +Claude response: ___ + +Developer B asks: "What's our git workflow?" +Claude response: ___ + +Responses identical? Yes/No +If no, identify conflict in memory files. +``` + +## Memory File Templates + +### Template 1: Minimal Project + +```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 +``` + +### Template 2: Team Project + +```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 +``` + +### Template 3: Monorepo + +```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 +``` + +### Template 4: Personal Defaults + +```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 +``` + +## Troubleshooting Checklist + +When memory isn't working: + +```markdown +- [ ] File named exactly "CLAUDE.md" (case-sensitive) +- [ ] File in correct location (project root or .claude/) +- [ ] File has valid markdown syntax +- [ ] Imports use correct paths (relative/absolute) +- [ ] No circular import loops +- [ ] Import depth ≀ 5 levels +- [ ] File size reasonable (< 20KB) +- [ ] Instructions are specific, not vague +- [ ] Used emphasis (IMPORTANT, YOU MUST) for critical rules +- [ ] No syntax errors in code blocks +- [ ] Tried reloading (/memory or restart) +- [ ] Verified loading with test marker +``` + +## Common Anti-Patterns + +### ❌ Anti-Pattern 1: Novel-Length Memory + +```markdown +# CLAUDE.md (2000 lines) +[Extensive documentation about everything...] +``` + +**Why Bad**: Wastes tokens, slows responses, high cost + +**Fix**: Keep to 100-200 lines, import details + +### ❌ Anti-Pattern 2: Vague Instructions + +```markdown +- Write good code +- Follow best practices +- Be secure +``` + +**Why Bad**: Too generic, Claude ignores + +**Fix**: Be specific with examples + +### ❌ Anti-Pattern 3: Mixing Concerns + +```markdown +# CLAUDE.md +[Project setup] +[Personal preferences] +[Team standards] +[Implementation details] +[API documentation] +[All mixed together] +``` + +**Why Bad**: Hard to maintain, conflicts + +**Fix**: Separate files by scope and audience + +### ❌ Anti-Pattern 4: Static Documentation + +```markdown +# Last updated: 6 months ago +[Outdated conventions] +[Deprecated tools] +[Old architecture] +``` + +**Why Bad**: Misleads Claude, causes errors + +**Fix**: Regular reviews, use # for quick updates + +### ❌ Anti-Pattern 5: No Imports + +```markdown +# CLAUDE.md (500 lines) +[Everything embedded inline] +``` + +**Why Bad**: Token waste, hard to navigate + +**Fix**: Use @imports for detailed docs + +## Advanced Techniques + +### Technique 1: Dynamic Context Loading + +```markdown +# CLAUDE.md +When working on: +- Frontend β†’ Read @frontend/CLAUDE.md +- Backend β†’ Read @backend/CLAUDE.md +- DevOps β†’ Read @docs/devops.md +- Testing β†’ Read @docs/testing.md +``` + +### Technique 2: Versioned Standards + +```markdown +# CLAUDE.md +Current API version: v2 +See @docs/api-v2.md + +Migration from v1: +@docs/migration-v1-to-v2.md +``` + +### Technique 3: Role-Based Memory + +```markdown +# CLAUDE.md +Your current role: Full-stack developer + +Available roles: +- @docs/role-frontend.md +- @docs/role-backend.md +- @docs/role-devops.md +- @docs/role-qa.md + +Switch with: "Act as [role]" +``` + +### Technique 4: Conditional Instructions + +```markdown +# CLAUDE.md +## Environment-Aware + +When in development: +- Verbose logging OK +- Use local DB + +When in production: +- Minimal logging +- Use RDS +- NEVER commit with `console.log` +``` + +### Technique 5: Memory Backup System + +```bash +# Create backup before major changes +cp CLAUDE.md CLAUDE.md.backup.$(date +%Y%m%d) + +# Or use git +git add CLAUDE.md +git commit -m "docs: update memory before refactor" + +# Rollback if needed +git checkout HEAD~1 -- CLAUDE.md +``` + +## Team Workflows + +### Workflow 1: Onboarding New Developer + +```bash +# 1. Clone repo (includes .claude/CLAUDE.md) +git clone repo + +# 2. Claude reads memory automatically +# New dev asks: "What's this project?" + +# 3. Claude uses CLAUDE.md to explain: +# - Tech stack +# - Architecture +# - Conventions +# - Common commands + +# 4. New dev productive immediately +``` + +### Workflow 2: Updating Standards + +```bash +# 1. Team decision: Switch to pnpm +# 2. Update CLAUDE.md: +# s/npm/pnpm/g + +# 3. Commit change +git commit -m "docs: switch to pnpm" + +# 4. All developers get update on pull +# 5. Claude uses new standard automatically +``` + +### Workflow 3: Feature-Specific Memory + +```bash +# Working on auth feature +cd features/auth + +# features/auth/CLAUDE.md +# Authentication Feature + +Uses JWT + refresh tokens +See @../../docs/auth-patterns.md + +Important: +- Password: bcrypt (min 12 rounds) +- Tokens: 15min access, 7d refresh +- MFA required for admin + +# Claude loads this when in auth directory +``` + +## Quick Fixes Reference + +| 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 | Check hierarchy, project wins over user | +| Import not found | Verify path, use relative for project files | +| Import loop | Check for circular references | +| Too verbose | Use bullets, not paragraphs | +| Team inconsistency | Put shared rules in `.claude/CLAUDE.md` (in git) | +| Personal conflicts | Use `.claude/CLAUDE.local.md` (gitignored) | + +## Resources + +- [Official Memory Documentation](https://docs.claude.com/en/docs/claude-code/memory) +- [Claude Code Plugins](../claude-code-plugins/SKILL.md) - For packaging memory in plugins +- [Slash Commands](../claude-code-slash-commands/SKILL.md) - Complement to memory +- [Hooks](../claude-code-hooks/SKILL.md) - Automation with memory + +--- + +**Remember**: Start with `/init`, keep memory lean (100-200 lines), be specific not vague, use imports for details, emphasize critical rules, test effectiveness, update regularly. diff --git a/claude-code/skills/claude-code-plugins/SKILL.md b/claude-code/skills/claude-code-plugins/SKILL.md new file mode 100644 index 0000000..2c94908 --- /dev/null +++ b/claude-code/skills/claude-code-plugins/SKILL.md @@ -0,0 +1,546 @@ +--- +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. +--- + +# Claude Code Plugin Development + +## When to Use This Skill + +Use this skill when: +- Creating a new Claude Code plugin from scratch +- Adding components to an existing plugin (commands, agents, skills, hooks) +- Configuring plugin manifests and metadata +- Setting up plugin distribution and marketplaces +- Troubleshooting plugin structure or installation issues + +Do NOT use this skill for: +- Creating standalone MCP servers (use MCP-specific documentation) +- General Claude Code usage (not plugin development) +- Creating individual skills without plugin context + +## Quick Start: Creating a Plugin + +### 1. Basic Plugin Structure + +```bash +# Create plugin directory +mkdir my-plugin +cd my-plugin + +# Create required manifest directory +mkdir -p .claude-plugin + +# Create plugin.json manifest +cat > .claude-plugin/plugin.json << 'EOF' +{ + "name": "my-plugin", + "description": "Description of what your plugin does", + "version": "1.0.0", + "author": { + "name": "Your Name" + } +} +EOF +``` + +### 2. Add Component Directories + +```bash +# Create directories for plugin components +mkdir -p commands # Slash commands +mkdir -p agents # Custom agents +mkdir -p skills # Agent Skills +mkdir -p hooks # Event handlers +``` + +**Result**: Basic plugin structure ready for adding components. + +## Plugin Manifest (plugin.json) + +### Required Fields + +```json +{ + "name": "plugin-name", // Lowercase, kebab-case + "description": "What it does", // Clear, concise description + "version": "1.0.0", // Semantic versioning + "author": { + "name": "Author Name" // Your name or organization + } +} +``` + +### Optional Fields + +```json +{ + "name": "my-plugin", + "description": "Advanced features", + "version": "1.2.0", + "author": { + "name": "Your Name", + "email": "you@example.com", + "url": "https://yoursite.com" + }, + "repository": { + "type": "git", + "url": "https://github.com/user/repo" + }, + "license": "MIT", + "keywords": ["productivity", "automation"] +} +``` + +## Plugin Components + +### 1. Commands (Slash Commands) + +Create markdown files in `commands/` directory: + +```bash +# commands/review-security.md +--- +description: Review code for security vulnerabilities +allowed-tools: Read(*), Grep(*) +--- + +Review the following files for common security issues: +- SQL injection vulnerabilities +- XSS vulnerabilities +- Hardcoded credentials +- Unsafe deserialization + +$ARGUMENTS +``` + +**Usage**: `/review-security @src/auth.js` + +### 2. Agents + +Create agent configurations in `agents/` directory: + +```bash +# agents/code-reviewer.md +--- +description: Reviews code for best practices +tools: [Read, Grep, Bash] +model: claude-sonnet-4 +--- + +You are a code review specialist. When reviewing code: +1. Check for common patterns and anti-patterns +2. Verify error handling +3. Look for security issues +4. Suggest improvements +``` + +### 3. Skills + +Create skill directories in `skills/`: + +```bash +mkdir -p skills/my-skill +# Then create skills/my-skill/SKILL.md with proper frontmatter +``` + +See the `claude-skills` skill for comprehensive skill creation guidance. + +### 4. Hooks + +Create `hooks/hooks.json` to define event handlers: + +```json +{ + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "echo 'File modified: $TOOL_ARGS' >> .claude/activity.log" + } + ] + } + ] +} +``` + +### 5. MCP Servers + +Create `.mcp.json` for external tools: + +```json +{ + "mcpServers": { + "my-server": { + "command": "node", + "args": ["server.js"], + "env": { + "API_KEY": "env:MY_API_KEY" + } + } + } +} +``` + +## 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: +--- + +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 +``` + +## Distribution & Installation + +### Local Development + +Test your plugin locally: + +```bash +# Install from local directory +/plugin install /path/to/my-plugin@local + +# Verify installation +/plugin list +``` + +### Development Marketplace + +Create a development marketplace for testing: + +```json +// ~/.claude/settings.json +{ + "plugin-marketplaces": { + "dev": { + "url": "file:///path/to/marketplace-dir" + } + } +} +``` + +### Team Distribution + +Add to project settings for automatic installation: + +```json +// .claude/settings.json +{ + "plugins": [ + "my-plugin@company-marketplace" + ], + "plugin-marketplaces": { + "company-marketplace": { + "url": "https://plugins.company.com" + } + } +} +``` + +## Best Practices + +### Plugin Design + +1. **Single responsibility**: Each plugin should have a focused purpose +2. **Clear naming**: Use descriptive, kebab-case names +3. **Semantic versioning**: Follow SemVer for version numbers +4. **Documentation**: Include comprehensive README.md + +### Directory Organization + +``` +my-plugin/ +β”œβ”€β”€ .claude-plugin/ # Manifest only +β”‚ └── plugin.json +β”œβ”€β”€ commands/ # At plugin root, not in .claude-plugin/ +β”œβ”€β”€ agents/ # At plugin root +β”œβ”€β”€ skills/ # At plugin root +└── README.md # Usage documentation +``` + +**IMPORTANT**: Component directories go at the plugin root, NOT inside `.claude-plugin/` + +### Testing Checklist + +- [ ] Plugin.json is valid JSON +- [ ] All required fields present +- [ ] Component directories at plugin root +- [ ] Commands have valid frontmatter +- [ ] Skills follow proper structure +- [ ] Local installation works +- [ ] No sensitive data in files +- [ ] README documents all features + +### Version Management + +```bash +# Update version in plugin.json +{ + "version": "1.1.0" // Increment for changes +} + +# Breaking changes: 2.0.0 +# New features: 1.1.0 +# Bug fixes: 1.0.1 +``` + +## Common Patterns + +### Multi-Command Plugin + +For related commands, use subdirectories: + +``` +git-tools/ +β”œβ”€β”€ .claude-plugin/plugin.json +└── commands/ + β”œβ”€β”€ commit.md + β”œβ”€β”€ pr.md + └── review.md +``` + +**Usage**: `/commit`, `/pr`, `/review` + +### Agent + Skill Combination + +Combine agents with specialized skills: + +``` +api-plugin/ +β”œβ”€β”€ .claude-plugin/plugin.json +β”œβ”€β”€ agents/ +β”‚ └── api-specialist.md +└── skills/ + └── rest-api/ + └── SKILL.md +``` + +The agent can leverage the skill for specialized knowledge. + +### Hook-Based Automation + +Use hooks for workflow automation: + +```json +{ + "PostToolUse": [ + { + "matcher": "Write", + "hooks": [ + { + "type": "command", + "command": "npm run format $TOOL_ARGS" + } + ] + } + ] +} +``` + +## Troubleshooting + +### Plugin Not Found + +**Issue**: `/plugin install` can't find plugin + +**Solutions**: +1. Check marketplace configuration in settings.json +2. Verify plugin name matches directory name +3. Ensure plugin.json exists in `.claude-plugin/` + +### Commands Not Available + +**Issue**: Slash commands don't appear + +**Solutions**: +1. Verify commands are in `commands/` at plugin root +2. Check markdown files have `.md` extension +3. Restart Claude Code to refresh + +### Invalid Structure Error + +**Issue**: Plugin fails to load + +**Solutions**: +1. Ensure `.claude-plugin/plugin.json` exists +2. Validate JSON syntax +3. Move component directories to plugin root (not in `.claude-plugin/`) + +## Security Considerations + +### Never Include + +- API keys or credentials in plugin files +- Personal identifying information +- Proprietary code without permission +- Hardcoded paths to user-specific locations + +### Use Environment Variables + +```json +// .mcp.json +{ + "mcpServers": { + "api-server": { + "env": { + "API_KEY": "env:MY_API_KEY" // Reference env var + } + } + } +} +``` + +### Command Permissions + +Limit tool access in command frontmatter: + +```markdown +--- +allowed-tools: Read(src/**), Grep(src/**) +--- +``` + +## Plugin Template + +Use this as a starting point: + +```bash +#!/bin/bash +# create-plugin.sh + +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/" +``` + +## 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) + +## Quick Reference + +### Required Structure +``` +plugin-name/ +└── .claude-plugin/ + └── plugin.json +``` + +### Common Commands +```bash +# Install +/plugin install plugin-name@marketplace + +# List installed +/plugin list + +# Uninstall +/plugin uninstall plugin-name +``` + +### Manifest Template +```json +{ + "name": "plugin-name", + "description": "What it does", + "version": "1.0.0", + "author": {"name": "Your Name"} +} +``` + +--- + +**Remember**: Plugins extend Claude Code with persistent, reusable functionality. Start simple with one or two components, test thoroughly, then expand based on actual needs. diff --git a/claude-code/skills/claude-code-slash-commands/SKILL.md b/claude-code/skills/claude-code-slash-commands/SKILL.md new file mode 100644 index 0000000..010faa7 --- /dev/null +++ b/claude-code/skills/claude-code-slash-commands/SKILL.md @@ -0,0 +1,698 @@ +--- +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: +--- + +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: +--- +``` + +### 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: +--- + +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: +--- + +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: +--- + +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: +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: +--- + +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: +--- + +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: + +# 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. diff --git a/claude-code/skills/claude-code-subagents/SKILL.md b/claude-code/skills/claude-code-subagents/SKILL.md new file mode 100644 index 0000000..6c63104 --- /dev/null +++ b/claude-code/skills/claude-code-subagents/SKILL.md @@ -0,0 +1,934 @@ +--- +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. diff --git a/claude-skills-plugin/.claude-plugin/plugin.json b/claude-skills-plugin/.claude-plugin/plugin.json new file mode 100644 index 0000000..fef9716 --- /dev/null +++ b/claude-skills-plugin/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "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" + ] +} diff --git a/claude-skills-plugin/README.md b/claude-skills-plugin/README.md new file mode 100644 index 0000000..99d81cb --- /dev/null +++ b/claude-skills-plugin/README.md @@ -0,0 +1,250 @@ +# 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. diff --git a/claude-skills/README.md b/claude-skills-plugin/skills/claude-skills/README.md similarity index 100% rename from claude-skills/README.md rename to claude-skills-plugin/skills/claude-skills/README.md diff --git a/claude-skills/SKILL.md b/claude-skills-plugin/skills/claude-skills/SKILL.md similarity index 100% rename from claude-skills/SKILL.md rename to claude-skills-plugin/skills/claude-skills/SKILL.md diff --git a/claude-skills/checklist.md b/claude-skills-plugin/skills/claude-skills/checklist.md similarity index 100% rename from claude-skills/checklist.md rename to claude-skills-plugin/skills/claude-skills/checklist.md diff --git a/claude-skills/examples.md b/claude-skills-plugin/skills/claude-skills/examples.md similarity index 100% rename from claude-skills/examples.md rename to claude-skills-plugin/skills/claude-skills/examples.md diff --git a/claude-skills/templates.md b/claude-skills-plugin/skills/claude-skills/templates.md similarity index 100% rename from claude-skills/templates.md rename to claude-skills-plugin/skills/claude-skills/templates.md