diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml new file mode 100644 index 000000000..205b0fe26 --- /dev/null +++ b/.github/workflows/claude-code-review.yml @@ -0,0 +1,57 @@ +name: Claude Code Review + +on: + pull_request: + types: [opened, synchronize] + # Optional: Only run on specific file changes + # paths: + # - "src/**/*.ts" + # - "src/**/*.tsx" + # - "src/**/*.js" + # - "src/**/*.jsx" + +jobs: + claude-review: + # Optional: Filter by PR author + # if: | + # github.event.pull_request.user.login == 'external-contributor' || + # github.event.pull_request.user.login == 'new-developer' || + # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' + + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code Review + id: claude-review + uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + prompt: | + REPO: ${{ github.repository }} + PR NUMBER: ${{ github.event.pull_request.number }} + + Please review this pull request and provide feedback on: + - Code quality and best practices + - Potential bugs or issues + - Performance considerations + - Security concerns + - Test coverage + + Use the repository's CLAUDE.md for guidance on style and conventions. Be constructive and helpful in your feedback. + + Use `gh pr comment` with your Bash tool to leave your review as a comment on the PR. + + # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md + # or https://docs.claude.com/en/docs/claude-code/cli-reference for available options + claude_args: '--allowed-tools "Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*)"' + diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 000000000..412cef9e6 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,50 @@ +name: Claude Code + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: | + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + actions: read # Required for Claude to read CI results on PRs + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code + id: claude + uses: anthropics/claude-code-action@v1 + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + + # This is an optional setting that allows Claude to read CI results on PRs + additional_permissions: | + actions: read + + # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it. + # prompt: 'Update the pull request description to include a summary of changes.' + + # Optional: Add claude_args to customize behavior and configuration + # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md + # or https://docs.claude.com/en/docs/claude-code/cli-reference for available options + # claude_args: '--allowed-tools Bash(gh pr:*)' + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..77571af78 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,327 @@ +# Contributing to Claude Skills + +Thank you for your interest in contributing to the Claude Skills repository! This guide will help you create, test, and submit high-quality skills. + +## Table of Contents + +- [Getting Started](#getting-started) +- [Contribution Types](#contribution-types) +- [Skill Development Process](#skill-development-process) +- [Submission Guidelines](#submission-guidelines) +- [Code Review Process](#code-review-process) +- [Best Practices](#best-practices) + +## Getting Started + +### Prerequisites + +1. Familiarity with Claude and how skills work +2. Understanding of the [Agent Skills Specification](agent_skills_spec.md) +3. Claude Code or Claude API access for testing + +### Repository Structure + +``` +skills/ +├── README.md # Main documentation +├── agent_skills_spec.md # Official specification +├── CONTRIBUTING.md # This file +├── SKILL_DEVELOPMENT_GUIDE.md # Detailed development guide +├── skill-creator/ # Meta-skill for creating skills +├── template-skill/ # Starting template +└── [skill-name]/ # Individual skills + ├── SKILL.md # Required: Instructions + ├── scripts/ # Optional: Executable code + ├── references/ # Optional: Documentation + └── assets/ # Optional: Output resources +``` + +## Contribution Types + +### 1. New Skills + +We welcome skills that: +- **Solve common problems** - Address frequently requested tasks +- **Demonstrate capabilities** - Show what's possible with skills +- **Fill gaps** - Cover domains not yet represented +- **Improve workflows** - Make complex tasks repeatable + +**Not Accepted:** +- Skills that duplicate existing functionality +- Malicious or harmful content +- Skills requiring proprietary/paid services without clear documentation +- Overly narrow use cases (consider if it should be a slash command instead) + +### 2. Skill Improvements + +- Bug fixes in existing skills +- Performance optimizations +- Better documentation or examples +- Additional bundled resources + +### 3. Documentation + +- Corrections to existing docs +- New tutorials or guides +- Translation efforts +- FAQ additions + +### 4. Tooling + +- Validation scripts +- Testing utilities +- Development helpers +- CI/CD improvements + +## Skill Development Process + +### Step 1: Plan Your Skill + +Before coding, answer these questions: + +1. **What problem does it solve?** Be specific about the use case +2. **Who is the audience?** Developers, designers, analysts, etc. +3. **What makes it reusable?** How does it generalize beyond one task? +4. **What resources are needed?** Scripts, references, assets? + +**Discussion First:** For significant new skills, open an issue first to discuss: +- Whether it fits the repository scope +- If similar functionality exists +- Design approach and structure + +### Step 2: Initialize Your Skill + +Use the skill-creator skill or manually create: + +```bash +# Option 1: Use the initialization script +python scripts/init_skill.py your-skill-name + +# Option 2: Copy the template +cp -r template-skill/ your-skill-name/ +cd your-skill-name/ +``` + +### Step 3: Develop Your Skill + +See [SKILL_DEVELOPMENT_GUIDE.md](SKILL_DEVELOPMENT_GUIDE.md) for detailed guidance on: +- Writing effective SKILL.md instructions +- Organizing bundled resources +- Progressive disclosure patterns +- Testing and validation + +**Key Requirements:** + +1. **SKILL.md** must include: + ```yaml + --- + name: your-skill-name + description: Clear description of what this skill does and when to use it + license: Apache-2.0 # or your chosen license + --- + ``` + +2. **Name conventions:** + - Lowercase only + - Hyphens for spaces (no underscores) + - Descriptive but concise + - Directory name must match `name` in frontmatter + +3. **Description guidelines:** + - Clearly state what the skill does + - Explain when Claude should use it + - Keep under 200 characters for marketplace display + +### Step 4: Test Your Skill + +**Manual Testing:** + +1. Test in Claude Code: + ```bash + # Symlink your skill to local skills directory + ln -s /path/to/your-skill ~/.claude/skills/your-skill-name + + # Test in Claude Code + # Trigger the skill and verify behavior + ``` + +2. Test with Claude API (if applicable) + +3. Verify with different inputs and edge cases + +**Validation:** + +Run the validation script to check for common issues: +```bash +python scripts/validate_skill.py your-skill-name/ +``` + +### Step 5: Document Your Skill + +Ensure your SKILL.md includes: + +- **Clear instructions** - What Claude should do +- **Examples** - Show expected inputs/outputs +- **Constraints** - Any limitations or requirements +- **Tool usage** - Which tools Claude should use +- **Error handling** - How to handle common failures + +Optional but recommended: +- Add examples/ directory with sample inputs +- Include LICENSE.txt if different from repository +- Add README.md for skill-specific developer notes + +### Step 6: Submit Your Contribution + +1. **Fork the repository** + ```bash + gh repo fork anthropics/skills + ``` + +2. **Create a feature branch** + ```bash + git checkout -b add-your-skill-name + ``` + +3. **Make your changes** + ```bash + git add your-skill-name/ + git commit -m "Add your-skill-name skill for [brief description]" + ``` + +4. **Push and create PR** + ```bash + git push origin add-your-skill-name + gh pr create --title "Add your-skill-name skill" --body "Description of your skill and what it does" + ``` + +## Submission Guidelines + +### Pull Request Requirements + +Your PR must include: + +1. **Complete skill directory** with all necessary files +2. **Updated README.md** adding your skill to the list +3. **Clear PR description** explaining: + - What the skill does + - Why it's useful + - Any testing you've performed + - Dependencies or requirements + +### Code Quality Standards + +- **SKILL.md clarity** - Instructions must be clear and unambiguous +- **No hardcoded secrets** - Use environment variables or user inputs +- **Error handling** - Scripts should handle failures gracefully +- **Dependencies documented** - List all requirements clearly +- **License compliance** - All code must be properly licensed + +### Documentation Standards + +- Use GitHub-flavored Markdown +- Include code examples with syntax highlighting +- Provide concrete examples, not abstract descriptions +- Keep instructions concise but complete +- Use progressive disclosure (basic → advanced) + +## Code Review Process + +### What Reviewers Look For + +1. **Functionality** - Does the skill work as described? +2. **Usefulness** - Will others benefit from this skill? +3. **Quality** - Is the code clean and well-documented? +4. **Specification compliance** - Follows agent_skills_spec.md? +5. **Security** - No vulnerabilities or malicious code? + +### Review Timeline + +- Initial review: Within 5 business days +- Follow-up reviews: Within 2 business days +- Merge: After approval from 2 maintainers + +### Addressing Feedback + +- Respond to all review comments +- Push changes to your PR branch +- Mark conversations as resolved when addressed +- Request re-review when ready + +## Best Practices + +### Skill Design + +1. **Start simple** - Begin with core functionality, add features later +2. **Think reusable** - Generalize beyond your specific use case +3. **Progressive disclosure** - Keep SKILL.md lean, use references/ for details +4. **Minimize context** - Use scripts for deterministic operations +5. **Clear triggers** - Make the description specific about when to use + +### Bundled Resources + +**Scripts:** +- Make them executable and self-contained +- Include shebangs (#!/usr/bin/env python3) +- Document dependencies at the top +- Return clear error messages + +**References:** +- Break long docs into focused files +- Use descriptive filenames +- Include grep patterns in SKILL.md for large files +- Keep technical depth appropriate for Claude + +**Assets:** +- Use common formats (PNG, SVG, JSON) +- Include source files when possible +- Document any generation process +- Keep file sizes reasonable (<10MB per file) + +### Testing + +- Test with typical inputs +- Test with edge cases (empty, very large, malformed) +- Test error conditions +- Verify cross-platform compatibility (if applicable) +- Check performance with large inputs + +### Documentation + +- Write for clarity, not cleverness +- Include "why" not just "what" +- Provide runnable examples +- Update docs when changing functionality +- Link to external resources when helpful + +## Getting Help + +### Resources + +- **Skill Creator Skill** - Use the skill-creator skill for guidance +- **Examples** - Study existing skills for patterns +- **Specification** - Refer to agent_skills_spec.md +- **Development Guide** - See SKILL_DEVELOPMENT_GUIDE.md + +### Communication + +- **Questions** - Open a GitHub issue with the `question` label +- **Bugs** - Report issues with the `bug` label +- **Feature Requests** - Use the `enhancement` label +- **Discussions** - Use GitHub Discussions for open-ended topics + +### Community Guidelines + +- Be respectful and constructive +- Assume good intent +- Help others learn and improve +- Give credit where due +- Focus on the contribution, not the contributor + +## License + +By contributing to this repository, you agree that your contributions will be licensed under the Apache License 2.0, unless otherwise specified in your skill's LICENSE.txt file. + +--- + +**Thank you for contributing to Claude Skills!** Your work helps the entire community build better AI-powered workflows. diff --git a/SKILLS_CATALOG.md b/SKILLS_CATALOG.md new file mode 100644 index 000000000..ed9f9eacd --- /dev/null +++ b/SKILLS_CATALOG.md @@ -0,0 +1,637 @@ +# Skills Catalog + +A comprehensive catalog of all available skills organized by category, with detailed descriptions, use cases, and complexity levels. + +## Quick Reference + +| Category | Skills Count | Best For | +|----------|--------------|----------| +| [Creative & Design](#creative--design) | 4 | Visual content, art, animations, theming | +| [Development & Technical](#development--technical) | 6 | Code quality, testing, API integration, documentation | +| [Enterprise & Communication](#enterprise--communication) | 2 | Business communications, branding | +| [Document Processing](#document-processing) | 4 | Creating/editing Office documents, PDFs | +| [Meta Skills](#meta-skills) | 2 | Learning to create skills, templates | + +**Total Skills:** 18 (13 example + 3 new + 4 document skills) + +--- + +## Creative & Design + +### algorithmic-art +**Purpose:** Generate beautiful, code-based art using p5.js with mathematical patterns and animations + +**Key Features:** +- Seeded randomness for reproducible results +- Flow fields and particle systems +- Noise-based animations +- Geometric patterns + +**Use Cases:** +- Creating unique visual art +- Generating branded visuals +- Learning generative art techniques +- Creating animated backgrounds + +**Complexity:** Medium +**Bundled Resources:** Templates for common patterns +**License:** Apache-2.0 + +**When to trigger:** User wants to create generative art, algorithmic visuals, or p5.js sketches + +--- + +### canvas-design +**Purpose:** Create professional visual art in PNG and PDF formats using design philosophy principles + +**Key Features:** +- Two-step design process (rough draft → refinement) +- Support for various design styles +- PNG and PDF output +- Design philosophy guidance + +**Use Cases:** +- Creating posters and graphics +- Design mockups +- Visual presentations +- Marketing materials + +**Complexity:** Medium +**Bundled Resources:** Design guidelines +**License:** Apache-2.0 + +**When to trigger:** User wants to create visual designs, posters, or graphics + +--- + +### slack-gif-creator +**Purpose:** Create animated GIFs specifically optimized for Slack's dimension and file size requirements + +**Key Features:** +- Automatic size optimization for Slack +- Multiple animation templates (wiggle, morph, fade, etc.) +- Color palette management +- Typography and visual effects +- Easing functions for smooth animations + +**Use Cases:** +- Slack emoji and reactions +- Team celebration animations +- Visual communication in chat +- Fun workplace content + +**Complexity:** High +**Bundled Resources:** +- Core animation engine (`core/`) +- Animation templates (`templates/`) +- Python dependencies (`requirements.txt`) + +**License:** Apache-2.0 + +**When to trigger:** User wants to create animated GIFs for Slack + +--- + +### theme-factory +**Purpose:** Apply professional visual themes to artifacts with 10 preset styles or custom theme generation + +**Key Features:** +- 10 pre-defined professional themes +- Custom theme generation +- Consistent color palettes +- Typography systems +- Theme showcase reference + +**Use Cases:** +- Branding consistency +- Rapid prototyping with different looks +- Creating themed documents +- Design system exploration + +**Complexity:** Low +**Bundled Resources:** +- Theme definitions (`themes/`) +- Theme showcase PDF + +**License:** Apache-2.0 + +**When to trigger:** User wants to style artifacts with themes or apply consistent design + +--- + +## Development & Technical + +### artifacts-builder +**Purpose:** Build complex, interactive HTML artifacts using React, Tailwind CSS, and shadcn/ui components + +**Key Features:** +- React component integration +- Tailwind CSS styling +- shadcn/ui component library +- Interactive UI elements +- Responsive design + +**Use Cases:** +- Creating interactive demos +- Building UI prototypes +- Generating web components +- Educational examples + +**Complexity:** High +**Bundled Resources:** Scripts and component templates +**License:** Apache-2.0 + +**When to trigger:** User wants to build React artifacts with Tailwind and shadcn/ui + +--- + +### mcp-builder +**Purpose:** Comprehensive guide for creating high-quality Model Context Protocol (MCP) servers + +**Key Features:** +- MCP server structure guidance +- Best practices for tool design +- Validation and testing patterns +- Resource management +- Error handling strategies + +**Use Cases:** +- Creating new MCP servers +- Integrating external APIs +- Building Claude extensions +- Service integration + +**Complexity:** High +**Bundled Resources:** +- Creation scripts (`scripts/`) +- Reference documentation (`reference/`) +- Example implementations + +**License:** Apache-2.0 + +**When to trigger:** User wants to create or improve MCP servers + +--- + +### webapp-testing +**Purpose:** Test local web applications using Playwright for automated UI testing and verification + +**Key Features:** +- Playwright integration +- UI element verification +- Screenshot capture +- Console log monitoring +- Static and dynamic site testing + +**Use Cases:** +- Automated UI testing +- Visual regression testing +- Debug web applications +- Verify UI functionality + +**Complexity:** Medium +**Bundled Resources:** +- Helper scripts (`scripts/`) +- Example test files (`examples/`) + +**License:** Apache-2.0 + +**When to trigger:** User wants to test web applications with Playwright + +--- + +### code-reviewer ⭐ NEW +**Purpose:** Perform systematic code reviews checking for bugs, security, performance, and code quality + +**Key Features:** +- Systematic review process +- Security vulnerability detection +- Performance analysis +- Code quality assessment +- Prioritized findings (Critical/High/Medium/Low) +- Constructive feedback with examples + +**Use Cases:** +- Pre-commit code reviews +- Learning from code analysis +- Security audits +- Performance optimization identification +- Maintaining code quality standards + +**Complexity:** Medium +**Bundled Resources:** None (instruction-based) +**License:** Apache-2.0 + +**When to trigger:** User requests code review, wants to check code quality, or asks to analyze/review code + +--- + +### api-documentation-writer ⭐ NEW +**Purpose:** Generate comprehensive, developer-friendly API documentation with examples and clear explanations + +**Key Features:** +- REST, GraphQL, and gRPC support +- Complete endpoint documentation +- Code examples in multiple languages +- Authentication documentation +- Error handling guides +- OpenAPI/Swagger spec generation + +**Use Cases:** +- Creating API reference documentation +- Generating OpenAPI specifications +- Documenting new APIs +- Updating existing API docs +- Creating developer portals + +**Complexity:** Medium +**Bundled Resources:** None (instruction-based) +**License:** Apache-2.0 + +**When to trigger:** User wants to document APIs, create API docs, or generate OpenAPI specs + +--- + +### test-generator ⭐ NEW +**Purpose:** Generate comprehensive test suites including unit tests, integration tests, and edge cases + +**Key Features:** +- Multi-framework support (Jest, pytest, JUnit, etc.) +- Unit and integration test generation +- Edge case coverage +- Mocking and fixture setup +- Component and API testing +- Test quality guidelines + +**Use Cases:** +- Adding tests to untested code +- TDD scaffolding +- Improving test coverage +- Learning testing patterns +- Generating test boilerplate + +**Complexity:** Medium +**Bundled Resources:** None (instruction-based) +**License:** Apache-2.0 + +**When to trigger:** User wants to generate tests, add test coverage, or create test suites + +--- + +## Enterprise & Communication + +### brand-guidelines +**Purpose:** Apply Anthropic's official brand colors, typography, and visual guidelines to artifacts + +**Key Features:** +- Official Anthropic brand colors +- Typography specifications +- Logo usage guidelines +- Visual identity standards + +**Use Cases:** +- Creating branded content +- Consistent corporate materials +- Following brand standards +- Company presentations + +**Complexity:** Low +**Bundled Resources:** None (guidelines in SKILL.md) +**License:** Apache-2.0 + +**When to trigger:** User wants to apply Anthropic branding or follow brand guidelines + +--- + +### internal-comms +**Purpose:** Write effective internal communications like status reports, newsletters, FAQs, and announcements + +**Key Features:** +- Multiple communication formats +- Professional writing patterns +- Structure templates +- Tone and style guidance + +**Use Cases:** +- Status reports +- Team newsletters +- FAQ documentation +- Internal announcements +- Policy updates + +**Complexity:** Low +**Bundled Resources:** Example communications (`examples/`) +**License:** Apache-2.0 + +**When to trigger:** User wants to write internal communications or company updates + +--- + +## Document Processing + +The document skills are source-available (not open source) snapshots of production skills used in Claude. They demonstrate advanced patterns for working with complex file formats. + +**Important:** These are point-in-time snapshots for reference. Actively maintained versions ship with Claude. + +### docx +**Purpose:** Create, edit, and analyze Word documents with full formatting support + +**Key Features:** +- Create new Word documents +- Edit existing documents +- Preserve formatting and styles +- Track changes and comments +- Text extraction and analysis +- Table and image support + +**Use Cases:** +- Generating reports +- Creating formatted documents +- Editing Word files +- Extracting document content +- Document automation + +**Complexity:** Very High +**Bundled Resources:** Complex scripts, schemas, validation tools +**License:** Source-available (proprietary) + +--- + +### pdf +**Purpose:** Comprehensive PDF manipulation toolkit for creating, editing, and analyzing PDFs + +**Key Features:** +- Extract text and tables +- Create new PDFs +- Merge and split documents +- Form field handling +- Annotation support +- Image extraction + +**Use Cases:** +- PDF generation +- Document merging +- Data extraction from PDFs +- Form processing +- Report generation + +**Complexity:** Very High +**Bundled Resources:** Complex scripts, reference docs +**License:** Source-available (proprietary) + +--- + +### pptx +**Purpose:** Create, edit, and analyze PowerPoint presentations with layouts and charts + +**Key Features:** +- Create presentations from scratch +- Edit existing slides +- Template support +- Chart generation +- Layout management +- Automated slide generation + +**Use Cases:** +- Presentation generation +- Report decks +- Data visualization in slides +- Template-based presentations +- Bulk slide updates + +**Complexity:** Very High +**Bundled Resources:** Complex scripts, schemas, templates +**License:** Source-available (proprietary) + +--- + +### xlsx +**Purpose:** Create, edit, and analyze Excel spreadsheets with formulas and formatting + +**Key Features:** +- Create spreadsheets +- Edit cells and ranges +- Formula support +- Data formatting +- Chart generation +- Data analysis + +**Use Cases:** +- Report generation +- Data analysis +- Financial models +- Automated data entry +- Spreadsheet templating + +**Complexity:** Very High +**Bundled Resources:** Complex scripts, schemas, validation +**License:** Source-available (proprietary) + +--- + +## Meta Skills + +### skill-creator +**Purpose:** Comprehensive guide for creating effective Claude skills with best practices + +**Key Features:** +- Skill creation methodology +- Structure and organization guidance +- Progressive disclosure patterns +- Bundled resource best practices +- Validation and testing approaches + +**Use Cases:** +- Learning to create skills +- Understanding skill patterns +- Planning new skills +- Improving existing skills +- Skill architecture decisions + +**Complexity:** Low (to use), High (to master) +**Bundled Resources:** +- Initialization script (`scripts/init_skill.py`) +- Packaging script (`scripts/package_skill.py`) +- Quick validation (`scripts/quick_validate.py`) + +**License:** Apache-2.0 + +**When to trigger:** User wants to create a new skill or learn about skill development + +--- + +### template-skill +**Purpose:** Minimal template for starting new skills with proper structure + +**Key Features:** +- Basic SKILL.md structure +- Required frontmatter +- Example instruction format +- Clean starting point + +**Use Cases:** +- Quick skill scaffolding +- Learning skill structure +- Starting point for development + +**Complexity:** Very Low +**Bundled Resources:** None +**License:** Apache-2.0 + +**When to trigger:** User wants a basic skill template to start from + +--- + +## Skill Selection Guide + +### By Complexity + +**Beginner (Low Complexity):** +- brand-guidelines +- internal-comms +- theme-factory +- template-skill + +**Intermediate (Medium Complexity):** +- algorithmic-art +- canvas-design +- webapp-testing +- code-reviewer ⭐ +- api-documentation-writer ⭐ +- test-generator ⭐ + +**Advanced (High Complexity):** +- artifacts-builder +- mcp-builder +- slack-gif-creator + +**Expert (Very High Complexity):** +- All document skills (docx, pdf, pptx, xlsx) + +### By Use Case + +**Code Quality & Development:** +- code-reviewer ⭐ +- test-generator ⭐ +- webapp-testing +- mcp-builder + +**Documentation:** +- api-documentation-writer ⭐ +- internal-comms + +**Creative Work:** +- algorithmic-art +- canvas-design +- slack-gif-creator +- theme-factory + +**Business & Enterprise:** +- brand-guidelines +- internal-comms +- All document skills + +**Learning & Development:** +- skill-creator +- template-skill + +### By Resource Requirements + +**No External Dependencies:** +- Most instruction-based skills +- brand-guidelines +- code-reviewer ⭐ +- api-documentation-writer ⭐ +- test-generator ⭐ +- internal-comms + +**Python Dependencies:** +- slack-gif-creator +- Most document skills + +**Node.js Dependencies:** +- artifacts-builder +- webapp-testing (Playwright) + +**Multiple Dependencies:** +- Document skills (complex toolchains) + +--- + +## Getting Started + +### For First-Time Users + +Start with these approachable skills: +1. **brand-guidelines** - Simple, clear example of instruction-based skills +2. **theme-factory** - Shows how bundled resources work +3. **code-reviewer** ⭐ - Practical, immediately useful +4. **internal-comms** - Good example of structured output + +### For Developers + +Try these technical skills: +1. **test-generator** ⭐ - Improve code quality +2. **code-reviewer** ⭐ - Learn review best practices +3. **api-documentation-writer** ⭐ - Generate docs +4. **webapp-testing** - Automated testing +5. **mcp-builder** - Extend Claude's capabilities + +### For Skill Creators + +Study these for patterns: +1. **skill-creator** - Meta-guidance on skill creation +2. **template-skill** - Minimal starting point +3. **code-reviewer** ⭐ - Well-structured instruction-based skill +4. **slack-gif-creator** - Complex bundled resources example +5. **mcp-builder** - Reference documentation patterns + +--- + +## Installation + +### Claude Code +```bash +# Add marketplace +/plugin marketplace add anthropics/skills + +# Install example skills (including new ones) +/plugin install example-skills@anthropic-agent-skills + +# Install document skills +/plugin install document-skills@anthropic-agent-skills +``` + +### Claude.ai +These skills are available to paid plans. Upload custom skills via the skills menu. + +### Claude API +Use the Skills API to upload and use custom skills. See [Skills API Quickstart](https://docs.claude.com/en/api/skills-guide#creating-a-skill). + +--- + +## Additional Resources + +- **[CONTRIBUTING.md](CONTRIBUTING.md)** - How to contribute new skills +- **[SKILL_DEVELOPMENT_GUIDE.md](SKILL_DEVELOPMENT_GUIDE.md)** - Comprehensive development guide +- **[agent_skills_spec.md](agent_skills_spec.md)** - Official specification +- **[README.md](README.md)** - Repository overview + +### Validation Tools + +- **scripts/validate_skill.py** - Comprehensive skill validation +- **skill-creator/scripts/quick_validate.py** - Quick validation + +--- + +## Legend + +- ⭐ **NEW** - Recently added skills +- **Complexity** - Relative difficulty: Low → Medium → High → Very High +- **Bundled Resources** - Additional files beyond SKILL.md +- **License** - Apache-2.0 (open source) or Source-available (reference only) + +--- + +**Last Updated:** October 2025 +**Total Skills:** 18 (16 open source, 4 source-available, 3 new additions) diff --git a/SKILL_DEVELOPMENT_GUIDE.md b/SKILL_DEVELOPMENT_GUIDE.md new file mode 100644 index 000000000..ee1aff621 --- /dev/null +++ b/SKILL_DEVELOPMENT_GUIDE.md @@ -0,0 +1,922 @@ +# Skill Development Guide + +A comprehensive guide to creating effective, efficient, and maintainable Claude skills. + +## Table of Contents + +- [Core Concepts](#core-concepts) +- [Writing Effective SKILL.md](#writing-effective-skillmd) +- [Bundled Resources Patterns](#bundled-resources-patterns) +- [Progressive Disclosure](#progressive-disclosure) +- [Common Design Patterns](#common-design-patterns) +- [Performance Optimization](#performance-optimization) +- [Testing Strategies](#testing-strategies) +- [Troubleshooting](#troubleshooting) + +## Core Concepts + +### What Makes a Good Skill? + +A good skill is: + +1. **Focused** - Solves one problem well rather than many problems poorly +2. **Reusable** - Works across multiple similar situations +3. **Clear** - Instructions are unambiguous and actionable +4. **Efficient** - Minimizes context usage through progressive disclosure +5. **Reliable** - Handles errors gracefully and produces consistent results + +### Skill vs. Slash Command + +Choose a **Skill** when: +- Multiple steps or complex logic required +- Bundled resources needed (scripts, references, assets) +- Repeated use with different inputs +- Domain expertise or specialized workflow +- Used across different conversations + +Choose a **Slash Command** when: +- Simple, one-time task +- Specific to your project/workflow +- No bundled resources needed +- Quick shortcut or template + +### Skill vs. MCP Server + +Choose a **Skill** when: +- Teaching Claude a workflow or methodology +- Primarily instruction-based +- Uses existing Claude tools +- Doesn't require external API calls + +Choose an **MCP Server** when: +- Providing new tools/capabilities +- Integrating external services +- Real-time data access needed +- System-level operations required + +## Writing Effective SKILL.md + +### Frontmatter Structure + +```yaml +--- +name: your-skill-name # REQUIRED: lowercase, hyphens only +description: Clear, concise description of when to use this skill and what it does # REQUIRED +license: Apache-2.0 # OPTIONAL: default is repository license +allowed-tools: [Read, Write, Bash] # OPTIONAL: Claude Code only +metadata: # OPTIONAL: custom properties + version: "1.0" + author: "Your Name" + tags: ["productivity", "code-generation"] +--- +``` + +### Description Best Practices + +The description is crucial - it determines when Claude will load your skill. + +**Good descriptions:** +- "Use this skill to generate p5.js algorithmic art with seeded randomness and particle systems" +- "Create animated GIFs optimized for Slack with specific dimension and file size requirements" +- "Guide users through creating high-quality MCP servers with best practices and validation" + +**Poor descriptions:** +- "Art generator" (too vague) +- "Use this skill whenever you need to make things" (not specific enough) +- "This skill helps with various tasks related to..." (unclear trigger) + +**Formula:** "Use this skill to [action] [specific output] [with/using] [key features/constraints]" + +### Instruction Writing Principles + +#### 1. Be Directive, Not Descriptive + +**Bad:** +``` +This skill helps create React components. +You might want to use TypeScript. +``` + +**Good:** +``` +Create React components using TypeScript and functional syntax. +Always include prop types and JSDoc comments. +``` + +#### 2. Provide Clear Steps + +**Bad:** +``` +Figure out what the user wants and make it. +``` + +**Good:** +``` +1. Ask the user to describe the component's purpose +2. Determine the required props and their types +3. Create the component file with the following structure: + - Imports + - Type definitions + - Component implementation + - Default export +4. Add example usage in comments +``` + +#### 3. Include Examples + +**Bad:** +``` +Use proper naming conventions. +``` + +**Good:** +``` +Use proper naming conventions: +- Components: PascalCase (Button, UserProfile) +- Functions: camelCase (handleClick, fetchUserData) +- Constants: UPPER_SNAKE_CASE (API_URL, MAX_RETRIES) + +Example: +```tsx +const MAX_RETRY_COUNT = 3; + +export function UserProfile({ userId }: UserProfileProps) { + // implementation +} +``` +``` + +#### 4. Specify Tool Usage + +**Bad:** +``` +Read some files and make changes. +``` + +**Good:** +``` +1. Use Glob to find all component files matching "*.component.tsx" +2. Use Read to examine each component's structure +3. Use Edit to update components that don't follow the pattern +4. Use Bash to run the linter: `npm run lint` +``` + +#### 5. Handle Edge Cases + +``` +Error Handling: +- If the file doesn't exist, create it in the src/components/ directory +- If TypeScript types are missing, generate them from the component usage +- If tests fail, show the user the error and ask how to proceed +- If the user's request is ambiguous, ask clarifying questions before proceeding +``` + +### Instruction Structure Template + +```markdown +--- +name: your-skill-name +description: [When to use this skill] +--- + +# Skill Name + +## Purpose +[One paragraph: what this skill does and why it's useful] + +## When to Use +- [Specific scenario 1] +- [Specific scenario 2] +- [Specific scenario 3] + +## Instructions + +### Step 1: [Phase Name] +[Detailed instructions for this phase] +[Examples if applicable] + +### Step 2: [Phase Name] +[Detailed instructions for this phase] +[Tool usage specifications] + +### Step 3: [Phase Name] +[Detailed instructions for this phase] +[Expected outputs] + +## Guidelines +- [Important rule 1] +- [Important rule 2] +- [Important rule 3] + +## Error Handling +- [Error condition 1]: [How to handle] +- [Error condition 2]: [How to handle] + +## Examples + +### Example 1: [Scenario] +Input: +``` +[Example input] +``` + +Output: +``` +[Example output] +``` + +### Example 2: [Scenario] +[Another example] + +## Bundled Resources +- `scripts/[filename]` - [Purpose] +- `references/[filename]` - [When to load this] +- `assets/[filename]` - [How to use this] +``` + +## Bundled Resources Patterns + +### Scripts Directory + +Use scripts for: +- **Deterministic operations** - Exact formatting, complex algorithms +- **External tool integration** - Calling APIs, processing files +- **Performance-critical tasks** - Large data processing +- **Repeated operations** - Same task multiple times + +#### Script Guidelines + +**Make scripts executable:** +```bash +chmod +x scripts/your_script.py +``` + +**Include clear shebangs:** +```python +#!/usr/bin/env python3 +``` + +**Document dependencies:** +```python +#!/usr/bin/env python3 +""" +Script to process user data. + +Dependencies: +- pandas>=2.0.0 +- requests>=2.28.0 + +Install: pip install pandas requests +""" +``` + +**Return structured output:** +```python +import json +import sys + +def main(): + try: + result = process_data() + print(json.dumps({"success": True, "data": result})) + sys.exit(0) + except Exception as e: + print(json.dumps({"success": False, "error": str(e)}), file=sys.stderr) + sys.exit(1) +``` + +**Example SKILL.md usage:** +```markdown +## Processing Data + +To process the user data, execute the processing script: + +```bash +python scripts/process_data.py input.csv output.json +``` + +The script will: +1. Validate the CSV format +2. Transform the data according to the schema +3. Output JSON in the required format + +If the script fails, check the error message and verify: +- Input file exists and is valid CSV +- Required columns are present +- Output directory is writable +``` + +### References Directory + +Use references for: +- **API documentation** - External service docs +- **Database schemas** - Table structures, relationships +- **Business logic** - Company-specific rules +- **Large examples** - Complete code samples +- **Technical specs** - Detailed format specifications + +#### Reference Organization Patterns + +**Pattern 1: By Topic** +``` +references/ +├── api-endpoints.md +├── database-schema.md +├── business-rules.md +└── examples.md +``` + +**Pattern 2: By Complexity** +``` +references/ +├── quick-reference.md # Load frequently +├── detailed-guide.md # Load when needed +└── complete-spec.md # Load rarely +``` + +**Pattern 3: By Phase** +``` +references/ +├── 1-planning.md +├── 2-implementation.md +├── 3-testing.md +└── 4-deployment.md +``` + +#### Reference Loading Instructions + +**For focused documents (<5k words):** +```markdown +When implementing authentication, read `references/auth-guide.md` for the complete authentication flow and security requirements. +``` + +**For large documents (>10k words):** +```markdown +The complete API documentation is in `references/api-docs.md`. +Use grep patterns to find specific endpoints: +- Authentication: grep "auth" references/api-docs.md +- User management: grep "user" references/api-docs.md +- Payments: grep "payment" references/api-docs.md + +Only read the full file if you need to understand the overall API structure. +``` + +### Assets Directory + +Use assets for: +- **Templates** - Boilerplate code, config files +- **Images** - Logos, icons, diagrams +- **Fonts** - Custom typography +- **Data files** - JSON schemas, example datasets + +#### Asset Usage Patterns + +**Templates:** +```markdown +## Creating a New Component + +Use the React component template as a starting point: + +1. Read `assets/templates/component.template.tsx` +2. Replace the placeholders: + - `{{ComponentName}}` with the actual component name + - `{{Props}}` with the required props + - `{{Implementation}}` with the component logic +3. Write the completed component to the appropriate directory +``` + +**Images in output:** +```markdown +## Generating Branded Documents + +Include the company logo in all generated documents: +- Logo file: `assets/logo.png` +- Usage: Insert at the top of each page +- Dimensions: Scale to 200px width, maintain aspect ratio +``` + +**Configuration templates:** +```markdown +## Setting Up Configuration + +Copy the base configuration and customize: + +1. Read `assets/config.template.json` +2. Update the following fields based on user input: + - `apiUrl`: The API endpoint + - `apiKey`: User's API key (ask user, never hardcode) + - `environment`: dev/staging/prod +3. Write to `config.json` in the project root +``` + +## Progressive Disclosure + +Progressive disclosure keeps context usage efficient by loading information only when needed. + +### Three-Level Loading + +**Level 1: Metadata (Always loaded)** +- Name and description only +- ~100 words +- Determines skill activation + +**Level 2: SKILL.md Body (Loaded when skill triggers)** +- Complete instructions +- Target: <5,000 words +- Includes pointers to Level 3 resources + +**Level 3: Bundled Resources (Loaded as needed)** +- Large references +- Multiple examples +- Detailed specifications +- Loaded explicitly by instructions + +### Progressive Disclosure Patterns + +#### Pattern 1: Basic → Advanced + +**SKILL.md:** +```markdown +## Quick Start + +For simple cases, follow this pattern: +[Simple instructions] + +## Advanced Usage + +For complex scenarios requiring [specific features], read `references/advanced-guide.md` which covers: +- [Advanced feature 1] +- [Advanced feature 2] +- [Advanced feature 3] +``` + +#### Pattern 2: Overview → Details + +**SKILL.md:** +```markdown +## API Integration Overview + +The API has four main endpoint categories: +1. Authentication - Login, logout, token refresh +2. Users - CRUD operations for user data +3. Content - Create and manage content +4. Analytics - Retrieve usage statistics + +For detailed endpoint specifications, read `references/api-documentation.md`. +``` + +#### Pattern 3: Common Cases → Edge Cases + +**SKILL.md:** +```markdown +## Standard Workflow + +Most users need: +[80% use case instructions] + +## Edge Cases + +If the user has special requirements, consult `references/edge-cases.md` for: +- Legacy system integration +- Custom authentication flows +- High-volume optimizations +``` + +### When to Break Up Content + +**Keep in SKILL.md:** +- Core workflow (always needed) +- Critical guidelines (always apply) +- Common patterns (frequently used) +- Tool usage instructions +- Error handling basics + +**Move to references/:** +- API documentation (>1000 lines) +- Complete code examples (>100 lines) +- Detailed specifications +- Optional advanced techniques +- Historical context or background + +## Common Design Patterns + +### Pattern: Multi-Step Workflow + +**Use case:** Complex processes with distinct phases + +```markdown +## Implementation Process + +### Phase 1: Discovery +1. Ask the user for [required information] +2. Use Glob to find [relevant files] +3. Analyze the current state + +### Phase 2: Planning +1. Based on discovery, determine [approach] +2. Identify [required changes] +3. Ask user to confirm the plan + +### Phase 3: Implementation +1. For each identified change: + - Use Read to examine the file + - Use Edit to make the change + - Document what was changed +2. Verify changes are consistent + +### Phase 4: Verification +1. Run tests: `npm test` +2. If tests fail, fix issues and retry +3. Confirm with user that changes meet requirements +``` + +### Pattern: User Configuration + +**Use case:** Customizable behavior based on user preferences + +```markdown +## Configuration + +Before starting, ask the user for their preferences: + +1. **Output format**: JSON, CSV, or YAML? +2. **Verbosity level**: Minimal, standard, or detailed? +3. **Include examples**: Yes or no? + +Store these preferences and use them throughout the workflow. + +Example interaction: +- Ask: "What output format would you like? (JSON/CSV/YAML)" +- Wait for response +- Proceed with the selected format +``` + +### Pattern: Iterative Refinement + +**Use case:** Output that may need multiple revisions + +```markdown +## Generation Process + +1. Create initial version based on user input +2. Present to user for feedback +3. If user requests changes: + - Apply the requested modifications + - Present updated version + - Repeat until user is satisfied +4. Finalize and save the result + +Always ask "Would you like any changes to this?" before finalizing. +``` + +### Pattern: Validation and Correction + +**Use case:** Ensuring output meets requirements + +```markdown +## Quality Assurance + +After generating the output: + +1. Validate against requirements: + - Check [requirement 1] + - Verify [requirement 2] + - Confirm [requirement 3] + +2. If validation fails: + - Explain what's missing or incorrect + - Automatically fix if possible + - Ask user for clarification if needed + +3. Run automated checks: + ```bash + python scripts/validate.py output.json + ``` + +4. Only proceed when all validations pass +``` + +### Pattern: Context Gathering + +**Use case:** Need to understand codebase before making changes + +```markdown +## Analysis Phase + +Before making any changes: + +1. **Understand the structure:** + - Use Glob to find all [relevant files] + - Use Grep to search for [key patterns] + - Identify the main [components/modules] + +2. **Analyze patterns:** + - Read [key files] to understand conventions + - Note the [naming patterns] + - Identify [common approaches] + +3. **Plan changes:** + - List files that need modification + - Describe what will change in each + - Ensure consistency with existing patterns + +4. **Confirm with user** before implementing +``` + +## Performance Optimization + +### Minimize Context Usage + +**Problem:** Loading unnecessary content into context +**Solution:** Use progressive disclosure and smart loading + +**Bad:** +```markdown +Read all files in references/ to understand the system. +``` + +**Good:** +```markdown +For authentication issues, grep "auth" in references/ to find relevant docs, then read only those files. +``` + +### Batch Operations + +**Problem:** Multiple small operations creating overhead +**Solution:** Batch similar operations together + +**Bad:** +```markdown +For each file: +1. Read the file +2. Check if it needs updating +3. If yes, edit the file +4. Continue to next file +``` + +**Good:** +```markdown +1. Use Glob to find all candidate files +2. Use Grep to filter files that need updates +3. For each file needing updates: + - Read and edit in sequence +4. Verify all changes together +``` + +### Smart Script Usage + +**Problem:** Reading large scripts into context +**Solution:** Execute without reading when possible + +**Bad:** +```markdown +Read scripts/large_processor.py to understand what it does, then execute it. +``` + +**Good:** +```markdown +Execute the data processor: +```bash +python scripts/large_processor.py input.json output.json +``` + +The script will: +- Validate input format +- Transform data according to schema +- Generate output file + +[No need to read the script itself] +``` + +### Conditional Loading + +**Problem:** Loading resources that may not be needed +**Solution:** Load based on specific conditions + +```markdown +## Reference Loading + +- If working with REST API: Read `references/rest-api.md` +- If working with GraphQL: Read `references/graphql-api.md` +- If working with WebSocket: Read `references/websocket-api.md` + +Only load the reference relevant to the current task. +``` + +## Testing Strategies + +### Manual Testing Checklist + +- [ ] **Happy path**: Does it work with typical inputs? +- [ ] **Edge cases**: Empty inputs, very large inputs, special characters? +- [ ] **Error handling**: How does it respond to invalid inputs? +- [ ] **Instructions**: Are they clear and unambiguous? +- [ ] **Tool usage**: Does Claude use the right tools? +- [ ] **Output quality**: Is the result correct and well-formatted? +- [ ] **Performance**: Does it complete in reasonable time? +- [ ] **Context usage**: Is progressive disclosure working? + +### Test Cases Template + +Create a `TESTING.md` in your skill directory: + +```markdown +# Test Cases for [Skill Name] + +## Test Case 1: Basic Usage +**Input:** [Describe user request] +**Expected Behavior:** [What should happen] +**Expected Output:** [What should be produced] +**Status:** ✅ Pass / ❌ Fail + +## Test Case 2: Edge Case - [Description] +**Input:** [Describe edge case] +**Expected Behavior:** [How it should handle this] +**Expected Output:** [Expected result] +**Status:** ✅ Pass / ❌ Fail + +## Test Case 3: Error Handling - [Description] +**Input:** [Describe error condition] +**Expected Behavior:** [How it should gracefully fail] +**Expected Output:** [Error message or recovery] +**Status:** ✅ Pass / ❌ Fail +``` + +### Testing with Different Claude Interfaces + +**Claude Code:** +```bash +# Symlink your skill for testing +ln -s /path/to/your-skill ~/.claude/skills/your-skill-name + +# Test by triggering the skill +# Observe behavior, check logs +``` + +**Claude.ai:** +- Upload skill as ZIP file +- Test in chat interface +- Verify across multiple conversations + +**Claude API:** +```python +from anthropic import Anthropic + +client = Anthropic(api_key="your-api-key") + +# Upload skill (if custom) +# Test with API calls +``` + +### Validation Script + +Create automated validation for your skill: + +```python +#!/usr/bin/env python3 +"""Validate skill structure and content.""" + +import os +import yaml +import sys + +def validate_skill(skill_dir): + errors = [] + + # Check SKILL.md exists + skill_md = os.path.join(skill_dir, "SKILL.md") + if not os.path.exists(skill_md): + errors.append("SKILL.md is missing") + return errors + + # Parse frontmatter + with open(skill_md) as f: + content = f.read() + if not content.startswith("---"): + errors.append("SKILL.md missing YAML frontmatter") + return errors + + parts = content.split("---", 2) + if len(parts) < 3: + errors.append("SKILL.md frontmatter not properly closed") + return errors + + try: + frontmatter = yaml.safe_load(parts[1]) + except yaml.YAMLError as e: + errors.append(f"Invalid YAML frontmatter: {e}") + return errors + + # Validate required fields + if "name" not in frontmatter: + errors.append("Missing required field: name") + elif not frontmatter["name"].islower() or "_" in frontmatter["name"]: + errors.append("name must be lowercase with hyphens only") + + if "description" not in frontmatter: + errors.append("Missing required field: description") + elif len(frontmatter["description"]) > 200: + errors.append("description should be under 200 characters") + + # Check directory name matches + dir_name = os.path.basename(skill_dir.rstrip("/")) + if "name" in frontmatter and frontmatter["name"] != dir_name: + errors.append(f"Directory name '{dir_name}' doesn't match skill name '{frontmatter['name']}'") + + # Check for empty instruction body + if len(parts[2].strip()) < 100: + errors.append("SKILL.md instruction body seems too short") + + return errors + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Usage: python validate_skill.py ") + sys.exit(1) + + errors = validate_skill(sys.argv[1]) + + if errors: + print(f"❌ Validation failed with {len(errors)} error(s):") + for error in errors: + print(f" - {error}") + sys.exit(1) + else: + print("✅ Skill validation passed") + sys.exit(0) +``` + +## Troubleshooting + +### Skill Not Triggering + +**Symptoms:** Claude doesn't load your skill when expected + +**Causes and solutions:** +1. **Vague description**: Make description more specific about when to use +2. **Wrong trigger words**: Include terms users would naturally use +3. **Too narrow**: Skill may be too specialized to trigger often +4. **Overlapping skills**: Another skill may be triggering instead + +**Fix:** Revise description to be clearer and more specific + +### Skill Loads But Doesn't Work + +**Symptoms:** Skill activates but Claude doesn't follow instructions + +**Causes and solutions:** +1. **Ambiguous instructions**: Be more directive and specific +2. **Missing tool specifications**: Explicitly state which tools to use +3. **Conflicting guidelines**: Check for contradictory instructions +4. **Missing examples**: Add concrete examples of expected behavior + +**Fix:** Rewrite instructions to be clearer and more prescriptive + +### High Context Usage + +**Symptoms:** Skill uses too much context, slow performance + +**Causes and solutions:** +1. **Large SKILL.md**: Move detailed content to references/ +2. **Loading all references**: Use conditional loading +3. **Reading scripts unnecessarily**: Execute scripts instead of reading +4. **No progressive disclosure**: Implement three-level loading pattern + +**Fix:** Refactor using progressive disclosure principles + +### Inconsistent Results + +**Symptoms:** Skill produces different outputs for similar inputs + +**Causes and solutions:** +1. **Ambiguous instructions**: Add more specific guidelines +2. **Missing validation**: Implement validation steps +3. **Unclear criteria**: Define clear success criteria +4. **No examples**: Add examples showing expected outputs + +**Fix:** Add validation, examples, and clearer criteria + +### Script Execution Failures + +**Symptoms:** Bundled scripts fail or produce errors + +**Causes and solutions:** +1. **Missing dependencies**: Document all requirements clearly +2. **Wrong paths**: Use absolute paths or proper relative paths +3. **Permission issues**: Ensure scripts are executable +4. **Environment issues**: Document required environment variables + +**Fix:** Improve script robustness and documentation + +--- + +## Additional Resources + +- [Agent Skills Specification](agent_skills_spec.md) - Official specification +- [Contributing Guide](CONTRIBUTING.md) - How to contribute skills +- [skill-creator/SKILL.md](skill-creator/SKILL.md) - Meta-skill for creating skills +- [template-skill/SKILL.md](template-skill/SKILL.md) - Basic template to start from + +--- + +**Need help?** Open an issue on GitHub or use the skill-creator skill for guidance! diff --git a/api-documentation-writer/SKILL.md b/api-documentation-writer/SKILL.md new file mode 100644 index 000000000..a3a2f513d --- /dev/null +++ b/api-documentation-writer/SKILL.md @@ -0,0 +1,561 @@ +--- +name: api-documentation-writer +description: Use this skill to generate comprehensive, developer-friendly API documentation with examples, covering endpoints, authentication, request/response formats, and error handling +license: Apache-2.0 +--- + +# API Documentation Writer + +Generate clear, comprehensive, and developer-friendly API documentation that helps users quickly understand and integrate with APIs. + +## When to Use + +Use this skill when: +- The user asks to "document the API" or "create API docs" +- The user wants to generate OpenAPI/Swagger documentation +- The user needs reference documentation for REST, GraphQL, or other APIs +- The user is building or updating an API and needs documentation +- The user wants to improve existing API documentation + +## Documentation Generation Process + +### Step 1: Gather Information + +**Understand the API:** +1. Ask the user about the API type (REST, GraphQL, gRPC, etc.) +2. Identify where the API is defined: + - Code files (routes, controllers, handlers) + - OpenAPI/Swagger spec files + - GraphQL schema files + - Existing documentation + +3. Use Glob and Grep to find relevant files: + ```bash + # Find route definitions + - REST: Look for route decorators, router files + - GraphQL: Look for schema definitions + - gRPC: Look for .proto files + ``` + +4. Read the API implementation files to understand: + - Available endpoints/queries/mutations + - Request parameters and body schemas + - Response formats + - Authentication requirements + - Error handling + +**Ask clarifying questions if needed:** +- What's the base URL for the API? +- What authentication methods are used? +- Are there rate limits? +- What environments are available (dev/staging/prod)? +- Are there SDK clients available? + +### Step 2: Structure the Documentation + +Organize documentation in this structure: + +```markdown +# API Documentation + +## Overview +- Brief description of what the API does +- Base URL(s) +- API version +- Key features + +## Getting Started +- Prerequisites +- Authentication setup +- Quick start example +- Common use cases + +## Authentication +- Supported methods (API keys, OAuth, JWT, etc.) +- How to obtain credentials +- How to include auth in requests +- Token refresh/expiration + +## Endpoints (or Queries/Mutations for GraphQL) +- Organized by resource or feature +- Each endpoint fully documented + +## Error Handling +- Common error codes +- Error response format +- Troubleshooting guide + +## Rate Limiting +- Limits and quotas +- Headers to check +- How to handle rate limit errors + +## SDKs and Tools +- Available client libraries +- Code generation tools +- Testing tools (Postman collections, etc.) + +## Changelog +- API version history +- Breaking changes +- Deprecations +``` + +### Step 3: Document Each Endpoint + +For REST APIs, document each endpoint with this template: + +```markdown +### [HTTP Method] [Endpoint Path] + +Brief description of what this endpoint does. + +**Endpoint:** `[METHOD] /api/v1/resource/:id` + +**Authentication:** Required/Optional - [Type] + +**Parameters:** + +Path Parameters: +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string | Yes | The unique identifier | + +Query Parameters: +| Name | Type | Required | Default | Description | +|------|------|----------|---------|-------------| +| limit | integer | No | 20 | Number of items to return | +| offset | integer | No | 0 | Number of items to skip | + +**Request Headers:** +| Name | Type | Required | Description | +|------|------|----------|-------------| +| Authorization | string | Yes | Bearer token | +| Content-Type | string | Yes | Must be application/json | + +**Request Body:** + +```json +{ + "field1": "string", + "field2": 123, + "nested": { + "field3": true + } +} +``` + +Field descriptions: +- `field1` (string, required): Description +- `field2` (integer, optional): Description +- `nested.field3` (boolean, optional): Description + +**Response:** + +Success Response (200 OK): +```json +{ + "id": "abc123", + "field1": "value", + "createdAt": "2025-01-15T10:30:00Z" +} +``` + +Field descriptions: +- `id` (string): Unique identifier +- `field1` (string): Description +- `createdAt` (string): ISO 8601 timestamp + +**Error Responses:** + +| Status Code | Description | Response Body | +|-------------|-------------|---------------| +| 400 | Bad Request | `{"error": "Invalid input", "details": [...]}` | +| 401 | Unauthorized | `{"error": "Invalid or missing token"}` | +| 404 | Not Found | `{"error": "Resource not found"}` | +| 500 | Server Error | `{"error": "Internal server error"}` | + +**Example Request:** + +```bash +curl -X POST https://api.example.com/api/v1/resource \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "field1": "example value", + "field2": 42 + }' +``` + +**Example Response:** + +```json +{ + "id": "abc123", + "field1": "example value", + "field2": 42, + "createdAt": "2025-01-15T10:30:00Z" +} +``` + +**Notes:** +- Additional information +- Edge cases +- Related endpoints +``` + +### Step 4: Add Code Examples + +Include examples in multiple languages: + +```markdown +## Code Examples + +### JavaScript/Node.js + +```javascript +const response = await fetch('https://api.example.com/api/v1/resource', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${token}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + field1: 'example value', + field2: 42 + }) +}); + +const data = await response.json(); +console.log(data); +``` + +### Python + +```python +import requests + +headers = { + 'Authorization': f'Bearer {token}', + 'Content-Type': 'application/json' +} + +data = { + 'field1': 'example value', + 'field2': 42 +} + +response = requests.post( + 'https://api.example.com/api/v1/resource', + headers=headers, + json=data +) + +result = response.json() +print(result) +``` + +### cURL + +```bash +curl -X POST https://api.example.com/api/v1/resource \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "field1": "example value", + "field2": 42 + }' +``` +``` + +### Step 5: Document Authentication + +Provide clear authentication guidance: + +```markdown +## Authentication + +This API uses [Bearer Token / API Key / OAuth 2.0] authentication. + +### Obtaining Credentials + +1. [Step-by-step process to get API credentials] +2. [Where to find them in the dashboard] +3. [How to generate tokens] + +### Using Authentication + +Include your credentials in the request header: + +``` +Authorization: Bearer YOUR_TOKEN_HERE +``` + +### Example + +```bash +curl -H "Authorization: Bearer abc123xyz789" \ + https://api.example.com/api/v1/resource +``` + +### Token Expiration + +- Access tokens expire after [duration] +- Refresh tokens are valid for [duration] +- Use the `/refresh` endpoint to get a new access token + +### Security Best Practices + +- Never commit tokens to version control +- Rotate tokens regularly +- Use environment variables for storing tokens +- Implement token refresh logic in your application +``` + +### Step 6: Error Handling Documentation + +Document errors comprehensively: + +```markdown +## Error Handling + +All errors follow this format: + +```json +{ + "error": { + "code": "ERROR_CODE", + "message": "Human-readable error message", + "details": { + "field": "Additional context" + } + } +} +``` + +### Common Error Codes + +| Code | Status | Description | Solution | +|------|--------|-------------|----------| +| INVALID_REQUEST | 400 | Request validation failed | Check request format and required fields | +| UNAUTHORIZED | 401 | Missing or invalid authentication | Verify your token is valid | +| FORBIDDEN | 403 | Insufficient permissions | Contact admin for access | +| NOT_FOUND | 404 | Resource doesn't exist | Verify the resource ID | +| RATE_LIMITED | 429 | Too many requests | Implement backoff and retry | +| SERVER_ERROR | 500 | Internal server error | Contact support if persists | + +### Handling Errors + +**Retry Logic:** +- Implement exponential backoff for 5xx errors +- Don't retry 4xx errors (except 429) +- Maximum 3 retry attempts recommended + +**Example Error Handling:** + +```javascript +async function makeAPIRequest() { + try { + const response = await fetch(url, options); + + if (!response.ok) { + const error = await response.json(); + + if (response.status === 429) { + // Rate limited - wait and retry + const retryAfter = response.headers.get('Retry-After'); + await sleep(retryAfter * 1000); + return makeAPIRequest(); // Retry + } + + throw new Error(`API Error: ${error.error.message}`); + } + + return await response.json(); + } catch (err) { + console.error('Request failed:', err); + throw err; + } +} +``` +``` + +### Step 7: Create Quick Start Guide + +Include a quick start section: + +```markdown +## Quick Start + +Get started with the API in 5 minutes. + +### 1. Get Your API Key + +[Instructions to obtain API key] + +### 2. Make Your First Request + +```bash +curl https://api.example.com/api/v1/users \ + -H "Authorization: Bearer YOUR_TOKEN" +``` + +### 3. Handle the Response + +```json +{ + "users": [ + {"id": "1", "name": "Alice"}, + {"id": "2", "name": "Bob"} + ] +} +``` + +### 4. Next Steps + +- Explore the [Endpoints](#endpoints) section +- Check out [Code Examples](#code-examples) +- Read about [Error Handling](#error-handling) +``` + +## For GraphQL APIs + +Use a modified structure: + +```markdown +### Query: [QueryName] + +Description of what this query does. + +**Arguments:** +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | ID! | Yes | User identifier | + +**Returns:** `User` + +**Example Query:** + +```graphql +query GetUser($id: ID!) { + user(id: $id) { + id + name + email + createdAt + } +} +``` + +**Variables:** + +```json +{ + "id": "abc123" +} +``` + +**Response:** + +```json +{ + "data": { + "user": { + "id": "abc123", + "name": "Alice", + "email": "alice@example.com", + "createdAt": "2025-01-15T10:30:00Z" + } + } +} +``` +``` + +## Documentation Guidelines + +- **Be clear and concise**: Use simple language +- **Provide examples**: Show don't just tell +- **Be consistent**: Use the same format throughout +- **Include edge cases**: Document limitations and special cases +- **Keep it updated**: Note when endpoints are deprecated +- **Use proper formatting**: + - Code blocks with syntax highlighting + - Tables for structured data + - Clear headers and sections +- **Test examples**: Ensure all code examples work +- **Link related sections**: Help users navigate + +## Output Formats + +Generate documentation in the requested format: + +- **Markdown** (.md) - For GitHub, GitLab, static site generators +- **OpenAPI 3.0** (.yaml/.json) - For Swagger UI, Redoc +- **HTML** - For custom documentation sites +- **Postman Collection** (.json) - For Postman import + +Ask the user which format they prefer if not specified. + +## Validation + +Before finalizing: + +1. **Completeness check:** + - All endpoints documented + - All parameters explained + - Examples provided + - Error cases covered + +2. **Accuracy check:** + - Examples are correct + - Types match implementation + - URLs are valid + - Authentication details are right + +3. **Clarity check:** + - Language is clear + - Structure is logical + - Navigation is easy + - Examples are realistic + +## Error Handling + +- If API code is not accessible, ask user for details +- If authentication is unclear, ask for clarification +- If examples can't be tested, note this in documentation +- If API structure is complex, suggest breaking docs into multiple files + +## Example Use Cases + +### Example 1: Document REST API from Express Routes + +User: "Document my Express API in the routes/ folder" + +Response: +1. Use Glob to find route files: `routes/**/*.js` +2. Read each route file +3. Extract endpoints, methods, parameters +4. Generate documentation following the template +5. Create markdown file with complete documentation + +### Example 2: Generate OpenAPI Spec + +User: "Create an OpenAPI spec for my API" + +Response: +1. Analyze the API implementation +2. Generate OpenAPI 3.0 YAML structure +3. Include all endpoints, schemas, parameters +4. Add examples and descriptions +5. Validate the spec is valid OpenAPI format + +### Example 3: Document GraphQL API + +User: "Document my GraphQL schema" + +Response: +1. Read the GraphQL schema file +2. Extract types, queries, mutations +3. Document each operation with examples +4. Include authentication requirements +5. Provide example queries with variables diff --git a/code-reviewer/SKILL.md b/code-reviewer/SKILL.md new file mode 100644 index 000000000..3ff1c6659 --- /dev/null +++ b/code-reviewer/SKILL.md @@ -0,0 +1,294 @@ +--- +name: code-reviewer +description: Use this skill to perform systematic code reviews with best practices, checking for bugs, security issues, performance problems, and code quality +license: Apache-2.0 +--- + +# Code Reviewer + +A comprehensive code review skill that systematically analyzes code for quality, security, performance, and maintainability issues. + +## When to Use + +Use this skill when: +- The user explicitly requests a code review +- The user asks to "review", "check", or "analyze" code +- The user wants to improve code quality +- The user needs feedback on their implementation +- You've completed a significant code change and want to validate it + +## Review Process + +### Step 1: Understand Context + +1. **Identify what to review:** + - If user specified files, review those + - If no files specified, ask the user which files to review + - Use Glob to find relevant files if pattern provided + +2. **Understand the purpose:** + - What does this code do? + - What problem does it solve? + - What are the requirements? + +### Step 2: Systematic Analysis + +Review the code in this order, checking each category: + +#### 2.1 Correctness & Bugs + +- **Logic errors**: Does the code do what it's supposed to? +- **Edge cases**: Are boundary conditions handled? +- **Null/undefined handling**: Are nil values checked? +- **Error handling**: Are errors caught and handled appropriately? +- **Off-by-one errors**: Are array indices and loops correct? + +#### 2.2 Security Issues + +- **Input validation**: Is user input validated and sanitized? +- **SQL injection**: Are database queries parameterized? +- **XSS vulnerabilities**: Is output properly escaped? +- **Authentication/authorization**: Are permissions checked? +- **Secrets exposure**: Are API keys, passwords, or tokens hardcoded? +- **CSRF protection**: Are state-changing operations protected? +- **Dependency vulnerabilities**: Are dependencies up to date and secure? + +#### 2.3 Performance + +- **Algorithmic complexity**: Can O(n²) be reduced to O(n)? +- **Database queries**: Are there N+1 query problems? +- **Caching opportunities**: Should results be cached? +- **Memory leaks**: Are resources properly released? +- **Unnecessary work**: Is redundant computation performed? +- **Large data handling**: Are large datasets processed efficiently? + +#### 2.4 Code Quality + +**Readability:** +- Are variable and function names clear and descriptive? +- Is the code easy to understand? +- Are complex sections commented? +- Is the formatting consistent? + +**Maintainability:** +- Is the code DRY (Don't Repeat Yourself)? +- Are functions focused and single-purpose? +- Is complexity manageable (cyclomatic complexity)? +- Are magic numbers replaced with named constants? + +**Architecture:** +- Does it follow established patterns? +- Are concerns properly separated? +- Is coupling minimized? +- Is cohesion maximized? + +**Testing:** +- Are there adequate tests? +- Are edge cases tested? +- Is error handling tested? +- Are tests clear and maintainable? + +#### 2.5 Best Practices + +**Language-specific best practices:** + +**Python:** +- PEP 8 compliance +- Type hints used where appropriate +- Context managers for resources +- List comprehensions over loops (when clearer) + +**JavaScript/TypeScript:** +- Modern ES6+ syntax +- Proper async/await usage +- No var, use const/let +- TypeScript types properly defined + +**Go:** +- Proper error handling patterns +- Goroutine and channel usage +- Interface usage appropriate +- defer for cleanup + +**Java:** +- Exception handling appropriate +- Stream API usage +- Null handling (Optional) +- Resource management (try-with-resources) + +**Rust:** +- Ownership and borrowing correct +- Error handling with Result +- No unnecessary clones +- Lifetime annotations appropriate + +### Step 3: Prioritize Findings + +Categorize issues by severity: + +**Critical (🔴):** +- Security vulnerabilities +- Data loss risks +- Crash/error conditions +- Major bugs + +**High (🟡):** +- Performance problems +- Maintainability issues +- Moderate bugs +- Missing error handling + +**Medium (🟠):** +- Code quality improvements +- Minor bugs +- Style inconsistencies +- Missing tests + +**Low (🟢):** +- Nitpicks +- Optional refactoring +- Documentation suggestions + +### Step 4: Provide Constructive Feedback + +For each issue found: + +1. **Explain the problem** clearly +2. **Show the specific code** location (file:line) +3. **Explain why** it's an issue +4. **Suggest a solution** with example code +5. **Provide context** (e.g., links to best practices) + +**Example Format:** + +``` +🔴 CRITICAL: SQL Injection Vulnerability + +Location: src/database/users.py:45 + +Problem: +The user input is directly interpolated into the SQL query, allowing SQL injection attacks. + +Current code: +```python +query = f"SELECT * FROM users WHERE email = '{email}'" +cursor.execute(query) +``` + +Why it's a problem: +An attacker could input `admin@example.com' OR '1'='1` to bypass authentication. + +Recommended fix: +Use parameterized queries: +```python +query = "SELECT * FROM users WHERE email = ?" +cursor.execute(query, (email,)) +``` + +Reference: https://owasp.org/www-community/attacks/SQL_Injection +``` + +### Step 5: Positive Feedback + +Also note what's done well: +- Good practices followed +- Clean code patterns +- Effective solutions +- Well-tested areas + +This provides balanced, constructive feedback. + +### Step 6: Summary and Recommendations + +Provide a summary at the end: + +1. **Overall assessment**: Brief quality rating +2. **Critical items**: Must-fix issues +3. **Recommended improvements**: High-priority items +4. **Nice-to-haves**: Optional improvements +5. **Positive notes**: What's done well + +## Review Output Format + +Structure your review as: + +``` +# Code Review: [Component/Feature Name] + +## Summary +[Brief overview of what was reviewed and overall quality] + +## Critical Issues (🔴) +[List critical issues with details] + +## High Priority (🟡) +[List high-priority issues with details] + +## Medium Priority (🟠) +[List medium-priority issues with details] + +## Low Priority (🟢) +[List low-priority suggestions] + +## Positive Notes ✅ +[What's done well] + +## Overall Recommendations +[Summary and next steps] +``` + +## Guidelines + +- **Be constructive**: Focus on improvement, not criticism +- **Be specific**: Reference exact files and line numbers +- **Provide examples**: Show good and bad code +- **Explain reasoning**: Don't just say "this is wrong", explain why +- **Consider context**: Understand project constraints +- **Be balanced**: Note both problems and good practices +- **Prioritize**: Don't overwhelm with minor issues +- **Be actionable**: Give clear steps to fix + +## Error Handling + +- If files don't exist, inform the user and ask for correct paths +- If code language is unclear, ask for clarification +- If scope is too large, suggest breaking into smaller reviews +- If you don't understand the requirements, ask questions + +## Examples + +### Example 1: Security Review Request + +User: "Review auth.py for security issues" + +Response: +1. Read auth.py +2. Focus on security aspects: + - Authentication implementation + - Password handling + - Session management + - Input validation +3. Provide detailed security findings +4. Prioritize by risk level + +### Example 2: General Code Review + +User: "Review my recent changes in src/api/" + +Response: +1. Use Glob to find files in src/api/ +2. Review each file systematically +3. Check all categories (correctness, security, performance, quality) +4. Provide comprehensive feedback +5. Summarize findings + +### Example 3: Performance Review + +User: "This function is slow, can you review it?" + +Response: +1. Read the function code +2. Analyze algorithmic complexity +3. Identify bottlenecks +4. Suggest optimizations with examples +5. Explain expected performance improvement diff --git a/scripts/validate_skill.py b/scripts/validate_skill.py new file mode 100755 index 000000000..a734d731e --- /dev/null +++ b/scripts/validate_skill.py @@ -0,0 +1,378 @@ +#!/usr/bin/env python3 +""" +Comprehensive skill validation script. + +Validates skill structure, frontmatter, content quality, and bundled resources. +""" + +import os +import sys +import re +import yaml +from pathlib import Path +from typing import List, Tuple, Dict, Any + + +class SkillValidator: + """Validates Claude skills according to the Agent Skills Specification.""" + + def __init__(self, skill_path: str): + self.skill_path = Path(skill_path) + self.errors: List[str] = [] + self.warnings: List[str] = [] + self.info: List[str] = [] + + def validate(self) -> bool: + """Run all validations. Returns True if skill is valid.""" + self.validate_structure() + self.validate_skill_md() + self.validate_bundled_resources() + return len(self.errors) == 0 + + def validate_structure(self): + """Validate basic skill directory structure.""" + # Check skill directory exists + if not self.skill_path.exists(): + self.errors.append(f"Skill directory not found: {self.skill_path}") + return + + if not self.skill_path.is_dir(): + self.errors.append(f"Skill path is not a directory: {self.skill_path}") + return + + # Check SKILL.md exists + skill_md = self.skill_path / "SKILL.md" + if not skill_md.exists(): + self.errors.append("SKILL.md is required but not found") + return + + if not skill_md.is_file(): + self.errors.append("SKILL.md must be a file") + return + + # Check for common bundled resource directories + for dirname in ["scripts", "references", "assets"]: + dirpath = self.skill_path / dirname + if dirpath.exists(): + if not dirpath.is_dir(): + self.warnings.append(f"{dirname} should be a directory, not a file") + else: + self.info.append(f"Found {dirname}/ directory") + + def validate_skill_md(self): + """Validate SKILL.md content and frontmatter.""" + skill_md = self.skill_path / "SKILL.md" + if not skill_md.exists(): + return # Already reported in validate_structure + + try: + content = skill_md.read_text(encoding="utf-8") + except Exception as e: + self.errors.append(f"Failed to read SKILL.md: {e}") + return + + # Validate frontmatter exists + if not content.startswith("---"): + self.errors.append("SKILL.md must start with YAML frontmatter (---)") + return + + # Extract frontmatter and body + parts = content.split("---", 2) + if len(parts) < 3: + self.errors.append("SKILL.md frontmatter not properly closed with ---") + return + + frontmatter_text = parts[1] + body = parts[2] + + # Parse YAML frontmatter + try: + frontmatter = yaml.safe_load(frontmatter_text) + except yaml.YAMLError as e: + self.errors.append(f"Invalid YAML frontmatter: {e}") + return + + if not isinstance(frontmatter, dict): + self.errors.append("Frontmatter must be a YAML object/dictionary") + return + + self.validate_frontmatter(frontmatter) + self.validate_body(body) + + def validate_frontmatter(self, frontmatter: Dict[str, Any]): + """Validate frontmatter fields.""" + # Check required fields + if "name" not in frontmatter: + self.errors.append("Missing required field: name") + else: + self.validate_name(frontmatter["name"]) + + if "description" not in frontmatter: + self.errors.append("Missing required field: description") + else: + self.validate_description(frontmatter["description"]) + + # Validate optional fields if present + if "license" in frontmatter: + self.info.append(f"License specified: {frontmatter['license']}") + + if "allowed-tools" in frontmatter: + self.validate_allowed_tools(frontmatter["allowed-tools"]) + + if "metadata" in frontmatter: + if not isinstance(frontmatter["metadata"], dict): + self.warnings.append("metadata should be a dictionary/object") + else: + self.info.append(f"Metadata fields: {', '.join(frontmatter['metadata'].keys())}") + + def validate_name(self, name: Any): + """Validate skill name.""" + if not isinstance(name, str): + self.errors.append(f"name must be a string, got {type(name).__name__}") + return + + # Check naming convention (lowercase with hyphens) + if not re.match(r"^[a-z0-9-]+$", name): + self.errors.append( + f"name '{name}' must be lowercase with hyphens only (no underscores, no uppercase)" + ) + + # Check for invalid patterns + if name.startswith("-") or name.endswith("-"): + self.errors.append(f"name '{name}' cannot start or end with a hyphen") + + if "--" in name: + self.errors.append(f"name '{name}' cannot contain consecutive hyphens") + + # Check directory name matches + dir_name = self.skill_path.name + if name != dir_name: + self.errors.append( + f"name '{name}' doesn't match directory name '{dir_name}'" + ) + + def validate_description(self, description: Any): + """Validate skill description.""" + if not isinstance(description, str): + self.errors.append( + f"description must be a string, got {type(description).__name__}" + ) + return + + # Check for minimum length + if len(description.strip()) < 20: + self.warnings.append( + "description seems too short (should clearly explain when to use this skill)" + ) + + # Check for maximum length (for marketplace display) + if len(description) > 200: + self.warnings.append( + f"description is {len(description)} characters; consider keeping under 200 for better marketplace display" + ) + + # Check for angle brackets (can cause issues in some contexts) + if "<" in description or ">" in description: + self.errors.append("description cannot contain angle brackets (< or >)") + + # Check that it's somewhat descriptive + vague_terms = ["helps", "assists", "various", "things", "stuff"] + desc_lower = description.lower() + if any(term in desc_lower for term in vague_terms): + self.warnings.append( + "description may be too vague; be specific about what the skill does and when to use it" + ) + + def validate_allowed_tools(self, allowed_tools: Any): + """Validate allowed-tools field (Claude Code specific).""" + if not isinstance(allowed_tools, list): + self.warnings.append( + f"allowed-tools should be a list, got {type(allowed_tools).__name__}" + ) + return + + # Check for valid tool names + known_tools = [ + "Read", "Write", "Edit", "Glob", "Grep", "Bash", "WebFetch", + "WebSearch", "TodoWrite", "Task", "NotebookEdit" + ] + + for tool in allowed_tools: + if not isinstance(tool, str): + self.warnings.append(f"allowed-tools contains non-string value: {tool}") + elif tool not in known_tools: + self.warnings.append( + f"Unknown tool '{tool}' in allowed-tools (may be valid but not recognized by this validator)" + ) + + self.info.append(f"Allowed tools: {', '.join(allowed_tools)}") + + def validate_body(self, body: str): + """Validate SKILL.md instruction body.""" + body = body.strip() + + # Check for minimum content + if len(body) < 100: + self.warnings.append( + "SKILL.md instruction body seems too short (should contain clear instructions)" + ) + + # Check for recommended sections + body_lower = body.lower() + + # Positive indicators + if "example" in body_lower or "```" in body: + self.info.append("Includes examples (good practice)") + + if "error" in body_lower or "fail" in body_lower: + self.info.append("Includes error handling guidance (good practice)") + + # Check for overly long content (should use progressive disclosure) + word_count = len(body.split()) + if word_count > 5000: + self.warnings.append( + f"SKILL.md body is {word_count} words; consider moving detailed content to references/ for progressive disclosure" + ) + + def validate_bundled_resources(self): + """Validate bundled resource directories.""" + # Validate scripts/ directory + scripts_dir = self.skill_path / "scripts" + if scripts_dir.exists(): + self.validate_scripts_directory(scripts_dir) + + # Validate references/ directory + references_dir = self.skill_path / "references" + if references_dir.exists(): + self.validate_references_directory(references_dir) + + # Validate assets/ directory + assets_dir = self.skill_path / "assets" + if assets_dir.exists(): + self.validate_assets_directory(assets_dir) + + def validate_scripts_directory(self, scripts_dir: Path): + """Validate scripts directory contents.""" + scripts = list(scripts_dir.glob("*")) + if not scripts: + self.warnings.append("scripts/ directory is empty") + return + + for script in scripts: + if script.is_file(): + # Check if executable + if not os.access(script, os.X_OK): + self.warnings.append( + f"Script {script.name} is not executable (consider chmod +x)" + ) + + # Check for shebang + try: + with open(script, "rb") as f: + first_line = f.readline() + if not first_line.startswith(b"#!"): + self.warnings.append( + f"Script {script.name} missing shebang (#!/usr/bin/env ...)" + ) + except Exception: + pass + + self.info.append(f"Found {len([s for s in scripts if s.is_file()])} script(s)") + + def validate_references_directory(self, references_dir: Path): + """Validate references directory contents.""" + references = list(references_dir.glob("*")) + if not references: + self.warnings.append("references/ directory is empty") + return + + file_count = len([r for r in references if r.is_file()]) + self.info.append(f"Found {file_count} reference file(s)") + + # Check for very large reference files + for ref in references: + if ref.is_file(): + size = ref.stat().st_size + if size > 100_000: # 100KB + self.info.append( + f"Large reference file: {ref.name} ({size / 1024:.1f}KB) - " + "ensure SKILL.md includes grep patterns for efficient loading" + ) + + def validate_assets_directory(self, assets_dir: Path): + """Validate assets directory contents.""" + assets = list(assets_dir.glob("*")) + if not assets: + self.warnings.append("assets/ directory is empty") + return + + file_count = len([a for a in assets if a.is_file()]) + self.info.append(f"Found {file_count} asset file(s)") + + # Check for extremely large assets + for asset in assets: + if asset.is_file(): + size = asset.stat().st_size + if size > 10_000_000: # 10MB + self.warnings.append( + f"Very large asset file: {asset.name} ({size / 1024 / 1024:.1f}MB) - " + "consider if this is necessary" + ) + + def print_results(self): + """Print validation results.""" + print(f"\n{'=' * 60}") + print(f"Skill Validation Results: {self.skill_path.name}") + print(f"{'=' * 60}\n") + + if self.errors: + print(f"❌ ERRORS ({len(self.errors)}):") + for error in self.errors: + print(f" • {error}") + print() + + if self.warnings: + print(f"⚠️ WARNINGS ({len(self.warnings)}):") + for warning in self.warnings: + print(f" • {warning}") + print() + + if self.info: + print(f"ℹ️ INFO ({len(self.info)}):") + for info in self.info: + print(f" • {info}") + print() + + if not self.errors: + print("✅ Skill validation PASSED") + print() + if self.warnings: + print("Note: Warnings are suggestions for improvement but don't prevent usage.") + else: + print("❌ Skill validation FAILED") + print("Please fix the errors above before using this skill.") + + print() + + +def main(): + """Main entry point.""" + if len(sys.argv) != 2: + print("Usage: python validate_skill.py ") + print() + print("Example:") + print(" python validate_skill.py ./my-skill/") + print(" python validate_skill.py /path/to/skills/my-skill/") + sys.exit(1) + + skill_path = sys.argv[1] + + validator = SkillValidator(skill_path) + is_valid = validator.validate() + validator.print_results() + + sys.exit(0 if is_valid else 1) + + +if __name__ == "__main__": + main() diff --git a/test-generator/SKILL.md b/test-generator/SKILL.md new file mode 100644 index 000000000..cf03ada22 --- /dev/null +++ b/test-generator/SKILL.md @@ -0,0 +1,619 @@ +--- +name: test-generator +description: Use this skill to generate comprehensive test suites including unit tests, integration tests, and edge cases for functions, classes, APIs, and components with appropriate test framework setup +license: Apache-2.0 +--- + +# Test Generator + +Generate comprehensive, well-structured test suites that ensure code quality and reliability through thorough testing coverage. + +## When to Use + +Use this skill when: +- The user asks to "generate tests" or "create test suite" +- The user wants to "add test coverage" for code +- The user needs to test a specific function, class, or module +- The user is implementing TDD and needs test scaffolding +- Code exists but lacks adequate tests + +## Test Generation Process + +### Step 1: Analyze the Code + +**Understand what needs testing:** + +1. **Read the source code** to understand: + - What does the code do? + - What are the inputs and outputs? + - What are the dependencies? + - What are the edge cases? + - What are the error conditions? + +2. **Identify the code type:** + - Functions/methods + - Classes + - API endpoints + - React/Vue components + - Database operations + - Async operations + +3. **Determine testing approach:** + - Unit tests (isolated functionality) + - Integration tests (component interactions) + - End-to-end tests (full workflows) + +### Step 2: Choose Test Framework + +Select the appropriate framework for the language: + +**JavaScript/TypeScript:** +- Jest (most common) +- Vitest (modern, fast) +- Mocha + Chai +- Testing Library (for React/Vue components) +- Cypress/Playwright (E2E) + +**Python:** +- pytest (recommended) +- unittest (built-in) +- doctest (for simple cases) + +**Go:** +- testing (built-in) +- testify (assertions) + +**Java:** +- JUnit 5 +- Mockito (mocking) +- AssertJ (assertions) + +**Rust:** +- Built-in test framework +- cargo test + +Ask the user about their framework preference if unclear. + +### Step 3: Generate Test Structure + +Create a well-organized test file: + +```javascript +// For: src/utils/calculator.js +// Create: src/utils/calculator.test.js + +import { describe, it, expect } from 'jest'; +import { calculator } from './calculator'; + +describe('calculator', () => { + describe('add', () => { + // Happy path tests + it('should add two positive numbers', () => { + expect(calculator.add(2, 3)).toBe(5); + }); + + // Edge cases + it('should handle zero', () => { + expect(calculator.add(0, 5)).toBe(5); + expect(calculator.add(5, 0)).toBe(5); + }); + + it('should handle negative numbers', () => { + expect(calculator.add(-2, 3)).toBe(1); + expect(calculator.add(-2, -3)).toBe(-5); + }); + + it('should handle decimals', () => { + expect(calculator.add(0.1, 0.2)).toBeCloseTo(0.3); + }); + + // Error cases + it('should throw error for non-numeric input', () => { + expect(() => calculator.add('a', 2)).toThrow('Invalid input'); + }); + }); +}); +``` + +### Step 4: Cover Test Scenarios + +Generate tests for all scenarios: + +#### 4.1 Happy Path (Expected Usage) + +Test the normal, expected use cases: +- Valid inputs producing expected outputs +- Standard workflows +- Common use patterns + +```python +def test_user_creation_with_valid_data(): + """Test creating a user with all valid fields.""" + user = create_user( + email="user@example.com", + name="John Doe", + age=30 + ) + + assert user.email == "user@example.com" + assert user.name == "John Doe" + assert user.age == 30 + assert user.id is not None +``` + +#### 4.2 Edge Cases + +Test boundary conditions and special cases: +- Empty inputs +- Zero values +- Very large values +- Minimum/maximum boundaries +- Special characters +- Unicode/international input + +```python +def test_empty_string(): + """Test handling of empty string input.""" + result = process_text("") + assert result == "" + +def test_max_length_string(): + """Test handling of maximum length string.""" + long_text = "a" * 10000 + result = process_text(long_text) + assert len(result) <= 10000 + +def test_unicode_characters(): + """Test handling of unicode characters.""" + text = "Hello 世界 🌍" + result = process_text(text) + assert "世界" in result +``` + +#### 4.3 Error Conditions + +Test how errors are handled: +- Invalid inputs +- Missing required parameters +- Type mismatches +- Resource not found +- Permission denied + +```python +def test_invalid_email_format(): + """Test that invalid email format raises ValueError.""" + with pytest.raises(ValueError, match="Invalid email format"): + create_user(email="invalid-email", name="John") + +def test_missing_required_field(): + """Test that missing required field raises error.""" + with pytest.raises(TypeError): + create_user(name="John") # Missing email +``` + +#### 4.4 State and Side Effects + +Test stateful behavior and side effects: +- Database changes +- File system operations +- External API calls +- State mutations + +```python +def test_user_is_saved_to_database(db_session): + """Test that user is persisted to database.""" + user = create_user(email="test@example.com", name="Test") + + # Verify in database + saved_user = db_session.query(User).filter_by(email="test@example.com").first() + assert saved_user is not None + assert saved_user.name == "Test" +``` + +#### 4.5 Async Operations + +Test asynchronous code properly: + +```javascript +describe('fetchUserData', () => { + it('should fetch user data successfully', async () => { + const userId = '123'; + const userData = await fetchUserData(userId); + + expect(userData).toHaveProperty('id', userId); + expect(userData).toHaveProperty('name'); + }); + + it('should handle fetch errors', async () => { + await expect(fetchUserData('invalid')).rejects.toThrow('User not found'); + }); +}); +``` + +### Step 5: Add Mocking and Fixtures + +Use mocks and fixtures for dependencies: + +**Mocking external dependencies:** + +```javascript +import { jest } from '@jest/globals'; +import { sendEmail } from './emailService'; + +// Mock the email service +jest.mock('./emailService'); + +describe('User registration', () => { + it('should send welcome email on successful registration', async () => { + sendEmail.mockResolvedValue({ success: true }); + + await registerUser({ email: 'test@example.com' }); + + expect(sendEmail).toHaveBeenCalledWith({ + to: 'test@example.com', + subject: 'Welcome!', + body: expect.any(String) + }); + }); +}); +``` + +**Using fixtures:** + +```python +import pytest + +@pytest.fixture +def sample_user(): + """Provide a sample user for tests.""" + return { + 'email': 'test@example.com', + 'name': 'Test User', + 'age': 25 + } + +def test_user_validation(sample_user): + """Test user validation with fixture.""" + result = validate_user(sample_user) + assert result.is_valid +``` + +### Step 6: Test Organization + +Organize tests logically: + +```python +# test_user_service.py + +class TestUserCreation: + """Tests for user creation functionality.""" + + def test_create_user_with_valid_data(self): + """Test creating user with valid data.""" + pass + + def test_create_user_with_invalid_email(self): + """Test error handling for invalid email.""" + pass + +class TestUserRetrieval: + """Tests for user retrieval functionality.""" + + def test_get_user_by_id(self): + """Test retrieving user by ID.""" + pass + + def test_get_user_not_found(self): + """Test handling when user doesn't exist.""" + pass + +class TestUserUpdate: + """Tests for user update functionality.""" + + def test_update_user_email(self): + """Test updating user email.""" + pass +``` + +### Step 7: Add Test Documentation + +Document tests clearly: + +```python +def test_password_hashing(): + """ + Test that passwords are properly hashed. + + This test verifies that: + 1. Plain text passwords are not stored + 2. Hashed passwords are different from original + 3. Hash is verifiable using check_password + 4. Same password hashed twice produces different hashes (due to salt) + """ + password = "secure_password_123" + hashed = hash_password(password) + + assert hashed != password + assert check_password(password, hashed) + assert hash_password(password) != hashed # Different salt +``` + +## Framework-Specific Patterns + +### Jest/Vitest (JavaScript/TypeScript) + +```javascript +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +describe('MyComponent', () => { + let instance; + + beforeEach(() => { + instance = new MyComponent(); + }); + + afterEach(() => { + instance.cleanup(); + }); + + it('should initialize with default state', () => { + expect(instance.state).toEqual({}); + }); +}); +``` + +### pytest (Python) + +```python +import pytest + +class TestCalculator: + @pytest.fixture(autouse=True) + def setup(self): + """Setup before each test.""" + self.calc = Calculator() + yield + # Teardown after each test + self.calc = None + + def test_addition(self): + assert self.calc.add(2, 3) == 5 + + @pytest.mark.parametrize("a,b,expected", [ + (2, 3, 5), + (0, 0, 0), + (-1, 1, 0), + (100, 200, 300), + ]) + def test_addition_multiple_cases(self, a, b, expected): + assert self.calc.add(a, b) == expected +``` + +### Go testing + +```go +package calculator + +import "testing" + +func TestAdd(t *testing.T) { + tests := []struct { + name string + a, b int + expected int + }{ + {"positive numbers", 2, 3, 5}, + {"with zero", 0, 5, 5}, + {"negative numbers", -2, -3, -5}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := Add(tt.a, tt.b) + if result != tt.expected { + t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected) + } + }) + } +} +``` + +### JUnit (Java) + +```java +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("Calculator Tests") +class CalculatorTest { + + private Calculator calculator; + + @BeforeEach + void setUp() { + calculator = new Calculator(); + } + + @Test + @DisplayName("Should add two positive numbers") + void testAddPositiveNumbers() { + assertEquals(5, calculator.add(2, 3)); + } + + @Test + @DisplayName("Should throw exception for invalid input") + void testInvalidInput() { + assertThrows(IllegalArgumentException.class, () -> { + calculator.divide(10, 0); + }); + } +} +``` + +## Component Testing + +### React Components (with Testing Library) + +```javascript +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { UserProfile } from './UserProfile'; + +describe('UserProfile', () => { + it('should render user information', () => { + const user = { name: 'John Doe', email: 'john@example.com' }; + + render(); + + expect(screen.getByText('John Doe')).toBeInTheDocument(); + expect(screen.getByText('john@example.com')).toBeInTheDocument(); + }); + + it('should call onEdit when edit button is clicked', () => { + const onEdit = jest.fn(); + const user = { name: 'John Doe', email: 'john@example.com' }; + + render(); + + fireEvent.click(screen.getByRole('button', { name: /edit/i })); + + expect(onEdit).toHaveBeenCalledWith(user); + }); + + it('should display loading state', async () => { + render(); + + expect(screen.getByText(/loading/i)).toBeInTheDocument(); + + await waitFor(() => { + expect(screen.getByText('John Doe')).toBeInTheDocument(); + }); + }); +}); +``` + +## API Testing + +```javascript +import request from 'supertest'; +import app from './app'; + +describe('POST /api/users', () => { + it('should create a new user', async () => { + const userData = { + email: 'test@example.com', + name: 'Test User' + }; + + const response = await request(app) + .post('/api/users') + .send(userData) + .expect(201); + + expect(response.body).toMatchObject({ + id: expect.any(String), + email: userData.email, + name: userData.name + }); + }); + + it('should return 400 for invalid email', async () => { + const response = await request(app) + .post('/api/users') + .send({ email: 'invalid', name: 'Test' }) + .expect(400); + + expect(response.body).toHaveProperty('error'); + }); +}); +``` + +## Test Quality Guidelines + +**Write tests that are:** + +1. **Clear**: Test names describe what's being tested +2. **Independent**: Each test runs in isolation +3. **Repeatable**: Same results every time +4. **Fast**: Quick to run +5. **Thorough**: Cover edge cases and errors +6. **Maintainable**: Easy to update when code changes + +**Avoid:** + +- Tests that depend on external services (use mocks) +- Tests that depend on other tests' side effects +- Tests with hard-coded dates/times (use fixtures) +- Overly complex test logic +- Testing implementation details instead of behavior + +## Coverage Goals + +Aim for: +- **Unit tests**: 80-90% code coverage +- **Integration tests**: Critical paths and workflows +- **E2E tests**: Key user journeys + +Don't aim for 100% coverage - focus on valuable tests. + +## Test Output Structure + +Generate tests in a file that: +1. Imports necessary dependencies +2. Sets up test fixtures and mocks +3. Organizes tests by functionality +4. Includes clear test names +5. Has helpful comments +6. Follows project conventions + +## Error Handling + +- If code language is unclear, ask the user +- If testing framework is not specified, suggest the most common one +- If dependencies are unclear, ask about mocking strategy +- If scope is too large, suggest breaking into multiple test files + +## Example Interactions + +### Example 1: Generate Unit Tests + +User: "Generate tests for utils/stringHelper.js" + +Response: +1. Read utils/stringHelper.js +2. Analyze functions and their behavior +3. Identify edge cases +4. Generate comprehensive test file +5. Include mocks for dependencies +6. Write to utils/stringHelper.test.js + +### Example 2: Test React Component + +User: "Create tests for my Button component" + +Response: +1. Read the Button component +2. Identify props and interactions +3. Set up Testing Library +4. Generate tests for: + - Rendering with different props + - Click handlers + - Disabled state + - Styling variants +5. Write component.test.tsx + +### Example 3: API Endpoint Tests + +User: "Test the POST /api/products endpoint" + +Response: +1. Analyze the endpoint implementation +2. Identify request/response format +3. Generate tests for: + - Successful creation + - Validation errors + - Authentication + - Edge cases +4. Use supertest or similar +5. Mock database operations