commit 7db5ade777a983a86279b8d45d468a81531453df Author: Luong NGUYEN Date: Sat Nov 8 00:09:21 2025 +0100 Initial commit: Claude How To project Added comprehensive examples for Claude Code features including slash commands, subagents, memory, MCP protocol, skills, and plugins with documentation and quick reference guides. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a2fcc2e --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# macOS +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# IDEs +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Environment variables +.env +.env.local +.env.*.local + +# Temporary files +*.tmp +*.temp diff --git a/01-slash-commands/README.md b/01-slash-commands/README.md new file mode 100644 index 0000000..7c01b82 --- /dev/null +++ b/01-slash-commands/README.md @@ -0,0 +1,59 @@ +# Slash Commands Examples + +This folder contains example slash commands that can be used with Claude Code. + +## Installation + +Copy these files to your project's `.claude/commands/` directory: + +```bash +cp *.md /path/to/your/project/.claude/commands/ +``` + +## Available Commands + +### 1. `/optimize` - Code Optimization +Analyzes code for performance issues, memory leaks, and optimization opportunities. + +**Usage:** +``` +/optimize +[Paste your code] +``` + +### 2. `/pr` - Pull Request Preparation +Guides you through PR preparation checklist including linting, testing, and commit message formatting. + +**Usage:** +``` +/pr +``` + +### 3. `/generate-api-docs` - API Documentation Generator +Generates comprehensive API documentation from source code. + +**Usage:** +``` +/generate-api-docs +``` + +## File Structure + +Place commands in your project: +``` +project/ +β”œβ”€β”€ .claude/ +β”‚ └── commands/ +β”‚ β”œβ”€β”€ optimize.md +β”‚ β”œβ”€β”€ pr.md +β”‚ └── docs/ +β”‚ └── generate-api-docs.md +``` + +## Best Practices + +- Use clear, action-oriented names +- Document trigger words in description +- Keep commands focused on single task +- Version control project commands +- Organize in subdirectories for categories diff --git a/01-slash-commands/generate-api-docs.md b/01-slash-commands/generate-api-docs.md new file mode 100644 index 0000000..d57e1ed --- /dev/null +++ b/01-slash-commands/generate-api-docs.md @@ -0,0 +1,21 @@ +--- +name: Generate API Documentation +description: Create comprehensive API documentation from source code +tags: documentation, api +--- + +# API Documentation Generator + +Generate API documentation by: + +1. Scanning all files in `/src/api/` +2. Extracting function signatures and JSDoc comments +3. Organizing by endpoint/module +4. Creating markdown with examples +5. Including request/response schemas +6. Adding error documentation + +Output format: +- Markdown file in `/docs/api.md` +- Include curl examples for all endpoints +- Add TypeScript types diff --git a/01-slash-commands/optimize.md b/01-slash-commands/optimize.md new file mode 100644 index 0000000..8af0839 --- /dev/null +++ b/01-slash-commands/optimize.md @@ -0,0 +1,21 @@ +--- +name: Code Optimization +description: Analyze code for performance issues and suggest optimizations +tags: performance, analysis +--- + +# Code Optimization + +Review the provided code for the following issues in order of priority: + +1. **Performance bottlenecks** - identify O(nΒ²) operations, inefficient loops +2. **Memory leaks** - find unreleased resources, circular references +3. **Algorithm improvements** - suggest better algorithms or data structures +4. **Caching opportunities** - identify repeated computations +5. **Concurrency issues** - find race conditions or threading problems + +Format your response with: +- Issue severity (Critical/High/Medium/Low) +- Location in code +- Explanation +- Recommended fix with code example diff --git a/01-slash-commands/pr.md b/01-slash-commands/pr.md new file mode 100644 index 0000000..e46d8b5 --- /dev/null +++ b/01-slash-commands/pr.md @@ -0,0 +1,27 @@ +--- +name: Prepare Pull Request +description: Clean up code, stage changes, and prepare a pull request +tags: git, workflow +--- + +# Pull Request Preparation Checklist + +Before creating a PR, execute these steps: + +1. Run linting: `prettier --write .` +2. Run tests: `npm test` +3. Review git diff: `git diff HEAD` +4. Stage changes: `git add .` +5. Create commit message following conventional commits: + - `fix:` for bug fixes + - `feat:` for new features + - `docs:` for documentation + - `refactor:` for code restructuring + - `test:` for test additions + - `chore:` for maintenance + +6. Generate PR summary including: + - What changed + - Why it changed + - Testing performed + - Potential impacts diff --git a/02-subagents/README.md b/02-subagents/README.md new file mode 100644 index 0000000..fc0e7cc --- /dev/null +++ b/02-subagents/README.md @@ -0,0 +1,94 @@ +# Subagents Examples + +This folder contains example subagent configurations for Claude Code. + +## Installation + +Copy these files to your project's `.claude/agents/` directory: + +```bash +cp *.md /path/to/your/project/.claude/agents/ +``` + +## Available Subagents + +### 1. Code Reviewer (`code-reviewer`) +Comprehensive code quality and maintainability analysis. + +**Tools**: read, grep, diff, lint_runner + +**Use Case**: Automated code reviews focusing on security, performance, and quality. + +### 2. Test Engineer (`test-engineer`) +Test strategy, coverage analysis, and automated testing. + +**Tools**: read, write, bash, grep + +**Use Case**: Creating comprehensive test suites with high coverage. + +### 3. Documentation Writer (`documentation-writer`) +Technical documentation, API docs, and user guides. + +**Tools**: read, write, grep + +**Use Case**: Generating and maintaining project documentation. + +### 4. Secure Reviewer (`secure-reviewer`) +Security-focused code review with minimal permissions. + +**Tools**: read, grep (read-only) + +**Use Case**: Security audits without modification capabilities. + +### 5. Implementation Agent (`implementation-agent`) +Full implementation capabilities for feature development. + +**Tools**: read, write, bash, grep, edit, glob + +**Use Case**: End-to-end feature implementation. + +## How Subagents Work + +Subagents are specialized AI assistants with: +- **Isolated context windows** - Clean slate for each task +- **Customized system prompts** - Specialized expertise +- **Tool access control** - Only necessary capabilities + +## Usage Example + +Main agent delegates work to subagents: + +```markdown +User: "Build a new authentication feature" + +Main Agent: +1. Delegates implementation to implementation-agent +2. Delegates security review to secure-reviewer +3. Delegates testing to test-engineer +4. Delegates documentation to documentation-writer +5. Synthesizes all results +``` + +## File Structure + +``` +project/ +β”œβ”€β”€ .claude/ +β”‚ └── agents/ +β”‚ β”œβ”€β”€ code-reviewer.md +β”‚ β”œβ”€β”€ test-engineer.md +β”‚ β”œβ”€β”€ documentation-writer.md +β”‚ β”œβ”€β”€ secure-reviewer.md +β”‚ └── implementation-agent.md +``` + +## When to Use Subagents + +| Scenario | Use Subagent | Why | +|----------|--------------|-----| +| Complex feature with many steps | βœ… Yes | Separate concerns | +| Quick code review | ❌ No | Unnecessary overhead | +| Parallel task execution | βœ… Yes | Independent contexts | +| Specialized expertise needed | βœ… Yes | Custom prompts | +| Long-running analysis | βœ… Yes | Prevent context exhaustion | +| Single simple task | ❌ No | Adds latency | diff --git a/02-subagents/code-reviewer.md b/02-subagents/code-reviewer.md new file mode 100644 index 0000000..f29a97b --- /dev/null +++ b/02-subagents/code-reviewer.md @@ -0,0 +1,41 @@ +--- +name: code-reviewer +description: Comprehensive code quality and maintainability analysis +tools: read, grep, diff, lint_runner +--- + +# Code Reviewer Agent + +You are an expert code reviewer specializing in: +- Performance optimization +- Security vulnerabilities +- Code maintainability +- Testing coverage +- Design patterns + +## Review Priorities (in order) + +1. **Security Issues** - Authentication, authorization, data exposure +2. **Performance Problems** - O(nΒ²) operations, memory leaks, inefficient queries +3. **Code Quality** - Readability, naming, documentation +4. **Test Coverage** - Missing tests, edge cases +5. **Design Patterns** - SOLID principles, architecture + +## Review Output Format + +For each issue: +- **Severity**: Critical / High / Medium / Low +- **Category**: Security / Performance / Quality / Testing / Design +- **Location**: File path and line number +- **Issue Description**: What's wrong and why +- **Suggested Fix**: Code example +- **Impact**: How this affects the system + +## Example Review + +### Issue: N+1 Query Problem +- **Severity**: High +- **Category**: Performance +- **Location**: src/user-service.ts:45 +- **Issue**: Loop executes database query in each iteration +- **Fix**: Use JOIN or batch query diff --git a/02-subagents/documentation-writer.md b/02-subagents/documentation-writer.md new file mode 100644 index 0000000..c9a452f --- /dev/null +++ b/02-subagents/documentation-writer.md @@ -0,0 +1,40 @@ +--- +name: documentation-writer +description: Technical documentation, API docs, and user guides +tools: read, write, grep +--- + +# Documentation Writer Agent + +You create: +- API documentation with examples +- User guides and tutorials +- Architecture documentation +- Changelog entries +- Code comment improvements + +## Documentation Standards + +1. **Clarity** - Use simple, clear language +2. **Examples** - Include practical code examples +3. **Completeness** - Cover all parameters and returns +4. **Structure** - Use consistent formatting +5. **Accuracy** - Verify against actual code + +## Documentation Sections + +### For APIs +- Description +- Parameters (with types) +- Returns (with types) +- Throws (possible errors) +- Examples (curl, JavaScript, Python) +- Related endpoints + +### For Features +- Overview +- Prerequisites +- Step-by-step instructions +- Expected outcomes +- Troubleshooting +- Related topics diff --git a/02-subagents/implementation-agent.md b/02-subagents/implementation-agent.md new file mode 100644 index 0000000..8971820 --- /dev/null +++ b/02-subagents/implementation-agent.md @@ -0,0 +1,19 @@ +--- +name: implementation-agent +description: Full implementation capabilities for feature development +tools: read, write, bash, grep, edit, glob +--- + +# Implementation Agent + +Builds features from specifications. + +This agent: +- βœ… Reads specifications +- βœ… Writes new code files +- βœ… Runs build commands +- βœ… Searches codebase +- βœ… Edits existing files +- βœ… Finds files matching patterns + +Full capabilities for independent feature development. diff --git a/02-subagents/secure-reviewer.md b/02-subagents/secure-reviewer.md new file mode 100644 index 0000000..6d5819b --- /dev/null +++ b/02-subagents/secure-reviewer.md @@ -0,0 +1,18 @@ +--- +name: secure-reviewer +description: Security-focused code review with minimal permissions +tools: read, grep +--- + +# Secure Code Reviewer + +Reviews code for security vulnerabilities only. + +This agent: +- βœ… Reads files to analyze +- βœ… Searches for patterns +- ❌ Cannot execute code +- ❌ Cannot modify files +- ❌ Cannot run tests + +This ensures the reviewer doesn't accidentally break anything. diff --git a/02-subagents/test-engineer.md b/02-subagents/test-engineer.md new file mode 100644 index 0000000..79ad860 --- /dev/null +++ b/02-subagents/test-engineer.md @@ -0,0 +1,36 @@ +--- +name: test-engineer +description: Test strategy, coverage analysis, and automated testing +tools: read, write, bash, grep +--- + +# Test Engineer Agent + +You are expert at: +- Writing comprehensive test suites +- Ensuring high code coverage (>80%) +- Testing edge cases and error scenarios +- Performance benchmarking +- Integration testing + +## Testing Strategy + +1. **Unit Tests** - Individual functions/methods +2. **Integration Tests** - Component interactions +3. **End-to-End Tests** - Complete workflows +4. **Edge Cases** - Boundary conditions +5. **Error Scenarios** - Failure handling + +## Test Output Requirements + +- Use Jest for JavaScript/TypeScript +- Include setup/teardown for each test +- Mock external dependencies +- Document test purpose +- Include performance assertions when relevant + +## Coverage Requirements + +- Minimum 80% code coverage +- 100% for critical paths +- Report missing coverage areas diff --git a/03-memory/README.md b/03-memory/README.md new file mode 100644 index 0000000..3661611 --- /dev/null +++ b/03-memory/README.md @@ -0,0 +1,122 @@ +# Memory Examples + +This folder contains example CLAUDE.md files for different memory scopes in Claude Code. + +## Memory Types + +### 1. Project Memory (`project-CLAUDE.md`) +**Location**: `./CLAUDE.md` or `./.claude/CLAUDE.md` + +**Purpose**: Team-wide project standards and configurations + +**Installation**: +```bash +cp project-CLAUDE.md /path/to/your/project/CLAUDE.md +``` + +**Contains**: +- Project overview and tech stack +- Development standards +- Naming conventions +- Git workflow +- Testing requirements +- API standards +- Common commands +- Team contacts + +### 2. Directory-Specific Memory (`directory-api-CLAUDE.md`) +**Location**: `./src/api/CLAUDE.md` + +**Purpose**: Override or extend project memory for specific directories + +**Installation**: +```bash +cp directory-api-CLAUDE.md /path/to/your/project/src/api/CLAUDE.md +``` + +**Contains**: +- API-specific standards +- Request validation rules +- Authentication requirements +- Response formats +- Pagination standards +- Rate limiting +- Caching strategy + +### 3. Personal Memory (`personal-CLAUDE.md`) +**Location**: `~/.claude/CLAUDE.md` + +**Purpose**: Personal preferences across all projects + +**Installation**: +```bash +cp personal-CLAUDE.md ~/.claude/CLAUDE.md +``` + +**Contains**: +- Personal coding preferences +- Communication style +- Debugging preferences +- Project organization +- Tooling preferences + +## Memory Hierarchy + +Claude searches for memory in this order: + +1. **Project Root** (`./CLAUDE.md`) - Highest priority +2. **Subdirectory** (`./subdir/CLAUDE.md`) - Directory-specific +3. **Personal** (`~/.claude/CLAUDE.md`) - Lowest priority + +## Usage + +Memory is automatically loaded by Claude Code when starting a session. + +### Updating Memory During Session + +```markdown +User: Remember that I prefer using async/await instead of promises + +Claude: I'll add that to your memory. Which memory file? +1. Project memory (./CLAUDE.md) +2. Personal memory (~/.claude/CLAUDE.md) + +User: Project memory + +Claude: βœ… Memory saved! +``` + +## File Imports + +You can import other markdown files in your CLAUDE.md: + +```markdown +## Architecture +@docs/architecture.md +@docs/api-standards.md +@docs/database-schema.md +``` + +## Best Practices + +### Do's βœ… +- Keep memory files organized and up-to-date +- Use project memory for team standards +- Use personal memory for individual preferences +- Version control project memory with git +- Import large docs instead of duplicating + +### Don'ts ❌ +- Don't store secrets or credentials +- Don't duplicate content across memory files +- Don't create too many subdirectory overrides +- Don't make memory files too long (>500 lines) + +## Memory vs Other Features + +| Feature | Persistence | Scope | Best For | +|---------|------------|-------|----------| +| **Memory** | Cross-session | User/Project | Long-term context | +| **Slash Commands** | Session only | Command | Quick shortcuts | +| **MCP** | Real-time | External data | Live information | +| **Skills** | Filesystem | Reusable | Automated workflows | diff --git a/03-memory/directory-api-CLAUDE.md b/03-memory/directory-api-CLAUDE.md new file mode 100644 index 0000000..590636d --- /dev/null +++ b/03-memory/directory-api-CLAUDE.md @@ -0,0 +1,61 @@ +# API Module Standards + +This file overrides root CLAUDE.md for everything in /src/api/ + +## API-Specific Standards + +### Request Validation +- Use Zod for schema validation +- Always validate input +- Return 400 with validation errors +- Include field-level error details + +### Authentication +- All endpoints require JWT token +- Token in Authorization header +- Token expires after 24 hours +- Implement refresh token mechanism + +### Response Format + +All responses must follow this structure: + +```json +{ + "success": true, + "data": { /* actual data */ }, + "timestamp": "2025-11-06T10:30:00Z", + "version": "1.0" +} +``` + +Error responses: +```json +{ + "success": false, + "error": { + "code": "VALIDATION_ERROR", + "message": "User message", + "details": { /* field errors */ } + }, + "timestamp": "2025-11-06T10:30:00Z" +} +``` + +### Pagination +- Use cursor-based pagination (not offset) +- Include `hasMore` boolean +- Limit max page size to 100 +- Default page size: 20 + +### Rate Limiting +- 1000 requests per hour for authenticated users +- 100 requests per hour for public endpoints +- Return 429 when exceeded +- Include retry-after header + +### Caching +- Use Redis for session caching +- Cache duration: 5 minutes default +- Invalidate on write operations +- Tag cache keys with resource type diff --git a/03-memory/personal-CLAUDE.md b/03-memory/personal-CLAUDE.md new file mode 100644 index 0000000..2f3c736 --- /dev/null +++ b/03-memory/personal-CLAUDE.md @@ -0,0 +1,60 @@ +# My Development Preferences + +## About Me +- **Experience Level**: 8 years full-stack development +- **Preferred Languages**: TypeScript, Python +- **Communication Style**: Direct, with examples +- **Learning Style**: Visual diagrams with code + +## Code Preferences + +### Error Handling +I prefer explicit error handling with try-catch blocks and meaningful error messages. +Avoid generic errors. Always log errors for debugging. + +### Comments +Use comments for WHY, not WHAT. Code should be self-documenting. +Comments should explain business logic or non-obvious decisions. + +### Testing +I prefer TDD (test-driven development). +Write tests first, then implementation. +Focus on behavior, not implementation details. + +### Architecture +I prefer modular, loosely-coupled design. +Use dependency injection for testability. +Separate concerns (Controllers, Services, Repositories). + +## Debugging Preferences +- Use console.log with prefix: `[DEBUG]` +- Include context: function name, relevant variables +- Use stack traces when available +- Always include timestamps in logs + +## Communication +- Explain complex concepts with diagrams +- Show concrete examples before explaining theory +- Include before/after code snippets +- Summarize key points at the end + +## Project Organization +I organize my projects as: +``` +project/ + β”œβ”€β”€ src/ + β”‚ β”œβ”€β”€ api/ + β”‚ β”œβ”€β”€ services/ + β”‚ β”œβ”€β”€ models/ + β”‚ └── utils/ + β”œβ”€β”€ tests/ + β”œβ”€β”€ docs/ + └── docker/ +``` + +## Tooling +- **IDE**: VS Code with vim keybindings +- **Terminal**: Zsh with Oh-My-Zsh +- **Format**: Prettier (100 char line length) +- **Linter**: ESLint with airbnb config +- **Test Framework**: Jest with React Testing Library diff --git a/03-memory/project-CLAUDE.md b/03-memory/project-CLAUDE.md new file mode 100644 index 0000000..033f518 --- /dev/null +++ b/03-memory/project-CLAUDE.md @@ -0,0 +1,88 @@ +# Project Configuration + +## Project Overview +- **Name**: E-commerce Platform +- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker +- **Team Size**: 5 developers +- **Deadline**: Q4 2025 + +## Architecture +@docs/architecture.md +@docs/api-standards.md +@docs/database-schema.md + +## Development Standards + +### Code Style +- Use Prettier for formatting +- Use ESLint with airbnb config +- Maximum line length: 100 characters +- Use 2-space indentation + +### Naming Conventions +- **Files**: kebab-case (user-controller.js) +- **Classes**: PascalCase (UserService) +- **Functions/Variables**: camelCase (getUserById) +- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL) +- **Database Tables**: snake_case (user_accounts) + +### Git Workflow +- Branch names: `feature/description` or `fix/description` +- Commit messages: Follow conventional commits +- PR required before merge +- All CI/CD checks must pass +- Minimum 1 approval required + +### Testing Requirements +- Minimum 80% code coverage +- All critical paths must have tests +- Use Jest for unit tests +- Use Cypress for E2E tests +- Test filenames: `*.test.ts` or `*.spec.ts` + +### API Standards +- RESTful endpoints only +- JSON request/response +- Use HTTP status codes correctly +- Version API endpoints: `/api/v1/` +- Document all endpoints with examples + +### Database +- Use migrations for schema changes +- Never hardcode credentials +- Use connection pooling +- Enable query logging in development +- Regular backups required + +### Deployment +- Docker-based deployment +- Kubernetes orchestration +- Blue-green deployment strategy +- Automatic rollback on failure +- Database migrations run before deploy + +## Common Commands + +| Command | Purpose | +|---------|---------| +| `npm run dev` | Start development server | +| `npm test` | Run test suite | +| `npm run lint` | Check code style | +| `npm run build` | Build for production | +| `npm run migrate` | Run database migrations | + +## Team Contacts +- Tech Lead: Sarah Chen (@sarah.chen) +- Product Manager: Mike Johnson (@mike.j) +- DevOps: Alex Kim (@alex.k) + +## Known Issues & Workarounds +- PostgreSQL connection pooling limited to 20 during peak hours +- Workaround: Implement query queuing +- Safari 14 compatibility issues with async generators +- Workaround: Use Babel transpiler + +## Related Projects +- Analytics Dashboard: `/projects/analytics` +- Mobile App: `/projects/mobile` +- Admin Panel: `/projects/admin` diff --git a/04-mcp/README.md b/04-mcp/README.md new file mode 100644 index 0000000..6c27f53 --- /dev/null +++ b/04-mcp/README.md @@ -0,0 +1,225 @@ +# MCP (Model Context Protocol) Examples + +This folder contains example MCP server configurations for Claude Code. + +## What is MCP? + +MCP (Model Context Protocol) enables Claude to access external tools, APIs, and real-time data sources. Unlike Memory, MCP provides live access to changing data. + +## Installation + +Copy the appropriate configuration to your project's `.claude/` directory: + +```bash +cp github-mcp.json /path/to/your/project/.claude/mcp.json +``` + +## Available MCP Configurations + +### 1. GitHub MCP (`github-mcp.json`) +Access GitHub repositories, PRs, issues, and commits. + +**Setup**: +```bash +export GITHUB_TOKEN="your_github_token" +cp github-mcp.json ~/.claude/mcp.json +``` + +**Available Tools**: +- `list_prs` - List all PRs in repository +- `get_pr` - Get PR details including diff +- `create_pr` - Create new PR +- `list_issues` - List all issues +- `create_issue` - Create new issue +- `get_commit` - Get commit details +- `search_code` - Search across codebase + +**Usage**: +``` +/mcp__github__list_prs completed:true last:7days +/mcp__github__get_pr 456 +/mcp__github__create_issue "Bug in login form" +``` + +### 2. Database MCP (`database-mcp.json`) +Query PostgreSQL/MySQL databases. + +**Setup**: +```bash +export DATABASE_URL="postgresql://user:pass@localhost/mydb" +cp database-mcp.json ~/.claude/mcp.json +``` + +**Usage**: +``` +User: Fetch all users with more than 10 orders + +Claude: I'll query your database: +SELECT u.*, COUNT(o.id) as order_count +FROM users u +LEFT JOIN orders o ON u.id = o.user_id +GROUP BY u.id +HAVING COUNT(o.id) > 10 +``` + +### 3. Filesystem MCP (`filesystem-mcp.json`) +File operations on local filesystem. + +**Setup**: +```bash +cp filesystem-mcp.json ~/.claude/mcp.json +``` + +**Available Operations**: +- List files +- Read file contents +- Write files +- Search in files +- Delete files + +### 4. Multi-MCP (`multi-mcp.json`) +Configure multiple MCP servers simultaneously. + +**Setup**: +```bash +export GITHUB_TOKEN="your_github_token" +export DATABASE_URL="postgresql://user:pass@localhost/mydb" +export SLACK_TOKEN="your_slack_token" +cp multi-mcp.json ~/.claude/mcp.json +``` + +## Available MCP Servers + +| MCP Server | Purpose | Auth | Real-time | +|------------|---------|------|-----------| +| **Filesystem** | File operations | OS permissions | βœ… Yes | +| **GitHub** | Repository management | OAuth | βœ… Yes | +| **Slack** | Team communication | Token | βœ… Yes | +| **Database** | SQL queries | Credentials | βœ… Yes | +| **Google Docs** | Document access | OAuth | βœ… Yes | +| **Asana** | Project management | API Key | βœ… Yes | +| **Stripe** | Payment data | API Key | βœ… Yes | + +## Configuration Format + +```json +{ + "mcpServers": { + "server-name": { + "command": "npx", + "args": ["@modelcontextprotocol/server-name"], + "env": { + "ENV_VAR": "${ENV_VAR}" + } + } + } +} +``` + +## Multi-MCP Workflow Example + +### Daily Report Generation + +```markdown +# Uses: GitHub MCP + Database MCP + Slack MCP + Filesystem MCP + +## Step 1: Fetch GitHub Data +/mcp__github__list_prs completed:true last:7days +β†’ Output: 42 PRs merged + +## Step 2: Query Database +SELECT COUNT(*) as sales, SUM(amount) as revenue +FROM orders WHERE created_at > NOW() - INTERVAL '1 day' +β†’ Output: 247 sales, $12,450 revenue + +## Step 3: Generate Report +Combine data into HTML report + +## Step 4: Save to Filesystem +Write report.html to /reports/ + +## Step 5: Post to Slack +Send summary to #daily-reports channel + +βœ… Report generated and posted +``` + +## MCP vs Memory + +```mermaid +graph TD + A["Need external data?"] + A -->|No| B["Use Memory"] + A -->|Yes| C["Does it change frequently?"] + C -->|No/Rarely| B + C -->|Yes/Often| D["Use MCP"] + + B -->|Stores| E["Preferences
Context
History"] + D -->|Accesses| F["Live APIs
Databases
Services"] +``` + +## Environment Variables + +Store sensitive credentials in environment variables: + +```bash +# ~/.bashrc or ~/.zshrc +export GITHUB_TOKEN="ghp_xxxxxxxxxxxxx" +export DATABASE_URL="postgresql://user:pass@localhost/mydb" +export SLACK_TOKEN="xoxb-xxxxxxxxxxxxx" +``` + +Then reference them in MCP config: + +```json +{ + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } +} +``` + +## Security Best Practices + +### Do's βœ… +- Use environment variables for credentials +- Rotate tokens regularly +- Use read-only tokens when possible +- Limit MCP server access scope +- Monitor MCP server usage + +### Don'ts ❌ +- Don't hardcode credentials in config files +- Don't commit tokens to git +- Don't share tokens in team chats +- Don't use personal tokens for team projects +- Don't grant unnecessary permissions + +## Troubleshooting + +### MCP Server Not Found +```bash +# Install MCP server globally +npm install -g @modelcontextprotocol/server-github +``` + +### Authentication Failed +```bash +# Verify environment variable is set +echo $GITHUB_TOKEN + +# Re-export if needed +export GITHUB_TOKEN="your_token" +``` + +### Connection Timeout +- Check network connectivity +- Verify API endpoint is accessible +- Check rate limits on API +- Try increasing timeout in config + +## Additional Resources + +- [MCP GitHub Repository](https://github.com/modelcontextprotocol/servers) +- [MCP Protocol Specification](https://modelcontextprotocol.io) +- [Claude Code MCP Guide](https://docs.claude.com/en/docs/claude-code/mcp) diff --git a/04-mcp/database-mcp.json b/04-mcp/database-mcp.json new file mode 100644 index 0000000..eaa832a --- /dev/null +++ b/04-mcp/database-mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "database": { + "command": "npx", + "args": ["@modelcontextprotocol/server-database"], + "env": { + "DATABASE_URL": "postgresql://user:pass@localhost/mydb" + } + } + } +} diff --git a/04-mcp/filesystem-mcp.json b/04-mcp/filesystem-mcp.json new file mode 100644 index 0000000..c76fdf6 --- /dev/null +++ b/04-mcp/filesystem-mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "filesystem": { + "command": "npx", + "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"] + } + } +} diff --git a/04-mcp/github-mcp.json b/04-mcp/github-mcp.json new file mode 100644 index 0000000..0f62131 --- /dev/null +++ b/04-mcp/github-mcp.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} diff --git a/04-mcp/multi-mcp.json b/04-mcp/multi-mcp.json new file mode 100644 index 0000000..62d8fa5 --- /dev/null +++ b/04-mcp/multi-mcp.json @@ -0,0 +1,29 @@ +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + }, + "database": { + "command": "npx", + "args": ["@modelcontextprotocol/server-database"], + "env": { + "DATABASE_URL": "${DATABASE_URL}" + } + }, + "slack": { + "command": "npx", + "args": ["@modelcontextprotocol/server-slack"], + "env": { + "SLACK_TOKEN": "${SLACK_TOKEN}" + } + }, + "filesystem": { + "command": "npx", + "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"] + } + } +} diff --git a/05-skills/README.md b/05-skills/README.md new file mode 100644 index 0000000..f4a9b5c --- /dev/null +++ b/05-skills/README.md @@ -0,0 +1,205 @@ +# Skills Examples + +This folder contains example skills for Claude Code. Skills are reusable, model-invoked capabilities that Claude automatically detects and uses. + +## Installation + +Copy skill folders to your skills directory: + +```bash +# For personal skills +cp -r code-review ~/.claude/skills/ + +# For project skills +cp -r code-review /path/to/project/.claude/skills/ +``` + +## Available Skills + +### 1. Code Review Skill +**Location**: `code-review/` + +**Purpose**: Comprehensive code review with security, performance, and quality analysis + +**Contents**: +- `SKILL.md` - Main skill definition +- `scripts/analyze-metrics.py` - Code metrics analyzer +- `scripts/compare-complexity.py` - Complexity comparison tool +- `templates/review-checklist.md` - Review checklist +- `templates/finding-template.md` - Finding documentation template + +**Usage**: Automatically invoked when user asks to review code + +``` +User: "Review this React component" + +Claude: [Automatically loads Code Review Skill] + [Analyzes code against checklist] + [Runs metrics scripts] + [Provides comprehensive review] +``` + +### 2. Brand Voice Skill +**Location**: `brand-voice/` + +**Purpose**: Ensure consistent brand voice in all communications + +**Contents**: +- `SKILL.md` - Brand guidelines and tone rules +- `templates/email-template.txt` - Email format +- `templates/social-post-template.txt` - Social media format +- `tone-examples.md` - Example messages in brand voice + +**Usage**: Automatically invoked when creating marketing copy or customer communications + +### 3. Documentation Generator Skill +**Location**: `doc-generator/` + +**Purpose**: Generate comprehensive API documentation from source code + +**Contents**: +- `SKILL.md` - Documentation standards and structure +- `generate-docs.py` - Python script to extract API docs from code + +**Usage**: Automatically invoked when creating or updating API documentation + +## How Skills Work + +Skills are: +- **Auto-invoked** - Claude detects when to use them based on user request +- **Reusable** - Define once, use across projects +- **Packaged** - Include instructions, scripts, and templates +- **Metadata-driven** - YAML frontmatter defines when to use + +## Skill Structure + +``` +skill-name/ +β”œβ”€β”€ SKILL.md # Main skill definition (required) +β”œβ”€β”€ scripts/ # Helper scripts (optional) +β”‚ └── helper.py +β”œβ”€β”€ templates/ # Document templates (optional) +β”‚ └── template.md +└── README.md # Usage documentation (optional) +``` + +## SKILL.md Format + +```yaml +--- +name: Skill Name +description: What this skill does +version: "1.0.0" +tags: + - category + - use-case +when_to_use: When users ask to... +--- + +# Skill Instructions + +Detailed instructions for Claude on how to execute this skill. +``` + +## Skill Discovery + +Claude automatically: +1. Scans available skills +2. Matches user request to skill metadata +3. Loads relevant skill instructions +4. Executes skill with full context + +## When to Use Skills + +| Scenario | Use Skill | Why | +|----------|-----------|-----| +| Repeated workflow | βœ… Yes | Standardize process | +| Domain expertise | βœ… Yes | Package knowledge | +| Quality standards | βœ… Yes | Ensure consistency | +| One-time task | ❌ No | Not worth packaging | +| Simple request | ❌ No | Use slash command | + +## Skills vs Other Features + +| Feature | Invocation | Best For | +|---------|-----------|----------| +| **Skills** | Auto-invoked | Automated workflows | +| **Slash Commands** | Manual (`/cmd`) | Quick shortcuts | +| **Subagents** | Auto-delegated | Task distribution | +| **Memory** | Auto-loaded | Long-term context | + +## Creating Custom Skills + +1. Create skill directory structure +2. Write SKILL.md with metadata and instructions +3. Add scripts and templates as needed +4. Test by copying to skills directory +5. Refine based on usage + +## Best Practices + +### Do's βœ… +- Use clear, descriptive names +- Include comprehensive instructions +- Add concrete examples +- Document when to use the skill +- Package related scripts and templates +- Test with real scenarios + +### Don'ts ❌ +- Don't create skills for one-time tasks +- Don't duplicate existing functionality +- Don't make skills too broad +- Don't forget metadata in SKILL.md +- Don't skip examples + +## Making Scripts Executable + +```bash +chmod +x code-review/scripts/*.py +chmod +x doc-generator/*.py +``` + +## Example Usage Scenarios + +### Code Review Workflow +``` +User: "Review this authentication module for security issues" + +Claude: +1. Detects "review" + "security" keywords +2. Loads Code Review Skill +3. Runs security checklist +4. Executes analyze-metrics.py +5. Provides detailed review with finding template +``` + +### Brand Voice Check +``` +User: "Write an email announcing our new feature" + +Claude: +1. Detects marketing/communication request +2. Loads Brand Voice Skill +3. Applies brand guidelines +4. Uses email template +5. Ensures consistent tone +``` + +### API Documentation +``` +User: "Generate API docs for this endpoint" + +Claude: +1. Detects API documentation request +2. Loads Documentation Generator Skill +3. Runs generate-docs.py if needed +4. Follows documentation structure +5. Creates comprehensive docs with examples +``` + +## Additional Resources + +- [Skills Cookbook](https://github.com/anthropic-ai/skills) +- [Claude Code Skills Guide](https://docs.claude.com/en/docs/claude-code/skills) +- [Skill Development Best Practices](https://docs.claude.com) diff --git a/05-skills/brand-voice/SKILL.md b/05-skills/brand-voice/SKILL.md new file mode 100644 index 0000000..b2843e4 --- /dev/null +++ b/05-skills/brand-voice/SKILL.md @@ -0,0 +1,77 @@ +--- +name: Brand Voice Consistency +description: Ensure all communication matches brand voice and tone guidelines +tags: + - brand + - writing + - consistency +when_to_use: When creating marketing copy, customer communications, or public-facing content +--- + +# Brand Voice Skill + +## Overview +This skill ensures all communications maintain consistent brand voice, tone, and messaging. + +## Brand Identity + +### Mission +Help teams automate their development workflows with AI + +### Values +- **Simplicity**: Make complex things simple +- **Reliability**: Rock-solid execution +- **Empowerment**: Enable human creativity + +### Tone of Voice +- **Friendly but professional** - approachable without being casual +- **Clear and concise** - avoid jargon, explain technical concepts simply +- **Confident** - we know what we're doing +- **Empathetic** - understand user needs and pain points + +## Writing Guidelines + +### Do's βœ… +- Use "you" when addressing readers +- Use active voice: "Claude generates reports" not "Reports are generated by Claude" +- Start with value proposition +- Use concrete examples +- Keep sentences under 20 words +- Use lists for clarity +- Include calls-to-action + +### Don'ts ❌ +- Don't use corporate jargon +- Don't patronize or oversimplify +- Don't use "we believe" or "we think" +- Don't use ALL CAPS except for emphasis +- Don't create walls of text +- Don't assume technical knowledge + +## Vocabulary + +### βœ… Preferred Terms +- Claude (not "the Claude AI") +- Code generation (not "auto-coding") +- Agent (not "bot") +- Streamline (not "revolutionize") +- Integrate (not "synergize") + +### ❌ Avoid Terms +- "Cutting-edge" (overused) +- "Game-changer" (vague) +- "Leverage" (corporate-speak) +- "Utilize" (use "use") +- "Paradigm shift" (unclear) + +## Examples + +### βœ… Good Example +"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and qualityβ€”saving your team hours every week." + +Why it works: Clear value, specific benefits, action-oriented + +### ❌ Bad Example +"Claude leverages cutting-edge AI to provide comprehensive software development solutions." + +Why it doesn't work: Vague, corporate jargon, no specific value diff --git a/05-skills/brand-voice/templates/email-template.txt b/05-skills/brand-voice/templates/email-template.txt new file mode 100644 index 0000000..741294d --- /dev/null +++ b/05-skills/brand-voice/templates/email-template.txt @@ -0,0 +1,14 @@ +Subject: [Clear, benefit-driven subject] + +Hi [Name], + +[Opening: What's the value for them] + +[Body: How it works / What they'll get] + +[Specific example or benefit] + +[Call to action: Clear next step] + +Best regards, +[Name] diff --git a/05-skills/brand-voice/templates/social-post-template.txt b/05-skills/brand-voice/templates/social-post-template.txt new file mode 100644 index 0000000..97fafba --- /dev/null +++ b/05-skills/brand-voice/templates/social-post-template.txt @@ -0,0 +1,4 @@ +[Hook: Grab attention in first line] +[2-3 lines: Value or interesting fact] +[Call to action: Link, question, or engagement] +[Emoji: 1-2 max for visual interest] diff --git a/05-skills/brand-voice/tone-examples.md b/05-skills/brand-voice/tone-examples.md new file mode 100644 index 0000000..648f7ce --- /dev/null +++ b/05-skills/brand-voice/tone-examples.md @@ -0,0 +1,13 @@ +# Brand Voice Tone Examples + +## Exciting Announcement +"Save 8 hours per week on code reviews. Claude reviews your PRs automatically." + +## Empathetic Support +"We know deployments can be stressful. Claude handles testing so you don't have to worry." + +## Confident Product Feature +"Claude doesn't just suggest code. It understands your architecture and maintains consistency." + +## Educational Blog Post +"Let's explore how agents improve code review workflows. Here's what we learned..." diff --git a/05-skills/code-review/SKILL.md b/05-skills/code-review/SKILL.md new file mode 100644 index 0000000..8cb437a --- /dev/null +++ b/05-skills/code-review/SKILL.md @@ -0,0 +1,72 @@ +--- +name: Code Review Specialist +description: Comprehensive code review with security, performance, and quality analysis +version: "1.0.0" +tags: + - code-review + - quality + - security +when_to_use: When users ask to review code, analyze code quality, or evaluate pull requests +--- + +# Code Review Skill + +This skill provides comprehensive code review capabilities focusing on: + +1. **Security Analysis** + - Authentication/authorization issues + - Data exposure risks + - Injection vulnerabilities + - Cryptographic weaknesses + - Sensitive data logging + +2. **Performance Review** + - Algorithm efficiency (Big O analysis) + - Memory optimization + - Database query optimization + - Caching opportunities + - Concurrency issues + +3. **Code Quality** + - SOLID principles + - Design patterns + - Naming conventions + - Documentation + - Test coverage + +4. **Maintainability** + - Code readability + - Function size (should be < 50 lines) + - Cyclomatic complexity + - Dependency management + - Type safety + +## Review Template + +For each piece of code reviewed, provide: + +### Summary +- Overall quality assessment (1-5) +- Key findings count +- Recommended priority areas + +### Critical Issues (if any) +- **Issue**: Clear description +- **Location**: File and line number +- **Impact**: Why this matters +- **Severity**: Critical/High/Medium +- **Fix**: Code example + +### Findings by Category + +#### Security (if issues found) +List security vulnerabilities with examples + +#### Performance (if issues found) +List performance problems with complexity analysis + +#### Quality (if issues found) +List code quality issues with refactoring suggestions + +#### Maintainability (if issues found) +List maintainability problems with improvements diff --git a/05-skills/code-review/scripts/analyze-metrics.py b/05-skills/code-review/scripts/analyze-metrics.py new file mode 100644 index 0000000..dc0fc0d --- /dev/null +++ b/05-skills/code-review/scripts/analyze-metrics.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +import re +import sys + +def analyze_code_metrics(code): + """Analyze code for common metrics.""" + + # Count functions + functions = len(re.findall(r'^def\s+\w+', code, re.MULTILINE)) + + # Count classes + classes = len(re.findall(r'^class\s+\w+', code, re.MULTILINE)) + + # Average line length + lines = code.split('\n') + avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0 + + # Estimate complexity + complexity = len(re.findall(r'\b(if|elif|else|for|while|and|or)\b', code)) + + return { + 'functions': functions, + 'classes': classes, + 'avg_line_length': avg_length, + 'complexity_score': complexity + } + +if __name__ == '__main__': + with open(sys.argv[1], 'r') as f: + code = f.read() + metrics = analyze_code_metrics(code) + for key, value in metrics.items(): + print(f"{key}: {value:.2f}") diff --git a/05-skills/code-review/scripts/compare-complexity.py b/05-skills/code-review/scripts/compare-complexity.py new file mode 100644 index 0000000..a93182b --- /dev/null +++ b/05-skills/code-review/scripts/compare-complexity.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +""" +Compare cyclomatic complexity of code before and after changes. +Helps identify if refactoring actually simplifies code structure. +""" + +import re +import sys +from typing import Dict, Tuple + +class ComplexityAnalyzer: + """Analyze code complexity metrics.""" + + def __init__(self, code: str): + self.code = code + self.lines = code.split('\n') + + def calculate_cyclomatic_complexity(self) -> int: + """ + Calculate cyclomatic complexity using McCabe's method. + Count decision points: if, elif, else, for, while, except, and, or + """ + complexity = 1 # Base complexity + + # Count decision points + decision_patterns = [ + r'\bif\b', + r'\belif\b', + r'\bfor\b', + r'\bwhile\b', + r'\bexcept\b', + r'\band\b(?!$)', + r'\bor\b(?!$)' + ] + + for pattern in decision_patterns: + matches = re.findall(pattern, self.code) + complexity += len(matches) + + return complexity + + def calculate_cognitive_complexity(self) -> int: + """ + Calculate cognitive complexity - how hard is it to understand? + Based on nesting depth and control flow. + """ + cognitive = 0 + nesting_depth = 0 + + for line in self.lines: + # Track nesting depth + if re.search(r'^\s*(if|for|while|def|class|try)\b', line): + nesting_depth += 1 + cognitive += nesting_depth + elif re.search(r'^\s*(elif|else|except|finally)\b', line): + cognitive += nesting_depth + + # Reduce nesting when unindenting + if line and not line[0].isspace(): + nesting_depth = 0 + + return cognitive + + def calculate_maintainability_index(self) -> float: + """ + Maintainability Index ranges from 0-100. + > 85: Excellent + > 65: Good + > 50: Fair + < 50: Poor + """ + lines = len(self.lines) + cyclomatic = self.calculate_cyclomatic_complexity() + cognitive = self.calculate_cognitive_complexity() + + # Simplified MI calculation + mi = 171 - 5.2 * (cyclomatic / lines) - 0.23 * (cognitive) - 16.2 * (lines / 1000) + + return max(0, min(100, mi)) + + def get_complexity_report(self) -> Dict: + """Generate comprehensive complexity report.""" + return { + 'cyclomatic_complexity': self.calculate_cyclomatic_complexity(), + 'cognitive_complexity': self.calculate_cognitive_complexity(), + 'maintainability_index': round(self.calculate_maintainability_index(), 2), + 'lines_of_code': len(self.lines), + 'avg_line_length': round(sum(len(l) for l in self.lines) / len(self.lines), 2) if self.lines else 0 + } + + +def compare_files(before_file: str, after_file: str) -> None: + """Compare complexity metrics between two code versions.""" + + with open(before_file, 'r') as f: + before_code = f.read() + + with open(after_file, 'r') as f: + after_code = f.read() + + before_analyzer = ComplexityAnalyzer(before_code) + after_analyzer = ComplexityAnalyzer(after_code) + + before_metrics = before_analyzer.get_complexity_report() + after_metrics = after_analyzer.get_complexity_report() + + print("=" * 60) + print("CODE COMPLEXITY COMPARISON") + print("=" * 60) + + print("\nBEFORE:") + print(f" Cyclomatic Complexity: {before_metrics['cyclomatic_complexity']}") + print(f" Cognitive Complexity: {before_metrics['cognitive_complexity']}") + print(f" Maintainability Index: {before_metrics['maintainability_index']}") + print(f" Lines of Code: {before_metrics['lines_of_code']}") + print(f" Avg Line Length: {before_metrics['avg_line_length']}") + + print("\nAFTER:") + print(f" Cyclomatic Complexity: {after_metrics['cyclomatic_complexity']}") + print(f" Cognitive Complexity: {after_metrics['cognitive_complexity']}") + print(f" Maintainability Index: {after_metrics['maintainability_index']}") + print(f" Lines of Code: {after_metrics['lines_of_code']}") + print(f" Avg Line Length: {after_metrics['avg_line_length']}") + + print("\nCHANGES:") + cyclomatic_change = after_metrics['cyclomatic_complexity'] - before_metrics['cyclomatic_complexity'] + cognitive_change = after_metrics['cognitive_complexity'] - before_metrics['cognitive_complexity'] + mi_change = after_metrics['maintainability_index'] - before_metrics['maintainability_index'] + loc_change = after_metrics['lines_of_code'] - before_metrics['lines_of_code'] + + print(f" Cyclomatic Complexity: {cyclomatic_change:+d}") + print(f" Cognitive Complexity: {cognitive_change:+d}") + print(f" Maintainability Index: {mi_change:+.2f}") + print(f" Lines of Code: {loc_change:+d}") + + print("\nASSESSMENT:") + if mi_change > 0: + print(" βœ… Code is MORE maintainable") + elif mi_change < 0: + print(" ⚠️ Code is LESS maintainable") + else: + print(" ➑️ Maintainability unchanged") + + if cyclomatic_change < 0: + print(" βœ… Complexity DECREASED") + elif cyclomatic_change > 0: + print(" ⚠️ Complexity INCREASED") + else: + print(" ➑️ Complexity unchanged") + + print("=" * 60) + + +if __name__ == '__main__': + if len(sys.argv) != 3: + print("Usage: python compare-complexity.py ") + sys.exit(1) + + compare_files(sys.argv[1], sys.argv[2]) diff --git a/05-skills/code-review/templates/finding-template.md b/05-skills/code-review/templates/finding-template.md new file mode 100644 index 0000000..17d7ee0 --- /dev/null +++ b/05-skills/code-review/templates/finding-template.md @@ -0,0 +1,113 @@ +# Code Review Finding Template + +Use this template when documenting each issue found during code review. + +--- + +## Issue: [TITLE] + +### Severity +- [ ] Critical (blocks deployment) +- [ ] High (should fix before merge) +- [ ] Medium (should fix soon) +- [ ] Low (nice to have) + +### Category +- [ ] Security +- [ ] Performance +- [ ] Code Quality +- [ ] Maintainability +- [ ] Testing +- [ ] Design Pattern +- [ ] Documentation + +### Location +**File:** `src/components/UserCard.tsx` + +**Lines:** 45-52 + +**Function/Method:** `renderUserDetails()` + +### Issue Description + +**What:** Describe what the issue is. + +**Why it matters:** Explain the impact and why this needs to be fixed. + +**Current behavior:** Show the problematic code or behavior. + +**Expected behavior:** Describe what should happen instead. + +### Code Example + +#### Current (Problematic) + +```typescript +// Shows the N+1 query problem +const users = fetchUsers(); +users.forEach(user => { + const posts = fetchUserPosts(user.id); // Query per user! + renderUserPosts(posts); +}); +``` + +#### Suggested Fix + +```typescript +// Optimized with JOIN query +const usersWithPosts = fetchUsersWithPosts(); +usersWithPosts.forEach(({ user, posts }) => { + renderUserPosts(posts); +}); +``` + +### Impact Analysis + +| Aspect | Impact | Severity | +|--------|--------|----------| +| Performance | 100+ queries for 20 users | High | +| User Experience | Slow page load | High | +| Scalability | Breaks at scale | Critical | +| Maintainability | Hard to debug | Medium | + +### Related Issues + +- Similar issue in `AdminUserList.tsx` line 120 +- Related PR: #456 +- Related issue: #789 + +### Additional Resources + +- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem) +- [Database Join Documentation](https://docs.example.com/joins) +- [Performance Optimization Guide](./docs/performance.md) + +### Reviewer Notes + +- This is a common pattern in this codebase +- Consider adding this to the code style guide +- Might be worth creating a helper function + +### Author Response (for feedback) + +*To be filled by the code author:* + +- [ ] Fix implemented in commit: `abc123` +- [ ] Fix status: Complete / In Progress / Needs Discussion +- [ ] Questions or concerns: (describe) + +--- + +## Finding Statistics (for Reviewer) + +When reviewing multiple findings, track: + +- **Total Issues Found:** X +- **Critical:** X +- **High:** X +- **Medium:** X +- **Low:** X + +**Recommendation:** βœ… Approve / ⚠️ Request Changes / πŸ”„ Needs Discussion + +**Overall Code Quality:** 1-5 stars diff --git a/05-skills/code-review/templates/review-checklist.md b/05-skills/code-review/templates/review-checklist.md new file mode 100644 index 0000000..5d48b61 --- /dev/null +++ b/05-skills/code-review/templates/review-checklist.md @@ -0,0 +1,47 @@ +# Code Review Checklist + +## Security Checklist +- [ ] No hardcoded credentials or secrets +- [ ] Input validation on all user inputs +- [ ] SQL injection prevention (parameterized queries) +- [ ] CSRF protection on state-changing operations +- [ ] XSS prevention with proper escaping +- [ ] Authentication checks on protected endpoints +- [ ] Authorization checks on resources +- [ ] Secure password hashing (bcrypt, argon2) +- [ ] No sensitive data in logs +- [ ] HTTPS enforced + +## Performance Checklist +- [ ] No N+1 queries +- [ ] Appropriate use of indexes +- [ ] Caching implemented where beneficial +- [ ] No blocking operations on main thread +- [ ] Async/await used correctly +- [ ] Large datasets paginated +- [ ] Database connections pooled +- [ ] Regular expressions optimized +- [ ] No unnecessary object creation +- [ ] Memory leaks prevented + +## Quality Checklist +- [ ] Functions < 50 lines +- [ ] Clear variable naming +- [ ] No duplicate code +- [ ] Proper error handling +- [ ] Comments explain WHY, not WHAT +- [ ] No console.logs in production +- [ ] Type checking (TypeScript/JSDoc) +- [ ] SOLID principles followed +- [ ] Design patterns applied correctly +- [ ] Self-documenting code + +## Testing Checklist +- [ ] Unit tests written +- [ ] Edge cases covered +- [ ] Error scenarios tested +- [ ] Integration tests present +- [ ] Coverage > 80% +- [ ] No flaky tests +- [ ] Mock external dependencies +- [ ] Clear test names diff --git a/05-skills/doc-generator/SKILL.md b/05-skills/doc-generator/SKILL.md new file mode 100644 index 0000000..fbd5b98 --- /dev/null +++ b/05-skills/doc-generator/SKILL.md @@ -0,0 +1,82 @@ +--- +name: API Documentation Generator +description: Generate comprehensive, accurate API documentation from source code +version: "1.0.0" +tags: + - documentation + - api + - automation +when_to_use: When creating or updating API documentation +--- + +# API Documentation Generator Skill + +## Generates + +- OpenAPI/Swagger specifications +- API endpoint documentation +- SDK usage examples +- Integration guides +- Error code references +- Authentication guides + +## Documentation Structure + +### For Each Endpoint + +```markdown +## GET /api/v1/users/:id + +### Description +Brief explanation of what this endpoint does + +### Parameters + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string | Yes | User ID | + +### Response + +**200 Success** +```json +{ + "id": "usr_123", + "name": "John Doe", + "email": "john@example.com", + "created_at": "2025-01-15T10:30:00Z" +} +``` + +**404 Not Found** +```json +{ + "error": "USER_NOT_FOUND", + "message": "User does not exist" +} +``` + +### Examples + +**cURL** +```bash +curl -X GET "https://api.example.com/api/v1/users/usr_123" \ + -H "Authorization: Bearer YOUR_TOKEN" +``` + +**JavaScript** +```javascript +const user = await fetch('/api/v1/users/usr_123', { + headers: { 'Authorization': 'Bearer token' } +}).then(r => r.json()); +``` + +**Python** +```python +response = requests.get( + 'https://api.example.com/api/v1/users/usr_123', + headers={'Authorization': 'Bearer token'} +) +user = response.json() +``` +``` diff --git a/05-skills/doc-generator/generate-docs.py b/05-skills/doc-generator/generate-docs.py new file mode 100644 index 0000000..2578315 --- /dev/null +++ b/05-skills/doc-generator/generate-docs.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +import ast +import json +from typing import Dict, List + +class APIDocExtractor(ast.NodeVisitor): + """Extract API documentation from Python source code.""" + + def __init__(self): + self.endpoints = [] + + def visit_FunctionDef(self, node): + """Extract function documentation.""" + if node.name.startswith('get_') or node.name.startswith('post_'): + doc = ast.get_docstring(node) + endpoint = { + 'name': node.name, + 'docstring': doc, + 'params': [arg.arg for arg in node.args.args], + 'returns': self._extract_return_type(node) + } + self.endpoints.append(endpoint) + self.generic_visit(node) + + def _extract_return_type(self, node): + """Extract return type from function annotation.""" + if node.returns: + return ast.unparse(node.returns) + return "Any" + +def generate_markdown_docs(endpoints: List[Dict]) -> str: + """Generate markdown documentation from endpoints.""" + docs = "# API Documentation\n\n" + + for endpoint in endpoints: + docs += f"## {endpoint['name']}\n\n" + docs += f"{endpoint['docstring']}\n\n" + docs += f"**Parameters**: {', '.join(endpoint['params'])}\n\n" + docs += f"**Returns**: {endpoint['returns']}\n\n" + docs += "---\n\n" + + return docs + +if __name__ == '__main__': + import sys + with open(sys.argv[1], 'r') as f: + tree = ast.parse(f.read()) + + extractor = APIDocExtractor() + extractor.visit(tree) + + markdown = generate_markdown_docs(extractor.endpoints) + print(markdown) diff --git a/06-plugins/README.md b/06-plugins/README.md new file mode 100644 index 0000000..cf53a51 --- /dev/null +++ b/06-plugins/README.md @@ -0,0 +1,313 @@ +# Claude Code Plugins Examples + +This folder contains complete plugin examples that bundle multiple Claude Code features into cohesive, installable packages. + +## What Are Plugins? + +Plugins are bundled collections of: +- Slash commands +- Subagents +- MCP servers +- Hooks +- Scripts and templates + +All installable with a single command. + +## Available Plugins + +### 1. PR Review Plugin +**Location**: [pr-review/](pr-review/) + +**Purpose**: Complete PR review workflow with security, testing, and documentation checks + +**Features**: +- 3 slash commands (`/review-pr`, `/check-security`, `/check-tests`) +- 3 specialized subagents +- GitHub MCP integration +- Pre-review validation hook + +**Installation**: +```bash +/plugin install pr-review +``` + +**Use Case**: Automated code reviews for pull requests + +--- + +### 2. DevOps Automation Plugin +**Location**: [devops-automation/](devops-automation/) + +**Purpose**: Complete DevOps automation for deployment, monitoring, and incident response + +**Features**: +- 4 slash commands (`/deploy`, `/rollback`, `/status`, `/incident`) +- 3 specialized subagents +- Kubernetes MCP integration +- Pre/post-deployment hooks +- Deployment scripts + +**Installation**: +```bash +/plugin install devops-automation +``` + +**Use Case**: Kubernetes deployment automation and incident management + +--- + +### 3. Documentation Plugin +**Location**: [documentation/](documentation/) + +**Purpose**: Comprehensive documentation generation and maintenance + +**Features**: +- 4 slash commands +- 3 documentation subagents +- GitHub MCP integration +- Documentation templates (API, function, ADR) + +**Installation**: +```bash +/plugin install documentation +``` + +**Use Case**: Automated documentation generation and maintenance + +--- + +## Plugin Structure + +``` +plugin-name/ +β”œβ”€β”€ plugin.yaml # Plugin manifest +β”œβ”€β”€ commands/ # Slash commands +β”‚ β”œβ”€β”€ command-1.md +β”‚ └── command-2.md +β”œβ”€β”€ agents/ # Subagents +β”‚ β”œβ”€β”€ agent-1.md +β”‚ └── agent-2.md +β”œβ”€β”€ mcp/ # MCP configurations +β”‚ └── config.json +β”œβ”€β”€ hooks/ # Event hooks +β”‚ β”œβ”€β”€ pre-hook.js +β”‚ └── post-hook.js +β”œβ”€β”€ scripts/ # Helper scripts +β”‚ └── script.sh +β”œβ”€β”€ templates/ # Document templates +β”‚ └── template.md +└── README.md # Plugin documentation +``` + +## Plugin Manifest (plugin.yaml) + +```yaml +--- +name: plugin-name +version: "1.0.0" +description: What this plugin does +author: Your Name +license: MIT +tags: + - category + - use-case + +requires: + - claude-code: ">=1.0.0" + +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: hooks + path: hooks/ + +config: + auto_load: true + enabled_by_default: true +--- +``` + +## Installation Methods + +### Official Plugin +```bash +/plugin install plugin-name +``` + +### Local Plugin (for development) +```bash +/plugin install ./path/to/plugin +``` + +### From Git Repository +```bash +/plugin install github:username/repo +``` + +## When to Create a Plugin + +Create a plugin when: + +βœ… You have multiple related commands/agents +βœ… You want one-command installation +βœ… You're sharing with a team +βœ… You need version control +βœ… You want marketplace distribution +βœ… Complex setup requires automation + +Don't create a plugin when: + +❌ Single slash command is sufficient +❌ One-time use case +❌ Personal preference (use individual features) +❌ Very simple functionality + +## Plugin vs Individual Features + +| Aspect | Plugin | Individual Features | +|--------|--------|-------------------| +| **Installation** | One command | Manual copy per feature | +| **Setup Time** | 2 minutes | 15-30 minutes | +| **Components** | Multiple bundled | One at a time | +| **Versioning** | Automatic | Manual | +| **Team Sharing** | Plugin ID | Copy files | +| **Updates** | Auto-available | Manual | +| **Marketplace** | Yes | No | + +## Creating Your Own Plugin + +### Step 1: Create Structure +```bash +mkdir my-plugin +cd my-plugin +mkdir commands agents mcp hooks scripts templates +``` + +### Step 2: Create plugin.yaml +```yaml +--- +name: my-plugin +version: "1.0.0" +description: My custom plugin +author: Your Name +--- +``` + +### Step 3: Add Components +- Add slash commands to `commands/` +- Add subagents to `agents/` +- Add MCP configs to `mcp/` +- Add hooks to `hooks/` +- Add helper scripts to `scripts/` + +### Step 4: Test Locally +```bash +/plugin install ./my-plugin +``` + +### Step 5: Publish +Submit to plugin marketplace or share via git repository. + +## Best Practices + +### Do's βœ… +- Use clear, descriptive plugin names +- Include comprehensive README +- Version your plugin properly +- Test all components together +- Document requirements clearly +- Provide usage examples +- Include error handling +- Tag appropriately for discovery + +### Don'ts ❌ +- Don't bundle unrelated features +- Don't hardcode credentials +- Don't skip testing +- Don't forget documentation +- Don't create redundant plugins +- Don't ignore versioning + +## Plugin Lifecycle + +``` +Discover β†’ Install β†’ Configure β†’ Use β†’ Update β†’ Disable/Remove +``` + +### Discovery +Browse plugin marketplace or search by tags + +### Installation +```bash +/plugin install plugin-name +``` + +### Configuration +Set up required environment variables and credentials + +### Usage +Use slash commands, subagents work automatically + +### Updates +```bash +/plugin update plugin-name +``` + +### Disable +```bash +/plugin disable plugin-name +``` + +### Remove +```bash +/plugin uninstall plugin-name +``` + +## Example: Complete Workflow + +### PR Review Plugin Workflow + +``` +1. User: /review-pr + +2. Plugin executes: + β”œβ”€β”€ pre-review.js hook validates git repo + β”œβ”€β”€ GitHub MCP fetches PR data + β”œβ”€β”€ security-reviewer subagent analyzes security + β”œβ”€β”€ test-checker subagent verifies coverage + └── performance-analyzer subagent checks performance + +3. Results synthesized and presented: + βœ… Security: No critical issues + ⚠️ Testing: Coverage 65% (recommend 80%+) + βœ… Performance: No significant impact + πŸ“ 12 recommendations provided +``` + +## Troubleshooting + +### Plugin Won't Install +- Check Claude Code version compatibility +- Verify plugin.yaml syntax +- Check internet connection (for remote plugins) + +### Components Not Loading +- Verify paths in plugin.yaml +- Check file permissions +- Review component file syntax + +### MCP Connection Failed +- Verify environment variables are set +- Check MCP server installation +- Test MCP connection independently + +## Additional Resources + +- [Plugin Development Guide](https://docs.claude.com/plugins) +- [Plugin Marketplace](https://plugins.claude.com) +- [Example Plugins Repository](https://github.com/anthropic/claude-plugins) +- [Plugin API Reference](https://docs.claude.com/api/plugins) diff --git a/06-plugins/devops-automation/README.md b/06-plugins/devops-automation/README.md new file mode 100644 index 0000000..0feeb54 --- /dev/null +++ b/06-plugins/devops-automation/README.md @@ -0,0 +1,102 @@ +# DevOps Automation Plugin + +Complete DevOps automation for deployment, monitoring, and incident response. + +## Features + +βœ… Automated deployments +βœ… Rollback procedures +βœ… System health monitoring +βœ… Incident response workflows +βœ… Kubernetes integration + +## Installation + +```bash +/plugin install devops-automation +``` + +## What's Included + +### Slash Commands +- `/deploy` - Deploy to production or staging +- `/rollback` - Rollback to previous version +- `/status` - Check system health +- `/incident` - Handle production incidents + +### Subagents +- `deployment-specialist` - Deployment operations +- `incident-commander` - Incident coordination +- `alert-analyzer` - System health analysis + +### MCP Servers +- Kubernetes integration + +### Scripts +- `deploy.sh` - Deployment automation +- `rollback.sh` - Rollback automation +- `health-check.sh` - Health check utilities + +### Hooks +- `pre-deploy.js` - Pre-deployment validation +- `post-deploy.js` - Post-deployment tasks + +## Usage + +### Deploy to Staging +``` +/deploy staging +``` + +### Deploy to Production +``` +/deploy production +``` + +### Rollback +``` +/rollback production +``` + +### Check Status +``` +/status +``` + +### Handle Incident +``` +/incident +``` + +## Requirements + +- Claude Code 1.0+ +- Kubernetes CLI (kubectl) +- Cluster access configured + +## Configuration + +Set up your Kubernetes config: +```bash +export KUBECONFIG=~/.kube/config +``` + +## Example Workflow + +``` +User: /deploy production + +Claude: +1. Runs pre-deploy hook (validates kubectl, cluster connection) +2. Delegates to deployment-specialist subagent +3. Runs deploy.sh script +4. Monitors deployment progress via Kubernetes MCP +5. Runs post-deploy hook (waits for pods, smoke tests) +6. Provides deployment summary + +Result: +βœ… Deployment complete +πŸ“¦ Version: v2.1.0 +πŸš€ Pods: 3/3 ready +⏱️ Time: 2m 34s +``` diff --git a/06-plugins/devops-automation/agents/alert-analyzer.md b/06-plugins/devops-automation/agents/alert-analyzer.md new file mode 100644 index 0000000..d455e24 --- /dev/null +++ b/06-plugins/devops-automation/agents/alert-analyzer.md @@ -0,0 +1,14 @@ +--- +name: alert-analyzer +description: Analyzes monitoring alerts and system metrics +tools: read, grep, bash +--- + +# Alert Analyzer + +Analyzes system health and alerts: +- Alert correlation +- Trend analysis +- Root cause identification +- Metric visualization +- Proactive issue detection diff --git a/06-plugins/devops-automation/agents/deployment-specialist.md b/06-plugins/devops-automation/agents/deployment-specialist.md new file mode 100644 index 0000000..47fe3f7 --- /dev/null +++ b/06-plugins/devops-automation/agents/deployment-specialist.md @@ -0,0 +1,14 @@ +--- +name: deployment-specialist +description: Handles all deployment operations +tools: read, write, bash, grep +--- + +# Deployment Specialist + +Expert in deployment operations: +- Blue-green deployments +- Canary releases +- Rollback procedures +- Health checks +- Database migrations diff --git a/06-plugins/devops-automation/agents/incident-commander.md b/06-plugins/devops-automation/agents/incident-commander.md new file mode 100644 index 0000000..d73929c --- /dev/null +++ b/06-plugins/devops-automation/agents/incident-commander.md @@ -0,0 +1,14 @@ +--- +name: incident-commander +description: Coordinates incident response +tools: read, write, bash, grep +--- + +# Incident Commander + +Manages incident response: +- Severity assessment +- Team coordination +- Status updates +- Resolution tracking +- Post-mortem facilitation diff --git a/06-plugins/devops-automation/commands/deploy.md b/06-plugins/devops-automation/commands/deploy.md new file mode 100644 index 0000000..4873ca3 --- /dev/null +++ b/06-plugins/devops-automation/commands/deploy.md @@ -0,0 +1,15 @@ +--- +name: Deploy +description: Deploy application to production or staging +--- + +# Deploy Application + +Execute deployment workflow: + +1. Run pre-deployment checks +2. Build application +3. Run tests +4. Deploy to target environment +5. Run health checks +6. Notify team on Slack diff --git a/06-plugins/devops-automation/commands/incident.md b/06-plugins/devops-automation/commands/incident.md new file mode 100644 index 0000000..b5c0459 --- /dev/null +++ b/06-plugins/devops-automation/commands/incident.md @@ -0,0 +1,16 @@ +--- +name: Incident Response +description: Handle production incidents with structured response +--- + +# Incident Response + +Structured incident response workflow: + +1. Create incident record +2. Assess severity and impact +3. Notify on-call team +4. Gather diagnostic information +5. Coordinate response efforts +6. Document resolution +7. Schedule post-mortem diff --git a/06-plugins/devops-automation/commands/rollback.md b/06-plugins/devops-automation/commands/rollback.md new file mode 100644 index 0000000..2eb20a3 --- /dev/null +++ b/06-plugins/devops-automation/commands/rollback.md @@ -0,0 +1,14 @@ +--- +name: Rollback +description: Rollback to previous deployment +--- + +# Rollback Deployment + +Rollback to previous stable version: + +1. Identify previous deployment +2. Verify rollback target is healthy +3. Execute rollback procedure +4. Run health checks +5. Notify team diff --git a/06-plugins/devops-automation/commands/status.md b/06-plugins/devops-automation/commands/status.md new file mode 100644 index 0000000..6c2e670 --- /dev/null +++ b/06-plugins/devops-automation/commands/status.md @@ -0,0 +1,15 @@ +--- +name: System Status +description: Check overall system health and status +--- + +# System Status Check + +Check system health across all services: + +1. Query Kubernetes pod status +2. Check database connections +3. Monitor API response times +4. Review error rates +5. Check resource utilization +6. Report overall health diff --git a/06-plugins/devops-automation/hooks/post-deploy.js b/06-plugins/devops-automation/hooks/post-deploy.js new file mode 100644 index 0000000..5c6537e --- /dev/null +++ b/06-plugins/devops-automation/hooks/post-deploy.js @@ -0,0 +1,34 @@ +#!/usr/bin/env node + +/** + * Post-deployment hook + * Runs after deployment completes + */ + +async function postDeploy() { + console.log('Running post-deployment tasks...'); + + const { execSync } = require('child_process'); + + // Wait for pods to be ready + console.log('Waiting for pods to be ready...'); + try { + execSync('kubectl wait --for=condition=ready pod -l app=myapp --timeout=300s', { + stdio: 'inherit' + }); + } catch (error) { + console.error('❌ Pods failed to become ready'); + process.exit(1); + } + + // Run smoke tests + console.log('Running smoke tests...'); + // Add your smoke test commands here + + console.log('βœ… Post-deployment tasks complete'); +} + +postDeploy().catch(error => { + console.error('Post-deploy hook failed:', error); + process.exit(1); +}); diff --git a/06-plugins/devops-automation/hooks/pre-deploy.js b/06-plugins/devops-automation/hooks/pre-deploy.js new file mode 100644 index 0000000..98983a4 --- /dev/null +++ b/06-plugins/devops-automation/hooks/pre-deploy.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node + +/** + * Pre-deployment hook + * Validates environment and prerequisites before deployment + */ + +async function preDeploy() { + console.log('Running pre-deployment checks...'); + + const { execSync } = require('child_process'); + + // Check if kubectl is installed + try { + execSync('which kubectl', { stdio: 'pipe' }); + } catch (error) { + console.error('❌ kubectl not found. Please install Kubernetes CLI.'); + process.exit(1); + } + + // Check if connected to cluster + try { + execSync('kubectl cluster-info', { stdio: 'pipe' }); + } catch (error) { + console.error('❌ Not connected to Kubernetes cluster'); + process.exit(1); + } + + console.log('βœ… Pre-deployment checks passed'); +} + +preDeploy().catch(error => { + console.error('Pre-deploy hook failed:', error); + process.exit(1); +}); diff --git a/06-plugins/devops-automation/mcp/kubernetes-config.json b/06-plugins/devops-automation/mcp/kubernetes-config.json new file mode 100644 index 0000000..3f3b842 --- /dev/null +++ b/06-plugins/devops-automation/mcp/kubernetes-config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "kubernetes": { + "command": "npx", + "args": ["@modelcontextprotocol/server-kubernetes"], + "env": { + "KUBECONFIG": "${KUBECONFIG}" + } + } + } +} diff --git a/06-plugins/devops-automation/plugin.yaml b/06-plugins/devops-automation/plugin.yaml new file mode 100644 index 0000000..1449adb --- /dev/null +++ b/06-plugins/devops-automation/plugin.yaml @@ -0,0 +1,31 @@ +--- +name: devops-automation +version: "1.0.0" +description: Complete DevOps automation for deployment, monitoring, and incident response +author: Community +license: MIT +tags: + - devops + - deployment + - monitoring + - automation + +requires: + - claude-code: ">=1.0.0" + +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: hooks + path: hooks/ + - type: scripts + path: scripts/ + +config: + auto_load: true + enabled_by_default: true +--- diff --git a/06-plugins/devops-automation/scripts/deploy.sh b/06-plugins/devops-automation/scripts/deploy.sh new file mode 100644 index 0000000..9acf5bd --- /dev/null +++ b/06-plugins/devops-automation/scripts/deploy.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e + +echo "πŸš€ Starting deployment..." + +# Load environment +ENV=${1:-staging} +echo "πŸ“¦ Target environment: $ENV" + +# Pre-deployment checks +echo "βœ“ Running pre-deployment checks..." +npm run lint +npm test + +# Build +echo "πŸ”¨ Building application..." +npm run build + +# Deploy +echo "🚒 Deploying to $ENV..." +kubectl apply -f k8s/$ENV/ + +# Health check +echo "πŸ₯ Running health checks..." +sleep 10 +curl -f http://api.$ENV.example.com/health + +echo "βœ… Deployment complete!" diff --git a/06-plugins/devops-automation/scripts/health-check.sh b/06-plugins/devops-automation/scripts/health-check.sh new file mode 100644 index 0000000..2ded117 --- /dev/null +++ b/06-plugins/devops-automation/scripts/health-check.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +echo "πŸ₯ System Health Check" +echo "====================" + +ENV=${1:-production} + +# Check API +echo -n "API: " +if curl -sf http://api.$ENV.example.com/health > /dev/null; then + echo "βœ… Healthy" +else + echo "❌ Unhealthy" +fi + +# Check Database +echo -n "Database: " +if pg_isready -h db.$ENV.example.com > /dev/null 2>&1; then + echo "βœ… Healthy" +else + echo "❌ Unhealthy" +fi + +# Check Pods +echo -n "Kubernetes Pods: " +PODS_READY=$(kubectl get pods -n $ENV --no-headers | grep "Running" | wc -l) +PODS_TOTAL=$(kubectl get pods -n $ENV --no-headers | wc -l) +echo "$PODS_READY/$PODS_TOTAL ready" + +echo "====================" diff --git a/06-plugins/devops-automation/scripts/rollback.sh b/06-plugins/devops-automation/scripts/rollback.sh new file mode 100644 index 0000000..0fe0cc2 --- /dev/null +++ b/06-plugins/devops-automation/scripts/rollback.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e + +echo "βͺ Starting rollback..." + +ENV=${1:-staging} +echo "πŸ“¦ Target environment: $ENV" + +# Get previous deployment +PREVIOUS=$(kubectl rollout history deployment/app -n $ENV | tail -2 | head -1 | awk '{print $1}') +echo "πŸ”„ Rolling back to revision: $PREVIOUS" + +# Execute rollback +kubectl rollout undo deployment/app -n $ENV + +# Wait for rollback +echo "⏳ Waiting for rollback to complete..." +kubectl rollout status deployment/app -n $ENV + +# Health check +echo "πŸ₯ Running health checks..." +sleep 5 +curl -f http://api.$ENV.example.com/health + +echo "βœ… Rollback complete!" diff --git a/06-plugins/documentation/README.md b/06-plugins/documentation/README.md new file mode 100644 index 0000000..730a732 --- /dev/null +++ b/06-plugins/documentation/README.md @@ -0,0 +1,114 @@ +# Documentation Plugin + +Comprehensive documentation generation and maintenance for your project. + +## Features + +βœ… API documentation generation +βœ… README creation and updates +βœ… Documentation synchronization +βœ… Code comment improvements +βœ… Example generation + +## Installation + +```bash +/plugin install documentation +``` + +## What's Included + +### Slash Commands +- `/generate-api-docs` - Generate API documentation +- `/generate-readme` - Create or update README +- `/sync-docs` - Sync docs with code changes +- `/validate-docs` - Validate documentation + +### Subagents +- `api-documenter` - API documentation specialist +- `code-commentator` - Code comment improvements +- `example-generator` - Code example creation + +### Templates +- `api-endpoint.md` - API endpoint documentation template +- `function-docs.md` - Function documentation template +- `adr-template.md` - Architecture Decision Record template + +### MCP Servers +- GitHub integration for documentation syncing + +## Usage + +### Generate API Documentation +``` +/generate-api-docs +``` + +### Create README +``` +/generate-readme +``` + +### Sync Documentation +``` +/sync-docs +``` + +### Validate Documentation +``` +/validate-docs +``` + +## Requirements + +- Claude Code 1.0+ +- GitHub access (optional) + +## Example Workflow + +``` +User: /generate-api-docs + +Claude: +1. Scans all API endpoints in /src/api/ +2. Delegates to api-documenter subagent +3. Extracts function signatures and JSDoc +4. Organizes by module/endpoint +5. Uses api-endpoint.md template +6. Generates comprehensive markdown docs +7. Includes curl, JavaScript, and Python examples + +Result: +βœ… API documentation generated +πŸ“„ Files created: + - docs/api/users.md + - docs/api/auth.md + - docs/api/products.md +πŸ“Š Coverage: 23/23 endpoints documented +``` + +## Templates Usage + +### API Endpoint Template +Use for documenting REST API endpoints with full examples. + +### Function Documentation Template +Use for documenting individual functions/methods. + +### ADR Template +Use for documenting architectural decisions. + +## Configuration + +Set up GitHub token for documentation syncing: +```bash +export GITHUB_TOKEN="your_github_token" +``` + +## Best Practices + +- Keep documentation close to code +- Update docs with code changes +- Include practical examples +- Validate regularly +- Use templates for consistency diff --git a/06-plugins/documentation/agents/api-documenter.md b/06-plugins/documentation/agents/api-documenter.md new file mode 100644 index 0000000..487c5a4 --- /dev/null +++ b/06-plugins/documentation/agents/api-documenter.md @@ -0,0 +1,14 @@ +--- +name: api-documenter +description: API documentation specialist +tools: read, write, grep +--- + +# API Documenter + +Creates comprehensive API documentation: +- Endpoint documentation +- Parameter descriptions +- Response schemas +- Code examples (curl, JS, Python) +- Error codes diff --git a/06-plugins/documentation/agents/code-commentator.md b/06-plugins/documentation/agents/code-commentator.md new file mode 100644 index 0000000..a039443 --- /dev/null +++ b/06-plugins/documentation/agents/code-commentator.md @@ -0,0 +1,14 @@ +--- +name: code-commentator +description: Code comment and inline documentation specialist +tools: read, write, edit +--- + +# Code Commentator + +Improves code documentation: +- JSDoc/docstring comments +- Inline explanations +- Parameter descriptions +- Return type documentation +- Usage examples diff --git a/06-plugins/documentation/agents/example-generator.md b/06-plugins/documentation/agents/example-generator.md new file mode 100644 index 0000000..1cd1c7e --- /dev/null +++ b/06-plugins/documentation/agents/example-generator.md @@ -0,0 +1,14 @@ +--- +name: example-generator +description: Code example and tutorial specialist +tools: read, write +--- + +# Example Generator + +Creates practical code examples: +- Getting started guides +- Common use cases +- Integration examples +- Best practices +- Troubleshooting scenarios diff --git a/06-plugins/documentation/commands/generate-api-docs.md b/06-plugins/documentation/commands/generate-api-docs.md new file mode 100644 index 0000000..a5bda46 --- /dev/null +++ b/06-plugins/documentation/commands/generate-api-docs.md @@ -0,0 +1,15 @@ +--- +name: Generate API Documentation +description: Generate comprehensive API documentation from source code +--- + +# API Documentation Generator + +Generate complete API documentation: + +1. Scan API endpoints +2. Extract function signatures and JSDoc +3. Organize by module/endpoint +4. Create markdown with examples +5. Include request/response schemas +6. Add error documentation diff --git a/06-plugins/documentation/commands/generate-readme.md b/06-plugins/documentation/commands/generate-readme.md new file mode 100644 index 0000000..119310a --- /dev/null +++ b/06-plugins/documentation/commands/generate-readme.md @@ -0,0 +1,15 @@ +--- +name: Generate README +description: Create or update project README +--- + +# README Generator + +Generate comprehensive README: + +1. Project overview and description +2. Installation instructions +3. Usage examples +4. API documentation links +5. Contributing guidelines +6. License information diff --git a/06-plugins/documentation/commands/sync-docs.md b/06-plugins/documentation/commands/sync-docs.md new file mode 100644 index 0000000..9681cc8 --- /dev/null +++ b/06-plugins/documentation/commands/sync-docs.md @@ -0,0 +1,14 @@ +--- +name: Sync Documentation +description: Sync documentation with code changes +--- + +# Documentation Sync + +Synchronize documentation with codebase: + +1. Detect code changes +2. Identify outdated documentation +3. Update affected docs +4. Verify examples still work +5. Update version numbers diff --git a/06-plugins/documentation/commands/validate-docs.md b/06-plugins/documentation/commands/validate-docs.md new file mode 100644 index 0000000..bd41f57 --- /dev/null +++ b/06-plugins/documentation/commands/validate-docs.md @@ -0,0 +1,14 @@ +--- +name: Validate Documentation +description: Validate documentation for completeness and accuracy +--- + +# Documentation Validation + +Validate documentation quality: + +1. Check for broken links +2. Verify code examples +3. Ensure completeness +4. Check formatting +5. Validate against actual code diff --git a/06-plugins/documentation/mcp/github-docs-config.json b/06-plugins/documentation/mcp/github-docs-config.json new file mode 100644 index 0000000..0f62131 --- /dev/null +++ b/06-plugins/documentation/mcp/github-docs-config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} diff --git a/06-plugins/documentation/plugin.yaml b/06-plugins/documentation/plugin.yaml new file mode 100644 index 0000000..62d3dea --- /dev/null +++ b/06-plugins/documentation/plugin.yaml @@ -0,0 +1,28 @@ +--- +name: documentation +version: "1.0.0" +description: Comprehensive documentation generation and maintenance +author: Community +license: MIT +tags: + - documentation + - api + - guides + +requires: + - claude-code: ">=1.0.0" + +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: templates + path: templates/ + +config: + auto_load: true + enabled_by_default: true +--- diff --git a/06-plugins/documentation/templates/adr-template.md b/06-plugins/documentation/templates/adr-template.md new file mode 100644 index 0000000..8cc3fc3 --- /dev/null +++ b/06-plugins/documentation/templates/adr-template.md @@ -0,0 +1,39 @@ +# ADR [Number]: [Title] + +## Status +[Proposed | Accepted | Deprecated | Superseded] + +## Context +What is the issue that we're seeing that is motivating this decision or change? + +## Decision +What is the change that we're proposing and/or doing? + +## Consequences +What becomes easier or more difficult to do because of this change? + +### Positive +- Benefit 1 +- Benefit 2 + +### Negative +- Drawback 1 +- Drawback 2 + +### Neutral +- Consideration 1 +- Consideration 2 + +## Alternatives Considered +What other options were considered and why were they not chosen? + +### Alternative 1 +Description and reason for not choosing. + +### Alternative 2 +Description and reason for not choosing. + +## References +- Related ADRs +- External documentation +- Discussion links diff --git a/06-plugins/documentation/templates/api-endpoint.md b/06-plugins/documentation/templates/api-endpoint.md new file mode 100644 index 0000000..33c3996 --- /dev/null +++ b/06-plugins/documentation/templates/api-endpoint.md @@ -0,0 +1,101 @@ +# [METHOD] /api/v1/[endpoint] + +## Description +Brief explanation of what this endpoint does. + +## Authentication +Required authentication method (e.g., Bearer token). + +## Parameters + +### Path Parameters +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string | Yes | Resource ID | + +### Query Parameters +| Name | Type | Required | Description | +|------|------|----------|-------------| +| page | integer | No | Page number (default: 1) | +| limit | integer | No | Items per page (default: 20) | + +### Request Body +```json +{ + "field": "value" +} +``` + +## Responses + +### 200 OK +```json +{ + "success": true, + "data": { + "id": "123", + "name": "Example" + } +} +``` + +### 400 Bad Request +```json +{ + "success": false, + "error": { + "code": "VALIDATION_ERROR", + "message": "Invalid input" + } +} +``` + +### 404 Not Found +```json +{ + "success": false, + "error": { + "code": "NOT_FOUND", + "message": "Resource not found" + } +} +``` + +## Examples + +### cURL +```bash +curl -X GET "https://api.example.com/api/v1/endpoint" \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -H "Content-Type: application/json" +``` + +### JavaScript +```javascript +const response = await fetch('/api/v1/endpoint', { + headers: { + 'Authorization': 'Bearer token', + 'Content-Type': 'application/json' + } +}); +const data = await response.json(); +``` + +### Python +```python +import requests + +response = requests.get( + 'https://api.example.com/api/v1/endpoint', + headers={'Authorization': 'Bearer token'} +) +data = response.json() +``` + +## Rate Limits +- 1000 requests per hour for authenticated users +- 100 requests per hour for public endpoints + +## Related Endpoints +- [GET /api/v1/related](#) +- [POST /api/v1/related](#) diff --git a/06-plugins/documentation/templates/function-docs.md b/06-plugins/documentation/templates/function-docs.md new file mode 100644 index 0000000..b1e137d --- /dev/null +++ b/06-plugins/documentation/templates/function-docs.md @@ -0,0 +1,50 @@ +# Function: `functionName` + +## Description +Brief description of what the function does. + +## Signature +```typescript +function functionName(param1: Type1, param2: Type2): ReturnType +``` + +## Parameters + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| param1 | Type1 | Yes | Description of param1 | +| param2 | Type2 | No | Description of param2 | + +## Returns +**Type**: `ReturnType` + +Description of what is returned. + +## Throws +- `Error`: When invalid input is provided +- `TypeError`: When wrong type is passed + +## Examples + +### Basic Usage +```typescript +const result = functionName('value1', 'value2'); +console.log(result); +``` + +### Advanced Usage +```typescript +const result = functionName( + complexParam1, + { option: true } +); +``` + +## Notes +- Additional notes or warnings +- Performance considerations +- Best practices + +## See Also +- [Related Function](#) +- [API Documentation](#) diff --git a/06-plugins/pr-review/README.md b/06-plugins/pr-review/README.md new file mode 100644 index 0000000..b6299dc --- /dev/null +++ b/06-plugins/pr-review/README.md @@ -0,0 +1,86 @@ +# PR Review Plugin + +Complete PR review workflow with security, testing, and documentation checks. + +## Features + +βœ… Security analysis +βœ… Test coverage checking +βœ… Documentation verification +βœ… Code quality assessment +βœ… Performance impact analysis + +## Installation + +```bash +/plugin install pr-review +``` + +## What's Included + +### Slash Commands +- `/review-pr` - Comprehensive PR review +- `/check-security` - Security-focused review +- `/check-tests` - Test coverage analysis + +### Subagents +- `security-reviewer` - Security vulnerability detection +- `test-checker` - Test coverage analysis +- `performance-analyzer` - Performance impact evaluation + +### MCP Servers +- GitHub integration for PR data + +### Hooks +- `pre-review.js` - Pre-review validation + +## Usage + +### Basic PR Review +``` +/review-pr +``` + +### Security Check Only +``` +/check-security +``` + +### Test Coverage Check +``` +/check-tests +``` + +## Requirements + +- Claude Code 1.0+ +- GitHub access +- Git repository + +## Configuration + +Set up your GitHub token: +```bash +export GITHUB_TOKEN="your_github_token" +``` + +## Example Workflow + +``` +User: /review-pr + +Claude: +1. Runs pre-review hook (validates git repo) +2. Fetches PR data via GitHub MCP +3. Delegates security review to security-reviewer subagent +4. Delegates testing to test-checker subagent +5. Delegates performance to performance-analyzer subagent +6. Synthesizes all findings +7. Provides comprehensive review report + +Result: +βœ… Security: No critical issues found +⚠️ Testing: Coverage is 65%, recommend 80%+ +βœ… Performance: No significant impact +πŸ“ Recommendations: Add tests for edge cases +``` diff --git a/06-plugins/pr-review/agents/performance-analyzer.md b/06-plugins/pr-review/agents/performance-analyzer.md new file mode 100644 index 0000000..2f70938 --- /dev/null +++ b/06-plugins/pr-review/agents/performance-analyzer.md @@ -0,0 +1,13 @@ +--- +name: performance-analyzer +description: Performance impact analysis +tools: read, grep, bash +--- + +# Performance Analyzer + +Evaluates performance impact of changes: +- Algorithm complexity +- Database query efficiency +- Memory usage +- Caching opportunities diff --git a/06-plugins/pr-review/agents/security-reviewer.md b/06-plugins/pr-review/agents/security-reviewer.md new file mode 100644 index 0000000..b5b2a16 --- /dev/null +++ b/06-plugins/pr-review/agents/security-reviewer.md @@ -0,0 +1,13 @@ +--- +name: security-reviewer +description: Security-focused code review +tools: read, grep, diff +--- + +# Security Reviewer + +Specializes in finding security vulnerabilities: +- Authentication/authorization issues +- Data exposure +- Injection attacks +- Secure configuration diff --git a/06-plugins/pr-review/agents/test-checker.md b/06-plugins/pr-review/agents/test-checker.md new file mode 100644 index 0000000..90a065d --- /dev/null +++ b/06-plugins/pr-review/agents/test-checker.md @@ -0,0 +1,13 @@ +--- +name: test-checker +description: Test coverage and quality analysis +tools: read, bash, grep +--- + +# Test Checker + +Analyzes test coverage and quality: +- Coverage percentage +- Missing test cases +- Test quality assessment +- Edge case identification diff --git a/06-plugins/pr-review/commands/check-security.md b/06-plugins/pr-review/commands/check-security.md new file mode 100644 index 0000000..58d5a68 --- /dev/null +++ b/06-plugins/pr-review/commands/check-security.md @@ -0,0 +1,14 @@ +--- +name: Security Check +description: Run security-focused code review +--- + +# Security Check + +Perform focused security analysis on code changes: + +1. Authentication/authorization checks +2. Data exposure risks +3. Injection vulnerabilities +4. Cryptographic weaknesses +5. Sensitive data in logs diff --git a/06-plugins/pr-review/commands/check-tests.md b/06-plugins/pr-review/commands/check-tests.md new file mode 100644 index 0000000..6674562 --- /dev/null +++ b/06-plugins/pr-review/commands/check-tests.md @@ -0,0 +1,14 @@ +--- +name: Test Coverage Check +description: Verify test coverage and quality +--- + +# Test Coverage Check + +Analyze test coverage and quality: + +1. Check test coverage percentage +2. Identify untested code paths +3. Review test quality +4. Suggest missing test cases +5. Verify edge cases are covered diff --git a/06-plugins/pr-review/commands/review-pr.md b/06-plugins/pr-review/commands/review-pr.md new file mode 100644 index 0000000..0078be3 --- /dev/null +++ b/06-plugins/pr-review/commands/review-pr.md @@ -0,0 +1,14 @@ +--- +name: Review PR +description: Start comprehensive PR review with security and testing checks +--- + +# PR Review + +This command initiates a complete pull request review including: + +1. Security analysis +2. Test coverage verification +3. Documentation updates +4. Code quality checks +5. Performance impact assessment diff --git a/06-plugins/pr-review/hooks/pre-review.js b/06-plugins/pr-review/hooks/pre-review.js new file mode 100644 index 0000000..2127709 --- /dev/null +++ b/06-plugins/pr-review/hooks/pre-review.js @@ -0,0 +1,37 @@ +#!/usr/bin/env node + +/** + * Pre-review hook + * Runs before starting PR review to ensure prerequisites are met + */ + +async function preReview() { + console.log('Running pre-review checks...'); + + // Check if git repository + const { execSync } = require('child_process'); + try { + execSync('git rev-parse --git-dir', { stdio: 'pipe' }); + } catch (error) { + console.error('❌ Not a git repository'); + process.exit(1); + } + + // Check for uncommitted changes + try { + const status = execSync('git status --porcelain', { encoding: 'utf-8' }); + if (status.trim()) { + console.warn('⚠️ Warning: Uncommitted changes detected'); + } + } catch (error) { + console.error('❌ Failed to check git status'); + process.exit(1); + } + + console.log('βœ… Pre-review checks passed'); +} + +preReview().catch(error => { + console.error('Pre-review hook failed:', error); + process.exit(1); +}); diff --git a/06-plugins/pr-review/mcp/github-config.json b/06-plugins/pr-review/mcp/github-config.json new file mode 100644 index 0000000..0f62131 --- /dev/null +++ b/06-plugins/pr-review/mcp/github-config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} diff --git a/06-plugins/pr-review/plugin.yaml b/06-plugins/pr-review/plugin.yaml new file mode 100644 index 0000000..f2f6b2b --- /dev/null +++ b/06-plugins/pr-review/plugin.yaml @@ -0,0 +1,28 @@ +--- +name: pr-review +version: "1.0.0" +description: Complete PR review workflow with security, testing, and docs +author: Anthropic +license: MIT +tags: + - code-review + - quality + - security + +requires: + - claude-code: ">=1.0.0" + +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: hooks + path: hooks/ + +config: + auto_load: true + enabled_by_default: true +--- diff --git a/INDEX.md b/INDEX.md new file mode 100644 index 0000000..4378e7e --- /dev/null +++ b/INDEX.md @@ -0,0 +1,517 @@ +# Claude Code Examples - Complete Index + +This document provides a complete index of all example files organized by feature type. + +## Summary Statistics + +- **Total Files**: 71 files +- **Categories**: 6 feature categories +- **Plugins**: 3 complete plugins +- **Skills**: 3 complete skills +- **Ready to Use**: All examples + +--- + +## πŸ“ 01. Slash Commands (4 files) + +User-invoked shortcuts for common workflows. + +| File | Description | Use Case | +|------|-------------|----------| +| `optimize.md` | Code optimization analyzer | Find performance issues | +| `pr.md` | Pull request preparation | PR workflow automation | +| `generate-api-docs.md` | API documentation generator | Generate API docs | +| `README.md` | Documentation | Setup and usage guide | + +**Installation Path**: `.claude/commands/` + +**Usage**: `/optimize`, `/pr`, `/generate-api-docs` + +--- + +## πŸ€– 02. Subagents (6 files) + +Specialized AI assistants with custom capabilities. + +| File | Description | Tools | Use Case | +|------|-------------|-------|----------| +| `code-reviewer.md` | Code quality analysis | read, grep, diff, lint_runner | Comprehensive reviews | +| `test-engineer.md` | Test coverage analysis | read, write, bash, grep | Test automation | +| `documentation-writer.md` | Documentation creation | read, write, grep | Doc generation | +| `secure-reviewer.md` | Security review (read-only) | read, grep | Security audits | +| `implementation-agent.md` | Full implementation | read, write, bash, grep, edit, glob | Feature development | +| `README.md` | Documentation | - | Setup and usage guide | + +**Installation Path**: `.claude/agents/` + +**Usage**: Automatically delegated by main agent + +--- + +## πŸ’Ύ 03. Memory (4 files) + +Persistent context and project standards. + +| File | Description | Scope | Location | +|------|-------------|-------|----------| +| `project-CLAUDE.md` | Team project standards | Project-wide | `./CLAUDE.md` | +| `directory-api-CLAUDE.md` | API-specific rules | Directory | `./src/api/CLAUDE.md` | +| `personal-CLAUDE.md` | Personal preferences | User | `~/.claude/CLAUDE.md` | +| `README.md` | Documentation | - | Reference | + +**Installation**: Copy to appropriate location + +**Usage**: Automatically loaded by Claude + +--- + +## πŸ”Œ 04. MCP Protocol (5 files) + +External tool and API integrations. + +| File | Description | Integrates With | Use Case | +|------|-------------|-----------------|----------| +| `github-mcp.json` | GitHub integration | GitHub API | PR/issue management | +| `database-mcp.json` | Database queries | PostgreSQL/MySQL | Live data queries | +| `filesystem-mcp.json` | File operations | Local filesystem | File management | +| `multi-mcp.json` | Multiple servers | GitHub + DB + Slack | Complete integration | +| `README.md` | Documentation | - | Setup and usage guide | + +**Installation Path**: `.claude/mcp.json` + +**Usage**: `/mcp__github__list_prs`, etc. + +--- + +## 🎯 05. Skills (11 files) + +Auto-invoked capabilities with scripts and templates. + +### Code Review Skill (5 files) +``` +code-review/ +β”œβ”€β”€ SKILL.md # Skill definition +β”œβ”€β”€ scripts/ +β”‚ β”œβ”€β”€ analyze-metrics.py # Code metrics analyzer +β”‚ └── compare-complexity.py # Complexity comparison +└── templates/ + β”œβ”€β”€ review-checklist.md # Review checklist + └── finding-template.md # Finding documentation +``` + +**Purpose**: Comprehensive code review with security, performance, and quality analysis + +**Auto-invoked**: When reviewing code + +--- + +### Brand Voice Skill (4 files) +``` +brand-voice/ +β”œβ”€β”€ SKILL.md # Skill definition +β”œβ”€β”€ templates/ +β”‚ β”œβ”€β”€ email-template.txt # Email format +β”‚ └── social-post-template.txt # Social media format +└── tone-examples.md # Example messages +``` + +**Purpose**: Ensure consistent brand voice in communications + +**Auto-invoked**: When creating marketing copy + +--- + +### Documentation Generator Skill (2 files) +``` +doc-generator/ +β”œβ”€β”€ SKILL.md # Skill definition +└── generate-docs.py # Python doc extractor +``` + +**Purpose**: Generate comprehensive API documentation from source code + +**Auto-invoked**: When creating/updating API documentation + +**Plus**: `README.md` - Skills overview and usage guide + +**Installation Path**: `~/.claude/skills/` or `.claude/skills/` + +--- + +## πŸ“¦ 06. Plugins (3 complete plugins, 40 files) + +Bundled collections of features. + +### PR Review Plugin (10 files) +``` +pr-review/ +β”œβ”€β”€ plugin.yaml # Plugin manifest +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ review-pr.md # Comprehensive review +β”‚ β”œβ”€β”€ check-security.md # Security check +β”‚ └── check-tests.md # Test coverage check +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ security-reviewer.md # Security specialist +β”‚ β”œβ”€β”€ test-checker.md # Test specialist +β”‚ └── performance-analyzer.md # Performance specialist +β”œβ”€β”€ mcp/ +β”‚ └── github-config.json # GitHub integration +β”œβ”€β”€ hooks/ +β”‚ └── pre-review.js # Pre-review validation +└── README.md # Plugin documentation +``` + +**Features**: Security analysis, test coverage, performance impact + +**Commands**: `/review-pr`, `/check-security`, `/check-tests` + +**Installation**: `/plugin install pr-review` + +--- + +### DevOps Automation Plugin (15 files) +``` +devops-automation/ +β”œβ”€β”€ plugin.yaml # Plugin manifest +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ deploy.md # Deployment +β”‚ β”œβ”€β”€ rollback.md # Rollback +β”‚ β”œβ”€β”€ status.md # System status +β”‚ └── incident.md # Incident response +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ deployment-specialist.md # Deployment expert +β”‚ β”œβ”€β”€ incident-commander.md # Incident coordinator +β”‚ └── alert-analyzer.md # Alert analyzer +β”œβ”€β”€ mcp/ +β”‚ └── kubernetes-config.json # Kubernetes integration +β”œβ”€β”€ hooks/ +β”‚ β”œβ”€β”€ pre-deploy.js # Pre-deployment checks +β”‚ └── post-deploy.js # Post-deployment tasks +β”œβ”€β”€ scripts/ +β”‚ β”œβ”€β”€ deploy.sh # Deployment automation +β”‚ β”œβ”€β”€ rollback.sh # Rollback automation +β”‚ └── health-check.sh # Health checks +└── README.md # Plugin documentation +``` + +**Features**: Kubernetes deployment, rollback, monitoring, incident response + +**Commands**: `/deploy`, `/rollback`, `/status`, `/incident` + +**Installation**: `/plugin install devops-automation` + +--- + +### Documentation Plugin (14 files) +``` +documentation/ +β”œβ”€β”€ plugin.yaml # Plugin manifest +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ generate-api-docs.md # API docs generation +β”‚ β”œβ”€β”€ generate-readme.md # README creation +β”‚ β”œβ”€β”€ sync-docs.md # Doc synchronization +β”‚ └── validate-docs.md # Doc validation +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ api-documenter.md # API doc specialist +β”‚ β”œβ”€β”€ code-commentator.md # Code comment specialist +β”‚ └── example-generator.md # Example creator +β”œβ”€β”€ mcp/ +β”‚ └── github-docs-config.json # GitHub integration +β”œβ”€β”€ templates/ +β”‚ β”œβ”€β”€ api-endpoint.md # API endpoint template +β”‚ β”œβ”€β”€ function-docs.md # Function doc template +β”‚ └── adr-template.md # ADR template +└── README.md # Plugin documentation +``` + +**Features**: API docs, README generation, doc sync, validation + +**Commands**: `/generate-api-docs`, `/generate-readme`, `/sync-docs`, `/validate-docs` + +**Installation**: `/plugin install documentation` + +**Plus**: `README.md` - Plugins overview and usage guide + +--- + +## πŸ“š Documentation Files (7 files) + +| File | Location | Description | +|------|----------|-------------| +| `README.md` | `/` | Main examples overview | +| `INDEX.md` | `/` | This complete index | +| `README.md` | `/01-slash-commands/` | Slash commands guide | +| `README.md` | `/02-subagents/` | Subagents guide | +| `README.md` | `/03-memory/` | Memory guide | +| `README.md` | `/04-mcp/` | MCP guide | +| `README.md` | `/05-skills/` | Skills guide | +| `README.md` | `/06-plugins/` | Plugins guide | + +--- + +## πŸ—‚οΈ Complete File Tree + +``` +claude-howto/ +β”œβ”€β”€ README.md # Main overview +β”œβ”€β”€ INDEX.md # This file +β”œβ”€β”€ QUICK_REFERENCE.md # Quick reference card +β”œβ”€β”€ claude_concepts_guide.md # Original guide +β”‚ +β”œβ”€β”€ 01-slash-commands/ # Slash Commands +β”‚ β”œβ”€β”€ optimize.md +β”‚ β”œβ”€β”€ pr.md +β”‚ β”œβ”€β”€ generate-api-docs.md +β”‚ └── README.md +β”‚ +β”œβ”€β”€ 02-subagents/ # Subagents +β”‚ β”œβ”€β”€ code-reviewer.md +β”‚ β”œβ”€β”€ test-engineer.md +β”‚ β”œβ”€β”€ documentation-writer.md +β”‚ β”œβ”€β”€ secure-reviewer.md +β”‚ β”œβ”€β”€ implementation-agent.md +β”‚ └── README.md +β”‚ +β”œβ”€β”€ 03-memory/ # Memory +β”‚ β”œβ”€β”€ project-CLAUDE.md +β”‚ β”œβ”€β”€ directory-api-CLAUDE.md +β”‚ β”œβ”€β”€ personal-CLAUDE.md +β”‚ └── README.md +β”‚ +β”œβ”€β”€ 04-mcp/ # MCP Protocol +β”‚ β”œβ”€β”€ github-mcp.json +β”‚ β”œβ”€β”€ database-mcp.json +β”‚ β”œβ”€β”€ filesystem-mcp.json +β”‚ β”œβ”€β”€ multi-mcp.json +β”‚ └── README.md +β”‚ +β”œβ”€β”€ 05-skills/ # Skills +β”‚ β”œβ”€β”€ code-review/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ β”œβ”€β”€ scripts/ +β”‚ β”‚ β”‚ β”œβ”€β”€ analyze-metrics.py +β”‚ β”‚ β”‚ └── compare-complexity.py +β”‚ β”‚ └── templates/ +β”‚ β”‚ β”œβ”€β”€ review-checklist.md +β”‚ β”‚ └── finding-template.md +β”‚ β”œβ”€β”€ brand-voice/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ β”œβ”€β”€ templates/ +β”‚ β”‚ β”‚ β”œβ”€β”€ email-template.txt +β”‚ β”‚ β”‚ └── social-post-template.txt +β”‚ β”‚ └── tone-examples.md +β”‚ β”œβ”€β”€ doc-generator/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ └── generate-docs.py +β”‚ └── README.md +β”‚ +└── 06-plugins/ # Plugins + β”œβ”€β”€ pr-review/ + β”‚ β”œβ”€β”€ plugin.yaml + β”‚ β”œβ”€β”€ commands/ + β”‚ β”‚ β”œβ”€β”€ review-pr.md + β”‚ β”‚ β”œβ”€β”€ check-security.md + β”‚ β”‚ └── check-tests.md + β”‚ β”œβ”€β”€ agents/ + β”‚ β”‚ β”œβ”€β”€ security-reviewer.md + β”‚ β”‚ β”œβ”€β”€ test-checker.md + β”‚ β”‚ └── performance-analyzer.md + β”‚ β”œβ”€β”€ mcp/ + β”‚ β”‚ └── github-config.json + β”‚ β”œβ”€β”€ hooks/ + β”‚ β”‚ └── pre-review.js + β”‚ └── README.md + β”œβ”€β”€ devops-automation/ + β”‚ β”œβ”€β”€ plugin.yaml + β”‚ β”œβ”€β”€ commands/ + β”‚ β”‚ β”œβ”€β”€ deploy.md + β”‚ β”‚ β”œβ”€β”€ rollback.md + β”‚ β”‚ β”œβ”€β”€ status.md + β”‚ β”‚ └── incident.md + β”‚ β”œβ”€β”€ agents/ + β”‚ β”‚ β”œβ”€β”€ deployment-specialist.md + β”‚ β”‚ β”œβ”€β”€ incident-commander.md + β”‚ β”‚ └── alert-analyzer.md + β”‚ β”œβ”€β”€ mcp/ + β”‚ β”‚ └── kubernetes-config.json + β”‚ β”œβ”€β”€ hooks/ + β”‚ β”‚ β”œβ”€β”€ pre-deploy.js + β”‚ β”‚ └── post-deploy.js + β”‚ β”œβ”€β”€ scripts/ + β”‚ β”‚ β”œβ”€β”€ deploy.sh + β”‚ β”‚ β”œβ”€β”€ rollback.sh + β”‚ β”‚ └── health-check.sh + β”‚ └── README.md + β”œβ”€β”€ documentation/ + β”‚ β”œβ”€β”€ plugin.yaml + β”‚ β”œβ”€β”€ commands/ + β”‚ β”‚ β”œβ”€β”€ generate-api-docs.md + β”‚ β”‚ β”œβ”€β”€ generate-readme.md + β”‚ β”‚ β”œβ”€β”€ sync-docs.md + β”‚ β”‚ └── validate-docs.md + β”‚ β”œβ”€β”€ agents/ + β”‚ β”‚ β”œβ”€β”€ api-documenter.md + β”‚ β”‚ β”œβ”€β”€ code-commentator.md + β”‚ β”‚ └── example-generator.md + β”‚ β”œβ”€β”€ mcp/ + β”‚ β”‚ └── github-docs-config.json + β”‚ β”œβ”€β”€ templates/ + β”‚ β”‚ β”œβ”€β”€ api-endpoint.md + β”‚ β”‚ β”œβ”€β”€ function-docs.md + β”‚ β”‚ └── adr-template.md + β”‚ └── README.md + └── README.md +``` + +--- + +## πŸš€ Quick Start by Use Case + +### Code Quality & Reviews +```bash +# Install slash command +cp 01-slash-commands/optimize.md .claude/commands/ + +# Install subagent +cp 02-subagents/code-reviewer.md .claude/agents/ + +# Install skill +cp -r 05-skills/code-review ~/.claude/skills/ + +# Or install complete plugin +/plugin install pr-review +``` + +### DevOps & Deployment +```bash +# Install plugin (includes everything) +/plugin install devops-automation +``` + +### Documentation +```bash +# Install slash command +cp 01-slash-commands/generate-api-docs.md .claude/commands/ + +# Install subagent +cp 02-subagents/documentation-writer.md .claude/agents/ + +# Install skill +cp -r 05-skills/doc-generator ~/.claude/skills/ + +# Or install complete plugin +/plugin install documentation +``` + +### Team Standards +```bash +# Set up project memory +cp 03-memory/project-CLAUDE.md ./CLAUDE.md + +# Edit to match your team's standards +``` + +### External Integrations +```bash +# Set environment variables +export GITHUB_TOKEN="your_token" +export DATABASE_URL="postgresql://..." + +# Install MCP config +cp 04-mcp/multi-mcp.json .claude/mcp.json +``` + +--- + +## πŸ“Š Feature Coverage Matrix + +| Category | Commands | Agents | MCP | Hooks | Scripts | Templates | Total | +|----------|----------|--------|-----|-------|---------|-----------|-------| +| **Slash Commands** | 3 | - | - | - | - | - | **3** | +| **Subagents** | - | 5 | - | - | - | - | **5** | +| **Memory** | - | - | - | - | - | 3 | **3** | +| **MCP** | - | - | 4 | - | - | - | **4** | +| **Skills** | - | - | - | - | 3 | 7 | **10** | +| **Plugins** | 11 | 9 | 3 | 3 | 3 | 3 | **32** | +| **Docs** | - | - | - | - | - | 8 | **8** | +| **TOTAL** | **14** | **14** | **7** | **3** | **6** | **21** | **65** | + +--- + +## 🎯 Learning Path + +### Beginner (Week 1) +1. βœ… Read `README.md` +2. βœ… Install 1-2 slash commands +3. βœ… Create project memory file +4. βœ… Try basic commands + +### Intermediate (Week 2-3) +1. βœ… Set up GitHub MCP +2. βœ… Install a subagent +3. βœ… Try delegating tasks +4. βœ… Install a skill + +### Advanced (Week 4+) +1. βœ… Install complete plugin +2. βœ… Create custom slash commands +3. βœ… Create custom subagent +4. βœ… Create custom skill +5. βœ… Build your own plugin + +--- + +## πŸ” Search by Keyword + +### Performance +- `01-slash-commands/optimize.md` - Performance analysis +- `02-subagents/code-reviewer.md` - Performance review +- `05-skills/code-review/` - Performance metrics +- `06-plugins/pr-review/agents/performance-analyzer.md` - Performance specialist + +### Security +- `02-subagents/secure-reviewer.md` - Security review +- `05-skills/code-review/` - Security analysis +- `06-plugins/pr-review/` - Security checks + +### Testing +- `02-subagents/test-engineer.md` - Test engineer +- `06-plugins/pr-review/commands/check-tests.md` - Test coverage + +### Documentation +- `01-slash-commands/generate-api-docs.md` - API docs command +- `02-subagents/documentation-writer.md` - Doc writer agent +- `05-skills/doc-generator/` - Doc generator skill +- `06-plugins/documentation/` - Complete doc plugin + +### Deployment +- `06-plugins/devops-automation/` - Complete DevOps solution + +--- + +## πŸ“ Notes + +- All examples are ready to use +- Modify to fit your specific needs +- Examples follow Claude Code best practices +- Each category has its own README with detailed instructions +- Scripts include proper error handling +- Templates are customizable + +--- + +## 🀝 Contributing + +Want to add more examples? Follow the structure: +1. Create appropriate subdirectory +2. Include README.md with usage +3. Follow naming conventions +4. Test thoroughly +5. Update this index + +--- + +**Last Updated**: November 2025 +**Total Examples**: 71 files +**Categories**: 6 features +**Ready to Use**: βœ… All examples diff --git a/QUICK_REFERENCE.md b/QUICK_REFERENCE.md new file mode 100644 index 0000000..41f0709 --- /dev/null +++ b/QUICK_REFERENCE.md @@ -0,0 +1,325 @@ +# Claude Code Examples - Quick Reference Card + +## πŸš€ Installation Quick Commands + +### Slash Commands +```bash +# Install all +cp 01-slash-commands/*.md .claude/commands/ + +# Install specific +cp 01-slash-commands/optimize.md .claude/commands/ +``` + +### Subagents +```bash +# Install all +cp 02-subagents/*.md .claude/agents/ + +# Install specific +cp 02-subagents/code-reviewer.md .claude/agents/ +``` + +### Memory +```bash +# Project memory +cp 03-memory/project-CLAUDE.md ./CLAUDE.md + +# Personal memory +cp 03-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md +``` + +### MCP +```bash +# Set credentials +export GITHUB_TOKEN="your_token" +export DATABASE_URL="postgresql://..." + +# Install config +cp 04-mcp/github-mcp.json ~/.claude/mcp.json +``` + +### Skills +```bash +# Personal skills +cp -r 05-skills/code-review ~/.claude/skills/ + +# Project skills +cp -r 05-skills/code-review .claude/skills/ +``` + +### Plugins +```bash +# Install from examples (if published) +/plugin install pr-review +/plugin install devops-automation +/plugin install documentation +``` + +--- + +## πŸ“‹ Feature Cheat Sheet + +| Feature | Install Path | Usage | +|---------|-------------|-------| +| **Slash Commands** | `.claude/commands/*.md` | `/command-name` | +| **Subagents** | `.claude/agents/*.md` | Auto-delegated | +| **Memory** | `./CLAUDE.md` | Auto-loaded | +| **MCP** | `.claude/mcp.json` | `/mcp__server__action` | +| **Skills** | `.claude/skills/*/SKILL.md` | Auto-invoked | +| **Plugins** | Via `/plugin install` | Bundles all | + +--- + +## 🎯 Common Use Cases + +### Code Review +```bash +# Method 1: Slash command +cp 01-slash-commands/optimize.md .claude/commands/ +# Use: /optimize + +# Method 2: Subagent +cp 02-subagents/code-reviewer.md .claude/agents/ +# Use: Auto-delegated + +# Method 3: Skill +cp -r 05-skills/code-review ~/.claude/skills/ +# Use: Auto-invoked + +# Method 4: Plugin (best) +/plugin install pr-review +# Use: /review-pr +``` + +### Documentation +```bash +# Slash command +cp 01-slash-commands/generate-api-docs.md .claude/commands/ + +# Subagent +cp 02-subagents/documentation-writer.md .claude/agents/ + +# Skill +cp -r 05-skills/doc-generator ~/.claude/skills/ + +# Plugin (complete solution) +/plugin install documentation +``` + +### DevOps +```bash +# Complete plugin +/plugin install devops-automation + +# Commands: /deploy, /rollback, /status, /incident +``` + +### Team Standards +```bash +# Project memory +cp 03-memory/project-CLAUDE.md ./CLAUDE.md + +# Edit for your team +vim CLAUDE.md +``` + +--- + +## πŸ“ File Locations Reference + +``` +Your Project/ +β”œβ”€β”€ .claude/ +β”‚ β”œβ”€β”€ commands/ # Slash commands go here +β”‚ β”œβ”€β”€ agents/ # Subagents go here +β”‚ β”œβ”€β”€ skills/ # Project skills go here +β”‚ └── mcp.json # MCP configuration +β”œβ”€β”€ CLAUDE.md # Project memory +└── src/ + └── api/ + └── CLAUDE.md # Directory-specific memory + +User Home/ +└── .claude/ + β”œβ”€β”€ commands/ # Personal commands + β”œβ”€β”€ skills/ # Personal skills + β”œβ”€β”€ mcp.json # Personal MCP config + └── CLAUDE.md # Personal memory +``` + +--- + +## πŸ” Finding Examples + +### By Category +- **Slash Commands**: `01-slash-commands/` +- **Subagents**: `02-subagents/` +- **Memory**: `03-memory/` +- **MCP**: `04-mcp/` +- **Skills**: `05-skills/` +- **Plugins**: `06-plugins/` + +### By Use Case +- **Performance**: `01-slash-commands/optimize.md` +- **Security**: `02-subagents/secure-reviewer.md` +- **Testing**: `02-subagents/test-engineer.md` +- **Docs**: `05-skills/doc-generator/` +- **DevOps**: `06-plugins/devops-automation/` + +### By Complexity +- **Simple**: Slash commands +- **Medium**: Subagents, Memory +- **Advanced**: Skills +- **Complete**: Plugins + +--- + +## πŸŽ“ Learning Path + +### Day 1 +```bash +# Read overview +cat README.md + +# Install a command +cp 01-slash-commands/optimize.md .claude/commands/ + +# Try it +/optimize +``` + +### Day 2-3 +```bash +# Set up memory +cp 03-memory/project-CLAUDE.md ./CLAUDE.md +vim CLAUDE.md + +# Install subagent +cp 02-subagents/code-reviewer.md .claude/agents/ +``` + +### Day 4-5 +```bash +# Set up MCP +export GITHUB_TOKEN="your_token" +cp 04-mcp/github-mcp.json .claude/mcp.json + +# Try MCP commands +/mcp__github__list_prs +``` + +### Week 2 +```bash +# Install skill +cp -r 05-skills/code-review ~/.claude/skills/ + +# Let it auto-invoke +# Just say: "Review this code for issues" +``` + +### Week 3+ +```bash +# Install complete plugin +/plugin install pr-review + +# Use bundled features +/review-pr +/check-security +/check-tests +``` + +--- + +## πŸ’‘ Tips & Tricks + +### Customization +- Start with examples as-is +- Modify to fit your needs +- Test before sharing with team +- Version control your configurations + +### Best Practices +- Use memory for team standards +- Use plugins for complete workflows +- Use subagents for complex tasks +- Use slash commands for quick tasks + +### Troubleshooting +```bash +# Check file locations +ls -la .claude/commands/ +ls -la .claude/agents/ + +# Verify YAML syntax +head -20 .claude/agents/code-reviewer.md + +# Test MCP connection +echo $GITHUB_TOKEN +``` + +--- + +## πŸ“Š Feature Matrix + +| Need | Use This | Example | +|------|----------|---------| +| Quick shortcut | Slash Command | `01-slash-commands/optimize.md` | +| Specialized task | Subagent | `02-subagents/code-reviewer.md` | +| Team standards | Memory | `03-memory/project-CLAUDE.md` | +| External data | MCP | `04-mcp/github-mcp.json` | +| Auto workflow | Skill | `05-skills/code-review/` | +| Complete solution | Plugin | `06-plugins/pr-review/` | + +--- + +## πŸ”— Quick Links + +- **Main Guide**: `README.md` +- **Complete Index**: `INDEX.md` +- **Summary**: `EXAMPLES_SUMMARY.md` +- **Original Guide**: `claude_concepts_guide.md` + +--- + +## πŸ“ž Common Questions + +**Q: Which should I use?** +A: Start with slash commands, add features as needed. + +**Q: Can I mix features?** +A: Yes! They work together. Memory + Commands + MCP = powerful. + +**Q: How do I share with team?** +A: Commit `.claude/` directory to git. + +**Q: What about secrets?** +A: Use environment variables, never hardcode. + +**Q: Can I modify examples?** +A: Absolutely! They're templates to customize. + +--- + +## βœ… Checklist + +Getting started checklist: + +- [ ] Read `README.md` +- [ ] Install 1 slash command +- [ ] Try the command +- [ ] Create project `CLAUDE.md` +- [ ] Install 1 subagent +- [ ] Set up 1 MCP integration +- [ ] Install 1 skill +- [ ] Try a complete plugin +- [ ] Customize for your needs +- [ ] Share with team + +--- + +**Quick Start**: `cat README.md` + +**Full Index**: `cat INDEX.md` + +**This Card**: Keep it handy for quick reference! diff --git a/README.md b/README.md new file mode 100644 index 0000000..d314440 --- /dev/null +++ b/README.md @@ -0,0 +1,424 @@ +Claude Logo + +# Claude How To + +Complete collection of examples for some important Claude Code features and concepts. + +## Quick Navigation + +| Feature | Description | Folder | +|---------|-------------|--------| +| **Slash Commands** | User-invoked shortcuts | [01-slash-commands/](01-slash-commands/) | +| **Subagents** | Specialized AI assistants | [02-subagents/](02-subagents/) | +| **Memory** | Persistent context | [03-memory/](03-memory/) | +| **MCP Protocol** | External tool access | [04-mcp/](04-mcp/) | +| **Skills** | Reusable capabilities | [05-skills/](05-skills/) | +| **Plugins** | Bundled features | [06-plugins/](06-plugins/) | + +--- + +## 01. Slash Commands + +**Location**: [01-slash-commands/](01-slash-commands/) + +**What**: User-invoked shortcuts stored as Markdown files + +**Examples**: +- `optimize.md` - Code optimization analysis +- `pr.md` - Pull request preparation +- `generate-api-docs.md` - API documentation generator + +**Installation**: +```bash +cp 01-slash-commands/*.md /path/to/project/.claude/commands/ +``` + +**Usage**: +``` +/optimize +/pr +/generate-api-docs +``` + +--- + +## 02. Subagents + +**Location**: [02-subagents/](02-subagents/) + +**What**: Specialized AI assistants with isolated contexts and custom prompts + +**Examples**: +- `code-reviewer.md` - Comprehensive code quality analysis +- `test-engineer.md` - Test strategy and coverage +- `documentation-writer.md` - Technical documentation +- `secure-reviewer.md` - Security-focused review (read-only) +- `implementation-agent.md` - Full feature implementation + +**Installation**: +```bash +cp 02-subagents/*.md /path/to/project/.claude/agents/ +``` + +**Usage**: Automatically delegated by main agent + +--- + +## 03. Memory + +**Location**: [03-memory/](03-memory/) + +**What**: Persistent context across sessions + +**Examples**: +- `project-CLAUDE.md` - Team-wide project standards +- `directory-api-CLAUDE.md` - Directory-specific rules +- `personal-CLAUDE.md` - Personal preferences + +**Installation**: +```bash +# Project memory +cp 03-memory/project-CLAUDE.md /path/to/project/CLAUDE.md + +# Directory memory +cp 03-memory/directory-api-CLAUDE.md /path/to/project/src/api/CLAUDE.md + +# Personal memory +cp 03-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md +``` + +**Usage**: Automatically loaded by Claude + +--- + +## 04. MCP Protocol + +**Location**: [04-mcp/](04-mcp/) + +**What**: Model Context Protocol for accessing external tools and APIs + +**Examples**: +- `github-mcp.json` - GitHub integration +- `database-mcp.json` - Database queries +- `filesystem-mcp.json` - File operations +- `multi-mcp.json` - Multiple MCP servers + +**Installation**: +```bash +# Set environment variables +export GITHUB_TOKEN="your_token" +export DATABASE_URL="postgresql://..." + +# Copy configuration +cp 04-mcp/github-mcp.json ~/.claude/mcp.json +``` + +**Usage**: +``` +/mcp__github__list_prs +/mcp__github__get_pr 456 +``` + +--- + +## 05. Skills + +**Location**: [05-skills/](05-skills/) + +**What**: Reusable, auto-invoked capabilities with instructions and scripts + +**Examples**: +- `code-review/` - Comprehensive code review with scripts +- `brand-voice/` - Brand voice consistency checker +- `doc-generator/` - API documentation generator + +**Installation**: +```bash +# Personal skills +cp -r 05-skills/code-review ~/.claude/skills/ + +# Project skills +cp -r 05-skills/code-review /path/to/project/.claude/skills/ +``` + +**Usage**: Automatically invoked when relevant + +--- + +## 06. Plugins + +**Location**: [06-plugins/](06-plugins/) + +**What**: Bundled collections of commands, agents, MCP, and hooks + +**Examples**: +- `pr-review/` - Complete PR review workflow +- `devops-automation/` - Deployment and monitoring +- `documentation/` - Documentation generation + +**Installation**: +```bash +/plugin install pr-review +/plugin install devops-automation +/plugin install documentation +``` + +**Usage**: Use bundled slash commands and features + +--- + +## Feature Comparison + +| Feature | Invocation | Persistence | Best For | +|---------|-----------|------------|----------| +| **Slash Commands** | Manual (`/cmd`) | Session only | Quick shortcuts | +| **Subagents** | Auto-delegated | Isolated context | Task distribution | +| **Memory** | Auto-loaded | Cross-session | Long-term learning | +| **MCP Protocol** | Auto-queried | Real-time | Live data access | +| **Skills** | Auto-invoked | Filesystem | Automated workflows | +| **Plugins** | One command | All features | Complete solutions | + +--- + +## Getting Started + +### Week 1: Basics +1. Copy slash commands to `.claude/commands/` +2. Try `/optimize` and `/pr` commands +3. Create project memory in `CLAUDE.md` + +### Week 2: Real-time Access +1. Set up GitHub MCP +2. Query PRs and issues +3. Try multi-MCP configuration + +### Week 3: Distribution +1. Create first subagent +2. Test with complex task +3. Delegate work to specialists + +### Week 4: Automation +1. Install a skill +2. Let Claude auto-invoke it +3. Create custom skill + +### Week 5: Complete Solution +1. Install a plugin +2. Use bundled features +3. Consider creating your own + +--- + +## Directory Structure + +``` + +β”œβ”€β”€ 01-slash-commands/ +β”‚ β”œβ”€β”€ optimize.md +β”‚ β”œβ”€β”€ pr.md +β”‚ β”œβ”€β”€ generate-api-docs.md +β”‚ └── README.md +β”œβ”€β”€ 02-subagents/ +β”‚ β”œβ”€β”€ code-reviewer.md +β”‚ β”œβ”€β”€ test-engineer.md +β”‚ β”œβ”€β”€ documentation-writer.md +β”‚ β”œβ”€β”€ secure-reviewer.md +β”‚ β”œβ”€β”€ implementation-agent.md +β”‚ └── README.md +β”œβ”€β”€ 03-memory/ +β”‚ β”œβ”€β”€ project-CLAUDE.md +β”‚ β”œβ”€β”€ directory-api-CLAUDE.md +β”‚ β”œβ”€β”€ personal-CLAUDE.md +β”‚ └── README.md +β”œβ”€β”€ 04-mcp/ +β”‚ β”œβ”€β”€ github-mcp.json +β”‚ β”œβ”€β”€ database-mcp.json +β”‚ β”œβ”€β”€ filesystem-mcp.json +β”‚ β”œβ”€β”€ multi-mcp.json +β”‚ └── README.md +β”œβ”€β”€ 05-skills/ +β”‚ β”œβ”€β”€ code-review/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ β”œβ”€β”€ scripts/ +β”‚ β”‚ └── templates/ +β”‚ β”œβ”€β”€ brand-voice/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ └── templates/ +β”‚ β”œβ”€β”€ doc-generator/ +β”‚ β”‚ β”œβ”€β”€ SKILL.md +β”‚ β”‚ └── generate-docs.py +β”‚ └── README.md +β”œβ”€β”€ 06-plugins/ +β”‚ β”œβ”€β”€ pr-review/ +β”‚ β”œβ”€β”€ devops-automation/ +β”‚ β”œβ”€β”€ documentation/ +β”‚ └── README.md +└── README.md (this file) +``` + +--- + +## Example Workflows + +### 1. Complete Code Review Workflow + +```markdown +# Uses: Slash Commands + Subagents + Memory + MCP + +User: /review-pr + +Claude: +1. Loads project memory (coding standards) +2. Fetches PR via GitHub MCP +3. Delegates to code-reviewer subagent +4. Delegates to test-engineer subagent +5. Synthesizes findings +6. Provides comprehensive review +``` + +### 2. Automated Documentation + +```markdown +# Uses: Skills + Subagents + Memory + +User: "Generate API documentation for the auth module" + +Claude: +1. Loads project memory (doc standards) +2. Detects doc generation request +3. Auto-invokes doc-generator skill +4. Delegates to api-documenter subagent +5. Creates comprehensive docs with examples +``` + +### 3. DevOps Deployment + +```markdown +# Uses: Plugins + MCP + Hooks + +User: /deploy production + +Claude: +1. Runs pre-deploy hook (validates environment) +2. Delegates to deployment-specialist subagent +3. Executes deployment via Kubernetes MCP +4. Monitors progress +5. Runs post-deploy hook (health checks) +6. Reports status +``` + +--- + +## Installation Quick Reference + +```bash +# Slash Commands +cp 01-slash-commands/*.md .claude/commands/ + +# Subagents +cp 02-subagents/*.md .claude/agents/ + +# Memory +cp 03-memory/project-CLAUDE.md ./CLAUDE.md + +# MCP +export GITHUB_TOKEN="token" +cp 04-mcp/github-mcp.json .claude/mcp.json + +# Skills +cp -r 05-skills/code-review ~/.claude/skills/ + +# Plugins +/plugin install pr-review +``` + +--- + +## Use Case Matrix + +| Use Case | Recommended Features | +|----------|---------------------| +| **Team Onboarding** | Memory + Slash Commands + Plugins | +| **Code Quality** | Subagents + Skills + Memory | +| **Documentation** | Skills + Subagents + Plugins | +| **DevOps** | Plugins + MCP + Hooks | +| **Security Review** | Subagents + Skills | +| **API Integration** | MCP + Memory | +| **Quick Tasks** | Slash Commands | +| **Complex Projects** | All Features | + +--- + +## Best Practices + +### Do's βœ… +- Start simple with slash commands +- Add features incrementally +- Use memory for team standards +- Test configurations locally first +- Document custom implementations +- Version control project configurations +- Share plugins with team + +### Don'ts ❌ +- Don't create redundant features +- Don't hardcode credentials +- Don't skip documentation +- Don't over-complicate simple tasks +- Don't ignore security best practices +- Don't commit sensitive data + +--- + +## Troubleshooting + +### Feature Not Loading +1. Check file location and naming +2. Verify YAML frontmatter syntax +3. Check file permissions +4. Review Claude Code version compatibility + +### MCP Connection Failed +1. Verify environment variables +2. Check MCP server installation +3. Test credentials +4. Review network connectivity + +### Subagent Not Delegating +1. Check tool permissions +2. Verify agent description clarity +3. Review task complexity +6. Test agent independently + +--- + +## Additional Resources + +- [Claude Code Documentation](https://docs.claude.com/en/docs/claude-code) +- [MCP Protocol Specification](https://modelcontextprotocol.io) +- [Plugin Marketplace](https://plugins.claude.com) +- [Community Examples](https://github.com/anthropic/claude-examples) + +--- + +## Contributing + +Found an issue or want to contribute an example? + +1. Create an issue describing the example +2. Follow existing structure and patterns +3. Include comprehensive README +4. Test thoroughly +5. Submit pull request + +--- + +## License + +These examples are provided as-is for educational purposes. Adapt and use them freely in your projects. + +--- + +**Last Updated**: November 2025 +**Claude Code Version**: 1.0+ +**Compatible Models**: Sonnet 4.5, Opus 4.1, Haiku 4.5 diff --git a/claude-ai-icon.webp b/claude-ai-icon.webp new file mode 100644 index 0000000..4e888a5 Binary files /dev/null and b/claude-ai-icon.webp differ diff --git a/claude_concepts_guide.md b/claude_concepts_guide.md new file mode 100644 index 0000000..09b623c --- /dev/null +++ b/claude_concepts_guide.md @@ -0,0 +1,2773 @@ +# Complete Guide to Claude Concepts + +A comprehensive reference guide covering Slash Commands, Subagents, Memory, MCP Protocol, and Agent Skills with tables, diagrams, and practical examples. + +--- + +## Table of Contents + +1. [Slash Commands](#slash-commands) +2. [Subagents](#subagents) +3. [Memory](#memory) +4. [MCP Protocol](#mcp-protocol) +5. [Agent Skills](#agent-skills) +6. [Comparison & Integration](#comparison--integration) + +--- + +## Slash Commands + +### Overview + +Slash commands are user-invoked shortcuts stored as Markdown files that Claude Code can execute. They enable teams to standardize frequently-used prompts and workflows. + +### Architecture + +```mermaid +graph TD + A["User Input: /command-name"] -->|Triggers| B["Search .claude/commands/"] + B -->|Finds| C["command-name.md"] + C -->|Loads| D["Markdown Content"] + D -->|Executes| E["Claude Processes Prompt"] + E -->|Returns| F["Result in Context"] +``` + +### File Structure + +```mermaid +graph LR + A["Project Root"] -->|contains| B[".claude/commands/"] + B -->|contains| C["optimize.md"] + B -->|contains| D["test.md"] + B -->|contains| E["docs/"] + E -->|contains| F["generate-api-docs.md"] + E -->|contains| G["generate-readme.md"] +``` + +### Command Organization Table + +| Location | Scope | Availability | Use Case | Git Tracked | +|----------|-------|--------------|----------|-------------| +| `.claude/commands/` | Project-specific | Team members | Team workflows, shared standards | βœ… Yes | +| `~/.claude/commands/` | Personal | Individual user | Personal shortcuts across projects | ❌ No | +| Subdirectories | Namespaced | Based on parent | Organize by category | βœ… Yes | + +### Features & Capabilities + +| Feature | Example | Supported | +|---------|---------|-----------| +| Shell script execution | `bash scripts/deploy.sh` | βœ… Yes | +| File references | `@path/to/file.js` | βœ… Yes | +| Bash integration | `$(git log --oneline)` | βœ… Yes | +| Arguments | `/pr --verbose` | βœ… Yes | +| MCP commands | `/mcp__github__list_prs` | βœ… Yes | + +### Practical Examples + +#### Example 1: Code Optimization Command + +**File:** `.claude/commands/optimize.md` + +```markdown +--- +name: Code Optimization +description: Analyze code for performance issues and suggest optimizations +tags: performance, analysis +--- + +# Code Optimization + +Review the provided code for the following issues in order of priority: + +1. **Performance bottlenecks** - identify O(nΒ²) operations, inefficient loops +2. **Memory leaks** - find unreleased resources, circular references +3. **Algorithm improvements** - suggest better algorithms or data structures +4. **Caching opportunities** - identify repeated computations +5. **Concurrency issues** - find race conditions or threading problems + +Format your response with: +- Issue severity (Critical/High/Medium/Low) +- Location in code +- Explanation +- Recommended fix with code example +``` + +**Usage:** +```bash +# User types in Claude Code +/optimize + +# Claude loads the prompt and waits for code input +``` + +#### Example 2: Pull Request Helper Command + +**File:** `.claude/commands/pr.md` + +```markdown +--- +name: Prepare Pull Request +description: Clean up code, stage changes, and prepare a pull request +tags: git, workflow +--- + +# Pull Request Preparation Checklist + +Before creating a PR, execute these steps: + +1. Run linting: `prettier --write .` +2. Run tests: `npm test` +3. Review git diff: `git diff HEAD` +4. Stage changes: `git add .` +5. Create commit message following conventional commits: + - `fix:` for bug fixes + - `feat:` for new features + - `docs:` for documentation + - `refactor:` for code restructuring + - `test:` for test additions + - `chore:` for maintenance + +6. Generate PR summary including: + - What changed + - Why it changed + - Testing performed + - Potential impacts +``` + +**Usage:** +```bash +/pr + +# Claude runs through checklist and prepares the PR +``` + +#### Example 3: Hierarchical Documentation Generator + +**File:** `.claude/commands/docs/generate-api-docs.md` + +```markdown +--- +name: Generate API Documentation +description: Create comprehensive API documentation from source code +tags: documentation, api +--- + +# API Documentation Generator + +Generate API documentation by: + +1. Scanning all files in `/src/api/` +2. Extracting function signatures and JSDoc comments +3. Organizing by endpoint/module +4. Creating markdown with examples +5. Including request/response schemas +6. Adding error documentation + +Output format: +- Markdown file in `/docs/api.md` +- Include curl examples for all endpoints +- Add TypeScript types +``` + +### Command Lifecycle Diagram + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude Code + participant FS as File System + participant CLI as Shell/Bash + + User->>Claude: Types /optimize + Claude->>FS: Searches .claude/commands/ + FS-->>Claude: Returns optimize.md + Claude->>Claude: Loads Markdown content + Claude->>User: Displays prompt context + User->>Claude: Provides code to analyze + Claude->>CLI: (May execute scripts) + CLI-->>Claude: Results + Claude->>User: Returns analysis +``` + +### Best Practices + +| βœ… Do | ❌ Don't | +|------|---------| +| Use clear, action-oriented names | Create commands for one-time tasks | +| Document trigger words in description | Build complex logic in commands | +| Keep commands focused on single task | Create redundant commands | +| Version control project commands | Hardcode sensitive information | +| Organize in subdirectories | Create long lists of commands | +| Use simple, readable prompts | Use abbreviated or cryptic wording | + +--- + +## Subagents + +### Overview + +Subagents are specialized AI assistants with isolated context windows and customized system prompts. They enable delegated task execution while maintaining clean separation of concerns. + +### Architecture Diagram + +```mermaid +graph TB + User["πŸ‘€ User"] + Main["🎯 Main Agent
(Coordinator)"] + Reviewer["πŸ” Code Reviewer
Subagent"] + Tester["βœ… Test Engineer
Subagent"] + Docs["πŸ“ Documentation
Subagent"] + + User -->|asks| Main + Main -->|delegates| Reviewer + Main -->|delegates| Tester + Main -->|delegates| Docs + Reviewer -->|returns result| Main + Tester -->|returns result| Main + Docs -->|returns result| Main + Main -->|synthesizes| User +``` + +### Subagent Lifecycle + +```mermaid +sequenceDiagram + participant User + participant MainAgent as Main Agent + participant CodeReviewer as Code Reviewer
Subagent + participant Context as Separate
Context Window + + User->>MainAgent: "Build new auth feature" + MainAgent->>MainAgent: Analyze task + MainAgent->>CodeReviewer: "Review this code" + CodeReviewer->>Context: Initialize clean context + Context->>CodeReviewer: Load reviewer instructions + CodeReviewer->>CodeReviewer: Perform review + CodeReviewer-->>MainAgent: Return findings + MainAgent->>MainAgent: Incorporate results + MainAgent-->>User: Provide synthesis +``` + +### Subagent Configuration Table + +| Configuration | Type | Purpose | Example | +|---------------|------|---------|---------| +| `name` | String | Agent identifier | `code-reviewer` | +| `description` | String | Purpose & trigger terms | `Comprehensive code quality analysis` | +| `tools` | List/String | Allowed capabilities | `read, grep, diff, lint_runner` | +| `system_prompt` | Markdown | Behavioral instructions | Custom guidelines | + +### Tool Access Hierarchy + +```mermaid +graph TD + A["Subagent Configuration"] -->|Option 1| B["Inherit All Tools
from Main Thread"] + A -->|Option 2| C["Specify Individual Tools"] + B -->|Includes| B1["File Operations"] + B -->|Includes| B2["Shell Commands"] + B -->|Includes| B3["MCP Tools"] + C -->|Explicit List| C1["read, grep, diff"] + C -->|Explicit List| C2["Bash(npm:*), Bash(test:*)"] +``` + +### Practical Examples + +#### Example 1: Complete Subagent Setup + +**File:** `.claude/agents/code-reviewer.md` + +```yaml +--- +name: code-reviewer +description: Comprehensive code quality and maintainability analysis +tools: read, grep, diff, lint_runner +--- + +# Code Reviewer Agent + +You are an expert code reviewer specializing in: +- Performance optimization +- Security vulnerabilities +- Code maintainability +- Testing coverage +- Design patterns + +## Review Priorities (in order) + +1. **Security Issues** - Authentication, authorization, data exposure +2. **Performance Problems** - O(nΒ²) operations, memory leaks, inefficient queries +3. **Code Quality** - Readability, naming, documentation +4. **Test Coverage** - Missing tests, edge cases +5. **Design Patterns** - SOLID principles, architecture + +## Review Output Format + +For each issue: +- **Severity**: Critical / High / Medium / Low +- **Category**: Security / Performance / Quality / Testing / Design +- **Location**: File path and line number +- **Issue Description**: What's wrong and why +- **Suggested Fix**: Code example +- **Impact**: How this affects the system + +## Example Review + +### Issue: N+1 Query Problem +- **Severity**: High +- **Category**: Performance +- **Location**: src/user-service.ts:45 +- **Issue**: Loop executes database query in each iteration +- **Fix**: Use JOIN or batch query +``` + +**File:** `.claude/agents/test-engineer.md` + +```yaml +--- +name: test-engineer +description: Test strategy, coverage analysis, and automated testing +tools: read, write, bash, grep +--- + +# Test Engineer Agent + +You are expert at: +- Writing comprehensive test suites +- Ensuring high code coverage (>80%) +- Testing edge cases and error scenarios +- Performance benchmarking +- Integration testing + +## Testing Strategy + +1. **Unit Tests** - Individual functions/methods +2. **Integration Tests** - Component interactions +3. **End-to-End Tests** - Complete workflows +4. **Edge Cases** - Boundary conditions +5. **Error Scenarios** - Failure handling + +## Test Output Requirements + +- Use Jest for JavaScript/TypeScript +- Include setup/teardown for each test +- Mock external dependencies +- Document test purpose +- Include performance assertions when relevant + +## Coverage Requirements + +- Minimum 80% code coverage +- 100% for critical paths +- Report missing coverage areas +``` + +**File:** `.claude/agents/documentation-writer.md` + +```yaml +--- +name: documentation-writer +description: Technical documentation, API docs, and user guides +tools: read, write, grep +--- + +# Documentation Writer Agent + +You create: +- API documentation with examples +- User guides and tutorials +- Architecture documentation +- Changelog entries +- Code comment improvements + +## Documentation Standards + +1. **Clarity** - Use simple, clear language +2. **Examples** - Include practical code examples +3. **Completeness** - Cover all parameters and returns +4. **Structure** - Use consistent formatting +5. **Accuracy** - Verify against actual code + +## Documentation Sections + +### For APIs +- Description +- Parameters (with types) +- Returns (with types) +- Throws (possible errors) +- Examples (curl, JavaScript, Python) +- Related endpoints + +### For Features +- Overview +- Prerequisites +- Step-by-step instructions +- Expected outcomes +- Troubleshooting +- Related topics +``` + +#### Example 2: Subagent Delegation in Action + +```markdown +# Scenario: Building a Payment Feature + +## User Request +"Build a secure payment processing feature that integrates with Stripe" + +## Main Agent Flow + +1. **Planning Phase** + - Understands requirements + - Determines tasks needed + - Plans architecture + +2. **Delegates to Code Reviewer Subagent** + - Task: "Review the payment processing implementation for security" + - Context: Auth, API keys, token handling + - Reviews for: SQL injection, key exposure, HTTPS enforcement + +3. **Delegates to Test Engineer Subagent** + - Task: "Create comprehensive tests for payment flows" + - Context: Success scenarios, failures, edge cases + - Creates tests for: Valid payments, declined cards, network failures, webhooks + +4. **Delegates to Documentation Writer Subagent** + - Task: "Document the payment API endpoints" + - Context: Request/response schemas + - Produces: API docs with curl examples, error codes + +5. **Synthesis** + - Main agent collects all outputs + - Integrates findings + - Returns complete solution to user +``` + +#### Example 3: Tool Permission Scoping + +**Restrictive Setup - Limited to Specific Commands** + +```yaml +--- +name: secure-reviewer +description: Security-focused code review with minimal permissions +tools: read, grep +--- + +# Secure Code Reviewer + +Reviews code for security vulnerabilities only. + +This agent: +- βœ… Reads files to analyze +- βœ… Searches for patterns +- ❌ Cannot execute code +- ❌ Cannot modify files +- ❌ Cannot run tests + +This ensures the reviewer doesn't accidentally break anything. +``` + +**Extended Setup - All Tools for Implementation** + +```yaml +--- +name: implementation-agent +description: Full implementation capabilities for feature development +tools: read, write, bash, grep, edit, glob +--- + +# Implementation Agent + +Builds features from specifications. + +This agent: +- βœ… Reads specifications +- βœ… Writes new code files +- βœ… Runs build commands +- βœ… Searches codebase +- βœ… Edits existing files +- βœ… Finds files matching patterns + +Full capabilities for independent feature development. +``` + +### Subagent Context Management + +```mermaid +graph TB + A["Main Agent Context
50,000 tokens"] + B["Subagent 1 Context
20,000 tokens"] + C["Subagent 2 Context
20,000 tokens"] + D["Subagent 3 Context
20,000 tokens"] + + A -->|Clean slate| B + A -->|Clean slate| C + A -->|Clean slate| D + + B -->|Results only| A + C -->|Results only| A + D -->|Results only| A + + style A fill:#e1f5ff + style B fill:#fff9c4 + style C fill:#fff9c4 + style D fill:#fff9c4 +``` + +### When to Use Subagents + +| Scenario | Use Subagent | Why | +|----------|--------------|-----| +| Complex feature with many steps | βœ… Yes | Separate concerns, prevent context pollution | +| Quick code review | ❌ No | Not necessary overhead | +| Parallel task execution | βœ… Yes | Each subagent has own context | +| Specialized expertise needed | βœ… Yes | Custom system prompts | +| Long-running analysis | βœ… Yes | Prevents main context exhaustion | +| Single task | ❌ No | Adds latency unnecessarily | + +--- + +## Memory + +### Overview + +Memory enables Claude to retain context across sessions and conversations. It exists in two forms: automatic synthesis in claude.ai, and filesystem-based CLAUDE.md in Claude Code. + +### Memory Architecture + +```mermaid +graph TB + A["Claude Session"] + B["User Input"] + C["Memory System"] + D["Memory Storage"] + + B -->|User provides info| C + C -->|Synthesizes every 24h| D + D -->|Loads automatically| A + A -->|Uses context| C +``` + +### Memory Hierarchy in Claude Code + +```mermaid +graph TD + A["Project Root"] -->|searches up| B["CLAUDE.md"] + B -->|highest priority| B1["Global instructions"] + A -->|searches down| C["Subdirectory CLAUDE.md"] + C -->|specific overrides| C1["Directory-specific rules"] + H["User Home"] -->|fallback| D["~/.claude/CLAUDE.md"] + D -->|personal preferences| D1["Personal settings"] + + B1 -->|imports| E["@docs/architecture.md"] + E -->|imports| F["@docs/api-standards.md"] +``` + +### Memory Locations Table + +| Location | Scope | Priority | Shared | Access | Best For | +|----------|-------|----------|--------|--------|----------| +| `./CLAUDE.md` | Project | High | Team | Git | Team standards, shared architecture | +| `./.claude/CLAUDE.md` | Project | High | Team | Git | Alternative project location | +| `./subdir/CLAUDE.md` | Directory | Medium | Team | Git | Directory-specific rules | +| `~/.claude/CLAUDE.md` | Personal | Low | Individual | Filesystem | Personal preferences | +| `~/.claude/my-project.md` | Personal | Low | Individual | Import | Project-specific personal notes | + +### Memory Update Lifecycle + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude Code + participant Editor as File System + participant Memory as CLAUDE.md + + User->>Claude: "Remember: use async/await" + Claude->>User: "Which memory file?" + User->>Claude: "Project memory" + Claude->>Editor: Open ~/.claude/settings.json + Claude->>Memory: Write to ./CLAUDE.md + Memory-->>Claude: File saved + Claude->>Claude: Load updated memory + Claude-->>User: "Memory saved!" +``` + +### Practical Examples + +#### Example 1: Project Memory Structure + +**File:** `./CLAUDE.md` + +```markdown +# Project Configuration + +## Project Overview +- **Name**: E-commerce Platform +- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker +- **Team Size**: 5 developers +- **Deadline**: Q4 2025 + +## Architecture +@docs/architecture.md +@docs/api-standards.md +@docs/database-schema.md + +## Development Standards + +### Code Style +- Use Prettier for formatting +- Use ESLint with airbnb config +- Maximum line length: 100 characters +- Use 2-space indentation + +### Naming Conventions +- **Files**: kebab-case (user-controller.js) +- **Classes**: PascalCase (UserService) +- **Functions/Variables**: camelCase (getUserById) +- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL) +- **Database Tables**: snake_case (user_accounts) + +### Git Workflow +- Branch names: `feature/description` or `fix/description` +- Commit messages: Follow conventional commits +- PR required before merge +- All CI/CD checks must pass +- Minimum 1 approval required + +### Testing Requirements +- Minimum 80% code coverage +- All critical paths must have tests +- Use Jest for unit tests +- Use Cypress for E2E tests +- Test filenames: `*.test.ts` or `*.spec.ts` + +### API Standards +- RESTful endpoints only +- JSON request/response +- Use HTTP status codes correctly +- Version API endpoints: `/api/v1/` +- Document all endpoints with examples + +### Database +- Use migrations for schema changes +- Never hardcode credentials +- Use connection pooling +- Enable query logging in development +- Regular backups required + +### Deployment +- Docker-based deployment +- Kubernetes orchestration +- Blue-green deployment strategy +- Automatic rollback on failure +- Database migrations run before deploy + +## Common Commands + +| Command | Purpose | +|---------|---------| +| `npm run dev` | Start development server | +| `npm test` | Run test suite | +| `npm run lint` | Check code style | +| `npm run build` | Build for production | +| `npm run migrate` | Run database migrations | + +## Team Contacts +- Tech Lead: Sarah Chen (@sarah.chen) +- Product Manager: Mike Johnson (@mike.j) +- DevOps: Alex Kim (@alex.k) + +## Known Issues & Workarounds +- PostgreSQL connection pooling limited to 20 during peak hours +- Workaround: Implement query queuing +- Safari 14 compatibility issues with async generators +- Workaround: Use Babel transpiler + +## Related Projects +- Analytics Dashboard: `/projects/analytics` +- Mobile App: `/projects/mobile` +- Admin Panel: `/projects/admin` +``` + +#### Example 2: Directory-Specific Memory + +**File:** `./src/api/CLAUDE.md` + +```markdown +# API Module Standards + +This file overrides root CLAUDE.md for everything in /src/api/ + +## API-Specific Standards + +### Request Validation +- Use Zod for schema validation +- Always validate input +- Return 400 with validation errors +- Include field-level error details + +### Authentication +- All endpoints require JWT token +- Token in Authorization header +- Token expires after 24 hours +- Implement refresh token mechanism + +### Response Format + +All responses must follow this structure: + +```json +{ + "success": true, + "data": { /* actual data */ }, + "timestamp": "2025-11-06T10:30:00Z", + "version": "1.0" +} +``` + +Error responses: +```json +{ + "success": false, + "error": { + "code": "VALIDATION_ERROR", + "message": "User message", + "details": { /* field errors */ } + }, + "timestamp": "2025-11-06T10:30:00Z" +} +``` + +### Pagination +- Use cursor-based pagination (not offset) +- Include `hasMore` boolean +- Limit max page size to 100 +- Default page size: 20 + +### Rate Limiting +- 1000 requests per hour for authenticated users +- 100 requests per hour for public endpoints +- Return 429 when exceeded +- Include retry-after header + +### Caching +- Use Redis for session caching +- Cache duration: 5 minutes default +- Invalidate on write operations +- Tag cache keys with resource type +``` + +#### Example 3: Personal Memory + +**File:** `~/.claude/CLAUDE.md` + +```markdown +# My Development Preferences + +## About Me +- **Experience Level**: 8 years full-stack development +- **Preferred Languages**: TypeScript, Python +- **Communication Style**: Direct, with examples +- **Learning Style**: Visual diagrams with code + +## Code Preferences + +### Error Handling +I prefer explicit error handling with try-catch blocks and meaningful error messages. +Avoid generic errors. Always log errors for debugging. + +### Comments +Use comments for WHY, not WHAT. Code should be self-documenting. +Comments should explain business logic or non-obvious decisions. + +### Testing +I prefer TDD (test-driven development). +Write tests first, then implementation. +Focus on behavior, not implementation details. + +### Architecture +I prefer modular, loosely-coupled design. +Use dependency injection for testability. +Separate concerns (Controllers, Services, Repositories). + +## Debugging Preferences +- Use console.log with prefix: `[DEBUG]` +- Include context: function name, relevant variables +- Use stack traces when available +- Always include timestamps in logs + +## Communication +- Explain complex concepts with diagrams +- Show concrete examples before explaining theory +- Include before/after code snippets +- Summarize key points at the end + +## Project Organization +I organize my projects as: +``` +project/ + β”œβ”€β”€ src/ + β”‚ β”œβ”€β”€ api/ + β”‚ β”œβ”€β”€ services/ + β”‚ β”œβ”€β”€ models/ + β”‚ └── utils/ + β”œβ”€β”€ tests/ + β”œβ”€β”€ docs/ + └── docker/ +``` + +## Tooling +- **IDE**: VS Code with vim keybindings +- **Terminal**: Zsh with Oh-My-Zsh +- **Format**: Prettier (100 char line length) +- **Linter**: ESLint with airbnb config +- **Test Framework**: Jest with React Testing Library +``` + +#### Example 4: Memory Update During Session + +**Session Interaction:** + +```markdown +User: Remember that I prefer using React hooks instead of class components + for all new components. + +Claude: I'm adding that to your memory. Which memory file should this go in? + 1. Project memory (./CLAUDE.md) + 2. Personal memory (~/.claude/CLAUDE.md) + +User: Project memory + +Claude: βœ… Memory saved! + +Added to ./CLAUDE.md: +--- + +### Component Development +- Use functional components with React Hooks +- Prefer hooks over class components +- Custom hooks for reusable logic +- Use useCallback for event handlers +- Use useMemo for expensive computations +``` + +### Memory in Claude Web/Desktop + +#### Memory Synthesis Timeline + +```mermaid +graph LR + A["Day 1: User
Conversations"] -->|24 hours| B["Day 2: Memory
Synthesis"] + B -->|Automatic| C["Memory Updated
Summarized"] + C -->|Loaded in| D["Day 2-N:
New Conversations"] + D -->|Add to| E["Memory"] + E -->|24 hours later| F["Memory Refreshed"] +``` + +**Example Memory Summary:** + +```markdown +## Claude's Memory of User + +### Professional Background +- Senior full-stack developer with 8 years experience +- Focus on TypeScript/Node.js backends and React frontends +- Active open source contributor +- Interested in AI and machine learning + +### Project Context +- Currently building e-commerce platform +- Tech stack: Node.js, PostgreSQL, React 18, Docker +- Working with team of 5 developers +- Using CI/CD and blue-green deployments + +### Communication Preferences +- Prefers direct, concise explanations +- Likes visual diagrams and examples +- Appreciates code snippets +- Explains business logic in comments + +### Current Goals +- Improve API performance +- Increase test coverage to 90% +- Implement caching strategy +- Document architecture +``` + +### Memory Features Comparison + +| Feature | Claude Web/Desktop | Claude Code (CLAUDE.md) | +|---------|-------------------|------------------------| +| Auto-synthesis | βœ… Every 24h | ❌ Manual | +| Cross-project | βœ… Shared | ❌ Project-specific | +| Team access | βœ… Shared projects | βœ… Git-tracked | +| Searchable | βœ… Built-in | βœ… Through `/memory` | +| Editable | βœ… In-chat | βœ… Direct file edit | +| Import/Export | βœ… Yes | βœ… Copy/paste | +| Persistent | βœ… 24h+ | βœ… Indefinite | + +--- + +## MCP Protocol + +### Overview + +MCP (Model Context Protocol) is a standardized way for Claude to access external tools, APIs, and real-time data sources. Unlike Memory, MCP provides live access to changing data. + +### MCP Architecture + +```mermaid +graph TB + A["Claude"] + B["MCP Server"] + C["External Service"] + + A -->|Request: list_issues| B + B -->|Query| C + C -->|Data| B + B -->|Response| A + + A -->|Request: create_issue| B + B -->|Action| C + C -->|Result| B + B -->|Response| A +``` + +### MCP Ecosystem + +```mermaid +graph TB + A["Claude"] -->|MCP| B["Filesystem
MCP Server"] + A -->|MCP| C["GitHub
MCP Server"] + A -->|MCP| D["Database
MCP Server"] + A -->|MCP| E["Slack
MCP Server"] + A -->|MCP| F["Google Docs
MCP Server"] + + B -->|File I/O| G["Local Files"] + C -->|API| H["GitHub Repos"] + D -->|Query| I["PostgreSQL/MySQL"] + E -->|Messages| J["Slack Workspace"] + F -->|Docs| K["Google Drive"] +``` + +### MCP Setup Process + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude Code + participant Config as Config File + participant Service as External Service + + User->>Claude: Type /mcp + Claude->>Claude: List available MCP servers + Claude->>User: Show options + User->>Claude: Select GitHub MCP + Claude->>Config: Update configuration + Config->>Claude: Activate connection + Claude->>Service: Test connection + Service-->>Claude: Authentication successful + Claude->>User: βœ… MCP connected! +``` + +### Available MCP Servers Table + +| MCP Server | Purpose | Common Tools | Auth | Real-time | +|------------|---------|--------------|------|-----------| +| **Filesystem** | File operations | read, write, delete | OS permissions | βœ… Yes | +| **GitHub** | Repository management | list_prs, create_issue, push | OAuth | βœ… Yes | +| **Slack** | Team communication | send_message, list_channels | Token | βœ… Yes | +| **Database** | SQL queries | query, insert, update | Credentials | βœ… Yes | +| **Google Docs** | Document access | read, write, share | OAuth | βœ… Yes | +| **Asana** | Project management | create_task, update_status | API Key | βœ… Yes | +| **Stripe** | Payment data | list_charges, create_invoice | API Key | βœ… Yes | +| **Memory** | Persistent memory | store, retrieve, delete | Local | ❌ No | + +### Practical Examples + +#### Example 1: GitHub MCP Configuration + +**File:** `.claude/mcp.json` + +```json +{ + "mcpServers": { + "github": { + "command": "npx", + "args": ["@modelcontextprotocol/server-github"], + "env": { + "GITHUB_TOKEN": "${GITHUB_TOKEN}" + } + } + } +} +``` + +**Available GitHub MCP Tools:** + +```markdown +# GitHub MCP Tools + +## Pull Request Management +- `list_prs` - List all PRs in repository +- `get_pr` - Get PR details including diff +- `create_pr` - Create new PR +- `update_pr` - Update PR description/title +- `merge_pr` - Merge PR to main branch +- `review_pr` - Add review comments + +Example request: +``` +/mcp__github__get_pr 456 + +# Returns: +Title: Add dark mode support +Author: @alice +Description: Implements dark theme using CSS variables +Status: OPEN +Reviewers: @bob, @charlie +``` + +## Issue Management +- `list_issues` - List all issues +- `get_issue` - Get issue details +- `create_issue` - Create new issue +- `close_issue` - Close issue +- `add_comment` - Add comment to issue + +## Repository Information +- `get_repo_info` - Repository details +- `list_files` - File tree structure +- `get_file_content` - Read file contents +- `search_code` - Search across codebase + +## Commit Operations +- `list_commits` - Commit history +- `get_commit` - Specific commit details +- `create_commit` - Create new commit +``` + +#### Example 2: Database MCP Setup + +**Configuration:** + +```json +{ + "mcpServers": { + "database": { + "command": "npx", + "args": ["@modelcontextprotocol/server-database"], + "env": { + "DATABASE_URL": "postgresql://user:pass@localhost/mydb" + } + } + } +} +``` + +**Example Usage:** + +```markdown +User: Fetch all users with more than 10 orders + +Claude: I'll query your database to find that information. + +# Using MCP database tool: +SELECT u.*, COUNT(o.id) as order_count +FROM users u +LEFT JOIN orders o ON u.id = o.user_id +GROUP BY u.id +HAVING COUNT(o.id) > 10 +ORDER BY order_count DESC; + +# Results: +- Alice: 15 orders +- Bob: 12 orders +- Charlie: 11 orders +``` + +#### Example 3: Multi-MCP Workflow + +**Scenario: Daily Report Generation** + +```markdown +# Daily Report Workflow using Multiple MCPs + +## Setup +1. GitHub MCP - fetch PR metrics +2. Database MCP - query sales data +3. Slack MCP - post report +4. Filesystem MCP - save report + +## Workflow + +### Step 1: Fetch GitHub Data +/mcp__github__list_prs completed:true last:7days + +Output: +- Total PRs: 42 +- Average merge time: 2.3 hours +- Review turnaround: 1.1 hours + +### Step 2: Query Database +SELECT COUNT(*) as sales, SUM(amount) as revenue +FROM orders +WHERE created_at > NOW() - INTERVAL '1 day' + +Output: +- Sales: 247 +- Revenue: $12,450 + +### Step 3: Generate Report +Combine data into HTML report + +### Step 4: Save to Filesystem +Write report.html to /reports/ + +### Step 5: Post to Slack +Send summary to #daily-reports channel + +Final Output: +βœ… Report generated and posted +πŸ“Š 47 PRs merged this week +πŸ’° $12,450 in daily sales +``` + +#### Example 4: Filesystem MCP Operations + +**Configuration:** + +```json +{ + "mcpServers": { + "filesystem": { + "command": "npx", + "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"] + } + } +} +``` + +**Available Operations:** + +| Operation | Command | Purpose | +|-----------|---------|---------| +| List files | `ls ~/projects` | Show directory contents | +| Read file | `cat src/main.ts` | Read file contents | +| Write file | `create docs/api.md` | Create new file | +| Edit file | `edit src/app.ts` | Modify file | +| Search | `grep "async function"` | Search in files | +| Delete | `rm old-file.js` | Delete file | + +### MCP vs Memory: Decision Matrix + +```mermaid +graph TD + A["Need external data?"] + A -->|No| B["Use Memory"] + A -->|Yes| C["Does it change frequently?"] + C -->|No/Rarely| B + C -->|Yes/Often| D["Use MCP"] + + B -->|Stores| E["Preferences
Context
History"] + D -->|Accesses| F["Live APIs
Databases
Services"] + + style B fill:#e1f5ff + style D fill:#fff9c4 +``` + +### Request/Response Pattern + +```mermaid +sequenceDiagram + participant App as Claude + participant MCP as MCP Server + participant DB as Database + + App->>MCP: Request: "SELECT * FROM users WHERE id=1" + MCP->>DB: Execute query + DB-->>MCP: Result set + MCP-->>App: Return parsed data + App->>App: Process result + App->>App: Continue task + + Note over MCP,DB: Real-time access
No caching +``` + +--- + +## Agent Skills + +### Overview + +Agent Skills are reusable, model-invoked capabilities packaged as folders containing instructions, scripts, and resources. Claude automatically detects and uses relevant skills. + +### Skill Architecture + +```mermaid +graph TB + A["Skill Directory"] + B["SKILL.md"] + C["YAML Metadata"] + D["Instructions"] + E["Scripts"] + F["Templates"] + + A --> B + B --> C + B --> D + E --> A + F --> A +``` + +### Skill Loading Process + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude + participant System as System + participant Skill as Skill + + User->>Claude: "Create Excel report" + Claude->>System: Scan available skills + System->>System: Load skill metadata + Claude->>Claude: Match user request to skills + Claude->>Skill: Load xlsx skill SKILL.md + Skill-->>Claude: Return instructions + tools + Claude->>Claude: Execute skill + Claude->>User: Generate Excel file +``` + +### Skill Types & Locations Table + +| Type | Location | Scope | Shared | Sync | Best For | +|------|----------|-------|--------|------|----------| +| Pre-built | Built-in | Global | All users | Auto | Document creation | +| Personal | `~/.claude/skills/` | Individual | No | Manual | Personal automation | +| Project | `.claude/skills/` | Team | Yes | Git | Team standards | +| Plugin | Via plugin install | Varies | Depends | Auto | Integrated features | + +### Pre-built Skills + +```mermaid +graph TB + A["Pre-built Skills"] + B["PowerPoint (pptx)"] + C["Excel (xlsx)"] + D["Word (docx)"] + E["PDF"] + + A --> B + A --> C + A --> D + A --> E + + B --> B1["Create presentations"] + B --> B2["Edit slides"] + C --> C1["Create spreadsheets"] + C --> C2["Analyze data"] + D --> D1["Create documents"] + D --> D2["Format text"] + E --> E1["Generate PDFs"] + E --> E2["Fill forms"] +``` + +### Practical Examples + +#### Example 1: Custom Code Review Skill + +**Directory Structure:** + +``` +~/.claude/skills/code-review/ +β”œβ”€β”€ SKILL.md +β”œβ”€β”€ templates/ +β”‚ β”œβ”€β”€ review-checklist.md +β”‚ └── finding-template.md +└── scripts/ + β”œβ”€β”€ analyze-metrics.py + └── compare-complexity.py +``` + +**File:** `~/.claude/skills/code-review/SKILL.md` + +```yaml +--- +name: Code Review Specialist +description: Comprehensive code review with security, performance, and quality analysis +version: "1.0.0" +tags: + - code-review + - quality + - security +when_to_use: When users ask to review code, analyze code quality, or evaluate pull requests +--- + +# Code Review Skill + +This skill provides comprehensive code review capabilities focusing on: + +1. **Security Analysis** + - Authentication/authorization issues + - Data exposure risks + - Injection vulnerabilities + - Cryptographic weaknesses + - Sensitive data logging + +2. **Performance Review** + - Algorithm efficiency (Big O analysis) + - Memory optimization + - Database query optimization + - Caching opportunities + - Concurrency issues + +3. **Code Quality** + - SOLID principles + - Design patterns + - Naming conventions + - Documentation + - Test coverage + +4. **Maintainability** + - Code readability + - Function size (should be < 50 lines) + - Cyclomatic complexity + - Dependency management + - Type safety + +## Review Template + +For each piece of code reviewed, provide: + +### Summary +- Overall quality assessment (1-5) +- Key findings count +- Recommended priority areas + +### Critical Issues (if any) +- **Issue**: Clear description +- **Location**: File and line number +- **Impact**: Why this matters +- **Severity**: Critical/High/Medium +- **Fix**: Code example + +### Findings by Category + +#### Security (if issues found) +List security vulnerabilities with examples + +#### Performance (if issues found) +List performance problems with complexity analysis + +#### Quality (if issues found) +List code quality issues with refactoring suggestions + +#### Maintainability (if issues found) +List maintainability problems with improvements +``` +## Python Script: analyze-metrics.py + +```python +#!/usr/bin/env python3 +import re +import sys + +def analyze_code_metrics(code): + """Analyze code for common metrics.""" + + # Count functions + functions = len(re.findall(r'^def\s+\w+', code, re.MULTILINE)) + + # Count classes + classes = len(re.findall(r'^class\s+\w+', code, re.MULTILINE)) + + # Average line length + lines = code.split('\n') + avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0 + + # Estimate complexity + complexity = len(re.findall(r'\b(if|elif|else|for|while|and|or)\b', code)) + + return { + 'functions': functions, + 'classes': classes, + 'avg_line_length': avg_length, + 'complexity_score': complexity + } + +if __name__ == '__main__': + with open(sys.argv[1], 'r') as f: + code = f.read() + metrics = analyze_code_metrics(code) + for key, value in metrics.items(): + print(f"{key}: {value:.2f}") +``` + +## Python Script: compare-complexity.py + +```python +#!/usr/bin/env python3 +""" +Compare cyclomatic complexity of code before and after changes. +Helps identify if refactoring actually simplifies code structure. +""" + +import re +import sys +from typing import Dict, Tuple + +class ComplexityAnalyzer: + """Analyze code complexity metrics.""" + + def __init__(self, code: str): + self.code = code + self.lines = code.split('\n') + + def calculate_cyclomatic_complexity(self) -> int: + """ + Calculate cyclomatic complexity using McCabe's method. + Count decision points: if, elif, else, for, while, except, and, or + """ + complexity = 1 # Base complexity + + # Count decision points + decision_patterns = [ + r'\bif\b', + r'\belif\b', + r'\bfor\b', + r'\bwhile\b', + r'\bexcept\b', + r'\band\b(?!$)', + r'\bor\b(?!$)' + ] + + for pattern in decision_patterns: + matches = re.findall(pattern, self.code) + complexity += len(matches) + + return complexity + + def calculate_cognitive_complexity(self) -> int: + """ + Calculate cognitive complexity - how hard is it to understand? + Based on nesting depth and control flow. + """ + cognitive = 0 + nesting_depth = 0 + + for line in self.lines: + # Track nesting depth + if re.search(r'^\s*(if|for|while|def|class|try)\b', line): + nesting_depth += 1 + cognitive += nesting_depth + elif re.search(r'^\s*(elif|else|except|finally)\b', line): + cognitive += nesting_depth + + # Reduce nesting when unindenting + if line and not line[0].isspace(): + nesting_depth = 0 + + return cognitive + + def calculate_maintainability_index(self) -> float: + """ + Maintainability Index ranges from 0-100. + > 85: Excellent + > 65: Good + > 50: Fair + < 50: Poor + """ + lines = len(self.lines) + cyclomatic = self.calculate_cyclomatic_complexity() + cognitive = self.calculate_cognitive_complexity() + + # Simplified MI calculation + mi = 171 - 5.2 * (cyclomatic / lines) - 0.23 * (cognitive) - 16.2 * (lines / 1000) + + return max(0, min(100, mi)) + + def get_complexity_report(self) -> Dict: + """Generate comprehensive complexity report.""" + return { + 'cyclomatic_complexity': self.calculate_cyclomatic_complexity(), + 'cognitive_complexity': self.calculate_cognitive_complexity(), + 'maintainability_index': round(self.calculate_maintainability_index(), 2), + 'lines_of_code': len(self.lines), + 'avg_line_length': round(sum(len(l) for l in self.lines) / len(self.lines), 2) if self.lines else 0 + } + + +def compare_files(before_file: str, after_file: str) -> None: + """Compare complexity metrics between two code versions.""" + + with open(before_file, 'r') as f: + before_code = f.read() + + with open(after_file, 'r') as f: + after_code = f.read() + + before_analyzer = ComplexityAnalyzer(before_code) + after_analyzer = ComplexityAnalyzer(after_code) + + before_metrics = before_analyzer.get_complexity_report() + after_metrics = after_analyzer.get_complexity_report() + + print("=" * 60) + print("CODE COMPLEXITY COMPARISON") + print("=" * 60) + + print("\nBEFORE:") + print(f" Cyclomatic Complexity: {before_metrics['cyclomatic_complexity']}") + print(f" Cognitive Complexity: {before_metrics['cognitive_complexity']}") + print(f" Maintainability Index: {before_metrics['maintainability_index']}") + print(f" Lines of Code: {before_metrics['lines_of_code']}") + print(f" Avg Line Length: {before_metrics['avg_line_length']}") + + print("\nAFTER:") + print(f" Cyclomatic Complexity: {after_metrics['cyclomatic_complexity']}") + print(f" Cognitive Complexity: {after_metrics['cognitive_complexity']}") + print(f" Maintainability Index: {after_metrics['maintainability_index']}") + print(f" Lines of Code: {after_metrics['lines_of_code']}") + print(f" Avg Line Length: {after_metrics['avg_line_length']}") + + print("\nCHANGES:") + cyclomatic_change = after_metrics['cyclomatic_complexity'] - before_metrics['cyclomatic_complexity'] + cognitive_change = after_metrics['cognitive_complexity'] - before_metrics['cognitive_complexity'] + mi_change = after_metrics['maintainability_index'] - before_metrics['maintainability_index'] + loc_change = after_metrics['lines_of_code'] - before_metrics['lines_of_code'] + + print(f" Cyclomatic Complexity: {cyclomatic_change:+d}") + print(f" Cognitive Complexity: {cognitive_change:+d}") + print(f" Maintainability Index: {mi_change:+.2f}") + print(f" Lines of Code: {loc_change:+d}") + + print("\nASSESSMENT:") + if mi_change > 0: + print(" βœ… Code is MORE maintainable") + elif mi_change < 0: + print(" ⚠️ Code is LESS maintainable") + else: + print(" ➑️ Maintainability unchanged") + + if cyclomatic_change < 0: + print(" βœ… Complexity DECREASED") + elif cyclomatic_change > 0: + print(" ⚠️ Complexity INCREASED") + else: + print(" ➑️ Complexity unchanged") + + print("=" * 60) + + +if __name__ == '__main__': + if len(sys.argv) != 3: + print("Usage: python compare-complexity.py ") + sys.exit(1) + + compare_files(sys.argv[1], sys.argv[2]) +``` + +## Template: review-checklist.md + +```markdown +# Code Review Checklist + +## Security Checklist +- [ ] No hardcoded credentials or secrets +- [ ] Input validation on all user inputs +- [ ] SQL injection prevention (parameterized queries) +- [ ] CSRF protection on state-changing operations +- [ ] XSS prevention with proper escaping +- [ ] Authentication checks on protected endpoints +- [ ] Authorization checks on resources +- [ ] Secure password hashing (bcrypt, argon2) +- [ ] No sensitive data in logs +- [ ] HTTPS enforced + +## Performance Checklist +- [ ] No N+1 queries +- [ ] Appropriate use of indexes +- [ ] Caching implemented where beneficial +- [ ] No blocking operations on main thread +- [ ] Async/await used correctly +- [ ] Large datasets paginated +- [ ] Database connections pooled +- [ ] Regular expressions optimized +- [ ] No unnecessary object creation +- [ ] Memory leaks prevented + +## Quality Checklist +- [ ] Functions < 50 lines +- [ ] Clear variable naming +- [ ] No duplicate code +- [ ] Proper error handling +- [ ] Comments explain WHY, not WHAT +- [ ] No console.logs in production +- [ ] Type checking (TypeScript/JSDoc) +- [ ] SOLID principles followed +- [ ] Design patterns applied correctly +- [ ] Self-documenting code + +## Testing Checklist +- [ ] Unit tests written +- [ ] Edge cases covered +- [ ] Error scenarios tested +- [ ] Integration tests present +- [ ] Coverage > 80% +- [ ] No flaky tests +- [ ] Mock external dependencies +- [ ] Clear test names +``` + +## Template: finding-template.md + +```markdown +# Code Review Finding Template + +Use this template when documenting each issue found during code review. + +--- + +## Issue: [TITLE] + +### Severity +- [ ] Critical (blocks deployment) +- [ ] High (should fix before merge) +- [ ] Medium (should fix soon) +- [ ] Low (nice to have) + +### Category +- [ ] Security +- [ ] Performance +- [ ] Code Quality +- [ ] Maintainability +- [ ] Testing +- [ ] Design Pattern +- [ ] Documentation + +### Location +**File:** `src/components/UserCard.tsx` + +**Lines:** 45-52 + +**Function/Method:** `renderUserDetails()` + +### Issue Description + +**What:** Describe what the issue is. + +**Why it matters:** Explain the impact and why this needs to be fixed. + +**Current behavior:** Show the problematic code or behavior. + +**Expected behavior:** Describe what should happen instead. + +### Code Example + +#### Current (Problematic) + +```typescript +// Shows the N+1 query problem +const users = fetchUsers(); +users.forEach(user => { + const posts = fetchUserPosts(user.id); // Query per user! + renderUserPosts(posts); +}); +``` + +#### Suggested Fix + +```typescript +// Optimized with JOIN query +const usersWithPosts = fetchUsersWithPosts(); +usersWithPosts.forEach(({ user, posts }) => { + renderUserPosts(posts); +}); +``` + +### Impact Analysis + +| Aspect | Impact | Severity | +|--------|--------|----------| +| Performance | 100+ queries for 20 users | High | +| User Experience | Slow page load | High | +| Scalability | Breaks at scale | Critical | +| Maintainability | Hard to debug | Medium | + +### Related Issues + +- Similar issue in `AdminUserList.tsx` line 120 +- Related PR: #456 +- Related issue: #789 + +### Additional Resources + +- [N+1 Query Problem](https://en.wikipedia.org/wiki/N%2B1_problem) +- [Database Join Documentation](https://docs.example.com/joins) +- [Performance Optimization Guide](./docs/performance.md) + +### Reviewer Notes + +- This is a common pattern in this codebase +- Consider adding this to the code style guide +- Might be worth creating a helper function + +### Author Response (for feedback) + +*To be filled by the code author:* + +- [ ] Fix implemented in commit: `abc123` +- [ ] Fix status: Complete / In Progress / Needs Discussion +- [ ] Questions or concerns: (describe) + +--- + +## Finding Statistics (for Reviewer) + +When reviewing multiple findings, track: + +- **Total Issues Found:** X +- **Critical:** X +- **High:** X +- **Medium:** X +- **Low:** X + +**Recommendation:** βœ… Approve / ⚠️ Request Changes / πŸ”„ Needs Discussion + +**Overall Code Quality:** 1-5 stars +``` + +## Usage Example + +```markdown +User: Review this React component code + +Claude: I'll conduct a comprehensive code review using my Code Review Skill. + +[Loads SKILL.md] +[Analyzes code against checklist] +[Runs Python metrics script] +[Applies templates] + +## Code Review Results + +### Summary +Quality Score: 3.5/5 +Key Findings: 7 items +Priority Areas: Performance optimization, error handling + +### Critical Issues: 1 + +**Issue**: N+1 Query Problem +**Location**: UserComponent.tsx, lines 45-52 +**Impact**: Renders 100+ database queries for list of 20 users +**Severity**: High +**Fix**: +```javascript +// Before: N+1 queries +const users = fetchUsers(); +users.forEach(user => fetchUserPosts(user.id)); // 20+ queries + +// After: Single query with JOIN +const users = fetchUsersWithPosts(); // 1 query +``` + +### Performance Findings +- Missing pagination on large lists +- Recommendation: Use React.memo() for items +- Database query: Could be optimized with index + +### Quality Findings +- Function in line 20 is 127 lines (max: 50) +- Missing error boundary +- Props should have TypeScript types +``` + +#### Example 2: Brand Voice Skill + +**Directory Structure:** + +``` +.claude/skills/brand-voice/ +β”œβ”€β”€ SKILL.md +β”œβ”€β”€ brand-guidelines.md +β”œβ”€β”€ tone-examples.md +└── templates/ + β”œβ”€β”€ email-template.txt + β”œβ”€β”€ social-post-template.txt + └── blog-post-template.md +``` + +**File:** `.claude/skills/brand-voice/SKILL.md` + +```yaml +--- +name: Brand Voice Consistency +description: Ensure all communication matches brand voice and tone guidelines +tags: + - brand + - writing + - consistency +when_to_use: When creating marketing copy, customer communications, or public-facing content +--- + +# Brand Voice Skill + +## Overview +This skill ensures all communications maintain consistent brand voice, tone, and messaging. + +## Brand Identity + +### Mission +Help teams automate their development workflows with AI + +### Values +- **Simplicity**: Make complex things simple +- **Reliability**: Rock-solid execution +- **Empowerment**: Enable human creativity + +### Tone of Voice +- **Friendly but professional** - approachable without being casual +- **Clear and concise** - avoid jargon, explain technical concepts simply +- **Confident** - we know what we're doing +- **Empathetic** - understand user needs and pain points + +## Writing Guidelines + +### Do's βœ… +- Use "you" when addressing readers +- Use active voice: "Claude generates reports" not "Reports are generated by Claude" +- Start with value proposition +- Use concrete examples +- Keep sentences under 20 words +- Use lists for clarity +- Include calls-to-action + +### Don'ts ❌ +- Don't use corporate jargon +- Don't patronize or oversimplify +- Don't use "we believe" or "we think" +- Don't use ALL CAPS except for emphasis +- Don't create walls of text +- Don't assume technical knowledge + +## Vocabulary + +### βœ… Preferred Terms +- Claude (not "the Claude AI") +- Code generation (not "auto-coding") +- Agent (not "bot") +- Streamline (not "revolutionize") +- Integrate (not "synergize") + +### ❌ Avoid Terms +- "Cutting-edge" (overused) +- "Game-changer" (vague) +- "Leverage" (corporate-speak) +- "Utilize" (use "use") +- "Paradigm shift" (unclear) +``` +## Examples + +### βœ… Good Example +"Claude automates your code review process. Instead of manually checking each PR, Claude reviews security, performance, and qualityβ€”saving your team hours every week." + +Why it works: Clear value, specific benefits, action-oriented + +### ❌ Bad Example +"Claude leverages cutting-edge AI to provide comprehensive software development solutions." + +Why it doesn't work: Vague, corporate jargon, no specific value + +## Template: Email + +``` +Subject: [Clear, benefit-driven subject] + +Hi [Name], + +[Opening: What's the value for them] + +[Body: How it works / What they'll get] + +[Specific example or benefit] + +[Call to action: Clear next step] + +Best regards, +[Name] +``` + +## Template: Social Media + +``` +[Hook: Grab attention in first line] +[2-3 lines: Value or interesting fact] +[Call to action: Link, question, or engagement] +[Emoji: 1-2 max for visual interest] +``` + +## File: tone-examples.md +``` +Exciting announcement: +"Save 8 hours per week on code reviews. Claude reviews your PRs automatically." + +Empathetic support: +"We know deployments can be stressful. Claude handles testing so you don't have to worry." + +Confident product feature: +"Claude doesn't just suggest code. It understands your architecture and maintains consistency." + +Educational blog post: +"Let's explore how agents improve code review workflows. Here's what we learned..." +``` + +#### Example 3: Documentation Generator Skill + +**File:** `.claude/skills/doc-generator/SKILL.md` + +```yaml +--- +name: API Documentation Generator +description: Generate comprehensive, accurate API documentation from source code +version: "1.0.0" +tags: + - documentation + - api + - automation +when_to_use: When creating or updating API documentation +--- + +# API Documentation Generator Skill + +## Generates + +- OpenAPI/Swagger specifications +- API endpoint documentation +- SDK usage examples +- Integration guides +- Error code references +- Authentication guides + +## Documentation Structure + +### For Each Endpoint + +```markdown +## GET /api/v1/users/:id + +### Description +Brief explanation of what this endpoint does + +### Parameters + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| id | string | Yes | User ID | + +### Response + +**200 Success** +```json +{ + "id": "usr_123", + "name": "John Doe", + "email": "john@example.com", + "created_at": "2025-01-15T10:30:00Z" +} +``` + +**404 Not Found** +```json +{ + "error": "USER_NOT_FOUND", + "message": "User does not exist" +} +``` + +### Examples + +**cURL** +```bash +curl -X GET "https://api.example.com/api/v1/users/usr_123" \ + -H "Authorization: Bearer YOUR_TOKEN" +``` + +**JavaScript** +```javascript +const user = await fetch('/api/v1/users/usr_123', { + headers: { 'Authorization': 'Bearer token' } +}).then(r => r.json()); +``` + +**Python** +```python +response = requests.get( + 'https://api.example.com/api/v1/users/usr_123', + headers={'Authorization': 'Bearer token'} +) +user = response.json() +``` + +## Python Script: generate-docs.py + +```python +#!/usr/bin/env python3 +import ast +import json +from typing import Dict, List + +class APIDocExtractor(ast.NodeVisitor): + """Extract API documentation from Python source code.""" + + def __init__(self): + self.endpoints = [] + + def visit_FunctionDef(self, node): + """Extract function documentation.""" + if node.name.startswith('get_') or node.name.startswith('post_'): + doc = ast.get_docstring(node) + endpoint = { + 'name': node.name, + 'docstring': doc, + 'params': [arg.arg for arg in node.args.args], + 'returns': self._extract_return_type(node) + } + self.endpoints.append(endpoint) + self.generic_visit(node) + + def _extract_return_type(self, node): + """Extract return type from function annotation.""" + if node.returns: + return ast.unparse(node.returns) + return "Any" + +def generate_markdown_docs(endpoints: List[Dict]) -> str: + """Generate markdown documentation from endpoints.""" + docs = "# API Documentation\n\n" + + for endpoint in endpoints: + docs += f"## {endpoint['name']}\n\n" + docs += f"{endpoint['docstring']}\n\n" + docs += f"**Parameters**: {', '.join(endpoint['params'])}\n\n" + docs += f"**Returns**: {endpoint['returns']}\n\n" + docs += "---\n\n" + + return docs + +if __name__ == '__main__': + import sys + with open(sys.argv[1], 'r') as f: + tree = ast.parse(f.read()) + + extractor = APIDocExtractor() + extractor.visit(tree) + + markdown = generate_markdown_docs(extractor.endpoints) + print(markdown) +``` +### Skill Discovery & Invocation + +```mermaid +graph TD + A["User Request"] --> B["Claude Analyzes"] + B -->|Scans| C["Available Skills"] + C -->|Metadata check| D["Skill Description Match?"] + D -->|Yes| E["Load SKILL.md"] + D -->|No| F["Try next skill"] + F -->|More skills?| D + F -->|No more| G["Use general knowledge"] + E --> H["Extract Instructions"] + H --> I["Execute Skill"] + I --> J["Return Results"] +``` + +### Skill vs Other Features + +```mermaid +graph TB + A["Extending Claude"] + B["Slash Commands"] + C["Subagents"] + D["Memory"] + E["MCP"] + F["Skills"] + + A --> B + A --> C + A --> D + A --> E + A --> F + + B -->|User-invoked| G["Quick shortcuts"] + C -->|Auto-delegated| H["Isolated contexts"] + D -->|Persistent| I["Cross-session context"] + E -->|Real-time| J["External data access"] + F -->|Auto-invoked| K["Autonomous execution"] +``` + +--- + +## Claude Code Plugins + +### Overview + +Claude Code Plugins are bundled collections of customizations (slash commands, subagents, MCP servers, and hooks) that install with a single command. They represent the highest-level extension mechanismβ€”combining multiple features into cohesive, shareable packages. + +### Architecture + +```mermaid +graph TB + A["Plugin"] + B["Slash Commands"] + C["Subagents"] + D["MCP Servers"] + E["Hooks"] + F["Configuration"] + + A -->|bundles| B + A -->|bundles| C + A -->|bundles| D + A -->|bundles| E + A -->|bundles| F +``` + +### Plugin Loading Process + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude Code + participant Plugin as Plugin Marketplace + participant Install as Installation + participant SlashCmds as Slash Commands + participant Subagents + participant MCPServers as MCP Servers + participant Hooks + participant Tools as Configured Tools + + User->>Claude: /plugin install pr-review + Claude->>Plugin: Download plugin manifest + Plugin-->>Claude: Return plugin definition + Claude->>Install: Extract components + Install->>SlashCmds: Configure + Install->>Subagents: Configure + Install->>MCPServers: Configure + Install->>Hooks: Configure + SlashCmds-->>Tools: Ready to use + Subagents-->>Tools: Ready to use + MCPServers-->>Tools: Ready to use + Hooks-->>Tools: Ready to use + Tools-->>Claude: Plugin installed βœ… +``` + +### Plugin Types & Distribution + +| Type | Scope | Shared | Authority | Examples | +|------|-------|--------|-----------|----------| +| Official | Global | All users | Anthropic | PR Review, Security Guidance | +| Community | Public | All users | Community | DevOps, Data Science | +| Organization | Internal | Team members | Company | Internal standards, tools | +| Personal | Individual | Single user | Developer | Custom workflows | + +### Plugin Definition Structure + +```yaml +--- +name: plugin-name +version: "1.0.0" +description: "What this plugin does" +author: "Your Name" +license: MIT + +# Plugin metadata +tags: + - category + - use-case + +# Requirements +requires: + - claude-code: ">=1.0.0" + +# Components bundled +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: hooks + path: hooks/ + +# Configuration +config: + auto_load: true + enabled_by_default: true +--- +``` + +### Plugin Structure + +``` +my-plugin/ +β”œβ”€β”€ plugin.yaml +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ task-1.md +β”‚ β”œβ”€β”€ task-2.md +β”‚ └── workflows/ +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ specialist-1.md +β”‚ β”œβ”€β”€ specialist-2.md +β”‚ └── configs/ +β”œβ”€β”€ mcp/ +β”‚ β”œβ”€β”€ mcp-config.json +β”‚ └── servers/ +β”œβ”€β”€ hooks/ +β”‚ β”œβ”€β”€ pre-deploy.js +β”‚ └── post-merge.js +β”œβ”€β”€ templates/ +β”‚ └── issue-template.md +β”œβ”€β”€ scripts/ +β”‚ β”œβ”€β”€ helper-1.sh +β”‚ └── helper-2.py +β”œβ”€β”€ docs/ +β”‚ β”œβ”€β”€ README.md +β”‚ └── USAGE.md +└── tests/ + └── plugin.test.js +``` + +### Practical Examples + +#### Example 1: PR Review Plugin + +**File:** `plugin.yaml` + +```yaml +--- +name: pr-review +version: "1.0.0" +description: Complete PR review workflow with security, testing, and docs +author: Anthropic +tags: + - code-review + - quality + - security + +components: + - type: commands + path: commands/ + - type: agents + path: agents/ + - type: mcp + path: mcp/ + - type: hooks + path: hooks/ +--- +``` + +**File:** `commands/review-pr.md` + +```markdown +--- +name: Review PR +description: Start comprehensive PR review with security and testing checks +--- + +# PR Review + +This command initiates a complete pull request review including: + +1. Security analysis +2. Test coverage verification +3. Documentation updates +4. Code quality checks +5. Performance impact assessment +``` + +**File:** `agents/security-reviewer.md` + +```yaml +--- +name: security-reviewer +description: Security-focused code review +tools: read, grep, diff +--- + +# Security Reviewer + +Specializes in finding security vulnerabilities: +- Authentication/authorization issues +- Data exposure +- Injection attacks +- Secure configuration +``` + +**Installation:** + +```bash +/plugin install pr-review + +# Result: +# βœ… 3 slash commands installed +# βœ… 3 subagents configured +# βœ… 2 MCP servers connected +# βœ… 4 hooks registered +# βœ… Ready to use! +``` + +#### Example 2: DevOps Plugin + +**Components:** + +``` +devops-automation/ +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ deploy.md +β”‚ β”œβ”€β”€ rollback.md +β”‚ β”œβ”€β”€ status.md +β”‚ └── incident.md +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ deployment-specialist.md +β”‚ β”œβ”€β”€ incident-commander.md +β”‚ └── alert-analyzer.md +β”œβ”€β”€ mcp/ +β”‚ β”œβ”€β”€ github-config.json +β”‚ β”œβ”€β”€ kubernetes-config.json +β”‚ └── prometheus-config.json +β”œβ”€β”€ hooks/ +β”‚ β”œβ”€β”€ pre-deploy.js +β”‚ β”œβ”€β”€ post-deploy.js +β”‚ └── on-error.js +└── scripts/ + β”œβ”€β”€ deploy.sh + β”œβ”€β”€ rollback.sh + └── health-check.sh +``` + +#### Example 3: Documentation Plugin + +**Bundled Components:** + +``` +documentation/ +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ generate-api-docs.md +β”‚ β”œβ”€β”€ generate-readme.md +β”‚ β”œβ”€β”€ sync-docs.md +β”‚ └── validate-docs.md +β”œβ”€β”€ agents/ +β”‚ β”œβ”€β”€ api-documenter.md +β”‚ β”œβ”€β”€ code-commentator.md +β”‚ └── example-generator.md +β”œβ”€β”€ mcp/ +β”‚ β”œβ”€β”€ github-docs-config.json +β”‚ └── slack-announce-config.json +└── templates/ + β”œβ”€β”€ api-endpoint.md + β”œβ”€β”€ function-docs.md + └── adr-template.md +``` + +### Plugin Marketplace + +```mermaid +graph TB + A["Plugin Marketplace"] + B["Official
Anthropic"] + C["Community
Marketplace"] + D["Enterprise
Registry"] + + A --> B + A --> C + A --> D + + B -->|Categories| B1["Development"] + B -->|Categories| B2["DevOps"] + B -->|Categories| B3["Documentation"] + + C -->|Search| C1["DevOps Automation"] + C -->|Search| C2["Mobile Dev"] + C -->|Search| C3["Data Science"] + + D -->|Internal| D1["Company Standards"] + D -->|Internal| D2["Legacy Systems"] + D -->|Internal| D3["Compliance"] +``` + +### Plugin Installation & Lifecycle + +```mermaid +graph LR + A["Discover"] -->|Browse| B["Marketplace"] + B -->|Select| C["Plugin Page"] + C -->|View| D["Components"] + D -->|Install| E["/plugin install"] + E -->|Extract| F["Configure"] + F -->|Activate| G["Use"] + G -->|Check| H["Update"] + H -->|Available| G + G -->|Done| I["Disable"] + I -->|Later| J["Enable"] + J -->|Back| G +``` + +### Plugin Features Comparison + +| Feature | Slash Command | Skill | Subagent | Plugin | +|---------|---------------|-------|----------|--------| +| **Installation** | Manual copy | Manual copy | Manual config | One command | +| **Setup Time** | 5 minutes | 10 minutes | 15 minutes | 2 minutes | +| **Bundling** | Single file | Single file | Single file | Multiple | +| **Versioning** | Manual | Manual | Manual | Automatic | +| **Team Sharing** | Copy file | Copy file | Copy file | Install ID | +| **Updates** | Manual | Manual | Manual | Auto-available | +| **Dependencies** | None | None | None | May include | +| **Marketplace** | No | No | No | Yes | +| **Distribution** | Repository | Repository | Repository | Marketplace | + +### Plugin Use Cases + +| Use Case | Recommendation | Why | +|----------|-----------------|-----| +| **Team Onboarding** | βœ… Use Plugin | Instant setup, all configurations | +| **Framework Setup** | βœ… Use Plugin | Bundles framework-specific commands | +| **Enterprise Standards** | βœ… Use Plugin | Central distribution, version control | +| **Quick Task Automation** | ❌ Use Command | Overkill complexity | +| **Single Domain Expertise** | ❌ Use Skill | Too heavy, use skill instead | +| **Specialized Analysis** | ❌ Use Subagent | Create manually or use skill | +| **Live Data Access** | ❌ Use MCP | Standalone, don't bundle | + +### When to Create a Plugin + +```mermaid +graph TD + A["Should I create a plugin?"] + A -->|Need multiple components| B{"Multiple commands
or subagents
or MCPs?"} + B -->|Yes| C["βœ… Create Plugin"] + B -->|No| D["Use Individual Feature"] + A -->|Team workflow| E{"Share with
team?"} + E -->|Yes| C + E -->|No| F["Keep as Local Setup"] + A -->|Complex setup| G{"Needs auto
configuration?"} + G -->|Yes| C + G -->|No| D +``` + +### Publishing a Plugin + +**Steps to publish:** + +1. Create plugin structure with all components +2. Write `plugin.yaml` manifest +3. Create `README.md` with documentation +4. Test locally with `/plugin install ./my-plugin` +5. Submit to plugin marketplace +6. Get reviewed and approved +7. Published on marketplace +8. Users can install with one command + +**Example submission:** + +```markdown +# PR Review Plugin + +## Description +Complete PR review workflow with security, testing, and documentation checks. + +## What's Included +- 3 slash commands for different review types +- 3 specialized subagents +- GitHub and CodeQL MCP integration +- Automated security scanning hooks + +## Installation +```bash +/plugin install pr-review +``` + +## Features +βœ… Security analysis +βœ… Test coverage checking +βœ… Documentation verification +βœ… Code quality assessment +βœ… Performance impact analysis + +## Usage +```bash +/review-pr +/check-security +/check-tests +``` + +## Requirements +- Claude Code 1.0+ +- GitHub access +- CodeQL (optional) +``` + +### Plugin vs Manual Configuration + +**Manual Setup (2+ hours):** +- Install slash commands one by one +- Create subagents individually +- Configure MCPs separately +- Set up hooks manually +- Document everything +- Share with team (hope they configure correctly) + +**With Plugin (2 minutes):** +```bash +/plugin install pr-review +# βœ… Everything installed and configured +# βœ… Ready to use immediately +# βœ… Team can reproduce exact setup +``` + +--- + +## Comparison & Integration + +### Feature Comparison Matrix + +| Feature | Invocation | Persistence | Scope | Use Case | +|---------|-----------|------------|-------|----------| +| **Slash Commands** | Manual (`/cmd`) | Session only | Single command | Quick shortcuts | +| **Subagents** | Auto-delegated | Isolated context | Specialized task | Task distribution | +| **Memory** | Auto-loaded | Cross-session | User/team context | Long-term learning | +| **MCP Protocol** | Auto-queried | Real-time external | Live data access | Dynamic information | +| **Skills** | Auto-invoked | Filesystem-based | Reusable expertise | Automated workflows | + +### Interaction Timeline + +```mermaid +graph LR + A["Session Start"] -->|Load| B["Memory (CLAUDE.md)"] + B -->|Discover| C["Available Skills"] + C -->|Register| D["Slash Commands"] + D -->|Connect| E["MCP Servers"] + E -->|Ready| F["User Interaction"] + + F -->|Type /cmd| G["Slash Command"] + F -->|Request| H["Skill Auto-Invoke"] + F -->|Query| I["MCP Data"] + F -->|Complex task| J["Delegate to Subagent"] + + G -->|Uses| B + H -->|Uses| B + I -->|Uses| B + J -->|Uses| B +``` + +### Practical Integration Example: Customer Support Automation + +#### Architecture + +```mermaid +graph TB + User["Customer Email"] -->|Receives| Router["Support Router"] + + Router -->|Analyze| Memory["Memory
Customer history"] + Router -->|Lookup| MCP1["MCP: Customer DB
Previous tickets"] + Router -->|Check| MCP2["MCP: Slack
Team status"] + + Router -->|Route Complex| Sub1["Subagent: Tech Support
Context: Technical issues"] + Router -->|Route Simple| Sub2["Subagent: Billing
Context: Payment issues"] + Router -->|Route Urgent| Sub3["Subagent: Escalation
Context: Priority handling"] + + Sub1 -->|Format| Skill1["Skill: Response Generator
Brand voice maintained"] + Sub2 -->|Format| Skill2["Skill: Response Generator"] + Sub3 -->|Format| Skill3["Skill: Response Generator"] + + Skill1 -->|Generate| Output["Formatted Response"] + Skill2 -->|Generate| Output + Skill3 -->|Generate| Output + + Output -->|Post| MCP3["MCP: Slack
Notify team"] + Output -->|Send| Reply["Customer Reply"] +``` + +#### Request Flow + +```markdown +## Customer Support Request Flow + +### 1. Incoming Email +"I'm getting error 500 when trying to upload files. This is blocking my workflow!" + +### 2. Memory Lookup +- Loads CLAUDE.md with support standards +- Checks customer history: VIP customer, 3rd incident this month + +### 3. MCP Queries +- GitHub MCP: List open issues (finds related bug report) +- Database MCP: Check system status (no outages reported) +- Slack MCP: Check if engineering is aware + +### 4. Skill Detection & Loading +- Request matches "Technical Support" skill +- Loads support response template from Skill + +### 5. Subagent Delegation +- Routes to Tech Support Subagent +- Provides context: customer history, error details, known issues +- Subagent has full access to: read, bash, grep tools + +### 6. Subagent Processing +Tech Support Subagent: +- Searches codebase for 500 error in file upload +- Finds recent change in commit 8f4a2c +- Creates workaround documentation + +### 7. Skill Execution +Response Generator Skill: +- Uses Brand Voice guidelines +- Formats response with empathy +- Includes workaround steps +- Links to related documentation + +### 8. MCP Output +- Posts update to #support Slack channel +- Tags engineering team +- Updates ticket in Jira MCP + +### 9. Response +Customer receives: +- Empathetic acknowledgment +- Explanation of cause +- Immediate workaround +- Timeline for permanent fix +- Link to related issues +``` + +### Complete Feature Orchestration + +```mermaid +sequenceDiagram + participant User + participant Claude as Claude Code + participant Memory as Memory
CLAUDE.md + participant MCP as MCP Servers + participant Skills as Skills + participant SubAgent as Subagents + + User->>Claude: Request: "Build auth system" + Claude->>Memory: Load project standards + Memory-->>Claude: Auth standards, team practices + Claude->>MCP: Query GitHub for similar implementations + MCP-->>Claude: Code examples, best practices + Claude->>Skills: Detect matching Skills + Skills-->>Claude: Security Review Skill + Testing Skill + Claude->>SubAgent: Delegate implementation + SubAgent->>SubAgent: Build feature + Claude->>Skills: Apply Security Review Skill + Skills-->>Claude: Security checklist results + Claude->>SubAgent: Delegate testing + SubAgent-->>Claude: Test results + Claude->>User: Complete system delivered +``` + +### When to Use Each Feature + +```mermaid +graph TD + A["New Task"] --> B{Type of Task?} + + B -->|Repeated workflow| C["Slash Command"] + B -->|Need real-time data| D["MCP Protocol"] + B -->|Remember for next time| E["Memory"] + B -->|Specialized subtask| F["Subagent"] + B -->|Domain-specific work| G["Skill"] + + C --> C1["βœ… Team shortcut"] + D --> D1["βœ… Live API access"] + E --> E1["βœ… Persistent context"] + F --> F1["βœ… Parallel execution"] + G --> G1["βœ… Auto-invoked expertise"] +``` + +### Selection Decision Tree + +```mermaid +graph TD + Start["Need to extend Claude?"] + + Start -->|Quick repeated task| A{"Manual or Auto?"} + A -->|Manual| B["Slash Command"] + A -->|Auto| C["Skill"] + + Start -->|Need external data| D{"Real-time?"} + D -->|Yes| E["MCP Protocol"] + D -->|No/Cross-session| F["Memory"] + + Start -->|Complex project| G{"Multiple roles?"} + G -->|Yes| H["Subagents"] + G -->|No| I["Skills + Memory"] + + Start -->|Long-term context| J["Memory"] + Start -->|Team workflow| K["Slash Command +
Memory"] + Start -->|Full automation| L["Skills +
Subagents +
MCP"] +``` + +--- + +## Summary Table + +| Aspect | Slash Commands | Subagents | Memory | MCP | Skills | Plugins | +|--------|---|---|---|---|---|---| +| **Setup Difficulty** | Easy | Medium | Easy | Medium | Medium | Easy | +| **Learning Curve** | Low | Medium | Low | Medium | Medium | Low | +| **Team Benefit** | High | High | Medium | High | High | Very High | +| **Automation Level** | Low | High | Medium | High | High | Very High | +| **Context Management** | Single-session | Isolated | Persistent | Real-time | Persistent | All features | +| **Maintenance Burden** | Low | Medium | Low | Medium | Medium | Low | +| **Scalability** | Good | Excellent | Good | Excellent | Excellent | Excellent | +| **Shareability** | Fair | Fair | Good | Good | Good | Excellent | +| **Versioning** | Manual | Manual | Manual | Manual | Manual | Automatic | +| **Installation** | Manual copy | Manual config | N/A | Manual config | Manual copy | One command | + +--- + +## Quick Start Guide + +### Week 1: Start Simple +- Create 2-3 slash commands for common tasks +- Enable Memory in Settings +- Document team standards in CLAUDE.md + +### Week 2: Add Real-time Access +- Set up 1 MCP (GitHub or Database) +- Use `/mcp` to configure +- Query live data in your workflows + +### Week 3: Distribute Work +- Create first Subagent for specific role +- Use `/agents` command +- Test delegation with simple task + +### Week 4: Automate Everything +- Create first Skill for repeated automation +- Use Skill marketplace or build custom +- Combine all features for full workflow + +### Ongoing +- Review and update Memory monthly +- Add new Skills as patterns emerge +- Optimize MCP queries +- Refine Subagent prompts + +--- + +## Resources + +- [Claude Documentation](https://docs.claude.com) +- [MCP GitHub Servers](https://github.com/modelcontextprotocol/servers) +- [Skills Cookbook](https://github.com/anthropic-ai/skills) +- [Claude Code Guide](https://docs.claude.com/en/docs/claude-code/overview) + +--- + +*Last updated: November 6, 2025* +*For Claude Haiku 4.5, Sonnet 4.5, and Opus 4.1*