diff --git a/01-slash-commands/README.md b/01-slash-commands/README.md
index 7c01b82..98caac8 100644
--- a/01-slash-commands/README.md
+++ b/01-slash-commands/README.md
@@ -1,45 +1,34 @@
-# Slash Commands Examples
+# Slash Commands
-This folder contains example slash commands that can be used with Claude Code.
+## Overview
-## Installation
+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.
-Copy these files to your project's `.claude/commands/` directory:
+## Architecture
-```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
+```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
-Place commands in your project:
+```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"]
+```
+
+### Recommended Structure
+
```
project/
├── .claude/
@@ -50,10 +39,377 @@ project/
│ └── generate-api-docs.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 |
+
+## Available Commands in This Folder
+
+### 1. `/optimize` - Code Optimization
+Analyzes code for performance issues, memory leaks, and optimization opportunities.
+
+**Usage:**
+```
+/optimize
+[Paste your code]
+```
+
+**Reviews for:**
+- Performance bottlenecks (O(n²) operations)
+- Memory leaks
+- Algorithm improvements
+- Caching opportunities
+- Concurrency issues
+
+### 2. `/pr` - Pull Request Preparation
+Guides you through PR preparation checklist including linting, testing, and commit message formatting.
+
+**Usage:**
+```
+/pr
+```
+
+**Checklist includes:**
+- Running linting
+- Running tests
+- Reviewing git diff
+- Staging changes
+- Creating conventional commit messages
+- Generating PR summary
+
+### 3. `/generate-api-docs` - API Documentation Generator
+Generates comprehensive API documentation from source code.
+
+**Usage:**
+```
+/generate-api-docs
+```
+
+**Features:**
+- Scans all files in `/src/api/`
+- Extracts function signatures and JSDoc comments
+- Organizes by endpoint/module
+- Creates markdown with examples
+- Includes request/response schemas
+- Adds error documentation
+
+## 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
+```
+
+## Installation
+
+### For Project-wide Use (Team)
+
+Copy these files to your project's `.claude/commands/` directory:
+
+```bash
+# Create commands directory if it doesn't exist
+mkdir -p .claude/commands
+
+# Copy command files
+cp 01-slash-commands/*.md .claude/commands/
+
+# Copy subdirectory commands
+cp -r 01-slash-commands/docs .claude/commands/
+```
+
+### For Personal Use
+
+Copy to your personal Claude commands directory:
+
+```bash
+# Create personal commands directory
+mkdir -p ~/.claude/commands
+
+# Copy command files
+cp 01-slash-commands/*.md ~/.claude/commands/
+```
+
+## Creating Your Own Commands
+
+### Basic Command Template
+
+Create a file `.claude/commands/my-command.md`:
+
+```markdown
+---
+name: My Command Name
+description: What this command does
+tags: category, task-type
+---
+
+# Command Title
+
+Instructions for Claude:
+
+1. First step
+2. Second step
+3. Third step
+
+Output format:
+- How to format the response
+- What to include
+```
+
+### Command with Frontmatter
+
+```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
+
+Format your response with:
+- Issue severity (Critical/High/Medium/Low)
+- Location in code
+- Explanation
+- Recommended fix with code example
+```
+
## 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
+| ✅ 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 |
+
+## Examples
+
+### Example 1: Simple Task Automation
+
+**File:** `.claude/commands/test.md`
+
+```markdown
+---
+name: Run Tests
+description: Execute test suite with coverage report
+---
+
+# Test Runner
+
+1. Run the test suite: `npm test`
+2. Generate coverage report
+3. Summarize results
+4. Highlight any failures
+```
+
+### Example 2: Multi-step Workflow
+
+**File:** `.claude/commands/deploy.md`
+
+```markdown
+---
+name: Deploy to Production
+description: Complete deployment workflow with checks
+---
+
+# Production Deployment
+
+Execute these steps in order:
+
+1. **Pre-deployment checks**
+ - Run `npm run lint`
+ - Run `npm test`
+ - Check git status is clean
+
+2. **Build**
+ - Run `npm run build`
+ - Verify build artifacts
+
+3. **Deploy**
+ - Run `npm run deploy`
+ - Monitor deployment logs
+
+4. **Post-deployment**
+ - Run smoke tests
+ - Verify deployment
+ - Notify team
+```
+
+### Example 3: Code Review Command
+
+**File:** `.claude/commands/review.md`
+
+```markdown
+---
+name: Code Review
+description: Comprehensive code review checklist
+---
+
+# Code Review
+
+Review the code for:
+
+## Security
+- [ ] No hardcoded credentials
+- [ ] Input validation present
+- [ ] SQL injection prevention
+- [ ] XSS prevention
+
+## Performance
+- [ ] No N+1 queries
+- [ ] Appropriate indexing
+- [ ] Efficient algorithms
+
+## Quality
+- [ ] Clear naming
+- [ ] Proper error handling
+- [ ] Adequate comments
+- [ ] No code duplication
+```
+
+## Advanced Usage
+
+### Using Arguments
+
+Commands can accept arguments:
+
+```bash
+/deploy production
+/review --verbose
+/test --coverage
+```
+
+Handle arguments in your command file:
+
+```markdown
+# Deployment Command
+
+Check the provided argument for environment:
+- If "production", use strict checks
+- If "staging", allow warnings
+- If "development", skip certain validations
+```
+
+### Integrating with MCP
+
+Commands can use MCP tools:
+
+```markdown
+# GitHub PR Command
+
+1. Use MCP to list open PRs: `/mcp__github__list_prs`
+2. Analyze each PR for:
+ - Review status
+ - CI/CD status
+ - Merge conflicts
+3. Provide summary
+```
+
+### Hierarchical Commands
+
+Organize related commands in subdirectories:
+
+```
+.claude/commands/
+├── deploy/
+│ ├── production.md
+│ ├── staging.md
+│ └── rollback.md
+├── test/
+│ ├── unit.md
+│ ├── integration.md
+│ └── e2e.md
+└── docs/
+ ├── api.md
+ └── readme.md
+```
+
+Access with: `/deploy/production`, `/test/unit`, `/docs/api`
+
+## Troubleshooting
+
+### Command Not Found
+
+**Problem:** Claude doesn't recognize `/my-command`
+
+**Solutions:**
+- Check file is in `.claude/commands/` directory
+- Verify filename matches command name
+- Restart Claude Code session
+- Check file has `.md` extension
+
+### Command Not Executing as Expected
+
+**Problem:** Command loads but doesn't work correctly
+
+**Solutions:**
+- Review command prompt clarity
+- Add more specific instructions
+- Include examples in command file
+- Test with simple inputs first
+
+### Personal vs Project Commands
+
+**When to use personal commands:**
+- Personal preferences/workflows
+- Not relevant to team
+- Experimental commands
+- Cross-project shortcuts
+
+**When to use project commands:**
+- Team standards
+- Project-specific workflows
+- Shared conventions
+- Onboarding helpers
+
+## Related Concepts
+
+- **[Subagents](../02-subagents/)** - For complex, delegated tasks
+- **[Memory](../03-memory/)** - For persistent context
+- **[Skills](../05-skills/)** - For auto-invoked capabilities
+- **[Plugins](../06-plugins/)** - For bundled command collections
+
+## Resources
+
+- [Claude Code Commands Documentation](https://docs.claude.com/en/docs/claude-code/custom-commands)
+- [Markdown Guide](https://www.markdownguide.org/)
+- [Command Examples Repository](https://github.com/anthropics/claude-code-examples)
+
+---
+
+*Part of the [Claude How To](../) guide series*
diff --git a/02-subagents/README.md b/02-subagents/README.md
index fc0e7cc..443e0f0 100644
--- a/02-subagents/README.md
+++ b/02-subagents/README.md
@@ -1,74 +1,663 @@
-# Subagents Examples
+# Subagents - Complete Reference Guide
-This folder contains example subagent configurations for Claude Code.
+Subagents are specialized AI assistants with isolated context windows and customized system prompts. They enable delegated task execution while maintaining clean separation of concerns.
-## Installation
+## Table of Contents
-Copy these files to your project's `.claude/agents/` directory:
+1. [Overview](#overview)
+2. [Architecture](#architecture)
+3. [Configuration](#configuration)
+4. [Tool Access Hierarchy](#tool-access-hierarchy)
+5. [Practical Examples](#practical-examples)
+6. [Context Management](#context-management)
+7. [When to Use Subagents](#when-to-use-subagents)
+8. [Best Practices](#best-practices)
+9. [Available Subagents in This Folder](#available-subagents-in-this-folder)
+10. [Installation Instructions](#installation-instructions)
+11. [Related Concepts](#related-concepts)
-```bash
-cp *.md /path/to/your/project/.claude/agents/
+---
+
+## Overview
+
+Subagents enable delegated task execution in Claude Code by:
+
+- Creating **isolated AI assistants** with separate context windows
+- Providing **customized system prompts** for specialized expertise
+- Enforcing **tool access control** to limit capabilities
+- Preventing **context pollution** from complex tasks
+- Enabling **parallel execution** of multiple specialized tasks
+
+Each subagent operates independently with a clean slate, receiving only the specific context necessary for their task, then returning results to the main agent for synthesis.
+
+### Key Benefits
+
+- **Separation of Concerns** - Each agent focuses on their specialty
+- **Clean Context** - No interference from unrelated information
+- **Scalability** - Multiple agents work on different aspects simultaneously
+- **Quality** - Specialized prompts improve output for domain-specific tasks
+- **Control** - Granular tool permissions prevent unintended modifications
+
+---
+
+## Architecture
+
+### High-Level Architecture
+
+```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
```
-## Available Subagents
+### Subagent Lifecycle
-### 1. Code Reviewer (`code-reviewer`)
-Comprehensive code quality and maintainability analysis.
+```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
+```
+
+---
+
+## Configuration
+
+### 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 |
+
+### Configuration File Format
+
+Subagents are defined in YAML front matter followed by the system prompt:
+
+```yaml
+---
+name: agent-name
+description: Brief description of purpose
+tools: read, grep, diff
+---
+
+# System Prompt (Markdown)
+
+You are an expert in [domain]...
+```
+
+### Tool Configuration Options
+
+**Option 1: Inherit All Tools from Main Thread**
+```yaml
+---
+name: full-access-agent
+description: Agent with all available tools
+tools: *
+---
+```
+
+**Option 2: Specify Individual Tools**
+```yaml
+---
+name: limited-agent
+description: Agent with specific tools only
+tools: read, grep, diff
+---
+```
+
+**Option 3: Conditional Tool Access**
+```yaml
+---
+name: conditional-agent
+description: Agent with filtered tool access
+tools: read, bash(npm:*), bash(test:*)
+---
+```
+
+---
+
+## 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:*)"]
+```
+
+### Common Tool Combinations
+
+**Code Review Agent**
+```yaml
+tools: read, grep, diff, lint_runner
+```
+
+**Implementation Agent**
+```yaml
+tools: read, write, bash, grep, edit, glob
+```
+
+**Documentation Agent**
+```yaml
+tools: read, write, grep
+```
+
+**Security Auditor**
+```yaml
+tools: read, grep
+```
+
+---
+
+## Practical Examples
+
+### Example 1: Complete Subagent Setup
+
+#### Code Reviewer Subagent
+
+**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
+```
+
+#### Test Engineer Subagent
+
+**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
+```
+
+#### Documentation Writer Subagent
+
+**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
+
+#### 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
+
+**File**: `.claude/agents/secure-reviewer.md`
+
+```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
+
+**File**: `.claude/agents/implementation-agent.md`
+
+```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.
+```
+
+---
+
+## 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
+```
+
+### Key Points
+
+- Each subagent gets a **fresh context window** without the main conversation history
+- Only the **relevant context** is passed to the subagent for their specific task
+- Results are **distilled** back to the main agent
+- This prevents **context token exhaustion** on long projects
+
+---
+
+## 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 |
+
+---
+
+## Best Practices
+
+### Design Principles
+
+✅ **Do:**
+- Create subagents for distinct specializations
+- Use clear, focused system prompts
+- Limit tools to what's necessary
+- Design for isolation and independence
+- Return structured results to main agent
+
+❌ **Don't:**
+- Create overlapping subagents with same roles
+- Give subagents unnecessary tool access
+- Use subagents for simple, single-step tasks
+- Mix concerns in one subagent's prompt
+- Forget to pass necessary context
+
+### System Prompt Best Practices
+
+1. **Be Specific About Role**
+ ```
+ You are an expert code reviewer specializing in [specific areas]
+ ```
+
+2. **Define Priorities Clearly**
+ ```
+ Review priorities (in order):
+ 1. Security Issues
+ 2. Performance Problems
+ 3. Code Quality
+ ```
+
+3. **Specify Output Format**
+ ```
+ For each issue provide: Severity, Category, Location, Description, Fix, Impact
+ ```
+
+4. **Set Expectations**
+ ```
+ Focus on issues that matter. Ignore formatting unless critical.
+ ```
+
+### Tool Access Strategy
+
+1. **Start Restrictive**: Begin with only essential tools
+2. **Expand Only When Needed**: Add tools as requirements demand
+3. **Read-Only When Possible**: Use read/grep for analysis agents
+4. **Sandboxed Execution**: Limit bash commands to specific patterns
+
+---
+
+## Available Subagents in This Folder
+
+### 1. Code Reviewer (`code-reviewer.md`)
+
+**Description**: Comprehensive code quality and maintainability analysis
**Tools**: read, grep, diff, lint_runner
-**Use Case**: Automated code reviews focusing on security, performance, and quality.
+**Specialization**:
+- Security vulnerability detection
+- Performance optimization identification
+- Code maintainability assessment
+- Test coverage analysis
+- Design pattern evaluation
-### 2. Test Engineer (`test-engineer`)
-Test strategy, coverage analysis, and automated testing.
+**Use When**: You need automated code reviews with focus on quality and security
+
+**Example**: Review pull requests before merging
+
+---
+
+### 2. Test Engineer (`test-engineer.md`)
+
+**Description**: Test strategy, coverage analysis, and automated testing
**Tools**: read, write, bash, grep
-**Use Case**: Creating comprehensive test suites with high coverage.
+**Specialization**:
+- Unit test creation
+- Integration test design
+- Edge case identification
+- Coverage analysis (>80% target)
+- Performance benchmarking
-### 3. Documentation Writer (`documentation-writer`)
-Technical documentation, API docs, and user guides.
+**Use When**: You need comprehensive test suite creation or coverage analysis
+
+**Example**: Generate tests for a new feature with high coverage
+
+---
+
+### 3. Documentation Writer (`documentation-writer.md`)
+
+**Description**: Technical documentation, API docs, and user guides
**Tools**: read, write, grep
-**Use Case**: Generating and maintaining project documentation.
+**Specialization**:
+- API endpoint documentation
+- User guide creation
+- Architecture documentation
+- Code comment improvement
+- Changelog generation
-### 4. Secure Reviewer (`secure-reviewer`)
-Security-focused code review with minimal permissions.
+**Use When**: You need to create or update project documentation
-**Tools**: read, grep (read-only)
+**Example**: Generate complete API documentation from code
-**Use Case**: Security audits without modification capabilities.
+---
-### 5. Implementation Agent (`implementation-agent`)
-Full implementation capabilities for feature development.
+### 4. Secure Reviewer (`secure-reviewer.md`)
+
+**Description**: Security-focused code review with minimal permissions
+
+**Tools**: read, grep
+
+**Specialization**:
+- Security vulnerability detection
+- Authentication/authorization issues
+- Data exposure risks
+- Injection attack identification
+- Secure configuration verification
+
+**Use When**: You need security audits without modification capabilities
+
+**Example**: Security-only code review with read-only access
+
+---
+
+### 5. Implementation Agent (`implementation-agent.md`)
+
+**Description**: Full implementation capabilities for feature development
**Tools**: read, write, bash, grep, edit, glob
-**Use Case**: End-to-end feature implementation.
+**Specialization**:
+- Feature implementation
+- Code generation
+- Build and test execution
+- File operations
+- Codebase modification
-## How Subagents Work
+**Use When**: You need a subagent to implement features end-to-end
-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
+**Example**: Implement a complete feature from specification
-## Usage Example
+---
-Main agent delegates work to subagents:
+## Installation Instructions
-```markdown
-User: "Build a new authentication feature"
+### Method 1: Copy to Project
-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
+Copy the agent files to your project's `.claude/agents/` directory:
+
+```bash
+# Navigate to your project
+cd /path/to/your/project
+
+# Create agents directory if it doesn't exist
+mkdir -p .claude/agents
+
+# Copy all agent files
+cp /path/to/02-subagents/*.md .claude/agents/
```
+### Method 2: Manual Setup
+
+If you prefer to set up individually:
+
+```bash
+# Copy specific agents you need
+cp 01-code-reviewer.md .claude/agents/code-reviewer.md
+cp 02-test-engineer.md .claude/agents/test-engineer.md
+cp 03-documentation-writer.md .claude/agents/documentation-writer.md
+cp 04-secure-reviewer.md .claude/agents/secure-reviewer.md
+cp 05-implementation-agent.md .claude/agents/implementation-agent.md
+```
+
+### Method 3: Create from Guide
+
+Copy the configuration from this README and create new files in your `.claude/agents/` directory.
+
+### Verification
+
+After installation, verify the agents are recognized:
+
+```bash
+# List agents in Claude Code
+/agents list
+
+# Should show:
+# - code-reviewer
+# - test-engineer
+# - documentation-writer
+# - secure-reviewer
+# - implementation-agent
+```
+
+---
+
## File Structure
```
@@ -80,15 +669,143 @@ project/
│ ├── documentation-writer.md
│ ├── secure-reviewer.md
│ └── implementation-agent.md
+└── README.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 |
+## Usage Example
+
+### Delegating Work to Subagents
+
+**User Request**:
+```
+"Build a new authentication feature"
+```
+
+**Main Agent Workflow**:
+
+```markdown
+Main Agent receives: "Build a new authentication feature"
+
+1. Delegates to implementation-agent:
+ "Implement JWT-based authentication with refresh tokens"
+
+2. Delegates to code-reviewer:
+ "Review the auth implementation for security issues"
+
+3. Delegates to test-engineer:
+ "Create comprehensive tests for auth flows"
+
+4. Delegates to documentation-writer:
+ "Document the authentication API"
+
+5. Synthesis:
+ Combines all results:
+ - ✅ Implementation complete
+ - ✅ Security reviewed
+ - ✅ Tests created (85% coverage)
+ - ✅ Documentation generated
+
+ Returns to user: Complete authentication feature with all components
+```
+
+---
+
+## Related Concepts
+
+### Related Features
+
+- **[Slash Commands](../01-slash-commands/)** - Quick user-invoked shortcuts
+- **[Memory](../03-memory/)** - Persistent cross-session context
+- **[MCP Protocol](../04-mcp-protocol/)** - Real-time external data access
+- **[Agent Skills](../05-agent-skills/)** - Reusable autonomous capabilities
+- **[Plugins](../06-plugins/)** - Bundled extension packages
+
+### Comparison with Other Features
+
+| Feature | User-Invoked | Auto-Invoked | Persistent | External Access | Isolated Context |
+|---------|--------------|--------------|-----------|------------------|------------------|
+| **Slash Commands** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
+| **Subagents** | ❌ No | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
+| **Memory** | ❌ Auto | ✅ Auto | ✅ Yes | ❌ No | ❌ No |
+| **MCP** | ❌ Auto | ✅ Yes | ❌ No | ✅ Yes | ❌ No |
+| **Skills** | ❌ No | ✅ Yes | ❌ No | ❌ No | ❌ No |
+
+### Integration Pattern
+
+```mermaid
+graph TD
+ User["User Request"] --> Main["Main Agent"]
+ Main -->|Uses| Memory["Memory
(Context)"]
+ Main -->|Queries| MCP["MCP
(Live Data)"]
+ Main -->|Invokes| Skills["Skills
(Auto Tools)"]
+ Main -->|Delegates| Subagents["Subagents
(Specialists)"]
+
+ Subagents -->|Use| Memory
+ Subagents -->|Query| MCP
+ Subagents -->|Isolated| Context["Clean Context
Window"]
+```
+
+---
+
+## Quick Reference
+
+### Create a Custom Subagent
+
+```yaml
+---
+name: my-specialist
+description: What this agent does
+tools: read, grep
+---
+
+# My Specialist Agent
+
+You are specialized in [domain].
+
+## Your Role
+
+[Detailed role description]
+
+## Guidelines
+
+[Key guidelines and constraints]
+```
+
+### Delegate to a Subagent
+
+```markdown
+Main agent asks subagent:
+"Please [task description] with focus on [specific goals]"
+
+Context provided:
+- Relevant code files
+- Project context
+- Specific requirements
+```
+
+### Subagent Returns
+
+```markdown
+Subagent provides:
+- Analysis or implementation
+- Structured findings
+- Recommendations
+- Code examples or output
+```
+
+---
+
+## Resources
+
+- [Claude Code Documentation](https://docs.claude.com/en/docs/claude-code/overview)
+- [Subagents in Claude Concepts Guide](../claude_concepts_guide.md#subagents)
+- [Agent Skills Guide](../05-agent-skills/)
+- [Memory and Context](../03-memory/)
+
+---
+
+*Last updated: November 8, 2025*
+
+*This guide covers complete subagent configuration, delegation patterns, and best practices for Claude Code.*
diff --git a/03-memory/README.md b/03-memory/README.md
index 3661611..d3a6d8b 100644
--- a/03-memory/README.md
+++ b/03-memory/README.md
@@ -1,122 +1,539 @@
-# Memory Examples
+# Memory Guide
-This folder contains example CLAUDE.md files for different memory scopes in Claude Code.
+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 Types
+## Overview
-### 1. Project Memory (`project-CLAUDE.md`)
-**Location**: `./CLAUDE.md` or `./.claude/CLAUDE.md`
+Memory in Claude Code provides persistent context that carries across multiple sessions and conversations. Unlike temporary context windows, memory files allow you to:
-**Purpose**: Team-wide project standards and configurations
+- Share project standards across your team
+- Store personal development preferences
+- Maintain directory-specific rules and configurations
+- Import external documentation
+- Version control memory as part of your project
-**Installation**:
-```bash
-cp project-CLAUDE.md /path/to/your/project/CLAUDE.md
+The memory system operates at multiple levels, from global personal preferences down to specific subdirectories, allowing for fine-grained control over what Claude remembers and how it applies that knowledge.
+
+## Memory Architecture
+
+Memory in Claude Code follows a hierarchical system where different scopes serve different purposes:
+
+```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
```
-**Contains**:
-- Project overview and tech stack
-- Development standards
-- Naming conventions
-- Git workflow
-- Testing requirements
-- API standards
-- Common commands
-- Team contacts
+## Memory Hierarchy in Claude Code
-### 2. Directory-Specific Memory (`directory-api-CLAUDE.md`)
-**Location**: `./src/api/CLAUDE.md`
+Claude searches for memory files in this order, with earlier locations taking precedence:
-**Purpose**: Override or extend project memory for specific directories
+```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"]
-**Installation**:
-```bash
-cp directory-api-CLAUDE.md /path/to/your/project/src/api/CLAUDE.md
+ B1 -->|imports| E["@docs/architecture.md"]
+ E -->|imports| F["@docs/api-standards.md"]
```
-**Contains**:
-- API-specific standards
-- Request validation rules
-- Authentication requirements
-- Response formats
-- Pagination standards
-- Rate limiting
-- Caching strategy
+## Memory Locations Table
-### 3. Personal Memory (`personal-CLAUDE.md`)
-**Location**: `~/.claude/CLAUDE.md`
+| 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 |
-**Purpose**: Personal preferences across all projects
+## Memory Update Lifecycle
-**Installation**:
-```bash
-cp personal-CLAUDE.md ~/.claude/CLAUDE.md
+Here's how memory updates flow through your Claude Code sessions:
+
+```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!"
```
-**Contains**:
-- Personal coding preferences
-- Communication style
-- Debugging preferences
-- Project organization
-- Tooling preferences
+## Practical Examples
-## Memory Hierarchy
+### Example 1: Project Memory Structure
-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
+**File:** `./CLAUDE.md`
```markdown
-User: Remember that I prefer using async/await instead of promises
+# Project Configuration
-Claude: I'll add that to your memory. Which memory file?
-1. Project memory (./CLAUDE.md)
-2. Personal memory (~/.claude/CLAUDE.md)
+## Project Overview
+- **Name**: E-commerce Platform
+- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker
+- **Team Size**: 5 developers
+- **Deadline**: Q4 2025
-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
+
+## 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 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 |
+
+### 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
```
## 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
+### Do's - What To Include
-### 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)
+- **Keep organized**: Structure memory files with clear sections
+- **Keep up-to-date**: Review and update memory regularly as standards change
+- **Use project memory for**: Team standards, architecture, coding conventions
+- **Use personal memory for**: Preferences, communication style, tooling choices
+- **Use directory memory for**: Module-specific rules and overrides
+- **Version control**: Commit CLAUDE.md files to git for team benefit
+- **Import docs**: Reference external files with @docs/file.md syntax
+- **Be specific**: Provide concrete examples and clear expectations
-## Memory vs Other Features
+### Don'ts - What To Avoid
-| 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 |
+- **Don't store secrets**: Never include API keys, passwords, or credentials
+- **Don't duplicate**: Avoid repeating content across memory files
+- **Don't create too many**: Keep subdirectory overrides minimal and focused
+- **Don't make it too long**: Keep memory files under 500 lines
+- **Don't include sensitive data**: No PII, private information, or proprietary secrets
+- **Don't forget to update**: Memory becomes stale if not maintained
+- **Don't over-organize**: Use hierarchy strategically, not excessively
+
+## Installation Instructions
+
+### Setup Project Memory
+
+1. **Create a CLAUDE.md in your project root:**
+ ```bash
+ cd /path/to/your/project
+ touch CLAUDE.md
+ ```
+
+2. **Add project standards:**
+ ```bash
+ cat > CLAUDE.md << 'EOF'
+ # Project Configuration
+
+ ## Project Overview
+ - **Name**: Your Project Name
+ - **Tech Stack**: List your technologies
+ - **Team Size**: Number of developers
+
+ ## Development Standards
+ - Your coding standards
+ - Naming conventions
+ - Testing requirements
+ EOF
+ ```
+
+3. **Commit to git:**
+ ```bash
+ git add CLAUDE.md
+ git commit -m "Add project memory configuration"
+ ```
+
+### Setup Personal Memory
+
+1. **Create ~/.claude directory:**
+ ```bash
+ mkdir -p ~/.claude
+ ```
+
+2. **Create personal CLAUDE.md:**
+ ```bash
+ touch ~/.claude/CLAUDE.md
+ ```
+
+3. **Add your preferences:**
+ ```bash
+ cat > ~/.claude/CLAUDE.md << 'EOF'
+ # My Development Preferences
+
+ ## About Me
+ - Experience Level: [Your level]
+ - Preferred Languages: [Your languages]
+ - Communication Style: [Your style]
+
+ ## Code Preferences
+ - [Your preferences]
+ EOF
+ ```
+
+### Setup Directory-Specific Memory
+
+1. **Create memory for specific directories:**
+ ```bash
+ mkdir -p /path/to/directory/.claude
+ touch /path/to/directory/CLAUDE.md
+ ```
+
+2. **Add directory-specific rules:**
+ ```bash
+ cat > /path/to/directory/CLAUDE.md << 'EOF'
+ # [Directory Name] Standards
+
+ This file overrides root CLAUDE.md for this directory.
+
+ ## [Specific Standards]
+ EOF
+ ```
+
+3. **Commit to version control:**
+ ```bash
+ git add /path/to/directory/CLAUDE.md
+ git commit -m "Add [directory] memory configuration"
+ ```
+
+### Verify Setup
+
+1. **Check memory locations:**
+ ```bash
+ # Project root memory
+ ls -la ./CLAUDE.md
+
+ # Personal memory
+ ls -la ~/.claude/CLAUDE.md
+ ```
+
+2. **Claude Code will automatically load** these files when starting a session
+
+3. **Test with Claude Code** by starting a new session in your project
+
+## Related Concepts Links
+
+### Core Memory Concepts
+- [CLAUDE.md File Format Guide](./examples/)
+- [Memory Examples](./examples/)
+- [Memory Hierarchy](./examples/)
+
+### Integration Points
+- [MCP Protocol](../04-mcp/) - Live data access alongside memory
+- [Slash Commands](../02-slash-commands/) - Session-specific shortcuts
+- [Skills](../05-skills/) - Automated workflows with memory context
+
+### Best Practices
+- [Code Organization](./examples/)
+- [Team Collaboration](./examples/)
+- [Documentation Strategy](./examples/)
+
+### Related Claude Features
+- [Claude Web Memory](https://claude.ai) - Automatic synthesis
+- [File Imports](./examples/) - Reference external documentation
+- [File Context](../01-context-window/) - Current session context
diff --git a/04-mcp/README.md b/04-mcp/README.md
index 6c27f53..e4ecdd4 100644
--- a/04-mcp/README.md
+++ b/04-mcp/README.md
@@ -1,10 +1,73 @@
-# MCP (Model Context Protocol) Examples
+# MCP (Model Context Protocol)
-This folder contains example MCP server configurations for Claude Code.
+This folder contains comprehensive documentation and examples for MCP server configurations and usage with Claude Code.
-## What is MCP?
+## Overview
-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.
+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.
+
+Key characteristics:
+- Real-time access to external services
+- Live data synchronization
+- Extensible architecture
+- Secure authentication
+- Tool-based interactions
+
+## 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!
+```
## Installation
@@ -14,10 +77,78 @@ Copy the appropriate configuration to your project's `.claude/` directory:
cp github-mcp.json /path/to/your/project/.claude/mcp.json
```
-## Available MCP Configurations
+## Available MCP Servers Table
-### 1. GitHub MCP (`github-mcp.json`)
-Access GitHub repositories, PRs, issues, and commits.
+| 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:**
+
+#### 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
**Setup**:
```bash
@@ -25,24 +156,44 @@ 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
+### Example 2: Database MCP Setup
-**Usage**:
-```
-/mcp__github__list_prs completed:true last:7days
-/mcp__github__get_pr 456
-/mcp__github__create_issue "Bug in login form"
+**Configuration:**
+
+```json
+{
+ "mcpServers": {
+ "database": {
+ "command": "npx",
+ "args": ["@modelcontextprotocol/server-database"],
+ "env": {
+ "DATABASE_URL": "postgresql://user:pass@localhost/mydb"
+ }
+ }
+ }
+}
```
-### 2. Database MCP (`database-mcp.json`)
-Query PostgreSQL/MySQL databases.
+**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
+```
**Setup**:
```bash
@@ -50,35 +201,52 @@ export DATABASE_URL="postgresql://user:pass@localhost/mydb"
cp database-mcp.json ~/.claude/mcp.json
```
-**Usage**:
+### 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
```
-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
@@ -88,63 +256,38 @@ export SLACK_TOKEN="your_slack_token"
cp multi-mcp.json ~/.claude/mcp.json
```
-## Available MCP Servers
+### Example 4: Filesystem MCP Operations
-| 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
+**Configuration:**
```json
{
"mcpServers": {
- "server-name": {
+ "filesystem": {
"command": "npx",
- "args": ["@modelcontextprotocol/server-name"],
- "env": {
- "ENV_VAR": "${ENV_VAR}"
- }
+ "args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
}
}
}
```
-## Multi-MCP Workflow Example
+**Available Operations:**
-### Daily Report Generation
+| 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 |
-```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
+**Setup**:
+```bash
+cp filesystem-mcp.json ~/.claude/mcp.json
```
-## MCP vs Memory
+## MCP vs Memory: Decision Matrix
```mermaid
graph TD
@@ -156,6 +299,27 @@ graph TD
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
```
## Environment Variables
@@ -179,27 +343,126 @@ Then reference them in MCP config:
}
```
-## Security Best Practices
+## Best Practices
-### Do's ✅
-- Use environment variables for credentials
-- Rotate tokens regularly
+### Security Considerations
+
+#### Do's ✅
+- Use environment variables for all credentials
+- Rotate tokens and API keys regularly (monthly recommended)
- Use read-only tokens when possible
-- Limit MCP server access scope
-- Monitor MCP server usage
+- Limit MCP server access scope to minimum required
+- Monitor MCP server usage and access logs
+- Use OAuth for external services when available
+- Implement rate limiting on MCP requests
+- Test MCP connections before production use
+- Document all active MCP connections
+- Keep MCP server packages updated
-### Don'ts ❌
+#### Don'ts ❌
- Don't hardcode credentials in config files
-- Don't commit tokens to git
-- Don't share tokens in team chats
+- Don't commit tokens or secrets to git
+- Don't share tokens in team chats or emails
- Don't use personal tokens for team projects
- Don't grant unnecessary permissions
+- Don't ignore authentication errors
+- Don't expose MCP endpoints publicly
+- Don't run MCP servers with root/admin privileges
+- Don't cache sensitive data in logs
+- Don't disable authentication mechanisms
+
+### Configuration Best Practices
+
+1. **Version Control**: Keep `.claude/mcp.json` in git but use environment variables for secrets
+2. **Least Privilege**: Grant minimum permissions needed for each MCP server
+3. **Isolation**: Run different MCP servers in separate processes when possible
+4. **Monitoring**: Log all MCP requests and errors for audit trails
+5. **Testing**: Test all MCP configurations before deploying to production
+
+### Performance Tips
+
+- Cache frequently accessed data at the application level
+- Use MCP queries that are specific to reduce data transfer
+- Monitor response times for MCP operations
+- Consider rate limiting for external APIs
+- Use batching when performing multiple operations
+
+## Installation Instructions
+
+### Prerequisites
+- Node.js and npm installed
+- Claude Code CLI installed
+- API tokens/credentials for external services
+
+### Step-by-Step Setup
+
+1. **Create MCP configuration file:**
+```bash
+mkdir -p ~/.claude
+touch ~/.claude/mcp.json
+```
+
+2. **Add your first MCP server** (example: GitHub):
+```json
+{
+ "mcpServers": {
+ "github": {
+ "command": "npx",
+ "args": ["@modelcontextprotocol/server-github"],
+ "env": {
+ "GITHUB_TOKEN": "${GITHUB_TOKEN}"
+ }
+ }
+ }
+}
+```
+
+3. **Set environment variables:**
+```bash
+export GITHUB_TOKEN="your_github_personal_access_token"
+```
+
+4. **Test the connection:**
+```bash
+claude /mcp
+```
+
+5. **Use MCP tools:**
+```bash
+/mcp__github__list_prs
+/mcp__github__create_issue "Title" "Description"
+```
+
+### Installation for Specific Services
+
+**GitHub MCP:**
+```bash
+npm install -g @modelcontextprotocol/server-github
+```
+
+**Database MCP:**
+```bash
+npm install -g @modelcontextprotocol/server-database
+```
+
+**Filesystem MCP:**
+```bash
+npm install -g @modelcontextprotocol/server-filesystem
+```
+
+**Slack MCP:**
+```bash
+npm install -g @modelcontextprotocol/server-slack
+```
## Troubleshooting
### MCP Server Not Found
```bash
-# Install MCP server globally
+# Verify MCP server is installed
+npm list -g @modelcontextprotocol/server-github
+
+# Install if missing
npm install -g @modelcontextprotocol/server-github
```
@@ -210,16 +473,45 @@ echo $GITHUB_TOKEN
# Re-export if needed
export GITHUB_TOKEN="your_token"
+
+# Verify token has correct permissions
+# Check GitHub token scopes at: https://github.com/settings/tokens
```
### Connection Timeout
-- Check network connectivity
+- Check network connectivity: `ping api.github.com`
- Verify API endpoint is accessible
- Check rate limits on API
- Try increasing timeout in config
+- Check for firewall or proxy issues
+
+### MCP Server Crashes
+- Check MCP server logs: `~/.claude/logs/`
+- Verify all environment variables are set
+- Ensure proper file permissions
+- Try reinstalling the MCP server package
+- Check for conflicting processes on the same port
+
+## Related Concepts
+
+### Memory vs MCP
+- **Memory**: Stores persistent, unchanging data (preferences, context, history)
+- **MCP**: Accesses live, changing data (APIs, databases, real-time services)
+
+### When to Use Each
+- **Use Memory** for: User preferences, conversation history, learned context
+- **Use MCP** for: Current GitHub issues, live database queries, real-time data
+
+### Integration with Other Claude Features
+- Combine MCP with Memory for rich context
+- Use MCP tools in prompts for better reasoning
+- Leverage multiple MCPs for complex workflows
## 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)
+- [Available MCP Servers](https://github.com/modelcontextprotocol/servers)
+- [Claude API Documentation](https://docs.anthropic.com)
+- [Environment Variables Setup Guide](https://www.digitalocean.com/community/tutorials/how-to-read-and-set-environmental-and-shell-variables)
diff --git a/05-skills/README.md b/05-skills/README.md
index f4a9b5c..f08b52f 100644
--- a/05-skills/README.md
+++ b/05-skills/README.md
@@ -1,134 +1,992 @@
-# Skills Examples
+# Agent Skills Guide
-This folder contains example skills for Claude Code. Skills are reusable, model-invoked capabilities that Claude automatically detects and uses.
+Agent Skills are reusable, model-invoked capabilities packaged as folders containing instructions, scripts, and resources. Claude automatically detects and uses relevant skills.
-## Installation
+## Overview
-Copy skill folders to your skills directory:
+Agent Skills enable you to:
+- **Package domain expertise** - Encapsulate specialized knowledge and processes
+- **Ensure consistency** - Apply standardized approaches across all projects
+- **Enable automation** - Let Claude automatically invoke skills when needed
+- **Scale workflows** - Reuse skills across multiple projects and teams
+- **Maintain quality** - Embed best practices directly into your workflow
-```bash
-# For personal skills
-cp -r code-review ~/.claude/skills/
+Skills are discovered automatically based on user requests and skill metadata, making them seamless to use without explicit commands.
-# For project skills
-cp -r code-review /path/to/project/.claude/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
```
-## Available Skills
+## Skill Loading Process
-### 1. Code Review Skill
-**Location**: `code-review/`
+```mermaid
+sequenceDiagram
+ participant User
+ participant Claude as Claude
+ participant System as System
+ participant Skill as Skill
-**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]
+ 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
```
-### 2. Brand Voice Skill
-**Location**: `brand-voice/`
+## Skill Types & Locations Table
-**Purpose**: Ensure consistent brand voice in all communications
+| 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 |
-**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
+## Pre-built Skills
-**Usage**: Automatically invoked when creating marketing copy or customer communications
+```mermaid
+graph TB
+ A["Pre-built Skills"]
+ B["PowerPoint (pptx)"]
+ C["Excel (xlsx)"]
+ D["Word (docx)"]
+ E["PDF"]
-### 3. Documentation Generator Skill
-**Location**: `doc-generator/`
+ A --> B
+ A --> C
+ A --> D
+ A --> E
-**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)
+ 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"]
```
-## SKILL.md Format
+## 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: Skill Name
-description: What this skill does
+name: Code Review Specialist
+description: Comprehensive code review with security, performance, and quality analysis
version: "1.0.0"
tags:
- - category
- - use-case
-when_to_use: When users ask to...
+ - code-review
+ - quality
+ - security
+when_to_use: When users ask to review code, analyze code quality, or evaluate pull requests
---
-# Skill Instructions
+# Code Review Skill
-Detailed instructions for Claude on how to execute this 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
```
-## Skill Discovery
+**Python Script:** `~/.claude/skills/code-review/scripts/analyze-metrics.py`
-Claude automatically:
-1. Scans available skills
-2. Matches user request to skill metadata
-3. Loads relevant skill instructions
-4. Executes skill with full context
+```python
+#!/usr/bin/env python3
+import re
+import sys
-## When to Use Skills
+def analyze_code_metrics(code):
+ """Analyze code for common metrics."""
-| 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 |
+ # Count functions
+ functions = len(re.findall(r'^def\s+\w+', code, re.MULTILINE))
-## Skills vs Other Features
+ # Count classes
+ classes = len(re.findall(r'^class\s+\w+', code, re.MULTILINE))
-| 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 |
+ # Average line length
+ lines = code.split('\n')
+ avg_length = sum(len(l) for l in lines) / len(lines) if lines else 0
-## Creating Custom Skills
+ # 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:** `~/.claude/skills/code-review/scripts/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:** `~/.claude/skills/code-review/templates/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:** `~/.claude/skills/code-review/templates/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)
+```
+
+**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-template.txt`
+
+```
+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-post-template.txt`
+
+```
+[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`
+
+```markdown
+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:** `.claude/skills/doc-generator/scripts/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"]
+```
+
+## 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
+- Include YAML metadata in SKILL.md
+- Organize skills by domain/purpose
+- Version your skills
+- Document dependencies
+
+### 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
+- Don't assume Claude knows skill context
+- Don't create circular dependencies
+- Don't ignore performance implications
+
+## Installation Instructions
+
+### For Personal Skills
+
+Copy skill folders to your personal skills directory:
+
+```bash
+# Copy individual skill
+cp -r code-review ~/.claude/skills/
+
+# Copy all skills
+cp -r * ~/.claude/skills/
+
+# Make scripts executable
+chmod +x ~/.claude/skills/code-review/scripts/*.py
+```
+
+### For Project Skills
+
+Copy skill folders to your project skills directory to share with team:
+
+```bash
+# Copy individual skill to project
+cp -r code-review /path/to/project/.claude/skills/
+
+# Copy all skills
+cp -r * /path/to/project/.claude/skills/
+
+# Commit to version control
+git add .claude/skills/
+git commit -m "Add project skills"
+```
+
+### Verifying Installation
+
+After copying skills:
+
+1. Check that SKILL.md exists in each skill directory
+2. Verify scripts have proper permissions: `ls -l ~/.claude/skills/code-review/scripts/`
+3. Test skill invocation with a sample request
+
+### Creating Custom Skills
1. Create skill directory structure
2. Write SKILL.md with metadata and instructions
@@ -136,70 +994,11 @@ Claude automatically:
4. Test by copying to skills directory
5. Refine based on usage
-## Best Practices
+## Related Concepts Links
-### 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)
+- **Slash Commands** - User-initiated shortcuts for specific tasks
+- **Subagents** - Delegated AI agents for task distribution
+- **Memory** - Persistent context across conversation sessions
+- **MCP (Model Context Protocol)** - Real-time access to external data sources
+- **Claude Code** - AI CLI for automated development workflows
+- **Skill Metadata** - YAML frontmatter that defines skill activation rules
diff --git a/06-plugins/README.md b/06-plugins/README.md
index cf53a51..13dc780 100644
--- a/06-plugins/README.md
+++ b/06-plugins/README.md
@@ -1,120 +1,87 @@
-# Claude Code Plugins Examples
+# Claude Code Plugins
This folder contains complete plugin examples that bundle multiple Claude Code features into cohesive, installable packages.
-## What Are Plugins?
+## Overview
-Plugins are bundled collections of:
-- Slash commands
-- Subagents
-- MCP servers
-- Hooks
-- Scripts and templates
+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.
-All installable with a single command.
+## Plugin Architecture
-## Available Plugins
+```mermaid
+graph TB
+ A["Plugin"]
+ B["Slash Commands"]
+ C["Subagents"]
+ D["MCP Servers"]
+ E["Hooks"]
+ F["Configuration"]
-### 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
+ A -->|bundles| B
+ A -->|bundles| C
+ A -->|bundles| D
+ A -->|bundles| E
+ A -->|bundles| F
```
-**Use Case**: Automated code reviews for pull requests
+## 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
-### 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
+ 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 ✅
```
-**Use Case**: Kubernetes deployment automation and incident management
+## 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 |
-### 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)
+## Plugin Definition Structure
```yaml
---
name: plugin-name
version: "1.0.0"
-description: What this plugin does
-author: Your Name
+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/
@@ -125,12 +92,233 @@ components:
- type: hooks
path: hooks/
+# Configuration
config:
auto_load: true
enabled_by_default: true
---
```
+## Plugin Structure Example
+
+```
+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 |
+
## Installation Methods
### Official Plugin
@@ -150,79 +338,117 @@ config:
## When to Create a Plugin
-Create a plugin when:
+```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
+```
-✅ 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
+### Plugin Use Cases
-Don't create a plugin when:
+| 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 |
-❌ Single slash command is sufficient
-❌ One-time use case
-❌ Personal preference (use individual features)
-❌ Very simple functionality
+## Publishing a Plugin
-## Plugin vs Individual Features
+**Steps to publish:**
-| 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 |
+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
-## Creating Your Own Plugin
+**Example submission:**
-### Step 1: Create Structure
+```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
-mkdir my-plugin
-cd my-plugin
-mkdir commands agents mcp hooks scripts templates
+/plugin install pr-review
```
-### Step 2: Create plugin.yaml
-```yaml
----
-name: my-plugin
-version: "1.0.0"
-description: My custom plugin
-author: Your Name
----
-```
+## Features
+✅ Security analysis
+✅ Test coverage checking
+✅ Documentation verification
+✅ Code quality assessment
+✅ Performance impact analysis
-### 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
+## Usage
```bash
-/plugin install ./my-plugin
+/review-pr
+/check-security
+/check-tests
```
-### Step 5: Publish
-Submit to plugin marketplace or share via git repository.
+## 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
+```
## Best Practices
### Do's ✅
- Use clear, descriptive plugin names
- Include comprehensive README
-- Version your plugin properly
+- Version your plugin properly (semver)
- Test all components together
- Document requirements clearly
- Provide usage examples
- Include error handling
- Tag appropriately for discovery
+- Maintain backward compatibility
+- Keep plugins focused and cohesive
+- Include comprehensive tests
+- Document all dependencies
### Don'ts ❌
- Don't bundle unrelated features
@@ -231,45 +457,82 @@ Submit to plugin marketplace or share via git repository.
- Don't forget documentation
- Don't create redundant plugins
- Don't ignore versioning
+- Don't overcomplicate component dependencies
+- Don't forget to handle errors gracefully
-## Plugin Lifecycle
+## Installation Instructions
-```
-Discover → Install → Configure → Use → Update → Disable/Remove
-```
+### Installing from Marketplace
-### Discovery
-Browse plugin marketplace or search by tags
+1. **Browse available plugins:**
+ ```bash
+ /plugin list
+ ```
+
+2. **View plugin details:**
+ ```bash
+ /plugin info plugin-name
+ ```
+
+3. **Install a plugin:**
+ ```bash
+ /plugin install plugin-name
+ ```
+
+### Installing from Local Path
-### Installation
```bash
-/plugin install plugin-name
+/plugin install ./path/to/plugin-directory
```
-### Configuration
-Set up required environment variables and credentials
+### Installing from GitHub
-### Usage
-Use slash commands, subagents work automatically
+```bash
+/plugin install github:username/repo
+```
+
+### Listing Installed Plugins
+
+```bash
+/plugin list --installed
+```
+
+### Updating a Plugin
-### Updates
```bash
/plugin update plugin-name
```
-### Disable
+### Disabling/Enabling a Plugin
+
```bash
+# Temporarily disable
/plugin disable plugin-name
+
+# Re-enable
+/plugin enable plugin-name
```
-### Remove
+### Uninstalling a Plugin
+
```bash
/plugin uninstall plugin-name
```
-## Example: Complete Workflow
+## Related Concepts
-### PR Review Plugin Workflow
+The following Claude Code features work together with plugins:
+
+- **[Slash Commands](../01-slash-commands/)** - Individual commands bundled in plugins
+- **[Subagents](../03-subagents/)** - Specialized agents included as plugin components
+- **[MCP Servers](../04-mcp-servers/)** - Model Context Protocol integrations bundled in plugins
+- **[Hooks](../05-hooks/)** - Event handlers that trigger plugin workflows
+- **[Skills](../02-skills/)** - Domain expertise that can be wrapped into plugins
+- **[Environments](../07-environments/)** - Configuration and secrets management for plugins
+
+## Complete Example Workflow
+
+### PR Review Plugin Full Workflow
```
1. User: /review-pr
@@ -291,23 +554,41 @@ Use slash commands, subagents work automatically
## Troubleshooting
### Plugin Won't Install
-- Check Claude Code version compatibility
-- Verify plugin.yaml syntax
+- Check Claude Code version compatibility: `/version`
+- Verify `plugin.yaml` syntax with `yaml` validator
- Check internet connection (for remote plugins)
+- Review permissions: `ls -la plugin/`
### Components Not Loading
-- Verify paths in plugin.yaml
-- Check file permissions
+- Verify paths in `plugin.yaml` match actual directory structure
+- Check file permissions: `chmod +x scripts/`
- Review component file syntax
+- Check logs: `/plugin debug plugin-name`
### MCP Connection Failed
-- Verify environment variables are set
-- Check MCP server installation
-- Test MCP connection independently
+- Verify environment variables are set correctly
+- Check MCP server installation and health
+- Test MCP connection independently with `/mcp test`
+- Review MCP configuration in `mcp/` directory
+
+### Commands Not Available After Install
+- Ensure plugin was installed successfully: `/plugin list --installed`
+- Check if plugin is enabled: `/plugin status plugin-name`
+- Restart Claude Code: `exit` and reopen
+- Check for naming conflicts with existing commands
+
+### Hook Execution Issues
+- Verify hook files have correct permissions
+- Check hook syntax and event names
+- Review hook logs for error details
+- Test hooks manually if possible
## Additional Resources
-- [Plugin Development Guide](https://docs.claude.com/plugins)
+- [Claude Code Documentation](https://docs.claude.com/claude-code)
- [Plugin Marketplace](https://plugins.claude.com)
-- [Example Plugins Repository](https://github.com/anthropic/claude-plugins)
-- [Plugin API Reference](https://docs.claude.com/api/plugins)
+- [Official Plugin Examples](https://github.com/anthropic/claude-plugins)
+- [Plugin Development Guide](https://docs.claude.com/plugins/development)
+- [MCP Server Reference](https://spec.modelcontextprotocol.io/)
+- [Subagent Configuration Guide](../03-subagents/README.md)
+- [Hook System Reference](../05-hooks/README.md)
diff --git a/07-hooks/README.md b/07-hooks/README.md
index d648382..9f20bfc 100644
--- a/07-hooks/README.md
+++ b/07-hooks/README.md
@@ -1,15 +1,25 @@
# Hooks
-Hooks are shell commands that execute automatically in response to specific events in Claude Code. They enable custom workflows, validation, and automation.
+Hooks are event-driven shell commands that execute automatically in response to Claude Code events. They enable automation, validation, and custom workflows without manual intervention.
-## What Are Hooks?
+## Overview
-Hooks are event-driven scripts that run at specific points during Claude Code's operation:
+Hooks are shell commands that execute automatically in response to specific events in Claude Code. They enable custom workflows, validation, and automation. Hooks are triggered by:
- **Pre-hooks**: Run before an action
- **Post-hooks**: Run after an action
- **Validation hooks**: Check conditions before proceeding
-## Available Hook Types
+Hooks enable you to automate repetitive tasks, enforce code quality standards, and create seamless development workflows.
+
+## Hook Types
+
+| Hook Type | Event | Use Cases |
+|-----------|-------|-----------|
+| **Tool Hooks** | PreToolUse:*, PostToolUse:* | Auto-formatting, validation, logging |
+| **Session Hooks** | UserPromptSubmit, SessionStart, SessionEnd | Input validation, initialization, cleanup |
+| **Git Hooks** | PreCommit, PostCommit, PrePush | Testing, linting, notifications |
+
+## Available Hook Types (Detailed)
### 1. Tool Hooks
Execute before/after tool usage:
@@ -29,6 +39,30 @@ Execute during git operations:
- `PostCommit` - After commit completes
- `PrePush` - Before pushing to remote
+## Common Hooks
+
+```bash
+# Pre-commit hook - run tests
+PreCommit: "npm test"
+
+# Post-write hook - format code
+PostToolUse:Write: "prettier --write ${file_path}"
+
+# Pre-tool-use hook - validate
+PreToolUse:Edit: "eslint ${file_path}"
+
+# User prompt validation
+UserPromptSubmit: "~/.claude/hooks/validate-prompt.sh"
+```
+
+## Hook Variables
+
+Available variables in hook commands:
+- `${file_path}` - Path to file being edited/written
+- `${command}` - Command being executed (Bash hooks)
+- `${tool_name}` - Name of the tool being used
+- `${session_id}` - Current session identifier
+
## Configuration
Hooks are configured in Claude Code settings:
@@ -44,14 +78,6 @@ Hooks are configured in Claude Code settings:
}
```
-## Hook Variables
-
-Available variables in hook commands:
-- `${file_path}` - Path to file being edited/written
-- `${command}` - Command being executed (Bash hooks)
-- `${tool_name}` - Name of the tool being used
-- `${session_id}` - Current session identifier
-
## Examples
### Example 1: Auto-format Code on Edit
@@ -224,19 +250,20 @@ Hooks communicate results via exit codes:
## Best Practices
### Do's ✅
-- Keep hooks fast (< 1 second when possible)
+- Keep hooks fast (< 1 second)
- Use hooks for validation and automation
+- Handle errors gracefully
+- Use absolute paths
- Log important events
- Make hooks idempotent
-- Handle errors gracefully
-- Use absolute paths in hooks
+- Test hooks independently before deploying
### Don'ts ❌
-- Don't make hooks interactive (no user input)
-- Don't use hooks for long-running tasks
-- Don't hardcode credentials in hooks
-- Don't ignore hook failures silently
-- Don't modify files unexpectedly
+- Make hooks interactive
+- Use hooks for long-running tasks
+- Hardcode credentials
+- Ignore hook failures silently
+- Modify files unexpectedly
## Common Use Cases
@@ -296,21 +323,44 @@ View hook execution logs:
tail -f ~/.claude/hooks.log
```
-## Installation
+## Installation Instructions
-1. Create hooks directory:
+### Step 1: Create Hooks Directory
```bash
mkdir -p ~/.claude/hooks
```
-2. Copy example hooks:
+### Step 2: Copy Example Hooks
```bash
cp 07-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
```
-3. Configure in settings:
-Edit `~/.claude/settings.json` to add hook configurations.
+### Step 3: Configure in Settings
+Edit `~/.claude/settings.json` to add hook configurations:
+
+```json
+{
+ "hooks": {
+ "PreToolUse:Write": "~/.claude/hooks/format-code.sh ${file_path}",
+ "PostToolUse:Write": "~/.claude/hooks/security-scan.sh ${file_path}",
+ "PreCommit": "~/.claude/hooks/pre-commit.sh",
+ "UserPromptSubmit": "~/.claude/hooks/validate-prompt.sh"
+ }
+}
+```
+
+### Step 4: Make Scripts Executable
+```bash
+chmod +x ~/.claude/hooks/*.sh
+```
+
+### Step 5: Test Your Hooks
+```bash
+# Enable debug mode for testing
+# Set "debug": true in hooks configuration
+tail -f ~/.claude/hooks.log
+```
## Troubleshooting
@@ -341,3 +391,12 @@ See the example files in this directory:
- `log-bash.sh` - Log all bash commands
- `validate-prompt.sh` - Validate user prompts
- `notify-team.sh` - Send notifications on events
+
+## Related Concepts
+
+For more information on related Claude Code features, see:
+- **[Checkpoints and Rewind](../08-checkpoints/)** - Save and restore conversation state
+- **[Custom Commands](../06-commands/)** - Create custom slash commands
+- **[Settings Configuration](../settings/)** - Configure Claude Code behavior
+- **[Advanced Features](../advanced-features/)** - Explore advanced Claude Code capabilities
+- **[Main Concepts Guide](../claude_concepts_guide.md)** - Complete reference documentation
diff --git a/08-checkpoints/README.md b/08-checkpoints/README.md
index 5014ac2..2c86e8f 100644
--- a/08-checkpoints/README.md
+++ b/08-checkpoints/README.md
@@ -2,24 +2,47 @@
Checkpoints allow you to save conversation state and rewind to previous points in your Claude Code session. This is invaluable for exploring different approaches, recovering from mistakes, or comparing alternative solutions.
-## What Are Checkpoints?
+## Overview
-Checkpoints are snapshots of your conversation state, including:
+Checkpoints allow you to save conversation state and rewind to previous points, enabling safe experimentation and exploration of multiple approaches. They are snapshots of your conversation state, including:
- All messages exchanged
- File modifications made
- Tool usage history
- Session context
+Checkpoints are invaluable when exploring different approaches, recovering from mistakes, or comparing alternative solutions.
+
## Key Concepts
-### Checkpoint
-A saved point in your conversation that you can return to later.
+| Concept | Description |
+|---------|-------------|
+| **Checkpoint** | Snapshot of conversation state including messages, files, and context |
+| **Rewind** | Return to a previous checkpoint, discarding subsequent changes |
+| **Branch Point** | Checkpoint from which multiple approaches are explored |
-### Rewind
-The action of returning to a previous checkpoint, discarding all changes made after that point.
+## Commands
-### Branch Point
-A checkpoint where you explored multiple different approaches.
+All checkpoint operations are performed using the `/checkpoint` command:
+
+```bash
+# Create checkpoint
+/checkpoint save "Before refactoring"
+
+# List checkpoints
+/checkpoint list
+
+# Rewind to checkpoint
+/checkpoint rewind "Before refactoring"
+
+# Compare checkpoints
+/checkpoint diff checkpoint-1 checkpoint-2
+
+# Delete checkpoint
+/checkpoint delete checkpoint-1
+
+# Export checkpoint
+/checkpoint export "name" ~/checkpoints/backup.json
+```
## Creating Checkpoints
@@ -41,6 +64,15 @@ User: /checkpoint save "Before API refactor"
User: /checkpoint create pre-deployment
```
+## Use Cases
+
+| Scenario | Workflow |
+|----------|----------|
+| **Exploring Approaches** | Save → Try A → Save → Rewind → Try B → Compare |
+| **Safe Refactoring** | Save → Refactor → Test → If fail: Rewind |
+| **A/B Testing** | Save → Design A → Save → Rewind → Design B → Compare |
+| **Mistake Recovery** | Notice issue → Rewind to last good state |
+
## Using Checkpoints
### List Checkpoints
@@ -308,7 +340,7 @@ Poor checkpoint names:
## Configuration
-Configure checkpoint behavior in settings:
+Configure checkpoint behavior in settings. Here's the comprehensive configuration with all available options:
```json
{
@@ -324,11 +356,11 @@ Configure checkpoint behavior in settings:
### Configuration Options
-- `autoCheckpoint`: Enable automatic checkpoints
-- `autoCheckpointInterval`: Minutes between auto-checkpoints
-- `maxCheckpoints`: Maximum number of checkpoints to retain
-- `compressionEnabled`: Compress checkpoint data
-- `includeFileContents`: Include full file contents in checkpoints
+- `autoCheckpoint`: Enable automatic checkpoints (default: true)
+- `autoCheckpointInterval`: Minutes between auto-checkpoints (default: 30)
+- `maxCheckpoints`: Maximum number of checkpoints to retain (default: 20)
+- `compressionEnabled`: Compress checkpoint data to save space (default: true)
+- `includeFileContents`: Include full file contents in checkpoints (default: true)
## Limitations
@@ -424,3 +456,24 @@ Use both together:
5. Verify system works
6. Proceed cautiously
```
+
+## Related Concepts
+
+- **[Planning Mode](../07-planning/)** - Create detailed implementation plans before coding
+- **[Memory Management](../06-memory/)** - Managing conversation history and context
+- **[Code Navigation](../05-code-navigation/)** - Understanding and navigating your codebase
+- **[Real-time Collaboration](../09-collaboration/)** - Working with teams using Claude Code
+- **[Error Handling](../10-error-handling/)** - Handling and recovering from errors
+- **[Best Practices](../11-best-practices/)** - General best practices for Claude Code usage
+
+## Summary
+
+Checkpoints are a powerful feature for safe exploration and experimentation in Claude Code. By combining checkpoints with your development workflow, you can:
+
+- Experiment fearlessly with multiple approaches
+- Quickly recover from mistakes without losing work
+- Compare different solutions side-by-side
+- Maintain clean, organized development sessions
+- Integrate safely with version control systems
+
+The key to effective checkpoint usage is creating them at meaningful points in your work and using descriptive names that make it easy to find and rewind to the right state when needed.
diff --git a/09-advanced-features/README.md b/09-advanced-features/README.md
index d6c0b85..2967994 100644
--- a/09-advanced-features/README.md
+++ b/09-advanced-features/README.md
@@ -4,14 +4,33 @@ Comprehensive guide to Claude Code's advanced capabilities including planning mo
## Table of Contents
-1. [Planning Mode](#planning-mode)
-2. [Extended Thinking](#extended-thinking)
-3. [Background Tasks](#background-tasks)
-4. [Permission Mode](#permission-mode)
-5. [Headless Mode](#headless-mode)
-6. [Session Management](#session-management)
-7. [Interactive Features](#interactive-features)
-8. [Configuration and Settings](#configuration-and-settings)
+1. [Overview](#overview)
+2. [Planning Mode](#planning-mode)
+3. [Extended Thinking](#extended-thinking)
+4. [Background Tasks](#background-tasks)
+5. [Permission Mode](#permission-mode)
+6. [Headless Mode](#headless-mode)
+7. [Session Management](#session-management)
+8. [Interactive Features](#interactive-features)
+9. [Configuration and Settings](#configuration-and-settings)
+10. [Best Practices](#best-practices)
+11. [Related Concepts](#related-concepts)
+
+---
+
+## Overview
+
+Advanced features in Claude Code extend the core capabilities with planning, reasoning, automation, and control mechanisms. These features enable sophisticated workflows for complex development tasks, code review, automation, and multi-session management.
+
+**Key advanced features include:**
+- **Planning Mode**: Create detailed implementation plans before coding
+- **Extended Thinking**: Deep reasoning for complex problems
+- **Background Tasks**: Run long operations without blocking the conversation
+- **Permission Modes**: Control what Claude can do (unrestricted, confirm, read-only, custom)
+- **Headless Mode**: Run Claude Code without interactive input for automation and CI/CD
+- **Session Management**: Manage multiple work sessions
+- **Interactive Features**: Keyboard shortcuts, multi-line input, and command history
+- **Configuration**: Customize behavior with JSON configuration files
---
@@ -43,8 +62,8 @@ Planning mode is a two-phase approach:
### Activating Planning Mode
**Explicit activation**:
-```
-User: /plan implement user authentication system
+```bash
+/plan Implement user authentication system
```
**Automatic activation**:
@@ -56,6 +75,13 @@ Claude: This is a complex task. Let me create a plan first...
[Enters planning mode]
```
+### Benefits of Planning Mode
+
+- **Clear roadmap with time estimates**: Detailed breakdown of implementation steps
+- **Risk assessment**: Identify potential issues before implementation
+- **Systematic task breakdown**: Organized phases and milestones
+- **Opportunity for review and modification**: Approve or adjust the plan before execution
+
### Example: Feature Implementation
```
@@ -142,13 +168,20 @@ Extended thinking is a deliberate, step-by-step reasoning process where Claude:
### Activating Extended Thinking
**Explicit activation**:
-```
-User: /think deeply about the best database architecture for this system
+```bash
+/think Should we use microservices or monolith?
```
**Automatic activation**:
For sufficiently complex queries, Claude automatically uses extended thinking.
+### Benefits of Extended Thinking
+
+- **Thorough analysis of trade-offs**: Examine pros and cons systematically
+- **Better architectural decisions**: Make informed choices with comprehensive evaluation
+- **Consideration of edge cases**: Think through potential issues and scenarios
+- **Systematic evaluation**: Structured approach to complex problem-solving
+
### Example: Architectural Decision
```
@@ -248,6 +281,18 @@ Background tasks run asynchronously while you continue working:
- Deployment scripts
- Analysis tools
+**Basic Usage:**
+```bash
+User: Run tests in background
+
+Claude: Started task bg-1234
+
+/task list # Show all tasks
+/task status bg-1234 # Check progress
+/task show bg-1234 # View output
+/task cancel bg-1234 # Cancel task
+```
+
### Starting Background Tasks
```
@@ -352,6 +397,23 @@ Claude: [Shows linter output from bg-5002]
Permission mode controls what actions Claude can take without explicit approval.
+### Permission Modes Table
+
+| Mode | Description | Use Case |
+|------|-------------|----------|
+| **Unrestricted** | Full access (default) | Active development |
+| **Confirm** | Ask before actions | Learning, pair programming |
+| **Read-only** | Analysis only | Code review |
+| **Custom** | Granular permissions | Fine-tuned control |
+
+### Permission Commands
+
+```bash
+/permission readonly # Code review mode
+/permission confirm # Learning mode
+/permission unrestricted # Full automation
+```
+
### Permission Levels
#### 1. Unrestricted Mode (Default)
@@ -453,7 +515,21 @@ Headless mode enables:
### Running in Headless Mode
```bash
-# Run a specific task
+# Run specific task
+claude-code --headless --task "Run all tests"
+
+# From script file
+claude-code --headless --script ./deploy.claude
+
+# CI/CD integration (GitHub Actions)
+- name: AI Code Review
+ run: claude-code --headless --task "Review PR"
+```
+
+### Additional Headless Usage Examples
+
+```bash
+# Run a specific task with output capture
claude-code --headless --task "Run all tests and generate coverage report"
# Run from a script file
@@ -540,7 +616,17 @@ claude-code --headless --script deploy.claude
Manage multiple Claude Code sessions effectively.
-### Session Commands
+### Session Management Commands
+
+```bash
+/session list # Show all sessions
+/session new "Feature" # Create new session
+/session switch "Bug" # Switch sessions
+/session save # Save current state
+/session load "name" # Load saved session
+```
+
+### Session Commands Details
**List sessions**:
```
@@ -616,6 +702,14 @@ claude-code --new
Claude Code supports keyboard shortcuts for efficiency:
+**Basic Navigation and Input:**
+- `Ctrl + R` - Search command history
+- `Tab` - Autocomplete
+- `↑ / ↓` - Command history
+- `Ctrl + L` - Clear screen
+
+**Extended Shortcuts:**
+
| Shortcut | Action |
|----------|--------|
| `Ctrl + C` | Cancel current operation |
@@ -668,6 +762,15 @@ User: Ctrl+R # Search history
For complex queries, use multi-line mode:
+```bash
+User: \
+> Long complex prompt
+> spanning multiple lines
+> \end
+```
+
+**Example:**
+
```
User: \
> Implement a user authentication system
@@ -703,6 +806,34 @@ User: Deploy to prodcutionuction
### Complete Configuration Example
+**Core advanced features configuration:**
+
+```json
+{
+ "planning": {
+ "autoEnter": true,
+ "requireApproval": true
+ },
+ "extendedThinking": {
+ "enabled": true,
+ "showThinkingProcess": true
+ },
+ "backgroundTasks": {
+ "enabled": true,
+ "maxConcurrentTasks": 5
+ },
+ "permissions": {
+ "mode": "unrestricted"
+ },
+ "headless": {
+ "exitOnError": true,
+ "verbose": true
+ }
+}
+```
+
+**Extended configuration example:**
+
```json
{
"general": {
@@ -897,3 +1028,17 @@ Create `.claude/config.json` in your project:
- ✅ Save important session states
- ✅ Clean up old sessions
- ❌ Don't mix unrelated work in one session
+
+---
+
+## Related Concepts
+
+For more information about Claude Code and related features, see:
+
+- [Main Claude Code Guide](../README.md)
+- [Claude Code Basics](../01-basics/)
+- [Advanced Code Analysis](../02-code-analysis/)
+- [Collaboration Features](../03-collaboration/)
+- [Troubleshooting Guide](../troubleshooting.md)
+- [Claude Documentation](https://docs.claude.com)
+- [MCP GitHub Servers](https://github.com/modelcontextprotocol/servers)